Please review changes against upstream code using SCM,
see the Vcs-* tags in debian/control for its location.

--- mksh-59c.orig/Build.sh
+++ mksh-59c/Build.sh
@@ -1,9 +1,10 @@
 #!/bin/sh
-srcversion='$MirOS: src/bin/mksh/Build.sh,v 1.763 2020/09/04 21:01:37 tg Exp $'
+srcversion='$MirOS: src/bin/mksh/Build.sh,v 1.858 2024/08/17 23:33:47 tg Exp $'
+set +evx
 #-
 # Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
 #		2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
-#		2020
+#		2020, 2021, 2022, 2023, 2024
 #	mirabilos <m@mirbsd.org>
 #
 # Provided that these terms and disclaimer and all copyright notices
@@ -29,6 +30,8 @@ srcversion='$MirOS: src/bin/mksh/Build.s
 LC_ALL=C; LANGUAGE=C
 export LC_ALL; unset LANGUAGE
 
+use_ach=x; unset use_ach
+
 case $ZSH_VERSION:$VERSION in
 :zsh*) ZSH_VERSION=2 ;;
 esac
@@ -44,10 +47,25 @@ if test -d /usr/xpg4/bin/. >/dev/null 2>
 	export PATH
 fi
 
+test_tool() {
+	x=`echo $2 | $3`
+	y=$?
+
+	test x"$y" = x"0" && test x"$x" = x"$4" && return
+	echo >&2 "E: your $1 does not work correctly!"
+	echo >&2 "N: 'echo $2 | $3' exited $y and returned '$x'; expected '$4'"
+	echo >&2 'N: install a better one and prepend its location to $PATH'
+	exit 1
+}
+test_tool grep foobarbaz 'grep bar' foobarbaz
+test_tool sed abc 'sed y/ac/AC/' AbC
+test_tool tr abc 'tr ac AC' AbC
+
+sp=' '
+ht='	'
 nl='
 '
-safeIFS='	'
-safeIFS=" $safeIFS$nl"
+safeIFS="$sp$ht$nl"
 IFS=$safeIFS
 allu=QWERTYUIOPASDFGHJKLZXCVBNM
 alll=qwertyuiopasdfghjklzxcvbnm
@@ -149,7 +167,7 @@ do_genopt() {
 			;;
 		*:@@*)
 			genopt_die ;;
-		0:/\*-|0:\ \**|0:)
+		0:/\*-|0:"$sp"\**|0:)
 			o_hdr=$o_hdr$nl$line
 			;;
 		0:@*|1:@*)
@@ -203,7 +221,8 @@ do_genopt() {
 	done | {
 		echo "$o_hdr"
 		echo "#ifndef $o_sym$o_gen"
-		echo "#else"
+		echo "#endif"
+		echo "#ifdef $o_sym"
 		cat
 		echo "#undef $o_sym"
 		echo "#endif"
@@ -223,6 +242,17 @@ fi
 
 echo "For the build logs, demonstrate that /dev/null and /dev/tty exist:"
 ls -l /dev/null /dev/tty
+cat <<EOF
+Flags on entry (plus HAVE_* which are not shown here):
+- CC        <$CC>
+- CFLAGS    <$CFLAGS>
+- CPPFLAGS  <$CPPFLAGS>
+- LDFLAGS   <$LDFLAGS>
+- LIBS      <$LIBS>
+- LDSTATIC  <$LDSTATIC>
+- TARGET_OS <$TARGET_OS> TARGET_OSREV <$TARGET_OSREV>
+
+EOF
 
 v() {
 	$e "$*"
@@ -244,7 +274,7 @@ vq() {
 rmf() {
 	for _f in "$@"; do
 		case $_f in
-		*.1|*.faq|*.ico) ;;
+		lksh.1|mksh.1|mksh.faq|mksh.ico) ;;
 		*) rm -f "$_f" ;;
 		esac
 	done
@@ -258,7 +288,7 @@ fx=
 me=`basename "$0"`
 orig_CFLAGS=$CFLAGS
 phase=x
-oldish_ed=stdout-ed,no-stderr-ed
+oldish_ed='stdout-ed no-stderr-ed'
 
 if test -t 1; then
 	bi='[1m'
@@ -313,6 +343,11 @@ ac_testinit() {
 			shift
 		fi
 		eval ft=\$HAVE_`upper $2`
+		if test_z "$ft"; then
+			echo >&2
+			echo >&2 "E: test $f depends on $2 which is not defined yet"
+			exit 255
+		fi
 		shift
 	fi
 	fd=${3-$f}
@@ -326,17 +361,28 @@ ac_testinit() {
 	return 0
 }
 
+cat_h_blurb() {
+	echo '#ifdef MKSH_USE_AUTOCONF_H
+/* things that “should” have been on the command line */
+#include "autoconf.h"
+#undef MKSH_USE_AUTOCONF_H
+#endif
+
+'
+	cat
+}
+
 # pipe .c | ac_test[n] [!] label [!] checkif[!]0 [setlabelifcheckis[!]0] useroutput
-ac_testnnd() {
+ac_testnndnd() {
 	if test x"$1" = x"!"; then
 		fr=1
 		shift
 	else
 		fr=0
 	fi
+	cat_h_blurb >conftest.c
 	ac_testinit "$@" || return 1
-	cat >conftest.c
-	vv ']' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN conftest.c $LIBS $ccpr"
+	vv ']' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN conftest.c $LIBS $ccpr"
 	test $tcfn = no && test -f a.out && tcfn=a.out
 	test $tcfn = no && test -f a.exe && tcfn=a.exe
 	test $tcfn = no && test -f conftest.exe && tcfn=conftest.exe
@@ -348,18 +394,28 @@ ac_testnnd() {
 	fi
 	vscan=
 	if test $phase = u; then
-		test $ct = gcc && vscan='unrecogni[sz]ed'
-		test $ct = hpcc && vscan='unsupported'
-		test $ct = pcc && vscan='unsupported'
-		test $ct = sunpro && vscan='-e ignored -e turned.off'
+		case $ct in
+		gcc*) vscan='unrecogni[sz]ed' ;;
+		hpcc) vscan='unsupported' ;;
+		pcc) vscan='unsupported' ;;
+		sunpro) vscan='-e ignored -e turned.off' ;;
+		esac
 	fi
 	test_n "$vscan" && grep $vscan vv.out >/dev/null 2>&1 && fv=$fr
 	return 0
 }
 ac_testn() {
-	ac_testnnd "$@" || return
-	rmf conftest.c conftest.o ${tcfn}* vv.out
-	ac_testdone
+	if ac_testnndnd "$@"; then
+		rmf conftest.c conftest.o ${tcfn}* vv.out
+		ac_testdone
+	else
+		rm -f conftest.c
+	fi
+}
+ac_testnnd() {
+	if ac_testnndnd "$@"; then
+		ac_testdone
+	fi
 }
 
 # ac_ifcpp cppexpr [!] label [!] checkif[!]0 [setlabelifcheckis[!]0] useroutput
@@ -384,6 +440,31 @@ EOF
 	test x"$fv" = x"1"
 }
 
+addtoach() {
+	if echo "$1" >>autoconf.h; then
+		echo ">>> $1"
+	else
+		echo >&2 "E: could not write autoconf.h"
+		exit 255
+	fi
+}
+
+# simple only (is IFS-split by shell)
+cpp_define() {
+	case $use_ach in
+	0)
+		add_cppflags "-D$1=$2"
+		;;
+	1)
+		addtoach "#define $1 $2"
+		;;
+	*)
+		echo >&2 "E: cpp_define() called too early!"
+		exit 255
+		;;
+	esac
+}
+
 add_cppflags() {
 	CPPFLAGS="$CPPFLAGS $*"
 }
@@ -392,7 +473,7 @@ ac_cppflags() {
 	test x"$1" = x"" || fu=$1
 	fv=$2
 	test x"$2" = x"" && eval fv=\$HAVE_$fu
-	add_cppflags -DHAVE_$fu=$fv
+	cpp_define HAVE_$fu $fv
 }
 
 ac_test() {
@@ -424,7 +505,7 @@ ac_flags() {
 		ac_testn can_$vn '' "$ft" <<-'EOF'
 			/* evil apo'stroph in comment test */
 			#include <unistd.h>
-			int main(void) { return (isatty(0)); }
+			int main(void) { int t[2]; return (isatty(pipe(t))); }
 		EOF
 		#'
 	fi
@@ -448,14 +529,17 @@ ac_header() {
 	do
 		case $i in
 		_time)
-			echo '#if HAVE_BOTH_TIME_H' >>x
+			echo '#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H' >>x
 			echo '#include <sys/time.h>' >>x
 			echo '#include <time.h>' >>x
-			echo '#elif HAVE_SYS_TIME_H' >>x
+			echo '#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H' >>x
 			echo '#include <sys/time.h>' >>x
 			echo '#elif HAVE_TIME_H' >>x
 			echo '#include <time.h>' >>x
 			echo '#endif' >>x
+			echo '#if HAVE_SYS_SELECT_H' >>x
+			echo '#include <sys/select.h>' >>x
+			echo '#endif' >>x
 			;;
 		*)
 			echo "#include <$i>" >>x
@@ -478,35 +562,62 @@ addsrcs() {
 		fr=1
 	fi
 	eval i=\$$1
-	test $fr = "$i" && case " $SRCS " in
-	*\ $2\ *)	;;
-	*)		SRCS="$SRCS $2" ;;
+	test $fr = "$i" && case "$sp$SRCS$sp" in
+	*"$sp$2$sp"*)	;;
+	*)		SRCS="$SRCS$sp$2" ;;
 	esac
 }
 
+# --- main ---
 
 curdir=`pwd` srcdir=`dirname "$0" 2>/dev/null`
+curdisp=.
+case x$curdir in
+x)
+	curdir=.
+	;;
+*"$sp"*|*"$ht"*|*"$nl"*)
+	echo >&2 Current directory should not contain space or tab or newline.
+	echo >&2 Errors may occur.
+	;;
+*"'"*)
+	echo >&2 Current directory should not contain single quotes.
+	echo >&2 Errors may occur.
+	;;
+*)
+	curdisp=$curdir
+	;;
+esac
 case x$srcdir in
 x)
 	srcdir=.
 	;;
-*\ *|*"	"*|*"$nl"*)
+*"$sp"*|*"$ht"*|*"$nl"*)
 	echo >&2 Source directory should not contain space or tab or newline.
 	echo >&2 Errors may occur.
 	;;
 *"'"*)
-	echo Source directory must not contain single quotes.
+	echo >&2 Source directory must not contain single quotes.
 	exit 1
 	;;
 esac
+srcdisp=`cd "$srcdir" && pwd` || srcdisp=
+test_n "$srcdisp" || srcdisp=$srcdir
+if test x"$srcdisp" = x"$curdir"; then
+	srcdisp=
+else
+	srcdisp=$srcdir/
+fi
 dstversion=`sed -n '/define MKSH_VERSION/s/^.*"\([^"]*\)".*$/\1/p' "$srcdir/sh.h"`
-add_cppflags -DMKSH_BUILDSH
+whatlong='The MirBSD Korn Shell (mksh)'
+whatshort=mksh
 
 e=echo
 r=0
 eq=0
 pm=0
 cm=normal
+Cg=
 optflags=-std-compile-opts
 check_categories=
 last=
@@ -518,7 +629,7 @@ ebcdic=false
 for i
 do
 	case $last:$i in
-	c:dragonegg|c:llvm)
+	c:dragonegg|c:llvm|c:trace)
 		cm=$i
 		last=
 		;;
@@ -530,6 +641,12 @@ do
 		optflags=$i
 		last=
 		;;
+	:-A)
+		rm -f autoconf.h
+		addtoach '/* work around NeXTstep bug */'
+		use_ach=1
+		add_cppflags -DMKSH_USE_AUTOCONF_H
+		;;
 	:-c)
 		last=c
 		;;
@@ -543,7 +660,7 @@ do
 	:-g)
 		# checker, debug, valgrind build
 		add_cppflags -DDEBUG
-		CFLAGS="$CFLAGS -g3 -fno-builtin"
+		Cg=' '
 		;;
 	:-j)
 		pm=1
@@ -577,7 +694,7 @@ do
 		;;
 	:-v)
 		echo "Build.sh $srcversion"
-		echo "for mksh $dstversion"
+		echo "for $whatlong $dstversion"
 		exit 0
 		;;
 	:*)
@@ -604,8 +721,10 @@ if test -d $tfn || test -d $tfn.exe; the
 	echo "$me: Error: ./$tfn is a directory!" >&2
 	exit 1
 fi
-rmf a.exe* a.out* conftest.c conftest.exe* *core core.* ${tfn}* *.bc *.dbg \
-    *.ll *.o *.gen *.cat1 Rebuild.sh lft no signames.inc test.sh x vv.out *.htm
+test x"$use_ach" = x"1" || use_ach=0
+cpp_define MKSH_BUILDSH 1
+rmf a.exe* a.out* conftest.* *core core.* ${tfn}* *.bc *.dbg *.ll *.o *.cat? \
+    *.gen Rebuild.sh Makefrag.inc lft no signames.inc test.sh x vv.out *.htm
 
 SRCS="lalloc.c edit.c eval.c exec.c expr.c funcs.c histrap.c jobs.c"
 SRCS="$SRCS lex.c main.c misc.c shf.c syn.c tree.c var.c"
@@ -614,21 +733,21 @@ if test $legacy = 0; then
 	check_categories="$check_categories shell:legacy-no int:32"
 else
 	check_categories="$check_categories shell:legacy-yes"
-	add_cppflags -DMKSH_LEGACY_MODE
+	cpp_define MKSH_LEGACY_MODE 1
 fi
 
 if $ebcdic; then
-	add_cppflags -DMKSH_EBCDIC
+	cpp_define MKSH_EBCDIC 1
 fi
 
 if test $textmode = 0; then
 	check_categories="$check_categories shell:textmode-no shell:binmode-yes"
 else
 	check_categories="$check_categories shell:textmode-yes shell:binmode-no"
-	add_cppflags -DMKSH_WITH_TEXTMODE
+	cpp_define MKSH_WITH_TEXTMODE 1
 fi
 
-if test x"$srcdir" = x"."; then
+if test_z "$srcdisp"; then
 	CPPFLAGS="-I. $CPPFLAGS"
 else
 	CPPFLAGS="-I. -I'$srcdir' $CPPFLAGS"
@@ -641,17 +760,30 @@ fi
 
 if test_z "$TARGET_OS"; then
 	x=`uname -s 2>/dev/null || uname`
-	test x"$x" = x"`uname -n 2>/dev/null`" || TARGET_OS=$x
+	case $x in
+	scosysv)
+		# SVR4 Unix with uname -s = uname -n, whitelist
+		TARGET_OS=$x
+		;;
+	syllable)
+		# other OS with uname -s = uname = uname -n, whitelist
+		TARGET_OS=$x
+		;;
+	*)
+		test x"$x" = x"`uname -n 2>/dev/null`" || TARGET_OS=$x
+		;;
+	esac
 fi
 if test_z "$TARGET_OS"; then
 	echo "$me: Set TARGET_OS, your uname is broken!" >&2
 	exit 1
 fi
+osnote=
 oswarn=
 ccpc=-Wc,
 ccpl=-Wl,
 tsts=
-ccpr='|| for _f in ${tcfn}*; do case $_f in *.1|*.faq|*.ico) ;; *) rm -f "$_f" ;; esac; done'
+ccpr='|| for _f in ${tcfn}*; do case $_f in lksh.1|mksh.1|mksh.faq|mksh.ico) ;; *) rm -f "$_f" ;; esac; done'
 
 # Evil hack
 if test x"$TARGET_OS" = x"Android"; then
@@ -665,7 +797,7 @@ if test x"$TARGET_OS" = x"Minix"; then
 WARNING: additional checks before running Build.sh required!
 You can avoid these by calling Build.sh correctly, see below.
 "
-	cat >conftest.c <<'EOF'
+	cat_h_blurb >conftest.c <<'EOF'
 #include <sys/types.h>
 const char *
 #ifdef _NETBSD_SOURCE
@@ -676,7 +808,7 @@ ct="Minix3"
 ;
 EOF
 	ct=unknown
-	vv ']' "${CC-cc} -E $CFLAGS $CPPFLAGS $NOWARN conftest.c | grep ct= | tr -d \\\\015 >x"
+	vv ']' "${CC-cc} -E $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c | grep ct= | tr -d \\\\015 >x"
 	sed 's/^/[ /' x
 	eval `cat x`
 	rmf x vv.out
@@ -709,17 +841,31 @@ NEXTSTEP)
 	    grep 'NeXT Mach [0-9][0-9.]*:' | \
 	    sed 's/^.*NeXT Mach \([0-9][0-9.]*\):.*$/\1/'`
 	;;
-QNX|SCO_SV)
+BeOS|HP-UX|QNX|SCO_SV)
 	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 	;;
 esac
 
+# SVR4 (some) workaround
+int_as_ssizet() {
+	cpp_define SSIZE_MIN INT_MIN
+	cpp_define SSIZE_MAX INT_MAX
+	cpp_define ssize_t int
+}
+
+cmplrflgs=
+
 # Configuration depending on OS name
 case $TARGET_OS in
 386BSD)
 	: "${HAVE_CAN_OTWO=0}"
-	add_cppflags -DMKSH_NO_SIGSETJMP
-	add_cppflags -DMKSH_TYPEDEF_SIG_ATOMIC_T=int
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define MKSH_TYPEDEF_SIG_ATOMIC_T int
+	;;
+4.4BSD)
+	osnote='; assuming BOW (BSD on Windows)'
+	check_categories="$check_categories nopiddependent noxperms"
+	check_categories="$check_categories nosymlink noweirdfilenames"
 	;;
 A/UX)
 	add_cppflags -D_POSIX_SOURCE
@@ -730,36 +876,54 @@ A/UX)
 	;;
 AIX)
 	add_cppflags -D_ALL_SOURCE
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 BeOS)
+	: "${CC=gcc}"
+	case $TARGET_OSREV in
+	[012345].*)
+		oswarn="; it has MAJOR issues"
+		test x"$TARGET_OSREV" = x"5.1" || \
+		    cpp_define MKSH_NO_SIGSUSPEND 1
+		;;
+	*)
+		oswarn="; it has minor issues"
+		;;
+	esac
 	case $KSH_VERSION in
 	*MIRBSD\ KSH*)
-		oswarn="; it has minor issues"
 		;;
 	*)
-		oswarn="; you must recompile mksh with"
-		oswarn="$oswarn${nl}itself in a second stage"
+		case $ZSH_VERSION in
+		*[0-9]*)
+			;;
+		*)
+			oswarn="; you must recompile mksh with"
+			oswarn="$oswarn${nl}itself in a second stage"
+			;;
+		esac
 		;;
 	esac
+	: "${MKSH_UNLIMITED=1}"
 	# BeOS has no real tty either
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_DISABLE_TTY_WARNING
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
 	# BeOS doesn't have different UIDs and GIDs
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	;;
 BSD/OS)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Coherent)
 	oswarn="; it has major issues"
-	add_cppflags -DMKSH__NO_SYMLINK
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH__NO_SETEUGID
-	add_cppflags -DMKSH_DISABLE_TTY_WARNING
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
 	;;
 CYGWIN*)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Darwin)
 	add_cppflags -D_DARWIN_C_SOURCE
@@ -771,26 +935,24 @@ FreeBSD)
 FreeMiNT)
 	oswarn="; it has minor issues"
 	add_cppflags -D_GNU_SOURCE
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 GNU)
 	case $CC in
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
-	# define MKSH__NO_PATH_MAX to use Hurd-only functions
-	add_cppflags -DMKSH__NO_PATH_MAX
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	;;
 GNU/kFreeBSD)
 	case $CC in
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	;;
 Haiku)
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
 	;;
@@ -800,42 +962,52 @@ Harvey)
 	add_cppflags -D_BSD_EXTENSION
 	add_cppflags -D_SUSV2_SOURCE
 	add_cppflags -D_GNU_SOURCE
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	oswarn=' and will currently not work'
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_NOPROSPECTOFWORK
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
 	# these taken from Harvey-OS github and need re-checking
-	add_cppflags -D_setjmp=setjmp -D_longjmp=longjmp
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
 	: "${HAVE_CAN_NO_EH_FRAME=0}"
 	: "${HAVE_CAN_FNOSTRICTALIASING=0}"
 	: "${HAVE_CAN_FSTACKPROTECTORSTRONG=0}"
 	;;
 HP-UX)
+	case $TARGET_OSREV in
+	B.09.*)
+		: "${CC=c89}"
+		add_cppflags -D_HPUX_SOURCE
+		cpp_define MBSDINT_H_SMALL_SYSTEM 1
+		;;
+	esac
 	;;
 Interix)
 	ccpc='-X '
 	ccpl='-Y '
 	add_cppflags -D_ALL_SOURCE
 	: "${LIBS=-lcrypt}"
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 IRIX*)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 Jehanne)
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH_DISABLE_REVOKE_WARNING
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH_DISABLE_REVOKE_WARNING 1
 	add_cppflags '-D_PATH_DEFPATH=\"/cmd\"'
 	add_cppflags '-DMKSH_DEFAULT_EXECSHELL=\"/cmd/mksh\"'
 	add_cppflags '-DMKSH_DEFAULT_PROFILEDIR=\"/cfg/mksh\"'
@@ -847,7 +1019,7 @@ Linux)
 	*tendracc*) ;;
 	*) add_cppflags -D_GNU_SOURCE ;;
 	esac
-	add_cppflags -DSETUID_CAN_FAIL_WITH_EAGAIN
+	cpp_define SETUID_CAN_FAIL_WITH_EAGAIN 1
 	: "${HAVE_REVOKE=0}"
 	;;
 LynxOS)
@@ -861,26 +1033,33 @@ midipix)
 MidnightBSD)
 	;;
 Minix-vmd)
-	add_cppflags -DMKSH__NO_SETEUGID
-	add_cppflags -DMKSH_UNEMPLOYED
 	add_cppflags -D_MINIX_SOURCE
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_UNEMPLOYED 1
 	oldish_ed=no-stderr-ed		# no /bin/ed, maybe see below
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Minix3)
-	add_cppflags -DMKSH_UNEMPLOYED
 	add_cppflags -D_POSIX_SOURCE -D_POSIX_1_SOURCE=2 -D_MINIX
+	cpp_define MKSH_UNEMPLOYED 1
 	oldish_ed=no-stderr-ed		# /usr/bin/ed(!) is broken
-	: "${HAVE_SETLOCALE_CTYPE=0}${MKSH_UNLIMITED=1}" #XXX recheck ulimit
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	: "${MKSH_UNLIMITED=1}"		#XXX recheck ulimit
+	;;
+Minoca)
+	: "${CC=gcc}"
 	;;
 MirBSD)
+	# for testing HAVE_SIGACTION=0 builds only (but fulfills the contract)
+	cpp_define MKSH_USABLE_SIGNALFUNC bsd_signal
 	;;
 MSYS_*)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
 	# almost same as CYGWIN* (from RT|Chatzilla)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	# broken on this OE (from ir0nh34d)
 	: "${HAVE_STDINT_H=0}"
 	;;
@@ -890,10 +1069,10 @@ NEXTSTEP)
 	add_cppflags -D_NEXT_SOURCE
 	add_cppflags -D_POSIX_SOURCE
 	: "${AWK=gawk}"
-	: "${CC=cc -posix}"
-	add_cppflags -DMKSH_NO_SIGSETJMP
+	: "${CC=cc -posix -traditional-cpp}"
+	cpp_define MKSH_NO_SIGSETJMP 1
 	# NeXTstep cannot get a controlling tty
-	add_cppflags -DMKSH_UNEMPLOYED
+	cpp_define MKSH_UNEMPLOYED 1
 	case $TARGET_OSREV in
 	4.2*)
 		# OpenStep 4.2 is broken by default
@@ -903,27 +1082,28 @@ NEXTSTEP)
 	;;
 Ninix3)
 	# similar to Minix3
-	add_cppflags -DMKSH_UNEMPLOYED
-	: "${MKSH_UNLIMITED=1}" #XXX recheck ulimit
+	cpp_define MKSH_UNEMPLOYED 1
+	: "${MKSH_UNLIMITED=1}"		#XXX recheck ulimit
 	# but no idea what else could be needed
 	oswarn="; it has unknown issues"
 	;;
 OpenBSD)
-	: "${HAVE_SETLOCALE_CTYPE=0}"
 	;;
 OS/2)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	# cf. https://github.com/komh/pdksh-os2/commit/590f2b19b0ff92a9a373295bce914654f9f5bf22
 	HAVE_TERMIOS_H=0
 	HAVE_MKNOD=0	# setmode() incompatible
 	check_categories="$check_categories nosymlink"
 	: "${CC=gcc}"
 	: "${SIZE=: size}"
 	SRCS="$SRCS os2.c"
-	add_cppflags -DMKSH_UNEMPLOYED
-	add_cppflags -DMKSH_NOPROSPECTOFWORK
-	add_cppflags -DMKSH_DOSPATH
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
+	cpp_define MKSH_DOSPATH 1
 	: "${MKSH_UNLIMITED=1}"
 	if test $textmode = 0; then
 		x='dis'
@@ -948,13 +1128,15 @@ the mksh-os2 porter.
 "
 	;;
 OS/390)
-	add_cppflags -DMKSH_ASSUME_UTF8=0
+	cpp_define MKSH_ASSUME_UTF8 0
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	: "${CC=xlc}"
 	: "${SIZE=: size}"
-	add_cppflags -DMKSH_FOR_Z_OS
+	cpp_define MKSH_FOR_Z_OS 1
 	add_cppflags -D_ALL_SOURCE
+	$ebcdic || add_cppflags -D_ENHANCED_ASCII_EXT=0xFFFFFFFF
 	oswarn='; EBCDIC support is incomplete'
 	;;
 OSF1)
@@ -963,29 +1145,31 @@ OSF1)
 	add_cppflags -D_POSIX_C_SOURCE=200112L
 	add_cppflags -D_XOPEN_SOURCE=600
 	add_cppflags -D_XOPEN_SOURCE_EXTENDED
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 Plan9)
 	add_cppflags -D_POSIX_SOURCE
 	add_cppflags -D_LIMITS_EXTENSION
 	add_cppflags -D_BSD_EXTENSION
 	add_cppflags -D_SUSV2_SOURCE
-	add_cppflags -DMKSH_ASSUME_UTF8
+	cpp_define MKSH_ASSUME_UTF8 1
 	HAVE_ISSET_MKSH_ASSUME_UTF8=1
 	HAVE_ISOFF_MKSH_ASSUME_UTF8=0
-	add_cppflags -DMKSH__NO_SYMLINK
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	cpp_define MKSH__NO_SYMLINK 1
 	check_categories="$check_categories nosymlink"
-	add_cppflags -DMKSH_NO_CMDLINE_EDITING
-	add_cppflags -DMKSH__NO_SETEUGID
+	cpp_define MKSH_NO_CMDLINE_EDITING 1
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
 	oswarn=' and will currently not work'
-	add_cppflags -DMKSH_UNEMPLOYED
+	cpp_define MKSH_UNEMPLOYED 1
 	# this is for detecting kencc
-	add_cppflags -DMKSH_MAYBE_KENCC
+	cmplrflgs=-DMKSH_MAYBE_KENCC
 	;;
 PW32*)
 	HAVE_SIG_T=0	# incompatible
 	oswarn=' and will currently not work'
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 QNX)
 	add_cppflags -D__NO_EXT_QNX
@@ -995,13 +1179,21 @@ QNX)
 		oldish_ed=no-stderr-ed		# oldish /bin/ed is broken
 		;;
 	esac
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	;;
+scosysv)
+	cmplrflgs=-DMKSH_MAYBE_QUICK_C
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	int_as_ssizet
+	cpp_define MKSH_UNEMPLOYED 1
+	: "${HAVE_POSIX_UTF8_LOCALE=0}${HAVE_TERMIOS_H=0}"
 	;;
 SCO_SV)
 	case $TARGET_OSREV in
 	3.2*)
 		# SCO OpenServer 5
-		add_cppflags -DMKSH_UNEMPLOYED
+		cpp_define MKSH_UNEMPLOYED 1
 		;;
 	5*)
 		# SCO OpenServer 6
@@ -1013,6 +1205,16 @@ SCO_SV)
 	esac
 	: "${HAVE_SYS_SIGLIST=0}${HAVE__SYS_SIGLIST=0}"
 	;;
+SerenityOS)
+	oswarn="; it has issues"
+	: "${MKSH_UNLIMITED=1}${HAVE_GETRUSAGE=0}"
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_DISABLE_TTY_WARNING 1
+	;;
+SINIX-Z)
+	: "${CC=cc -Xa}"
+	cmplrflgs=-DMKSH_MAYBE_SCDE
+	;;
 skyos)
 	oswarn="; it has minor issues"
 	;;
@@ -1022,13 +1224,13 @@ SunOS)
 	;;
 syllable)
 	add_cppflags -D_GNU_SOURCE
-	add_cppflags -DMKSH_NO_SIGSUSPEND
-	oswarn=' and will currently not work'
+	cpp_define MKSH_NO_SIGSUSPEND 1
+	: "${MKSH_UNLIMITED=1}"
 	;;
 ULTRIX)
 	: "${CC=cc -YPOSIX}"
-	add_cppflags -DMKSH_TYPEDEF_SSIZE_T=int
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	int_as_ssizet
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
 	;;
 UnixWare|UNIX_SV)
 	# SCO UnixWare
@@ -1040,21 +1242,41 @@ UWIN*)
 	tsts=" 3<>/dev/tty"
 	oswarn="; it will compile, but the target"
 	oswarn="$oswarn${nl}platform itself is very flakey/unreliable"
-	: "${HAVE_SETLOCALE_CTYPE=0}"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	;;
+XENIX)
+	# mostly when crosscompiling from scosysv
+	cmplrflgs=-DMKSH_MAYBE_QUICK_C
+	# this can barely do anything
+	cpp_define MKSH__NO_SETEUGID 1
+	: "${HAVE_SETRESUGID=0}"
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
+	cpp_define USE_REALLOC_MALLOC 0
+	int_as_ssizet
+	# per http://www.polarhome.com/service/man/?qf=signal&of=Xenix
+	cpp_define MKSH_USABLE_SIGNALFUNC signal
+	cpp_define MKSH_UNEMPLOYED 1
+	cpp_define MKSH_NOPROSPECTOFWORK 1
+	cpp_define MKSH__NO_SYMLINK 1
+	check_categories="$check_categories nosymlink"
+	: "${HAVE_POSIX_UTF8_LOCALE=0}"
+	# these are broken
+	HAVE_TERMIOS_H=0
 	;;
 _svr4)
 	# generic target for SVR4 Unix with uname -s = uname -n
-	# this duplicates the * target below
 	oswarn='; it may or may not work'
-	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
+	: "${CC=cc -Xa}"
+	cmplrflgs=-DMKSH_MAYBE_SCDE
+	int_as_ssizet #XXX maybe not for *all* _svr4? here for Dell UNIX
 	;;
 *)
 	oswarn='; it may or may not work'
-	test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 	;;
 esac
-
-: "${HAVE_MKNOD=0}"
+test_n "$TARGET_OSREV" || TARGET_OSREV=`uname -r`
 
 : "${AWK=awk}${CC=cc}${NROFF=nroff}${SIZE=size}"
 test 0 = $r && echo | $NROFF -v 2>&1 | grep GNU >/dev/null 2>&1 && \
@@ -1085,7 +1307,7 @@ OSF1)
 	vv '|' "uname -a >&2"
 	vv '|' "/usr/sbin/sizer -v >&2"
 	;;
-SCO_SV|UnixWare|UNIX_SV)
+scosysv|SCO_SV|UnixWare|UNIX_SV|XENIX)
 	vv '|' "uname -a >&2"
 	vv '|' "uname -X >&2"
 	;;
@@ -1094,13 +1316,18 @@ SCO_SV|UnixWare|UNIX_SV)
 	;;
 esac
 test_z "$oswarn" || echo >&2 "
-Warning: mksh has not yet been ported to or tested on your
-operating system '$TARGET_OS'$oswarn. If you can provide
-a shell account to the developer, this may improve; please
-drop us a success or failure notice or even send in diffs,
-at the very least, complete logs (Build.sh + test.sh) will help.
+Warning: $whatshort has not yet been ported to or tested on your
+operating system '$TARGET_OS'$oswarn."
+test_z "$osnote" || echo >&2 "
+Note: $whatshort is not fully ported to or tested yet on your
+operating system '$TARGET_OS'$osnote."
+test_z "$osnote$oswarn" || echo >&2 "
+If you can provide a shell account to the developer, this
+may improve; please drop us a success or failure notice or
+even send patches for the remaining issues, or, at the very
+least, complete logs (Build.sh + test.sh) will help.
 "
-$e "$bi$me: Building the MirBSD Korn Shell$ao $ui$dstversion$ao on $TARGET_OS ${TARGET_OSREV}..."
+$e "$bi$me: Building $whatlong$ao $ui$dstversion$ao on $TARGET_OS ${TARGET_OSREV}..."
 
 #
 # Start of mirtoconf checks
@@ -1117,7 +1344,7 @@ $e $bi$me: Scanning for functions... ple
 # - nwcc defines __GNUC__ too
 CPP="$CC -E"
 $e ... which compiler type seems to be used
-cat >conftest.c <<'EOF'
+cat_h_blurb >conftest.c <<'EOF'
 const char *
 #if defined(__ICC) || defined(__INTEL_COMPILER)
 ct="icc"
@@ -1163,6 +1390,8 @@ ct="tcc"
 ct="clang"
 #elif defined(__NWCC__)
 ct="nwcc"
+#elif defined(__GNUC__) && (__GNUC__ < 2)
+ct="gcc1"
 #elif defined(__GNUC__)
 ct="gcc"
 #elif defined(_COMPILER_VERSION)
@@ -1177,9 +1406,13 @@ ct="ucode"
 ct="uslc"
 #elif defined(__LCC__)
 ct="lcc"
+#elif defined(MKSH_MAYBE_QUICK_C) && defined(_M_BITFIELDS)
+ct="quickc"
 #elif defined(MKSH_MAYBE_KENCC)
 /* and none of the above matches */
 ct="kencc"
+#elif defined(MKSH_MAYBE_SCDE)
+ct="tryscde"
 #else
 ct="unknown"
 #endif
@@ -1187,6 +1420,8 @@ ct="unknown"
 const char *
 #if defined(__KLIBC__) && !defined(__OS2__)
 et="klibc"
+#elif defined(__dietlibc__)
+et="dietlibc"
 #else
 et="unknown"
 #endif
@@ -1194,24 +1429,43 @@ et="unknown"
 EOF
 ct=untested
 et=untested
-vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c | \
+vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN $cmplrflgs conftest.c | \
     sed -n '/^ *[ce]t *= */s/^ *\([ce]t\) *= */\1=/p' | tr -d \\\\015 >x"
 sed 's/^/[ /' x
 eval `cat x`
 rmf x vv.out
-cat >conftest.c <<'EOF'
+cat_h_blurb >conftest.c <<'EOF'
 #include <unistd.h>
 int main(void) { return (isatty(0)); }
 EOF
+test_z "$Cg" || Cg=-g  # generic
+case $ct:$TARGET_OS in
+tryscde:*)
+	case `LC_ALL=C; export LC_ALL; $CC -V 2>&1` in
+	*'Standard C Development Environment'*)
+		ct=scde ;;
+	*)
+		ct=unknown ;;
+	esac
+	;;
+gcc:_svr4)
+	# weirdly needed to find NSIG
+	case $CC$CPPFLAGS in
+	*STDC*) ;;
+	*) CC="$CC -U__STDC__ -D__STDC__=0" ;;
+	esac
+	;;
+esac
 case $ct in
 ack)
 	# work around "the famous ACK const bug"
 	CPPFLAGS="-Dconst= $CPPFLAGS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 adsp)
 	echo >&2 'Warning: Analog Devices C++ compiler for Blackfin, TigerSHARC
     and SHARC (21000) DSPs detected. This compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 bcc)
@@ -1221,10 +1475,9 @@ bcc)
 	;;
 clang)
 	# does not work with current "ccc" compiler driver
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS --version"
 	# one of these two works, for now
 	vv '|' "${CLANG-clang} -version"
-	vv '|' "${CLANG-clang} --version"
 	# ensure compiler and linker are in sync unless overridden
 	case $CCC_CC:$CCC_LD in
 	:*)	;;
@@ -1233,8 +1486,9 @@ clang)
 	: "${HAVE_STRING_POOLING=i1}"
 	;;
 dec)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 dmc)
 	echo >&2 "Warning: Digital Mars Compiler detected. When running under"
@@ -1242,41 +1496,58 @@ dmc)
 	echo >&2 "    of this platform. Continue at your own risk,"
 	echo >&2 "    please report success/failure to the developers."
 	;;
+gcc1)
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' 'eval echo "\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
+		 "gcc\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}" # false positive
+	;;
 gcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	vv '|' 'eval echo "\`$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
-		 "gcc\`$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
+	test_z "$Cg" || Cg='-g3 -fno-builtin'
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' 'eval echo "\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpmachine\`" \
+		 "gcc\`$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -dumpversion\`"'
 	: "${HAVE_STRING_POOLING=i2}"
 	;;
 hpcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	case $TARGET_OS,$TARGET_OSREV in
+	HP-UX,B.09.*)
+		: "${HAVE_ATTRIBUTE_EXTENSION=0}"
+		;;
+	esac
 	;;
 iar)
 	echo >&2 'Warning: IAR Systems (http://www.iar.com) compiler for embedded
     systems detected. This unsupported compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 icc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
 	;;
 kencc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 lacc)
 	# no version information
 	;;
 lcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	add_cppflags -D__inline__=__inline
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	cpp_define __inline__ __inline
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 metrowerks)
 	echo >&2 'Warning: Metrowerks C compiler detected. This has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 mipspro)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	test_z "$Cg" || Cg='-g3'
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	: "${HAVE_STDINT_H=0}" # broken unless building with __c99
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 msc)
 	ccpr=		# errorlevels are not reliable
@@ -1298,41 +1569,51 @@ msc)
 	esac
 	;;
 neatcc)
-	add_cppflags -DMKSH_DONT_EMIT_IDSTRING
-	add_cppflags -DMKSH_NO_SIGSETJMP
-	add_cppflags -Dsig_atomic_t=int
+	cpp_define MKSH_DONT_EMIT_IDSTRING 1
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define sig_atomic_t int
 	vv '|' "$CC"
 	;;
 nwcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -version"
 	;;
 pcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
 	;;
 pgi)
 	echo >&2 'Warning: PGI detected. This unknown compiler has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
+quickc)
+	# no version information
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
+	;;
+scde)
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
+	;;
 sdcc)
 	echo >&2 'Warning: sdcc (http://sdcc.sourceforge.net), the small devices
     C compiler for embedded systems detected. This has not yet
-    been tested for compatibility with mksh. Continue at your
+    been tested for compatibility with this. Continue at your
     own risk, please report success/failure to the developers.'
 	;;
 sunpro)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
 	;;
 tcc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -v"
 	;;
 tendra)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V 2>&1 | \
-	    grep -F -i -e version -e release"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V 2>&1 | \
+	    grep -i -e version -e release"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}" # false positive
 	;;
 ucode)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -V"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -Wl,-V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 uslc)
 	case $TARGET_OS:$TARGET_OSREV in
@@ -1342,32 +1623,52 @@ uslc)
 		: "${HAVE_CAN_OTWO=0}${HAVE_CAN_OPTIMISE=0}"
 		;;
 	esac
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	: "${HAVE_ATTRIBUTE_EXTENSION=0}"  # skip checking as we know it absent
 	;;
 watcom)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
 	;;
 xlc)
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion=verbose"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN $LIBS -qversion=verbose"
 	vv '|' "ld -V"
 	;;
 *)
 	test x"$ct" = x"untested" && $e "!!! detecting preprocessor failed"
 	ct=unknown
 	vv '|' "$CC --version"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
-	vv '|' "$CC $CFLAGS $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -v conftest.c $LIBS"
+	vv '|' "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $NOWARN -V conftest.c $LIBS"
 	;;
 esac
 case $cm in
 dragonegg|llvm)
 	vv '|' "llc -version"
 	;;
+trace)
+	case $ct in
+	gcc) ;;
+	*)
+		echo >&2 "E: -c trace does not work with $cm"
+		exit 1
+		;;
+	esac
+	;;
 esac
 etd=" on $et"
+# still imake style but… can’t be helped
 case $et in
+dietlibc)
+	# live, BSD, live❣
+	add_cppflags -D_BSD_SOURCE
+	# broken
+	HAVE_POSIX_UTF8_LOCALE=0
+	;;
 klibc)
+	cpp_define MKSH_NO_SIGSETJMP 1
+	cpp_define _setjmp setjmp
+	cpp_define _longjmp longjmp
 	: "${MKSH_UNLIMITED=1}"
 	;;
 unknown)
@@ -1453,6 +1754,10 @@ msc)
 	save_NOWARN="${ccpc}/w"
 	DOWARN="${ccpc}/WX"
 	;;
+quickc)
+	;;
+scde)
+	;;
 sunpro)
 	test x"$save_NOWARN" = x"" && save_NOWARN='-errwarn=%none'
 	ac_flags 0 errwarnnone "$save_NOWARN"
@@ -1505,7 +1810,7 @@ hpcc)
 	ac_flags 1 otwo +O2
 	phase=x
 	;;
-kencc|tcc|tendra)
+kencc|quickc|scde|tcc|tendra)
 	# no special optimisation
 	;;
 sunpro)
@@ -1525,7 +1830,16 @@ xlc)
 	test 1 = $HAVE_CAN_OTHREE || ac_flags 1 otwo -O2
 	;;
 *)
-	ac_flags 1 otwo -O2
+	if test_n "$Cg"; then
+		ac_flags 1 ogee -Og
+		if test 1 = $HAVE_CAN_OGEE; then
+			HAVE_CAN_OTWO=1 # for below
+		else
+			ac_flags 1 otwo -O2
+		fi
+	else
+		ac_flags 1 otwo -O2
+	fi
 	test 1 = $HAVE_CAN_OTWO || ac_flags 1 optimise -O
 	;;
 esac
@@ -1546,18 +1860,28 @@ dmc)
 	ac_flags 1 decl "${ccpc}-r" 'for strict prototype checks'
 	ac_flags 1 schk "${ccpc}-s" 'for stack overflow checking'
 	;;
+gcc1)
+	# The following tests run with -Werror (gcc only) if possible
+	NOWARN=$DOWARN; phase=u
+	ac_flags 1 wnodeprecateddecls -Wno-deprecated-declarations
+	# we do not even use CFrustFrust in MirBSD so don’t code in it…
+	ac_flags 1 no_eh_frame -fno-asynchronous-unwind-tables
+	ac_flags 1 fnostrictaliasing -fno-strict-aliasing
+	ac_flags 1 data_abi_align -malign-data=abi
+	i=1
+	;;
 gcc)
 	ac_flags 1 fnolto -fno-lto 'whether we can explicitly disable buggy GCC LTO' -fno-lto
 	# The following tests run with -Werror (gcc only) if possible
 	NOWARN=$DOWARN; phase=u
 	ac_flags 1 wnodeprecateddecls -Wno-deprecated-declarations
-	# mksh is not written in CFrustFrust!
+	# we do not even use CFrustFrust in MirBSD so don’t code in it…
 	ac_flags 1 no_eh_frame -fno-asynchronous-unwind-tables
 	ac_flags 1 fnostrictaliasing -fno-strict-aliasing
 	ac_flags 1 fstackprotectorstrong -fstack-protector-strong
 	test 1 = $HAVE_CAN_FSTACKPROTECTORSTRONG || \
 	    ac_flags 1 fstackprotectorall -fstack-protector-all
-	test $cm = dragonegg && case " $CC $CFLAGS $LDFLAGS " in
+	test $cm = dragonegg && case " $CC $CFLAGS $Cg $LDFLAGS " in
 	*\ -fplugin=*dragonegg*) ;;
 	*) ac_flags 1 fplugin_dragonegg -fplugin=dragonegg ;;
 	esac
@@ -1618,6 +1942,9 @@ icc)
 	;;
 mipspro)
 	ac_flags 1 fullwarn -fullwarn 'for remark output support'
+	# unreachable-from-prevline loop, unused variable, enum vs int @exec.c
+	# unused parameter, conversion pointer/same-sized integer
+	ac_flags 1 diagsupp '-diag_suppress 1127,1174,1185,3201,3970' 'to quieten MIPSpro down'
 	;;
 msc)
 	ac_flags 1 strpool "${ccpc}/GF" 'if string pooling can be enabled'
@@ -1680,7 +2007,7 @@ if test 1 = $i; then
 fi
 
 # “on demand” means: GCC version >= 4
-fd='if to rely on compiler for string pooling'
+fd='whether to rely on compiler for string pooling'
 ac_cache string_pooling || case $HAVE_STRING_POOLING in
 2) fx=' (on demand, cached)' ;;
 i1) fv=1 ;;
@@ -1697,12 +2024,8 @@ test $ct = pcc && phase=u
 #
 # Compiler: check for stuff that only generates warnings
 #
-ac_test attribute_bounded '' 'for __attribute__((__bounded__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+: "${HAVE_ATTRIBUTE_EXTENSION=1}" # not a separate test but a dependency
+ac_test attribute_bounded attribute_extension 0 'for __attribute__((__bounded__))' <<-'EOF'
 	#include <string.h>
 	#undef __attribute__
 	int xcopy(const void *, void *, size_t)
@@ -1716,14 +2039,8 @@ ac_test attribute_bounded '' 'for __attr
 		 */
 		memmove(d, s, n); return ((int)n);
 	}
-	#endif
 EOF
-ac_test attribute_format '' 'for __attribute__((__format__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_format attribute_extension 0 'for __attribute__((__format__))' <<-'EOF'
 	#define fprintf printfoo
 	#include <stdio.h>
 	#undef __attribute__
@@ -1731,57 +2048,25 @@ ac_test attribute_format '' 'for __attri
 	extern int fprintf(FILE *, const char *format, ...)
 	    __attribute__((__format__(__printf__, 2, 3)));
 	int main(int ac, char *av[]) { return (fprintf(stderr, "%s%d", *av, ac)); }
-	#endif
 EOF
-ac_test attribute_noreturn '' 'for __attribute__((__noreturn__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_noreturn attribute_extension 0 'for __attribute__((__noreturn__))' <<-'EOF'
 	#include <stdlib.h>
 	#undef __attribute__
 	void fnord(void) __attribute__((__noreturn__));
 	int main(void) { fnord(); }
 	void fnord(void) { exit(0); }
-	#endif
-EOF
-ac_test attribute_pure '' 'for __attribute__((__pure__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
-	#include <unistd.h>
-	#undef __attribute__
-	int foo(const char *) __attribute__((__pure__));
-	int main(int ac, char *av[]) { return (foo(av[ac - 1]) + isatty(0)); }
-	int foo(const char *s) { return ((int)s[0]); }
-	#endif
 EOF
-ac_test attribute_unused '' 'for __attribute__((__unused__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_unused attribute_extension 0 'for __attribute__((__unused__))' <<-'EOF'
 	#include <unistd.h>
 	#undef __attribute__
 	int main(int ac __attribute__((__unused__)), char *av[]
 	    __attribute__((__unused__))) { return (isatty(0)); }
-	#endif
 EOF
-ac_test attribute_used '' 'for __attribute__((__used__))' <<-'EOF'
-	#if defined(__TenDRA__) || (defined(__GNUC__) && (__GNUC__ < 2))
-	extern int thiswillneverbedefinedIhope(void);
-	/* force a failure: TenDRA and gcc 1.42 have false positive here */
-	int main(void) { return (thiswillneverbedefinedIhope()); }
-	#else
+ac_test attribute_used attribute_extension 0 'for __attribute__((__used__))' <<-'EOF'
 	#include <unistd.h>
 	#undef __attribute__
 	static const char fnord[] __attribute__((__used__)) = "42";
 	int main(void) { return (isatty(0)); }
-	#endif
 EOF
 
 # End of tests run with -Werror
@@ -1807,7 +2092,7 @@ ac_ifcpp 'ifdef MKSH_NOPROSPECTOFWORK' i
     "if mksh will be built without job signals" && \
     check_categories="$check_categories arge nojsig"
 ac_ifcpp 'ifdef MKSH_ASSUME_UTF8' isset_MKSH_ASSUME_UTF8 '' \
-    'if the default UTF-8 mode is specified' && : "${HAVE_SETLOCALE_CTYPE=0}"
+    'if the default UTF-8 mode is specified' && : "${HAVE_POSIX_UTF8_LOCALE=0}"
 ac_ifcpp 'if !MKSH_ASSUME_UTF8' isoff_MKSH_ASSUME_UTF8 \
     isset_MKSH_ASSUME_UTF8 0 \
     'if the default UTF-8 mode is disabled' && \
@@ -1833,15 +2118,24 @@ ac_test both_time_h '' 'whether <sys/tim
 	#include <sys/time.h>
 	#include <time.h>
 	#include <unistd.h>
-	int main(void) { struct tm tm; return ((int)sizeof(tm) + isatty(0)); }
+	int main(void) { struct timeval tv; return ((int)sizeof(tv) + isatty(0)); }
+EOF
+ac_header sys/select.h sys/types.h
+test "11" = "$HAVE_SYS_TIME_H$HAVE_SYS_SELECT_H" || HAVE_SELECT_TIME_H=1
+ac_test select_time_h '' 'whether <sys/time.h> and <sys/select.h> can both be included' <<-'EOF'
+	#include <sys/types.h>
+	#include <sys/time.h>
+	#include <sys/select.h>
+	#include <unistd.h>
+	int main(void) { struct timeval tv; return ((int)sizeof(tv) + isatty(0)); }
 EOF
 ac_header sys/bsdtypes.h
 ac_header sys/file.h sys/types.h
 ac_header sys/mkdev.h sys/types.h
 ac_header sys/mman.h sys/types.h
 ac_header sys/param.h
+ac_header sys/ptem.h sys/types.h sys/stream.h
 ac_header sys/resource.h sys/types.h _time
-ac_header sys/select.h sys/types.h
 ac_header sys/sysmacros.h
 ac_header bstring.h
 ac_header grp.h sys/types.h
@@ -1854,18 +2148,16 @@ ac_header stdint.h stdarg.h
 ac_header strings.h sys/types.h string.h
 ac_header termios.h
 ac_header ulimit.h sys/types.h
-ac_header values.h
 
 #
 # Environment: definitions
 #
 echo '#include <sys/types.h>
 #include <unistd.h>
-/* check that off_t can represent 2^63-1 correctly, thx FSF */
-#define LARGE_OFF_T ((((off_t)1 << 31) << 31) - 1 + (((off_t)1 << 31) << 31))
-int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 &&
-    LARGE_OFF_T % 2147483647 == 1) ? 1 : -1];
-int main(void) { return (isatty(0)); }' >lft.c
+struct ctassert_offt {
+	off_t min63bits:63;
+};
+int main(void) { return ((int)sizeof(struct ctassert_offt)); }' >lft.c
 ac_testn can_lfs '' "for large file support" <lft.c
 save_CPPFLAGS=$CPPFLAGS
 add_cppflags -D_FILE_OFFSET_BITS=64
@@ -1882,25 +2174,35 @@ rmf lft*	# end of large file support tes
 #
 # Environment: types
 #
-ac_test can_inttypes '!' stdint_h 1 "for standard 32-bit integer types" <<-'EOF'
-	#include <sys/types.h>
-	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((uint32_t)(size_t)*av + (int32_t)ac); }
-EOF
-ac_test can_ucbints '!' can_inttypes 1 "for UCB 32-bit integer types" <<-'EOF'
-	#include <sys/types.h>
-	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((u_int32_t)(size_t)*av + (int32_t)ac); }
-EOF
-ac_test can_int8type '!' stdint_h 1 "for standard 8-bit integer type" <<-'EOF'
+HAVE_MBI_CTAS=x
+ac_testn mbi_ctas '' 'if integer types are sane enough' <<-'EOF'
 	#include <sys/types.h>
+	#if HAVE_STDINT_H
+	#include <stdarg.h>
+	#include <stdint.h>
+	#endif
+	#include <limits.h>
 	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((uint8_t)(size_t)av[ac]); }
+	#undef MBSDINT_H_SKIP_CTAS
+	#include "mbsdcc.h"
+	#include "mbsdint.h"
+	#include <unistd.h>
+	int main(void) { return (isatty(0)); }
 EOF
-ac_test can_ucbint8 '!' can_int8type 1 "for UCB 8-bit integer type" <<-'EOF'
+test 1 = $HAVE_MBI_CTAS || exit 1
+
+ac_test can_inttypes '' "for standard 32-bit integer types" <<-'EOF'
 	#include <sys/types.h>
+	#include <limits.h>
 	#include <stddef.h>
-	int main(int ac, char *av[]) { return ((u_int8_t)(size_t)av[ac]); }
+	#if HAVE_STDINT_H
+	#include <stdarg.h>
+	#include <stdint.h>
+	#endif
+	int main(int ac, char *av[]) {
+		return ((int)((uint32_t)(size_t)*av +
+		    ((int32_t)ac - INT32_MAX)));
+	}
 EOF
 
 # only testn: added later below
@@ -1920,7 +2222,7 @@ ac_testn sighandler_t '!' sig_t 0 <<-'EO
 	int main(void) { return (foo == (sighandler_t)0); }
 EOF
 if test 1 = $HAVE_SIGHANDLER_T; then
-	add_cppflags -Dsig_t=sighandler_t
+	cpp_define sig_t sighandler_t
 	HAVE_SIG_T=1
 fi
 
@@ -1932,11 +2234,11 @@ ac_testn __sighandler_t '!' sig_t 0 <<-'
 	int main(void) { return (foo == (__sighandler_t)0); }
 EOF
 if test 1 = $HAVE___SIGHANDLER_T; then
-	add_cppflags -Dsig_t=__sighandler_t
+	cpp_define sig_t __sighandler_t
 	HAVE_SIG_T=1
 fi
 
-test 1 = $HAVE_SIG_T || add_cppflags -Dsig_t=nosig_t
+test 1 = $HAVE_SIG_T || cpp_define sig_t nosig_t
 ac_cppflags SIG_T
 
 #
@@ -1946,13 +2248,17 @@ if test $cm = makefile; then
 	: nothing to check
 else
 	HAVE_LINK_WORKS=x
-	ac_testinit link_works '' 'checking if the final link command may succeed'
+	ac_testinit link_works '' 'if the final link command may succeed'
 	fv=1
 	cat >conftest.c <<-EOF
 		#define EXTERN
 		#define MKSH_INCLUDES_ONLY
+		#define MKSH_DO_MBI_CTAS
 		#include "sh.h"
 		__RCSID("$srcversion");
+		__IDSTRING(mbsdcc_h_rcsid, SYSKERN_MBSDCC_H);
+		__IDSTRING(mbsdint_h_rcsid, SYSKERN_MBSDINT_H);
+		__IDSTRING(sh_h_rcsid, MKSH_SH_H_ID);
 		int main(void) {
 			struct timeval tv;
 			printf("Hello, World!\\n");
@@ -1961,27 +2267,33 @@ else
 EOF
 	case $cm in
 	llvm)
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -emit-llvm -c conftest.c" || fv=0
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -emit-llvm -c conftest.c" || fv=0
 		rmf $tfn.s
 		test $fv = 0 || v "llvm-link -o - conftest.o | opt $optflags | llc -o $tfn.s" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
 		;;
 	dragonegg)
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -S -flto conftest.c" || fv=0
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -S -flto conftest.c" || fv=0
 		test $fv = 0 || v "mv conftest.s conftest.ll"
 		test $fv = 0 || v "llvm-as conftest.ll" || fv=0
 		rmf $tfn.s
 		test $fv = 0 || v "llvm-link -o - conftest.bc | opt $optflags | llc -o $tfn.s" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $tfn.s $LIBS $ccpr"
 		;;
 	combine)
-		v "$CC $CFLAGS $CPPFLAGS $LDFLAGS -fwhole-program --combine $NOWARN -o $tcfn conftest.c $LIBS $ccpr"
+		v "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS -fwhole-program --combine $NOWARN -o $tcfn conftest.c $LIBS $ccpr"
 		;;
 	lto|normal)
 		cm=normal
-		v "$CC $CFLAGS $CPPFLAGS $NOWARN -c conftest.c" || fv=0
-		test $fv = 0 || v "$CC $CFLAGS $LDFLAGS -o $tcfn conftest.o $LIBS $ccpr"
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -c conftest.c" || fv=0
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn conftest.o $LIBS $ccpr"
 		;;
+	trace)
+		rm -f conftest.d conftest.o
+		v "$CC $CFLAGS $Cg $CPPFLAGS $NOWARN -MD -c conftest.c" || fv=0
+		test -f conftest.d && test -s conftest.d || fv=0
+		test -f conftest.o && test -s conftest.o || fv=0
+		test $fv = 0 || v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn conftest.o $LIBS -Wl,-t,-t $ccpr"
 	esac
 	test -f $tcfn || fv=0
 	ac_testdone
@@ -1991,43 +2303,65 @@ fi
 #
 # Environment: errors and signals
 #
-test x"NetBSD" = x"$TARGET_OS" && $e Ignore the compatibility warning.
 
-ac_testn sys_errlist '' "the sys_errlist[] array and sys_nerr" <<-'EOF'
+HAVE_SOME_ERRLIST=0
+
+ac_test strerrordesc_np '!' some_errlist 0 "GNU strerrordesc_np()" <<-'EOF'
+	extern const char *strerrordesc_np(int);
+	int main(int ac, char *av[]) { return (*strerrordesc_np(*av[ac])); }
+EOF
+test 1 = "$HAVE_STRERRORDESC_NP" && HAVE_SOME_ERRLIST=1
+
+ac_testn sys_errlist '!' some_errlist 0 "the sys_errlist[] array and sys_nerr" <<-'EOF'
 	extern const int sys_nerr;
 	extern const char * const sys_errlist[];
 	extern int isatty(int);
 	int main(void) { return (*sys_errlist[sys_nerr - 1] + isatty(0)); }
 EOF
-ac_testn _sys_errlist '!' sys_errlist 0 "the _sys_errlist[] array and _sys_nerr" <<-'EOF'
+test 1 = "$HAVE_SYS_ERRLIST" && HAVE_SOME_ERRLIST=1
+
+ac_testn _sys_errlist '!' some_errlist 0 "the _sys_errlist[] array and _sys_nerr" <<-'EOF'
 	extern const int _sys_nerr;
 	extern const char * const _sys_errlist[];
 	extern int isatty(int);
 	int main(void) { return (*_sys_errlist[_sys_nerr - 1] + isatty(0)); }
 EOF
 if test 1 = "$HAVE__SYS_ERRLIST"; then
-	add_cppflags -Dsys_nerr=_sys_nerr
-	add_cppflags -Dsys_errlist=_sys_errlist
+	cpp_define sys_nerr _sys_nerr
+	cpp_define sys_errlist _sys_errlist
 	HAVE_SYS_ERRLIST=1
+	HAVE_SOME_ERRLIST=1
 fi
+
 ac_cppflags SYS_ERRLIST
 
 for what in name list; do
 	uwhat=`upper $what`
-	ac_testn sys_sig$what '' "the sys_sig$what[] array" <<-EOF
+	eval HAVE_SOME_SIG$uwhat=0
+
+	case $what in name) x=sigabbrev_np ;; list) x=sigdescr_np ;; esac
+	ac_test $x '!' some_sig$what 0 "GNU $x()" <<-EOF
+		extern const char *$x(int);
+		int main(int ac, char *av[]) { return (*$x(*av[ac])); }
+	EOF
+	test x"1" = x"$fv" && eval HAVE_SOME_SIG$uwhat=1
+
+	ac_testn sys_sig$what '!' some_sig$what 0 "the sys_sig$what[] array" <<-EOF
 		extern const char * const sys_sig$what[];
 		extern int isatty(int);
 		int main(void) { return (sys_sig$what[0][0] + isatty(0)); }
 	EOF
-	ac_testn _sys_sig$what '!' sys_sig$what 0 "the _sys_sig$what[] array" <<-EOF
+	test x"1" = x"$fv" && eval HAVE_SOME_SIG$uwhat=1
+
+	ac_testn _sys_sig$what '!' some_sig$what 0 "the _sys_sig$what[] array" <<-EOF
 		extern const char * const _sys_sig$what[];
 		extern int isatty(int);
 		int main(void) { return (_sys_sig$what[0][0] + isatty(0)); }
 	EOF
-	eval uwhat_v=\$HAVE__SYS_SIG$uwhat
-	if test 1 = "$uwhat_v"; then
-		add_cppflags -Dsys_sig$what=_sys_sig$what
+	if test x"1" = x"$fv"; then
+		cpp_define sys_sig$what _sys_sig$what
 		eval HAVE_SYS_SIG$uwhat=1
+		eval HAVE_SOME_SIG$uwhat=1
 	fi
 	ac_cppflags SYS_SIG$uwhat
 done
@@ -2067,16 +2401,19 @@ ac_test rlimit '' 'getrlimit and setrlim
 	}
 EOF
 
-ac_test rlim_t rlimit 0 <<-'EOF'
+ac_testnnd rlim_t rlimit 0 <<-'EOF'
 	#include <sys/types.h>
-	#if HAVE_BOTH_TIME_H
+	#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#include <time.h>
-	#elif HAVE_SYS_TIME_H
+	#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#elif HAVE_TIME_H
 	#include <time.h>
 	#endif
+	#if HAVE_SYS_SELECT_H
+	#include <sys/select.h>
+	#endif
 	#if HAVE_SYS_RESOURCE_H
 	#include <sys/resource.h>
 	#endif
@@ -2084,6 +2421,95 @@ ac_test rlim_t rlimit 0 <<-'EOF'
 	int main(void) { return (((int)(rlim_t)0) + isatty(0)); }
 EOF
 
+if test 10 = "$HAVE_RLIMIT$HAVE_RLIM_T"; then
+	fv=$MKSH_RLIM_T
+	fd='for what rlim_t could have been'
+	# reuses here document from above
+	if test x"$fv" = x"" || test x"$fv" = x"x"; then
+		$e ... $fd
+		vv ']' "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c | grep -v '^#' | tr -d \\\\015 >x"
+		fx=0
+		fr=
+		while read line; do
+			case $fx in
+			0)
+				case $line in
+				*struct*[\	\ ]rlimit|*struct*[\	\ ]rlimit[\	\ \{]*)
+					fr=$line
+					fx=1
+					;;
+				esac ;;
+			1)
+				fr="$fr $line"
+				case $line in
+				*\}*)
+					fx=2
+					;;
+				esac ;;
+			esac
+		done <x
+		echo "[ $fr"
+		fr=`echo " $fr" | sed \
+		    -e 's/[	 ][	 ]*/ /g' \
+		    -e 's/^ *struct rlimit *[{] *//' \
+		    -e 's/ *;.*$//'`
+		fx=
+		case $fr in
+		*\ rlim_cur)
+			fr=`echo " $fr" | sed \
+			    -e 's/^ //' \
+			    -e 's/ rlim_cur$//'`
+			;;
+		*\ rlim_max)
+			fr=`echo " $fr" | sed \
+			    -e 's/^ //' \
+			    -e 's/ rlim_max$//'`
+			;;
+		*)
+			fr=
+			;;
+		esac
+		case $fr in
+		int|signed\ int)
+			fv=RLT_SI ;;
+		u_int|unsigned|unsigned\ int)
+			fv=RLT_UI ;;
+		long|long\ int|signed\ long|signed\ long\ int)
+			fv=RLT_SL ;;
+		u_long|unsigned\ long|unsigned\ long\ int)
+			fv=RLT_UL ;;
+		long\ long|long\ long\ int|signed\ long\ long|signed\ long\ long\ int)
+			fv=RLT_SQ ;;
+		unsigned\ long\ long|unsigned\ long\ long\ int)
+			fv=RLT_UQ ;;
+		[a-z_]*_t)
+			fv=`echo " $fr" | sed -n '/^ \([a-z0-9_]*_t\)$/s//\1/p'` ;;
+		*)
+			fv= ;;
+		esac
+		test_n "$fv" || fx="(could not be determined from $fr)"
+	else
+		fx=' (cached)'
+	fi
+	test_z "$fv" || cpp_define MKSH_RLIM_T "$fv"
+	$e "$bi==> $fd...$ao $ui$fv$ao$fx"
+	fx=
+fi
+
+ac_test get_current_dir_name <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { return (!get_current_dir_name()); }
+EOF
+
+ac_test getrandom <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#define HAVE_GETRANDOM 1
+	#include "sh.h"
+	char buf;
+	int main(void) { return ((int)getrandom(&buf, 1, GRND_NONBLOCK)); }
+EOF
+
 ac_test getrusage <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
@@ -2122,6 +2548,7 @@ ac_test memmove <<-'EOF'
 	}
 EOF
 
+: "${HAVE_MKNOD=0}"
 ac_test mknod '' 'if to use mknod(), makedev() and friends' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
@@ -2144,7 +2571,7 @@ ac_test mmap lock_fcntl 0 'for mmap and
 	#include <stddef.h>
 	#include <stdlib.h>
 	int main(void) { return ((void *)mmap(NULL, (size_t)0,
-	    PROT_READ, MAP_PRIVATE, 0, (off_t)0) == (void *)NULL ? 1 :
+	    PROT_READ, MAP_PRIVATE, 0, (off_t)0) == (void *)0UL ? 1 :
 	    munmap(NULL, 0)); }
 EOF
 
@@ -2158,6 +2585,13 @@ ac_test nice <<-'EOF'
 	int main(void) { return (nice(4)); }
 EOF
 
+ac_test rename <<-'EOF'
+	#include <fcntl.h>
+	#include <stdio.h>
+	#include <unistd.h>
+	int main(int ac, char *av[]) { return (rename(*av, av[ac - 1])); }
+EOF
+
 ac_test revoke <<-'EOF'
 	#include <sys/types.h>
 	#if HAVE_LIBUTIL_H
@@ -2167,34 +2601,33 @@ ac_test revoke <<-'EOF'
 	int main(int ac, char *av[]) { return (ac + revoke(av[0])); }
 EOF
 
-ac_test setlocale_ctype '' 'setlocale(LC_CTYPE, "")' <<-'EOF'
+ac_test posix_utf8_locale '' 'for setlocale(LC_CTYPE, "") and nl_langinfo(CODESET)' <<-'EOF'
 	#include <locale.h>
-	#include <stddef.h>
-	int main(void) { return ((int)(size_t)(void *)setlocale(LC_CTYPE, "")); }
+	#include <langinfo.h>
+	int main(void) { return (!setlocale(LC_CTYPE, "") || !nl_langinfo(CODESET)); }
 EOF
 
-ac_test langinfo_codeset setlocale_ctype 0 'nl_langinfo(CODESET)' <<-'EOF'
-	#include <langinfo.h>
-	#include <stddef.h>
-	int main(void) { return ((int)(size_t)(void *)nl_langinfo(CODESET)); }
+$ebcdic && ac_test setlocale_lcall <<-'EOF'
+	#include <locale.h>
+	int main(void) { return (!setlocale(LC_ALL, "")); }
 EOF
 
 ac_test select <<-'EOF'
 	#include <sys/types.h>
-	#if HAVE_BOTH_TIME_H
+	#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#include <time.h>
-	#elif HAVE_SYS_TIME_H
+	#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 	#include <sys/time.h>
 	#elif HAVE_TIME_H
 	#include <time.h>
 	#endif
-	#if HAVE_SYS_BSDTYPES_H
-	#include <sys/bsdtypes.h>
-	#endif
 	#if HAVE_SYS_SELECT_H
 	#include <sys/select.h>
 	#endif
+	#if HAVE_SYS_BSDTYPES_H
+	#include <sys/bsdtypes.h>
+	#endif
 	#if HAVE_BSTRING_H
 	#include <bstring.h>
 	#endif
@@ -2227,6 +2660,23 @@ ac_test setgroups setresugid 0 <<-'EOF'
 	int main(void) { gid_t gid = 0; return (setgroups(0, &gid)); }
 EOF
 
+ac_test sigaction <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(int ac, char *av[]) {
+		struct sigaction sa, osa;
+		ssize_t n;
+
+		memset(&sa, 0, sizeof(sa));
+		sigemptyset(&sa.sa_mask);
+		sa.sa_handler = SIG_IGN;
+		sigaction(ac, &sa, &osa);
+		n = write(1, *av, strlen(*av));
+		sigaction(ac, &osa, NULL);
+		return ((size_t)n != strlen(*av));
+	}
+EOF
+
 if test x"$et" = x"klibc"; then
 
 	ac_testn __rt_sigsuspend '' 'whether klibc uses RT signals' <<-'EOF'
@@ -2255,16 +2705,16 @@ EOF
 
 	if test "000" = "$HAVE___RT_SIGSUSPEND$HAVE___SIGSUSPEND_S$HAVE___SIGSUSPEND_XXS"; then
 		# no usable sigsuspend(), use pause() *ugh*
-		add_cppflags -DMKSH_NO_SIGSUSPEND
+		cpp_define MKSH_NO_SIGSUSPEND 1
 	fi
 fi
 
-ac_test strerror '!' sys_errlist 0 <<-'EOF'
+ac_test strerror '!' some_errlist 0 <<-'EOF'
 	extern char *strerror(int);
 	int main(int ac, char *av[]) { return (*strerror(*av[ac])); }
 EOF
 
-ac_test strsignal '!' sys_siglist 0 <<-'EOF'
+ac_test strsignal '!' some_siglist 0 <<-'EOF'
 	#include <string.h>
 	#include <signal.h>
 	int main(void) { return (strsignal(1)[0]); }
@@ -2276,6 +2726,11 @@ ac_test strlcpy <<-'EOF'
 	    (size_t)ac)); }
 EOF
 
+ac_test strstr <<-'EOF'
+	#include <string.h>
+	int main(int ac, char *av[]) { return (!strstr(av[ac - 1], "meow")); }
+EOF
+
 #
 # check headers for declarations
 #
@@ -2303,15 +2758,49 @@ ac_test sys_siglist_decl sys_siglist 0 '
 	int main(void) { return (sys_siglist[0][0] + isatty(0)); }
 EOF
 
-ac_test st_mtim '' 'for struct stat.st_mtim.tv_nsec' <<-'EOF'
+ac_testn st_mtimensec '' 'for struct stat.st_mtimensec' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtimensec)); }
+EOF
+ac_testn st_mtimespec '!' st_mtimensec 0 'for struct stat.st_mtimespec.tv_nsec' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtimespec.tv_nsec)); }
+EOF
+if test 1 = "$HAVE_ST_MTIMESPEC"; then
+	cpp_define st_mtimensec st_mtimespec.tv_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_testn st_mtim '!' st_mtimensec 0 'for struct stat.st_mtim.tv_nsec' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
 	int main(void) { struct stat sb; return (sizeof(sb.st_mtim.tv_nsec)); }
 EOF
-ac_test st_mtimensec '!' st_mtim 0 'for struct stat.st_mtimensec' <<-'EOF'
+if test 1 = "$HAVE_ST_MTIM"; then
+	cpp_define st_mtimensec st_mtim.tv_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_testn st_mtime_nsec '!' st_mtimensec 0 'for struct stat.st_mtime_nsec' <<-'EOF'
 	#define MKSH_INCLUDES_ONLY
 	#include "sh.h"
-	int main(void) { struct stat sb; return (sizeof(sb.st_mtimensec)); }
+	int main(void) { struct stat sb; return (sizeof(sb.st_mtime_nsec)); }
+EOF
+if test 1 = "$HAVE_ST_MTIME_NSEC"; then
+	cpp_define st_mtimensec st_mtime_nsec
+	HAVE_ST_MTIMENSEC=1
+fi
+ac_cppflags ST_MTIMENSEC
+
+ac_test intconstexpr_rsize_max '' 'whether RSIZE_MAX is an integer constant expression' <<-'EOF'
+	#define MKSH_INCLUDES_ONLY
+	#include "sh.h"
+	int tstarr[((int)(RSIZE_MAX) & 1) + 1] = {0};
+	mbCTA_BEG(conftest_c);
+	 mbCTA(rsizemax_check,
+	    ((mbiHUGE_U)(RSIZE_MAX) == (mbiHUGE_U)(size_t)(RSIZE_MAX)));
+	mbCTA_END(conftest_c);
+	int main(void) { return (isatty(0)); }
 EOF
 
 #
@@ -2335,12 +2824,13 @@ if test $legacy = 1; then
 		#ifndef CHAR_BIT
 		#define CHAR_BIT 0
 		#endif
-		struct ctasserts {
-		#define cta(name,assertion) char name[(assertion) ? 1 : -1]
-			cta(char_is_8_bits, (CHAR_BIT) == 8);
-			cta(long_is_32_bits, sizeof(long) == 4);
-		};
-		int main(void) { return (sizeof(struct ctasserts)); }
+		mbCTA_BEG(conftest);
+			mbCTA(char_is_8_bits, (CHAR_BIT) == 8);
+			mbCTA(long_is_4_chars, sizeof(long) == 4);
+			mbCTA(ulong_is_32_bits, mbiTYPE_UBITS(unsigned long) == 32U);
+			mbCTA(slong_is_31_bits, mbiMASK_BITS(LONG_MAX) == 31U);
+		mbCTA_END(conftest);
+		int main(void) { return (sizeof(struct ctassert_conftest)); }
 EOF
 
 	ac_test long_64bit '!' long_32bit 0 'whether long is 64 bit wide' <<-'EOF'
@@ -2349,12 +2839,13 @@ EOF
 		#ifndef CHAR_BIT
 		#define CHAR_BIT 0
 		#endif
-		struct ctasserts {
-		#define cta(name,assertion) char name[(assertion) ? 1 : -1]
-			cta(char_is_8_bits, (CHAR_BIT) == 8);
-			cta(long_is_64_bits, sizeof(long) == 8);
-		};
-		int main(void) { return (sizeof(struct ctasserts)); }
+		mbCTA_BEG(conftest);
+			mbCTA(char_is_8_bits, (CHAR_BIT) == 8);
+			mbCTA(long_is_8_chars, sizeof(long) == 8);
+			mbCTA(ulong_is_64_bits, mbiTYPE_UBITS(unsigned long) == 64U);
+			mbCTA(slong_is_63_bits, mbiMASK_BITS(LONG_MAX) == 63U);
+		mbCTA_END(conftest);
+		int main(void) { return (sizeof(struct ctassert_conftest)); }
 EOF
 
 	case $HAVE_LONG_32BIT$HAVE_LONG_64BIT in
@@ -2367,10 +2858,10 @@ fi
 #
 # Compiler: Praeprocessor (only if needed)
 #
-test 0 = $HAVE_SYS_SIGNAME && if ac_testinit cpp_dd '' \
+test 0 = $HAVE_SOME_SIGNAME && if ac_testinit cpp_dd '' \
     'checking if the C Preprocessor supports -dD'; then
 	echo '#define foo bar' >conftest.c
-	vv ']' "$CPP $CFLAGS $CPPFLAGS $NOWARN -dD conftest.c >x"
+	vv ']' "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN -dD conftest.c >x"
 	grep '#define foo bar' x >/dev/null 2>&1 && fv=1
 	rmf conftest.c x vv.out
 	ac_testdone
@@ -2388,7 +2879,7 @@ ed x <x 2>/dev/null | grep 3 >/dev/null
     check_categories="$check_categories $oldish_ed"
 rmf x vv.out
 
-if test 0 = $HAVE_SYS_SIGNAME; then
+if test 0 = $HAVE_SOME_SIGNAME; then
 	if test 1 = $HAVE_CPP_DD; then
 		$e Generating list of signal names...
 	else
@@ -2407,15 +2898,12 @@ if test 0 = $HAVE_SYS_SIGNAME; then
 #define cfg_NSIG (SIGMAX + 1)
 #elif defined(_SIGMAX)
 #define cfg_NSIG (_SIGMAX + 1)
-#else
-/*XXX better error out, see sh.h */
-#define cfg_NSIG 64
 #endif
 int
 mksh_cfg= cfg_NSIG
-;' >conftest.c
+;' | cat_h_blurb >conftest.c
 	# GNU sed 2.03 segfaults when optimising this to sed -n
-	NSIG=`vq "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c" | \
+	NSIG=`vq "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c" | \
 	    grep -v '^#' | \
 	    sed '/mksh_cfg.*= *$/{
 		N
@@ -2436,8 +2924,9 @@ mksh_cfg= cfg_NSIG
 	sigs="$sigs STOP TSTP TTIN TTOU USR1 USR2 POLL PROF SYS TRAP URG VTALRM"
 	sigs="$sigs XCPU XFSZ INFO WINCH EMT IO DIL LOST PWR SAK CLD IOT STKFLT"
 	sigs="$sigs ABND DCE DUMP IOERR TRACE DANGER THCONT THSTOP RESV UNUSED"
+	sigs="$sigs PROT"
 	test 1 = $HAVE_CPP_DD && test $NSIG -gt 1 && sigs="$sigs "`vq \
-	    "$CPP $CFLAGS $CPPFLAGS $NOWARN -dD conftest.c" | \
+	    "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN -dD conftest.c" | \
 	    grep '[	 ]SIG[A-Z0-9][A-Z0-9]*[	 ]' | \
 	    sed 's/^.*[	 ]SIG\([A-Z0-9][A-Z0-9]*\)[	 ].*$/\1/' | sort`
 	test $NSIG -gt 1 || sigs=
@@ -2451,7 +2940,7 @@ mksh_cfg= cfg_NSIG
 		echo mksh_cfg= SIG$name >>conftest.c
 		echo ';' >>conftest.c
 		# GNU sed 2.03 croaks on optimising this, too
-		vq "$CPP $CFLAGS $CPPFLAGS $NOWARN conftest.c" | \
+		vq "$CPP $CFLAGS $Cg $CPPFLAGS $NOWARN conftest.c" | \
 		    grep -v '^#' | \
 		    sed '/mksh_cfg.*= *$/{
 			N
@@ -2474,14 +2963,17 @@ mksh_cfg= cfg_NSIG
 	$e done.
 fi
 
+check_categories="$check_categories have:select:$HAVE_SELECT"
+
 if test 1 = "$MKSH_UNLIMITED"; then
-	add_cppflags -DMKSH_UNLIMITED
+	cpp_define MKSH_UNLIMITED 1
 else
 	MKSH_UNLIMITED=0
 fi
 
 if test 1 = "$USE_PRINTF_BUILTIN"; then
-	add_cppflags -DMKSH_PRINTF_BUILTIN
+	cpp_define MKSH_PRINTF_BUILTIN 1
+	check_categories="$check_categories printf-builtin"
 else
 	USE_PRINTF_BUILTIN=0
 fi
@@ -2491,41 +2983,38 @@ addsrcs USE_PRINTF_BUILTIN printf.c
 addsrcs '!' MKSH_UNLIMITED ulimit.c
 
 test 1 = "$HAVE_CAN_VERB" && CFLAGS="$CFLAGS -verbose"
-add_cppflags -DMKSH_BUILD_R=593
+cpp_define MKSH_BUILD_R 599
 
 $e $bi$me: Finished configuration testing, now producing output.$ao
 
 files=
 objs=
-sp=
+fsp=
 case $tcfn in
 a.exe|conftest.exe)
-	mkshexe=$tfn.exe
-	add_cppflags -DMKSH_EXE_EXT
+	buildoutput=$tfn.exe
+	cpp_define MKSH_EXE_EXT 1
 	;;
 *)
-	mkshexe=$tfn
+	buildoutput=$tfn
 	;;
 esac
-case $curdir in
-*\ *)	mkshshebang="#!./$mkshexe" ;;
-*)	mkshshebang="#!$curdir/$mkshexe" ;;
-esac
 cat >test.sh <<-EOF
-	$mkshshebang
+	#!$curdisp/$buildoutput
 	LC_ALL=C PATH='$PATH'; export LC_ALL PATH
 	case \$KSH_VERSION in
 	*MIRBSD*|*LEGACY*) ;;
 	*) exit 1 ;;
 	esac
 	set -A check_categories -- $check_categories
-	pflag='$curdir/$mkshexe'
+	pflag='$curdisp/$buildoutput'
 	sflag='$srcdir/check.t'
-	usee=0 useU=0 Pflag=0 Sflag=0 uset=0 vflag=1 xflag=0
+	usee=0 usef=1 useU=0 Pflag=0 Sflag=0 uset=0 vflag=1 xflag=0
 	while getopts "C:e:fPp:QSs:t:U:v" ch; do case \$ch {
 	(C)	check_categories[\${#check_categories[*]}]=\$OPTARG ;;
 	(e)	usee=1; eflag=\$OPTARG ;;
-	(f)	check_categories[\${#check_categories[*]}]=fastbox ;;
+	(f)	usef=1 ;;
+	(+f)	usef=0 ;;
 	(P)	Pflag=1 ;;
 	(+P)	Pflag=0 ;;
 	(p)	pflag=\$OPTARG ;;
@@ -2546,6 +3035,11 @@ cat >test.sh <<-EOF
 	if $ebcdic; then
 		args[\${#args[*]}]=-E
 	fi
+	if (( usef )); then
+		check_categories[\${#check_categories[*]}]=system:fast-yes
+	else
+		check_categories[\${#check_categories[*]}]=system:fast-no
+	fi
 	x=
 	for y in "\${check_categories[@]}"; do
 		x=\$x,\$y
@@ -2574,7 +3068,7 @@ cat >test.sh <<-EOF
 		args[\${#args[*]}]=\$TMPDIR
 	fi
 	print Testing mksh for conformance:
-	grep -F -e 'KSH R' -e Mir''OS: "\$sflag" | sed '/KSH/s/^./&           /'
+	grep -e 'KSH R' -e Mir''OS: "\$sflag" | sed '/KSH/s/^./&           /'
 	print "This shell is actually:\\n\\t\$KSH_VERSION"
 	print 'test.sh built for mksh $dstversion'
 	cstr='\$os = defined \$^O ? \$^O : "unknown";'
@@ -2622,9 +3116,7 @@ llvm)
 	;;
 esac
 echo ": # work around NeXTstep bug" >Rebuild.sh
-cd "$srcdir"
-optfiles=`echo *.opt`
-cd "$curdir"
+optfiles=`cd "$srcdir" && echo *.opt`
 for file in $optfiles; do
 	echo "echo + Running genopt on '$file'..."
 	echo "(srcfile='$srcdir/$file'; BUILDSH_RUN_GENOPT=1; . '$srcdir/Build.sh')"
@@ -2633,16 +3125,16 @@ echo set -x >>Rebuild.sh
 for file in $SRCS; do
 	op=`echo x"$file" | sed 's/^x\(.*\)\.c$/\1./'`
 	test -f $file || file=$srcdir/$file
-	files="$files$sp$file"
-	echo "$CC $CFLAGS $CPPFLAGS $emitbc $file || exit 1" >>Rebuild.sh
+	files="$files$fsp$file"
+	echo "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file || exit 1" >>Rebuild.sh
 	if test $cm = dragonegg; then
 		echo "mv ${op}s ${op}ll" >>Rebuild.sh
 		echo "llvm-as ${op}ll || exit 1" >>Rebuild.sh
-		objs="$objs$sp${op}bc"
+		objs="$objs$fsp${op}bc"
 	else
-		objs="$objs$sp${op}o"
+		objs="$objs$fsp${op}o"
 	fi
-	sp=' '
+	fsp=$sp
 done
 case $cm in
 dragonegg|llvm)
@@ -2654,41 +3146,54 @@ dragonegg|llvm)
 	lobjs=$objs
 	;;
 esac
-echo tcfn=$mkshexe >>Rebuild.sh
-echo "$CC $CFLAGS $LDFLAGS -o \$tcfn $lobjs $LIBS $ccpr" >>Rebuild.sh
+echo tcfn=$buildoutput >>Rebuild.sh
+echo "$CC $CFLAGS $Cg $LDFLAGS -o \$tcfn $lobjs $LIBS $ccpr" >>Rebuild.sh
 echo "test -f \$tcfn || exit 1; $SIZE \$tcfn" >>Rebuild.sh
 if test $cm = makefile; then
-	extras='emacsfn.h exprtok.h rlimits.opt sh.h sh_flags.opt ulimits.opt var_spec.h'
-	test 0 = $HAVE_SYS_SIGNAME && extras="$extras signames.inc"
+	extras='emacsfn.h exprtok.h mbsdcc.h mbsdint.h mirhash.h mksh.faq rlimits.opt sh.h sh_flags.opt ulimits.opt var_spec.h'
+	test 0 = $HAVE_SOME_SIGNAME && extras="$extras signames.inc"
 	gens= genq=
 	for file in $optfiles; do
 		genf=`basename "$file" | sed 's/.opt$/.gen/'`
 		gens="$gens $genf"
-		genq="$genq$nl$genf: $srcdir/Build.sh $srcdir/$file
-			srcfile=$srcdir/$file; BUILDSH_RUN_GENOPT=1; . $srcdir/Build.sh"
+		genq="$genq$nl$genf: \$(SRCDIR)/Build.sh \$(SRCDIR)/$file
+	srcfile='\$(SRCDIR)/$file'; BUILDSH_RUN_GENOPT=1; . '\$(SRCDIR)/Build.sh'"
 	done
+	if test $legacy = 0; then
+		manpage=mksh.1
+	else
+		manpage=lksh.1
+	fi
 	cat >Makefrag.inc <<EOF
-# Makefile fragment for building mksh $dstversion
+# Makefile fragment for building $whatlong $dstversion
 
-PROG=		$mkshexe
-MAN=		mksh.1
+PROG=		$buildoutput
+MAN=		$manpage
+FAQ=		FAQ.htm
+SRCDIR=		$srcdir
+MF_DIR=		$curdisp
 SRCS=		$SRCS
 SRCS_FP=	$files
 OBJS_BP=	$objs
 INDSRCS=	$extras
 NONSRCS_INST=	dot.mkshrc \$(MAN)
-NONSRCS_NOINST=	Build.sh Makefile Rebuild.sh check.pl check.t test.sh
+NONSRCS_NOINST=	Build.sh FAQ2HTML.sh Makefile Rebuild.sh check.pl check.t mksh.ico test.sh
 CC=		$CC
-CPPFLAGS=	$CPPFLAGS
-CFLAGS=		$CFLAGS
+CPPFLAGS=	$CPPFLAGS -I'\$(MF_DIR)'
+CFLAGS=		$CFLAGS $Cg
 LDFLAGS=	$LDFLAGS
 LIBS=		$LIBS
 
+# for all make variants:
+#all: \$(PROG) \$(FAQ)
+
 .depend \$(OBJS_BP):$gens$genq
 
+FAQ.htm: \$(SRCDIR)/FAQ2HTML.sh \$(SRCDIR)/mksh.faq
+	\$(SHELL) '\$(SRCDIR)/FAQ2HTML.sh' '\$(SRCDIR)/mksh.faq'
+
 # not BSD make only:
-#VPATH=		$srcdir
-#all: \$(PROG)
+#VPATH=		\$(SRCDIR)
 #\$(PROG): \$(OBJS_BP)
 #	\$(CC) \$(CFLAGS) \$(LDFLAGS) -o \$@ \$(OBJS_BP) \$(LIBS)
 #\$(OBJS_BP): \$(SRCS_FP) \$(NONSRCS)
@@ -2698,11 +3203,18 @@ LIBS=		$LIBS
 # for all make variants:
 #REGRESS_FLAGS=	-f
 #regress:
-#	./test.sh \$(REGRESS_FLAGS)
+#	'\$(MF_DIR)/test.sh' \$(REGRESS_FLAGS)
 check_categories=$check_categories
+#PERL=		perl
+#UTFLOCALE=	C.UTF-8
+#TESTONLY=
+#altregress:
+#	\$(PERL) '\$(SRCDIR)/check.pl' -p ./$buildoutput \\
+#	    -C \`echo "X\$(check_categories)" | sed -e 's/^X[	 ]*//' -e 's/ /,/g'\` \\
+#	    -U \$(UTFLOCALE) -v -s '\$(SRCDIR)/check.t' \$(TESTONLY)
 
 # for BSD make only:
-#.PATH: $srcdir
+#.PATH: \$(SRCDIR)
 #.include <bsd.prog.mk>
 EOF
 	$e
@@ -2713,18 +3225,22 @@ for file in $optfiles; do
 	$e "+ Running genopt on '$file'..."
 	do_genopt "$srcdir/$file" || exit 1
 done
+if test $cm = trace; then
+	emitbc='-MD -c'
+	rm -f *.d
+fi
 if test $cm = combine; then
-	objs="-o $mkshexe"
+	objs="-o $buildoutput"
 	for file in $SRCS; do
 		test -f $file || file=$srcdir/$file
 		objs="$objs $file"
 	done
 	emitbc="-fwhole-program --combine"
-	v "$CC $CFLAGS $CPPFLAGS $LDFLAGS $emitbc $objs $LIBS $ccpr"
+	v "$CC $CFLAGS $Cg $CPPFLAGS $LDFLAGS $emitbc $objs $LIBS $ccpr"
 elif test 1 = $pm; then
 	for file in $SRCS; do
 		test -f $file || file=$srcdir/$file
-		v "$CC $CFLAGS $CPPFLAGS $emitbc $file" &
+		v "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file" &
 	done
 	wait
 else
@@ -2732,7 +3248,7 @@ else
 		test $cm = dragonegg && \
 		    op=`echo x"$file" | sed 's/^x\(.*\)\.c$/\1./'`
 		test -f $file || file=$srcdir/$file
-		v "$CC $CFLAGS $CPPFLAGS $emitbc $file" || exit 1
+		v "$CC $CFLAGS $Cg $CPPFLAGS $emitbc $file" || exit 1
 		if test $cm = dragonegg; then
 			v "mv ${op}s ${op}ll"
 			v "llvm-as ${op}ll" || exit 1
@@ -2745,12 +3261,99 @@ dragonegg|llvm)
 	v "llvm-link -o - $objs | opt $optflags | llc -o $tfn.s"
 	;;
 esac
-tcfn=$mkshexe
-test $cm = combine || v "$CC $CFLAGS $LDFLAGS -o $tcfn $lobjs $LIBS $ccpr"
+tcfn=$buildoutput
+case $cm in
+combine)
+	;;
+trace)
+	rm -f $tfn.*.t
+	v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $lobjs $LIBS -Wl,-t,-t >$tfn.l.t $ccpr"
+	;;
+*)
+	v "$CC $CFLAGS $Cg $LDFLAGS -o $tcfn $lobjs $LIBS $ccpr"
+	;;
+esac
 test -f $tcfn || exit 1
 test 1 = $r || v "$NROFF -mdoc <'$srcdir/lksh.1' >lksh.cat1" || rmf lksh.cat1
 test 1 = $r || v "$NROFF -mdoc <'$srcdir/mksh.1' >mksh.cat1" || rmf mksh.cat1
 test 1 = $r || v "(set -- ''; . '$srcdir/FAQ2HTML.sh')" || rmf FAQ.htm
+if test $cm = trace; then
+	echo >&2 "I: tracing compilation, linking and binding inputs"
+    (
+	if test -n "$KSH_VERSION"; then
+		Xe() { print -r -- "$1"; }
+	elif test -n "$BASH_VERSION"; then
+		Xe() { printf '%s\n' "$1"; }
+	else
+		Xe() { echo "$1"; }
+	fi
+	Xgrep() {
+		set +e
+		grep "$@"
+		XgrepRV=$?
+		set -e
+		test $XgrepRV -lt 2
+	}
+	set -e
+	tsrc=`readlink -f "$srcdir"`
+	tdst=`readlink -f .`
+	# some sh don’t like ${foo#bar} or ${#foo} at parse time
+	eval 'if test ${#tsrc} -lt ${#tdst}; then
+		mkr() {
+			r=`readlink -f "$1"`
+			case $r in #((
+			"$tdst"|"$tdst/"*) r="<<BLDDIR>>${r#"$tdst"}" ;;
+			"$tsrc"|"$tsrc/"*) r="<<SRCDIR>>${r#"$tsrc"}" ;;
+			esac
+		}
+	else
+		mkr() {
+			r=`readlink -f "$1"`
+			case $r in #((
+			"$tsrc"|"$tsrc/"*) r="<<SRCDIR>>${r#"$tsrc"}" ;;
+			"$tdst"|"$tdst/"*) r="<<BLDDIR>>${r#"$tdst"}" ;;
+			esac
+		}
+	fi'
+
+	cat *.d >$tfn.c1.t
+	set -o noglob
+	while read dst src; do
+		for f in $src; do
+			Xe "$f"
+		done
+	done <$tfn.c1.t >$tfn.c2.t
+	set +o noglob
+	sort -u <$tfn.c2.t >$tfn.c3.t
+	while IFS= read -r name; do
+		mkr "$name"
+		Xe "$r"
+	done <$tfn.c3.t >$tfn.c4.t
+	sort -u <$tfn.c4.t >$tfn.cz.t
+
+	sort -u <$tfn.l.t >$tfn.l1.t
+	sed -n '/^(/s///p' <$tfn.l1.t >$tfn.l2l.t #)
+	Xgrep -v '^(' <$tfn.l1.t >$tfn.l2.t
+	b=
+	while IFS=')' read -r lib memb; do
+		test x"$lib" = x"$b" || {
+			Xgrep -F -v -x "$lib" <$tfn.l2.t >$tfn.l2a.t
+			mv $tfn.l2a.t $tfn.l2.t
+			b=$lib
+			mkr "$lib"
+		}
+		Xe "$r($memb)"
+	done <$tfn.l2l.t >$tfn.l3.t
+	while IFS= read -r name; do
+		mkr "$name"
+		Xe "$r"
+	done <$tfn.l2.t >>$tfn.l3.t
+	sort -u <$tfn.l3.t >$tfn.lz.t
+	cat $tfn.cz.t $tfn.lz.t >$tfn.trace
+	rm $tfn.*.t
+    )
+	test 0 = $eq && sed 's/^/- /' <$tfn.trace
+fi
 test 0 = $eq && v $SIZE $tcfn
 i=install
 test -f /usr/ucb/$i && i=/usr/ucb/$i
@@ -2760,7 +3363,7 @@ $e Installing the shell:
 $e "# $i -c -s -o root -g bin -m 555 $tfn /bin/$tfn"
 if test $legacy = 0; then
 	$e "# grep -x /bin/$tfn /etc/shells >/dev/null || echo /bin/$tfn >>/etc/shells"
-	$e "# $i -c -o root -g bin -m 444 dot.mkshrc /usr/share/doc/mksh/examples/"
+	$e "# $i -c -o root -g bin -m 444 ${srcdisp}dot.mkshrc /usr/share/doc/mksh/examples/"
 fi
 $e
 $e Installing the manual:
@@ -2777,12 +3380,12 @@ if test -f mksh.cat1; then
 	    "/usr/share/man/cat1/mksh.0"
 	$e or
 fi
-$e "# $i -c -o root -g bin -m 444 lksh.1 mksh.1 /usr/share/man/man1/"
+$e "# $i -c -o root -g bin -m 444 ${srcdisp}lksh.1 ${srcdisp}mksh.1 /usr/share/man/man1/"
 $e
 $e Run the regression test suite: ./test.sh
-$e Please also read the sample file dot.mkshrc and the fine manual.
+$e Please also read the sample file ${srcdisp}dot.mkshrc and the fine manual.
 test -f FAQ.htm || \
-    $e Run FAQ2HTML.sh and place FAQ.htm into a suitable location as well.
+    $e Run ${srcdisp}FAQ2HTML.sh and place FAQ.htm into a suitable location as well.
 exit 0
 
 : <<'EOD'
@@ -2801,8 +3404,8 @@ LIBS				default empty; added after sourc
 				[Interix] default: -lcrypt (XXX still needed?)
 NOWARN				-Wno-error or similar
 NROFF				default: nroff
-TARGET_OS			default: $(uname -s || uname)
-TARGET_OSREV			[QNX] default: $(uname -r)
+TARGET_OS			default: `uname -s || uname`
+TARGET_OSREV			default: `uname -r` [only needed on some OS]
 
 ==== feature selectors ====
 MKSH_UNLIMITED			1 to omit ulimit builtin completely
@@ -2819,6 +3422,7 @@ KSH_VERSIONNAME_VENDOR_EXT	when patching
 MKSHRC_PATH			"~/.mkshrc" (do not change)
 MKSH_A4PB			force use of arc4random_pushb
 MKSH_ASSUME_UTF8		(0=disabled, 1=enabled; default: unset)
+				note will vanish with full locale tracking!
 MKSH_BINSHPOSIX			if */sh or */-sh, enable set -o posix
 MKSH_BINSHREDUCED		if */sh or */-sh, enable set -o sh
 MKSH_CLS_STRING			KSH_ESC_STRING "[;H" KSH_ESC_STRING "[J"
@@ -2841,7 +3445,6 @@ MKSH_SMALL			omit some code, optimise ha
 MKSH_SMALL_BUT_FAST		disable some hard-for-size optim. (modern sys.)
 MKSH_S_NOVI=1			disable Vi editing mode (default if MKSH_SMALL)
 MKSH_TYPEDEF_SIG_ATOMIC_T	define to e.g. 'int' if sig_atomic_t is missing
-MKSH_TYPEDEF_SSIZE_T		define to e.g. 'long' if your OS has no ssize_t
 MKSH_UNEMPLOYED			disable job control (but not jobs/co-processes)
 USE_REALLOC_MALLOC		define as 0 to not use realloc as malloc
 
@@ -2853,7 +3456,7 @@ them, set to a value other than 0 or 1.
 MKSH_SMALL but with Vi mode, add -DMKSH_S_NOVI=0 to CPPFLAGS as well.
 
 Normally, the following command is what you want to run, then:
-$ (sh Build.sh -r && ./test.sh -f) 2>&1 | tee log
+$ (sh Build.sh -r && ./test.sh) 2>&1 | tee log
 
 Copy dot.mkshrc to /etc/skel/.mkshrc; install mksh into $prefix/bin; or
 /bin; install the manpage, if omitting the -r flag a catmanpage is made
--- mksh-59c.orig/FAQ2HTML.sh
+++ mksh-59c/FAQ2HTML.sh
@@ -1,7 +1,7 @@
 #!/bin/sh
-rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,v 1.2 2020/10/31 04:17:36 tg Exp $'
+rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,v 1.9 2025/02/27 02:30:08 tg Exp $'
 #-
-# Copyright © 2020
+# Copyright © 2020, 2023
 #	mirabilos <m@mirbsd.org>
 #
 # Provided that these terms and disclaimer and all copyright notices
@@ -20,33 +20,43 @@ rcsid='$MirOS: src/bin/mksh/FAQ2HTML.sh,
 # of said person’s immediate fault when using the work as intended.
 #-
 
-set -e
+die() {
+	echo >&2 "E: $*"
+	exit 1
+}
+
 LC_ALL=C; LANGUAGE=C
 export LC_ALL; unset LANGUAGE
 nl='
 '
-srcdir=$(dirname "$0")
+srcdir=`dirname "$0" 2>/dev/null` || die 'cannot find srcdir'
 
 p=--posix
 sed $p -e q </dev/null >/dev/null 2>&1 || p=
 
 v=$1
 if test -z "$v"; then
-	v=$(sed $p -n '/^#define MKSH_VERSION "\(.*\)"$/s//\1/p' "$srcdir"/sh.h)
+	v=`sed $p -n '/^#define MKSH_VERSION "\(.*\)"$/s//\1/p' "$srcdir"/sh.h`
 fi
-src_id=$(sed $p -n '/^RCSID: /s///p' "$srcdir"/mksh.faq)
+test -n "$v" || die 'cannot find version'
+src_id=`sed $p -n '/^RCSID: /s///p' "$srcdir"/mksh.faq`
 # sanity check
-case $src_id in
+case x$src_id in
+x)
+	die 'cannot find RCSID'
+	;;
 *"$nl"*)
-	echo >&2 "E: more than one RCSID in mksh.faq?"
-	exit 1 ;;
+	die 'more than one RCSID in mksh.faq?'
+	;;
 esac
 
 sed $p \
     -e '/^RCSID: \$/s/^.*$/----/' \
     -e 's!@@RELPATH@@!http://www.mirbsd.org/!g' \
     -e 's^	<span style="display:none;">	</span>' \
-    "$srcdir"/mksh.faq | tr '\n' '' | sed $p \
+    "$srcdir"/mksh.faq >FAQ.tm1 || die 'sed (1)'
+tr '\n' '' <FAQ.tm1 >FAQ.tm2 || die 'tr (2)'
+sed $p \
     -e 'sg' \
     -e 's----g' \
     -e 's\([^]*\)\1g' \
@@ -56,14 +66,16 @@ sed $p \
     -e 's^</div>*' \
     -e 's$</div>' \
     -e 's<><error><>g' \
-    -e 'sg' | tr '' '\n' >FAQ.tmp
+    -e 'sg' <FAQ.tm2 >FAQ.tm3 || die 'sed (3)'
+tr '' '\n' <FAQ.tm3 >FAQ.tm4 || die 'tr (4)'
 
-exec >FAQ.htm~
+exec >FAQ.tm5
 cat <<EOF
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta name="tdm-reservation" content="1" />
  <title>mksh $v FAQ (local copy)</title>
  <meta name="source" content="$src_id" />
  <meta name="generator" content="$rcsid" />
@@ -109,7 +121,7 @@ cat <<EOF
  }
  /*]]>*/--></style>
 </head><body>
-<p>Note: Links marked like <a href="irc://chat.freenode.net/!/bin/mksh">this
+<p>Note: Links marked like <a href="irc://irc.mirbsd.org/!/bin/mksh">this
  one to the mksh IRC channel</a> connect to external resources.</p>
 <p>⚠ <b>Notice:</b> the website will have <a
  href="http://www.mirbsd.org/mksh-faq.htm">the latest version of the
@@ -119,18 +131,19 @@ cat <<EOF
 EOF
 sed $p -n \
     '/^<h2 id="\([^"]*"\)><a[^>]*\(>.*<\/a><\/\)h2>$/s//<li><a href="#\1\2li>/p' \
-    <FAQ.tmp
+    <FAQ.tm4 || die 'sed (ToC)'
 cat <<EOF
 </ul>
 
 <h1>Frequently Asked Questions</h1>
 EOF
-cat FAQ.tmp - <<EOF
+cat FAQ.tm4 - <<EOF
 <h1>Imprint</h1>
 <p>This offline HTML page for mksh $v was automatically generated
  from the sources.</p>
 </body></html>
 EOF
 exec >/dev/null
-rm FAQ.tmp
-mv FAQ.htm~ FAQ.htm
+rm FAQ.tm1 FAQ.tm2 FAQ.tm3 FAQ.tm4
+mv FAQ.tm5 FAQ.htm || die 'final mv'
+exit 0
--- mksh-59c.orig/check.pl
+++ mksh-59c/check.pl
@@ -1,8 +1,8 @@
-# $MirOS: src/bin/mksh/check.pl,v 1.51 2020/06/22 17:10:59 tg Exp $
+# $MirOS: src/bin/mksh/check.pl,v 1.55 2021/10/03 22:45:34 tg Exp $
 # $OpenBSD: th,v 1.1 2013/12/02 20:39:44 millert Exp $
 #-
 # Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
-#		2012, 2013, 2014, 2015, 2017
+#		2012, 2013, 2014, 2015, 2017, 2021
 #	mirabilos <m@mirbsd.org>
 #
 # Provided that these terms and disclaimer and all copyright notices
@@ -40,6 +40,19 @@
 #	is expected to produce "hi*" (no trailing newline) on standard output,
 #	"+ echo hi*\n+false\n" on standard error, and an exit code of 1.
 #
+# The test-program is invoked with a new environment vector by default which
+# is composed of the following parameters from the inherited environ if set:
+#	HOME, LD_LIBRARY_PATH, LOCPATH, LOGNAME,
+#	PATH, PERLIO, SHELL, UNIXMODE, UNIXROOT, USER
+# Additionally, some parameters are set as follows (without the quotes):
+#	CYGWIN to "nodosfilewarning"
+#	ENV to "/nonexistant"
+#	LANG to "C"
+#	__perlname to $^X (perlexe)
+# Any -e option arguments are added, or, if no equals sign is given, removed.
+# Each test's env-setup (see below) is processed in the same way affecting
+# the environment of that test. Finally, in the per-test environ, __progname
+# is set to the -p argument or (if -P) its first word.
 #
 # Format of test files:
 # - blank lines and lines starting with # are ignored
@@ -65,22 +78,12 @@
 #	perl-cleanup		m	Value is a perl script which is executed
 #					just after the test is run. Try to
 #					avoid using this...
-#	env-setup		M	Value is a list of NAME=VALUE elements
-#					which are put in the environment before
-#					the test is run. If the =VALUE is
-#					missing, NAME is removed from the
-#					environment. Programs are run with
-#					the following minimal environment:
-#					    HOME, LD_LIBRARY_PATH, LOCPATH,
-#					    LOGNAME, PATH, SHELL, UNIXMODE,
-#					    UNIXROOT, USER
-#					(values taken from the environment of
-#					the test harness).
-#					CYGWIN is set to nodosfilewarning.
-#					ENV is set to /nonexistant.
-#					__progname is set to the -p argument.
-#					__perlname is set to $^X (perlexe).
-#					@utflocale@ is substituted from -U.
+#	env-setup		M	Value is a list of elements that are
+#					removed from the per-test environment
+#					(if no equals sign present) or added
+#					to it if of the NAME=VALUE form, after
+#					substituting @utflocale@ for -U option.
+#					For more about test environ see above.
 #	file-setup		mps	Used to create files, directories
 #					and symlinks. First word is either
 #					file, dir or symlink; second word is
@@ -198,7 +201,7 @@ Usage: $prog [-Pv] [-C cat] [-e e=v] [-p
 		scanned for test files (which end in .t).
 	-T dir	Use dir instead of /tmp to hold temporary files
 	-t t	Use t as default time limit for tests (default is unlimited)
-	-U lcl	Use lcl as UTF-8 locale (e.g. C.UTF-8) instead of the default
+	-U lcl	Specify UTF-8 locale (e.g. en_US.UTF-8) instead of the default
 	-v	Verbose mode: print reason test failed.
 	name	specifies the name of the test(s) to run; if none are
 		specified, all tests are run.
@@ -259,7 +262,7 @@ $verbose = defined $opt_v && $opt_v;
 $is_ebcdic = defined $opt_E && $opt_E;
 $test_set = $opt_s;
 $temp_base = $opt_T || "/tmp";
-$utflocale = $opt_U || (($os eq "hpux") ? "en_US.utf8" : "en_US.UTF-8");
+$utflocale = $opt_U || (($os eq "hpux") ? "en_US.utf8" : ($os eq "darwin") ? "UTF-8" : "C.UTF-8");
 if (defined $opt_t) {
     die "$prog: bad -t argument (should be number > 0): $opt_t\n"
 	if $opt_t !~ /^\d+$/ || $opt_t <= 0;
@@ -297,23 +300,26 @@ foreach $env (('HOME', 'LD_LIBRARY_PATH'
 }
 $new_env{'CYGWIN'} = 'nodosfilewarning';
 $new_env{'ENV'} = '/nonexistant';
+$new_env{'LANG'} = 'C';
 
-if (($os eq 'VMS') || ($Config{perlpath} =~ m/$Config{_exe}$/i)) {
-	$new_env{'__perlname'} = $Config{perlpath};
-} else {
-	$new_env{'__perlname'} = $Config{perlpath} . $Config{_exe};
+$pn = $Config{perlpath};
+if ($pn ne '' and $os ne 'VMS' and $pn !~ m/$Config{_exe}$/i) {
+	$pn .= $Config{_exe};
+}
+if (($pn eq '' or ! -f $pn or ! -x $pn) and -f $^X and -x $^X) {
+	$pn = $^X;
 }
-$new_env{'__perlname'} = $^X if ($new_env{'__perlname'} eq '') and -f $^X and -x $^X;
-if ($new_env{'__perlname'} eq '') {
-	foreach $pathelt (split /:/,$ENV{'PATH'}) {
+if ($pn eq '' or ! -f $pn or ! -x $pn) {
+	foreach $pathelt (split /:/, $ENV{'PATH'}) {
 		chomp($pathelt = `pwd`) if $pathelt eq '';
 		my $x = $pathelt . '/' . $^X;
 		next unless -f $x and -x $x;
-		$new_env{'__perlname'} = $x;
+		$pn = $x;
 		last;
 	}
 }
-$new_env{'__perlname'} = $^X if ($new_env{'__perlname'} eq '');
+$pn = $^X if ($pn eq '');
+$new_env{'__perlname'} = $pn;
 
 if (defined $opt_e) {
     # XXX need a way to allow many -e arguments...
--- mksh-59c.orig/check.t
+++ mksh-59c/check.t
@@ -1,9 +1,9 @@
-# $MirOS: src/bin/mksh/check.t,v 1.853 2020/10/31 03:53:03 tg Exp $
+# $MirOS: src/bin/mksh/check.t,v 1.919 2025/02/18 23:30:35 tg Exp $
 # -*- mode: sh -*-
 #-
 # Copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
 #	      2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
-#	      2019, 2020
+#	      2019, 2020, 2021, 2022, 2023, 2024
 #	mirabilos <m@mirbsd.org>
 #
 # Provided that these terms and disclaimer and all copyright notices
@@ -31,7 +31,7 @@
 # (2013/12/02 20:39:44) http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/regress/bin/ksh/?sortby=date
 
 expected-stdout:
-	KSH R59 2020/10/31
+	KSH R59 2024/07/26
 description:
 	Check base version of full shell
 stdin:
@@ -136,8 +136,36 @@ stdin:
 	print '#!'"$__progname"'\necho tf' >lq
 	chmod +x lq
 	./lq
+	echo = $?
 expected-stdout:
 	tf
+	= 0
+---
+name: selftest-exec-perl
+description:
+	Ensure we can run perl scriptlets in tests as well
+stdin:
+	print '#!'"$__perlname"'\nprint 3x"3"."\\n";' >lq
+	chmod +x lq
+	./lq
+	echo = $?
+expected-stdout:
+	333
+	= 0
+---
+name: selftest-exec-a
+description:
+	Ensure using 'exec -a' to change argv[0] works
+file-setup: file 644 "pass"
+	print -r -- "fail, args:"
+	i=-1
+	for x in "$0" "$@"; do
+		print -r -- "$((++i))<$x>"
+	done
+stdin:
+	exec -a -print "$__progname" pass '\u20AC'
+expected-stdout:
+	pass €
 ---
 name: selftest-env
 description:
@@ -150,9 +178,8 @@ name: selftest-direct-builtin-call
 description:
 	Check that direct builtin calls work
 stdin:
-	ln -s "$__progname" cat || cp "$__progname" cat
-	ln -s "$__progname" echo || cp "$__progname" echo
-	./echo -c 'echo  foo' | ./cat -u
+	ln -s "$__progname" echo 2>/dev/null || cp "$__progname" echo
+	./echo -c 'echo  foo'
 expected-stdout:
 	-c echo  foo
 ---
@@ -176,6 +203,25 @@ stdin:
 expected-stdout:
 	;
 ---
+name: selftest-tools
+description:
+	Check that relevant tools work as expected. If not, e.g. on SerenityOS,
+	install better tools from ports and prepend /usr/local/bin to $PATH.
+stdin:
+	echo foobarbaz | grep bar
+	echo = $?
+	echo abc | sed y/ac/AC/
+	echo = $?
+	echo abc | tr ac AC
+	echo = $?
+expected-stdout:
+	foobarbaz
+	= 0
+	AbC
+	= 0
+	AbC
+	= 0
+---
 name: selftest-tty-absent
 description:
 	Check that a controlling tty is not present as regress:no-ctty was used
@@ -191,7 +237,7 @@ stdin:
 expected-stdout:
 	ok
 expected-stderr-pattern:
-	/ksh: warning: won't have full job control\nXX/
+	/^W: .*find tty fd.*\nW: .*have full job control\nXX$/
 ---
 name: selftest-tty-present
 description:
@@ -395,6 +441,21 @@ stdin:
 expected-stderr:
 	1
 ---
+name: arith-divnull
+description:
+	Check what happens if dividing by 0
+stdin:
+	echo 1 $((0 ? 2/0 : 666)) .
+	echo 2 $?
+	echo 3 $((1 ? 2/0 : 666)) .
+	echo 4 $?
+expected-stdout:
+	1 666 .
+	2 0
+expected-exit: e != 0
+expected-stderr-pattern:
+	/^[^\n]*: zero divisor$/
+---
 name: arith-lazy-1
 description:
 	Check that only one side of ternary operator is evaluated
@@ -566,7 +627,7 @@ expected-stderr-pattern:
 name: arith-div-intmin-by-minusone
 description:
 	Check division overflow wraps around silently
-category: int:32
+category: shell:legacy-no
 stdin:
 	echo signed:$((-2147483648 / -1))r$((-2147483648 % -1)).
 	echo unsigned:$((# -2147483648 / -1))r$((# -2147483648 % -1)).
@@ -574,17 +635,6 @@ expected-stdout:
 	signed:-2147483648r0.
 	unsigned:0r2147483648.
 ---
-name: arith-div-intmin-by-minusone-64
-description:
-	Check division overflow wraps around silently
-category: int:64
-stdin:
-	echo signed:$((-9223372036854775808 / -1))r$((-9223372036854775808 % -1)).
-	echo unsigned:$((# -9223372036854775808 / -1))r$((# -9223372036854775808 % -1)).
-expected-stdout:
-	signed:-9223372036854775808r0.
-	unsigned:0r9223372036854775808.
----
 name: arith-assop-assoc-1
 description:
 	Check associativity of assignment-operator operator
@@ -1402,10 +1452,10 @@ name: cd-pe
 description:
 	Check package for cd -Pe
 need-pass: no
-# the mv command fails on Cygwin and z/OS
+# the mv command fails on Cygwin, LynxOS 3.0, z/OS
 # Hurd aborts the testsuite (permission denied)
 # QNX does not find subdir to cd into
-category: !os:cygwin,!os:gnu,!os:midipix,!os:msys,!os:nto,!os:os390,!nosymlink
+category: !os:cygwin,!os:gnu,!os:lynxos,!os:midipix,!os:msys,!os:nto,!os:os390,!nosymlink
 file-setup: file 644 "x"
 	mkdir noread noread/target noread/target/subdir
 	ln -s noread link
@@ -1423,7 +1473,8 @@ file-setup: file 644 "x"
 	cd -P$1 subdir
 	echo 2=$?,${PWD#$bwd/}
 	cd $bwd
-	chmod 755 noread renamed 2>/dev/null
+	chmod 755 noread 2>/dev/null
+	chmod 755 renamed 2>/dev/null
 	rm -rf noread link renamed
 stdin:
 	export TSHELL="$__progname"
@@ -1447,14 +1498,13 @@ file-setup: file 644 "foo"
 	XXX=_
 	PS1=X
 	false && echo hmmm
-need-ctty: yes
 arguments: !-i!
 stdin:
 	echo hi${XXX}there
 expected-stdout:
 	hi_there
-expected-stderr: !
-	XX
+expected-stderr-pattern:
+	/^(?:W: [^\n]*(?:find tty fd|have full job control)[^\n]*\n)*XX$/
 ---
 name: expand-ugly
 description:
@@ -1933,6 +1983,8 @@ expected-stderr-pattern: /not set/
 name: expand-bang-2
 description:
 	Check corner case of ${!var} vs. ${var op} with var=!
+category: !nopiddependent
+time-limit: 15
 stdin:
 	echo 1 $! .
 	echo 2 ${!#} .
@@ -2012,7 +2064,7 @@ expected-stdout:
 name: eglob-bad-1
 description:
 	Check that globbing isn't done when glob has syntax error
-category: !os:cygwin,!os:midipix,!os:msys,!os:os2
+category: !os:cygwin,!os:lynxos,!os:midipix,!os:msys,!os:os2,!noweirdfilenames
 file-setup: file 644 "@(a[b|)c]foo"
 stdin:
 	echo @(a[b|)c]*
@@ -2473,18 +2525,21 @@ stdin:
 	echo [-ab]*
 	echo [!-ab]*
 	echo [!ab]*
+	echo [\!ab]*
 	echo []ab]*
 	echo [^ab]*
+	echo [\^ab]*
 	echo [+--]*
 	echo [--1]*
-
 expected-stdout:
 	-bc abc bbc
 	-bc abc bbc
 	!bc +bc ,bc 0bc 1bc ^bc cbc
 	!bc +bc ,bc -bc 0bc 1bc ^bc cbc
+	!bc abc bbc
 	abc bbc
 	^bc abc bbc
+	^bc abc bbc
 	+bc ,bc -bc
 	-bc 0bc 1bc
 ---
@@ -2504,7 +2559,7 @@ description:
 # breaks on Mac OSX (HFS+ non-standard UTF-8 canonical decomposition)
 # breaks on Cygwin 1.7 (files are now UTF-16 or something)
 # breaks on QNX 6.4.1 (says RT)
-category: !os:cygwin,!os:midipix,!os:darwin,!os:msys,!os:nto,!os:os2,!os:os390
+category: !os:cygwin,!os:midipix,!os:darwin,!os:msys,!os:nto,!os:os2,!os:os390,!noweirdfilenames
 need-pass: no
 file-setup: file 644 "ac"
 stdin:
@@ -3073,7 +3128,7 @@ description:
 	Check high-bit7 separators work
 stdin:
 	u=ä
-	tr a-z A-Z <<-…
+	tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ <<-…
 		m${u}h
 	…
 	echo ok
@@ -3430,23 +3485,23 @@ stdin:
 	# Background eval so main shell doesn't do parsing
 	eval '
 		foo() {
-			cat <<- EOF
-			hi
+			sed -e "s/^/N: /" -e "s/\\.[a-z]*\$//" <<-EOF
+			hi$1
 			EOF
 		}
-		foo
+		foo 1
 		# sleep so eval can die
-		(sleep 1; foo) &
-		(sleep 1; foo) &
-		foo
+		(sleep 1; foo 3.a) &
+		(sleep 1; foo 3.b) &
+		foo 2
 	    ' &
-	sleep 5
+	sleep 3
 	echo Left overs: *
 expected-stdout:
-	hi
-	hi
-	hi
-	hi
+	N: hi1
+	N: hi2
+	N: hi3
+	N: hi3
 	Left overs: *
 ---
 name: heredoc-quoting-unsubst
@@ -4144,7 +4199,7 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4168,7 +4223,7 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4200,7 +4255,7 @@ description:
 category: stdout-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4233,7 +4288,7 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4255,7 +4310,7 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4284,7 +4339,7 @@ description:
 category: !no-stderr-ed
 need-ctty: yes
 need-pass: no
-arguments: !-i!
+arguments: !-ie!
 env-setup: !ENV=./Env!HISTFILE=hist.file!
 file-setup: file 644 "Env"
 	PS1=X
@@ -4786,7 +4841,7 @@ description:
 	'emulate sh' zsh has extra fields in
 	- a5ins (IFS_NWS unquoted $*)
 	- b5ins, matching mksh’s
-	!!WARNING!! more to come: http://austingroupbugs.net/view.php?id=888
+	!!WARNING!! more to come: https://www.austingroupbugs.net/view.php?id=888
 stdin:
 	"$__progname" -c 'pfb() { for s_arg in "$@"; do print -r -- "[$s_arg]"; done; }; pfn() { for s_arg in "$@"; do print -r -- "<$s_arg>"; done; };
 		IFS=; set -- "" 2 ""; pfb $*; x=$*; pfn "$x"'
@@ -4936,7 +4991,7 @@ expected-stdout:
 ---
 name: IFS-subst-8
 description:
-	http://austingroupbugs.net/view.php?id=221
+	https://www.austingroupbugs.net/view.php?id=221
 stdin:
 	n() { echo "$#"; }; n "${foo-$@}"
 expected-stdout:
@@ -4996,7 +5051,7 @@ expected-stdout:
 ---
 name: IFS-arith-1
 description:
-	http://austingroupbugs.net/view.php?id=832
+	https://www.austingroupbugs.net/view.php?id=832
 stdin:
 	${ZSH_VERSION+false} || emulate sh
 	${BASH_VERSION+set -o posix}
@@ -5036,7 +5091,6 @@ description:
 	Syntax errors in expressions and effects on bases
 	(interactive so errors don't cause exits)
 	(ksh88 fails this test - shell exits, even with -i)
-need-ctty: yes
 arguments: !-i!
 stdin:
 	PS1= # minimise prompt hassles
@@ -5047,7 +5101,7 @@ stdin:
 	typeset -i2 a=2+
 	echo $a
 expected-stderr-pattern:
-	/^([#\$] )?.*:.*2+.*\n.*:.*2+.*\n$/
+	/^(?:W: [^\n]*(?:find tty fd|have full job control)[^\n]*\n)*([#\$] )?.*:.*2\+.*\n.*:.*2\+.*\n$/
 expected-stdout:
 	4#22
 	4#22
@@ -5264,48 +5318,47 @@ description:
 	Check behaviour for base two to 36, and that 37 degrades to 10
 stdin:
 	i=1
-	while (( ++i <= 37 )); do
-		eval 'echo '$i':$(('$i'#10)).'
+	while (( ++i <= 36 )); do
+		eval 'echo '$i':$(('$i'#100)).'
 	done
-	echo 37:$($__progname -c 'echo $((37#10))').$?:
+	echo 37:$($__progname -c 'echo $((37#100))').$?:
 expected-stdout:
-	2:2.
-	3:3.
-	4:4.
-	5:5.
-	6:6.
-	7:7.
-	8:8.
-	9:9.
-	10:10.
-	11:11.
-	12:12.
-	13:13.
-	14:14.
-	15:15.
-	16:16.
-	17:17.
-	18:18.
-	19:19.
-	20:20.
-	21:21.
-	22:22.
-	23:23.
-	24:24.
-	25:25.
-	26:26.
-	27:27.
-	28:28.
-	29:29.
-	30:30.
-	31:31.
-	32:32.
-	33:33.
-	34:34.
-	35:35.
-	36:36.
-	37:10.
-	37:10.0:
+	2:4.
+	3:9.
+	4:16.
+	5:25.
+	6:36.
+	7:49.
+	8:64.
+	9:81.
+	10:100.
+	11:121.
+	12:144.
+	13:169.
+	14:196.
+	15:225.
+	16:256.
+	17:289.
+	18:324.
+	19:361.
+	20:400.
+	21:441.
+	22:484.
+	23:529.
+	24:576.
+	25:625.
+	26:676.
+	27:729.
+	28:784.
+	29:841.
+	30:900.
+	31:961.
+	32:1024.
+	33:1089.
+	34:1156.
+	35:1225.
+	36:1296.
+	37:100.0:
 ---
 name: integer-base-check-numeric-to-1
 description:
@@ -5379,10 +5432,10 @@ expected-stdout:
 	36:36#1S.64.
 	37:64.64.
 ---
-name: integer-arithmetic-span
+name: integer-arithmetic-span-signed
 description:
 	Check wraparound and size that is defined in mksh
-category: int:32
+category: shell:legacy-no
 stdin:
 	echo s:$((2147483647+1)).$(((2147483647*2)+1)).$(((2147483647*2)+2)).
 	echo u:$((#2147483647+1)).$((#(2147483647*2)+1)).$((#(2147483647*2)+2)).
@@ -5390,15 +5443,22 @@ expected-stdout:
 	s:-2147483648.-1.0.
 	u:2147483648.4294967295.0.
 ---
+name: integer-arithmetic-span-32
+description:
+	Check unsigned wraparound and size that should also work in lksh
+category: int:32
+stdin:
+	echo u:$((#2147483647+1)).$((#(2147483647*2)+1)).$((#(2147483647*2)+2)).
+expected-stdout:
+	u:2147483648.4294967295.0.
+---
 name: integer-arithmetic-span-64
 description:
-	Check wraparound and size that is defined in mksh
+	Check unsigned wraparound and size that should also work in lksh
 category: int:64
 stdin:
-	echo s:$((9223372036854775807+1)).$(((9223372036854775807*2)+1)).$(((9223372036854775807*2)+2)).
 	echo u:$((#9223372036854775807+1)).$((#(9223372036854775807*2)+1)).$((#(9223372036854775807*2)+2)).
 expected-stdout:
-	s:-9223372036854775808.-1.0.
 	u:9223372036854775808.18446744073709551615.0.
 ---
 name: integer-size-FAIL-to-detect
@@ -5554,17 +5614,34 @@ stdin:
 	echo =1
 	trap "echo trap 2 executed" UNKNOWNSIGNAL EXIT 999999 FNORD
 	echo = $?
-	) 2>&1 | sed "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG"
+	) 2>&1 | sed \
+	    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG" \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG" \
+	    -e "s/bad signal '\\(.*\\)'\$/bad signal: \\1/"
 expected-stdout:
-	PROG: trap: bad signal 'UNKNOWNSIGNAL'
+	PROG: trap: bad signal: UNKNOWNSIGNAL
 	foo
 	=1
-	PROG: trap: bad signal 'UNKNOWNSIGNAL'
-	PROG: trap: bad signal '999999'
-	PROG: trap: bad signal 'FNORD'
+	PROG: trap: bad signal: UNKNOWNSIGNAL
+	PROG: trap: bad signal: 999999
+	PROG: trap: bad signal: FNORD
 	= 1
 	trap 2 executed
 ---
+name: uncatchable-trap
+description:
+	Ensure trying to trap SIGKILL is a nop (POSIX says undefined)
+stdin:
+	trap 'echo sighit $? .' KILL EXIT
+	"$__perlname" -e 'print $=.$/;'
+	echo meow $? .
+	(exit 7)
+expected-exit: 7
+expected-stdout:
+	60
+	meow 0 .
+	sighit 7 .
+---
 name: read-IFS-1
 description:
 	Simple test, default IFS
@@ -6173,6 +6250,8 @@ expected-stdout:
 name: regression-33
 description:
 	Does umask print a leading 0 when umask is 3 digits?
+# prints 0600…
+category: !os:skyos
 stdin:
 	# on MiNT, the first umask call seems to fail
 	umask 022
@@ -6184,7 +6263,7 @@ expected-stdout:
 ---
 name: regression-35
 description:
-	Temporay files used for here-docs in functions get trashed after
+	Temporary files used for heredocs in functions get trashed after
 	the function is parsed (before it is executed)
 stdin:
 	f1() {
@@ -6228,8 +6307,8 @@ description:
 	Machines with broken times() (reported by <sjg@void.zen.oz.au>)
 	time does not report correct real time
 stdin:
-	time sleep 1
-expected-stderr-pattern: !/^\s*0\.0[\s\d]+real|^\s*real[\s]+0+\.0/
+	time -p sleep 1
+expected-stderr-pattern: /^real +(?![0.]*$)[0-9]+(?:\.[0-9]+)?$/m
 ---
 name: regression-38
 description:
@@ -6279,7 +6358,7 @@ expected-stdout:
 ---
 name: regression-42
 description:
-	Can't use command line assignments to assign readonly parameters.
+	Can't use command line assignments to assign read-only parameters.
 stdin:
 	print '#!'"$__progname"'\nunset RANDOM\nexport | while IFS= read -r' \
 	    'RANDOM; do eval '\''print -r -- "$RANDOM=$'\''"$RANDOM"'\'\"\'\; \
@@ -6728,7 +6807,7 @@ stdin:
 		echo FNORD-7
 		typeset -
 		echo FNORD-8
-	} | fgrep FNORD
+	} | grep FNORD
 	fnord=(42 23)
 	typeset -p fnord
 	echo FNORD-9
@@ -6799,19 +6878,6 @@ stdin:
 		time
 	}
 ---
-name: regression-65
-description:
-	check for a regression with sleep builtin and signal mask
-category: !nojsig
-time-limit: 5
-stdin:
-	sleep 1
-	echo blub |&
-	while read -p line; do :; done
-	echo ok
-expected-stdout:
-	ok
----
 name: regression-66
 description:
 	Check that quoting is sane
@@ -6861,17 +6927,17 @@ stdin:
 	echo 13 $(( a &= 4 )) .
 	echo 14 $(( a ^= a )) .
 	echo 15 $(( a |= 5 )) .
-	echo 16 $(( 5 << 1 )) .
-	echo 17 $(( 5 >> 1 )) .
+	echo 16 $(( 5 << 1 )) , $(( 5 << 0 )) .
+	echo 17 $(( 5 >> 1 )) , $(( 5 >> 0 )) .
 	echo 18 $(( 5 <= 6 )) , $(( 5 <= 5 )) , $(( 5 <= 4 )) .
 	echo 19 $(( 5 >= 6 )) , $(( 5 >= 5 )) , $(( 5 >= 4 )) .
 	echo 20 $(( 5 < 6 )) , $(( 5 < 5 )) , $(( 5 < 4 )) .
 	echo 21 $(( 5 > 6 )) , $(( 5 > 5 )) , $(( 5 > 4 )) .
 	echo 22 $(( 0 && 0 )) , $(( 0 && 1 )) , $(( 1 && 0 )) , $(( 1 && 1 )) .
 	echo 23 $(( 0 || 0 )) , $(( 0 || 1 )) , $(( 1 || 0 )) , $(( 1 || 1 )) .
-	echo 24 $(( 5 * 3 )) .
+	echo 24 $(( 5 * 3 )) , $(( 5 * 0 )) .
 	echo 25 $(( 7 / 2 )) .
-	echo 26 $(( 5 % 5 )) , $(( 5 % 4 )) , $(( 5 % 1 )) , $(( 5 % -1 )) , $(( 5 % -2 )) .
+	echo 26 $(( 5 % 5 )) , $(( 5 % 4 )) , $(( 5 % 1 )) :
 	echo 27 $(( 5 + 2 )) , $(( 5 + 0 )) , $(( 5 + -2 )) .
 	echo 28 $(( 5 - 2 )) , $(( 5 - 0 )) , $(( 5 - -2 )) .
 	echo 29 $(( 6 & 4 )) , $(( 6 & 8 )) .
@@ -6898,17 +6964,17 @@ expected-stdout:
 	13 4 .
 	14 0 .
 	15 5 .
-	16 10 .
-	17 2 .
+	16 10 , 5 .
+	17 2 , 5 .
 	18 1 , 1 , 0 .
 	19 0 , 1 , 1 .
 	20 1 , 0 , 0 .
 	21 0 , 0 , 1 .
 	22 0 , 0 , 0 , 1 .
 	23 0 , 1 , 1 , 1 .
-	24 15 .
+	24 15 , 0 .
 	25 3 .
-	26 0 , 1 , 0 , 0 , 1 .
+	26 0 , 1 , 0 :
 	27 7 , 5 , 3 .
 	28 3 , 5 , 7 .
 	29 4 , 0 .
@@ -6920,6 +6986,15 @@ expected-stdout:
 	35 1 , 0 , 1 , 1 .
 	36 5 .
 ---
+name: regression-68-nolksh
+description:
+	Things POSIX/C arithmetics don’t guarantee
+category: shell:legacy-no
+stdin:
+	echo '1(26)' , $(( 5 % -1 )) , $(( 5 % -2 )) .
+expected-stdout:
+	1(26) , 0 , 1 .
+---
 name: regression-69
 description:
 	Check that all non-lksh arithmetic operators work as expected
@@ -6928,13 +7003,15 @@ stdin:
 	a=5 b=0x80000005
 	echo 1 $(( a ^<= 1 )) , $(( b ^<= 1 )) .
 	echo 2 $(( a ^>= 2 )) , $(( b ^>= 2 )) .
-	echo 3 $(( 5 ^< 1 )) .
-	echo 4 $(( 5 ^> 1 )) .
+	echo 3 $(( 5 ^< 1 )) , $(( 5 ^< 0 )) .
+	echo 4 $(( 5 ^> 1 )) , $((# 5 ^> 1 )) .
+	echo 5 $(( 5 ^> 0 )) , $((# 5 ^> 0 )) .
 expected-stdout:
 	1 10 , 11 .
 	2 -2147483646 , -1073741822 .
-	3 10 .
-	4 -2147483646 .
+	3 10 , 5 .
+	4 -2147483646 , 2147483650 .
+	5 5 , 5 .
 ---
 name: export-1
 description:
@@ -6971,7 +7048,7 @@ expected-stderr-pattern:
 ---
 name: readonly-1
 description:
-	http://austingroupbugs.net/view.php?id=367 for export
+	https://www.austingroupbugs.net/view.php?id=367 for export
 stdin:
 	"$__progname" -c 'readonly foo; export foo=a; echo $?' || echo aborted, $?
 expected-stdout:
@@ -6990,7 +7067,7 @@ expected-stdout:
 ---
 name: readonly-2b
 description:
-	http://austingroupbugs.net/view.php?id=367 for getopts
+	https://www.austingroupbugs.net/view.php?id=367 for getopts
 stdin:
 	"$__progname" -c 'readonly c; set -- -a b; getopts a c; echo $? $c .' || echo aborted, $?
 expected-stdout:
@@ -7000,7 +7077,7 @@ expected-stderr-pattern:
 ---
 name: readonly-3
 description:
-	http://austingroupbugs.net/view.php?id=367 for read
+	https://www.austingroupbugs.net/view.php?id=367 for read
 stdin:
 	echo x | "$__progname" -c 'read s; echo $? $s .' || echo aborted, $?
 	echo y | "$__progname" -c 'readonly s; read s; echo $? $s .' || echo aborted, $?
@@ -7130,7 +7207,7 @@ expected-stdout:
 ---
 name: xxx-exec-environment-1
 description:
-	Check to see if exec sets it's environment correctly
+	Check to see if exec sets its environment correctly
 stdin:
 	print '#!'"$__progname"'\nunset RANDOM\nexport | while IFS= read -r' \
 	    'RANDOM; do eval '\''print -r -- "$RANDOM=$'\''"$RANDOM"'\'\"\'\; \
@@ -7162,47 +7239,73 @@ expected-stdout:
 	y1-
 	x-3- z-
 ---
-name: exec-modern-korn-shell
+name: exec-execs
+description:
+	Ensure that exec never returns
+need-ctty: yes
+env-setup: !ENV=./envf!
+file-setup: file 644 "envf"
+	PS1=X
+arguments: !-i!
+stdin:
+	oldPATH=$PATH
+	PATH=$PWD
+	exec bla
+	PATH=$oldPATH
+	echo fail
+expected-stderr-pattern:
+	/X+.*: bla: (?:inaccessible or )?not found\n/
+expected-exit: 127
+---
+name: exec-modern
 description:
 	Check that exec can execute any command that makes it
 	through syntax and parser
 stdin:
-	print '#!'"$__progname"'\necho tf' >lq
-	chmod +x lq
+	echo '#!'"$__progname" >f
+	echo 'echo >&3 FAIL' >>f
+	echo '#!'"$__progname" >lq
+	echo 'echo tf' >>lq
+	chmod +x lq f
 	PATH=$PWD
-	exec 2>&1
-	foo() { print two; }
-	print =1
-	(exec print one)
-	print =2
-	(exec foo)
-	print =3
-	(exec ls)
-	print =4
-	(exec lq)
+	exec 3>&2 2>&1
+	foo() { echo two; }
+	echo =1
+	(exec echo one; ./f)
+	echo =2
+	(exec foo; ./f)
+	echo =3
+	(exec ls; ./f)
+	echo =4
+	(exec lq; ./f)
 expected-stdout-pattern:
-	/=1\none\n=2\ntwo\n=3\n.*: ls: inaccessible or not found\n=4\ntf\n/
+	/=1\none\n=2\ntwo\n=3\n.*: ls: (?:inaccessible or )?not found\n=4\ntf\n/
 ---
 name: exec-ksh88
 description:
 	Check that exec only executes after a PATH search
+	(POSIX Issue 8 uses utility ipv command for the synopsis)
+	cf. https://www.austingroupbugs.net/view.php?id=1157
 arguments: !-o!posix!
 stdin:
-	print '#!'"$__progname"'\necho tf' >lq
-	chmod +x lq
+	echo '#!'"$__progname" >f
+	echo 'echo >&3 FAIL' >>f
+	echo '#!'"$__progname" >lq
+	echo 'echo tf' >>lq
+	chmod +x lq f
 	PATH=$PWD
-	exec 2>&1
-	foo() { print two; }
-	print =1
-	(exec print one)
-	print =2
-	(exec foo)
-	print =3
-	(exec ls)
-	print =4
-	(exec lq)
+	exec 3>&2 2>&1
+	foo() { echo two; }
+	echo =1
+	(exec echo one; ./f)
+	echo =2
+	(exec foo; ./f)
+	echo =3
+	(exec ls; ./f)
+	echo =4
+	(exec lq; ./f)
 expected-stdout-pattern:
-	/=1\n.*: print: inaccessible or not found\n=2\n.*: foo: inaccessible or not found\n=3\n.*: ls: inaccessible or not found\n=4\ntf\n/
+	/=1\n.*: echo: (?:inaccessible or )?not found\n=2\n.*: foo: (?:inaccessible or )?not found\n=3\n.*: ls: (?:inaccessible or )?not found\n=4\ntf\n/
 ---
 name: xxx-what-do-you-call-this-1
 stdin:
@@ -7339,7 +7442,7 @@ need-ctty: yes
 arguments: !-i!
 stdin:
 	exec echo hi
-	echo still herre
+	echo still here
 expected-stdout:
 	hi
 expected-stderr-pattern: /.*/
@@ -7470,19 +7573,26 @@ name: xxx-param-subst-qmark-namespec
 description:
 	Check special names are output correctly
 stdin:
+	prgsub() {
+		sed \
+		    -e "s^${__progname%.exe}\.*e*x*e*: PROG: " \
+		    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: PROG: " \
+		    -e 's/^qmark_foo: /E: &/' \
+		    -e "s/^/$1: /g"
+	}
 	doit() {
 		"$__progname" -c "$@" >o1 2>o2
 		rv=$?
 		echo RETVAL: $rv
-		sed -e "s^${__progname%.exe}\.*e*x*e*: PROG: " -e 's/^/STDOUT: /g' <o1
-		sed -e "s^${__progname%.exe}\.*e*x*e*: PROG: " -e 's/^/STDERR: /g' <o2
+		prgsub STDOUT <o1
+		prgsub STDERR <o2
 	}
 	doit 'echo ${1x}'
 	doit 'echo "${1x}"'
 	doit 'echo ${1?}'
 	doit 'echo ${19?}'
 	doit 'echo ${!:?}'
-	doit -u 'echo ${*:?}' foo ""
+	doit -u 'echo ${*:?}' qmark_foo ""
 expected-stdout:
 	RETVAL: 1
 	STDERR: PROG: ${1x}: bad substitution
@@ -7495,7 +7605,7 @@ expected-stdout:
 	RETVAL: 1
 	STDERR: PROG: !: parameter null or not set
 	RETVAL: 1
-	STDERR: foo: ${*:?}: bad substitution
+	STDERR: E: qmark_foo: ${*:?}: bad substitution
 ---
 name: xxx-param-_-1
 # fails due to weirdness of execv stuff
@@ -7827,25 +7937,35 @@ expected-stdout:
 ---
 name: exit-enoent-1
 description:
-	SUSv4 says that the shell should exit with 126/127 in some situations
+	SUSv4 says that the shell should exit with 127 in some situations
 stdin:
-	i=0
 	(echo; echo :) >x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo 0 $r .
 	echo exit 42 >x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo 42 $r .
 	rm -f x
-	"$__progname" ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
-	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo $((i++)) $r .
+	"$__progname" ./x >/dev/null 2>&1; r=$?; echo notexist $r .
 expected-stdout:
 	0 0 .
-	1 126 .
-	2 42 .
-	3 126 .
-	4 127 .
-	5 127 .
+	42 42 .
+	notexist 127 .
+---
+name: exit-enoent-2
+description:
+	SUSv4 says that the shell should exit with 126 in some situations
+# fails because x permissions handled wrong
+category: !os:skyos,!noxperms
+stdin:
+	(echo; echo :) >x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo 0 $r .
+	echo exit 42 >x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo 42 $r .
+	rm -f x
+	"$__progname" -c ./x >/dev/null 2>&1; r=$?; echo notexist $r .
+expected-stdout:
+	0 126 .
+	42 126 .
+	notexist 127 .
 ---
 name: exit-eval-1
 description:
@@ -7884,6 +8004,80 @@ expected-stdout:
 	G 12
 	H 0
 ---
+name: exit-stdout-1
+description:
+	cf. https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=990265, Austin ML
+# SIGPIPE seems hosed on BeOS and SkyOS
+category: !os:beos,!os:skyos
+stdin:
+	if test -c /dev/full && test -w /dev/full; then
+		if pwd >/dev/full 2>e; then
+			cat e
+			echo fail
+		else
+			echo pass
+		fi
+	else
+		echo skip
+	fi
+	case " $(echo $( (set -o posix) >/dev/null 2>&1 && set -o posix >/dev/null 2>&1; kill -l)) " in
+	(*' PIPE '*)
+		:>s
+		{ trap '' PIPE; sleep 1; pwd 2>e; echo $? >s; } | :
+		case x$(cat s) in
+		(x)
+			cat e
+			echo fail else ;;
+		(x0)
+			cat e
+			echo fail 0 ;;
+		(*)
+			echo pass ;;
+		esac
+		;;
+	(*)
+		echo skip ;;
+	esac
+expected-stdout-pattern:
+	/^(pass|skip)\n(pass|skip)\n$/
+---
+name: exit-stdout-2
+description:
+	same, except for external utility / direct builtin call
+category: !os:beos,!os:skyos
+stdin:
+	ln -s "$__progname" pwd 2>/dev/null || cp "$__progname" pwd
+	if test -c /dev/full && test -w /dev/full; then
+		if ./pwd >/dev/full 2>e; then
+			cat e
+			echo fail
+		else
+			echo pass
+		fi
+	else
+		echo skip
+	fi
+	case " $(echo $( (set -o posix) >/dev/null 2>&1 && set -o posix >/dev/null 2>&1; kill -l)) " in
+	(*' PIPE '*)
+		:>s
+		{ trap '' PIPE; sleep 1; ./pwd 2>e; echo $? >s; } | :
+		case x$(cat s) in
+		(x)
+			cat e
+			echo fail else ;;
+		(x0)
+			cat e
+			echo fail 0 ;;
+		(*)
+			echo pass ;;
+		esac
+		;;
+	(*)
+		echo skip ;;
+	esac
+expected-stdout-pattern:
+	/^(pass|skip)\n(pass|skip)\n$/
+---
 name: exit-trap-1
 description:
 	Check that "exit" with no arguments behaves SUSv4 conformant.
@@ -7899,7 +8093,7 @@ description:
 	Check that ERR and EXIT traps are run just like GNU bash does.
 	ksh93 runs ERtrap after “parameter null or not set” (which mksh
 	used to do) but (bug) continues “and out”, exit 0, in +e eval-undef.
-file-setup: file 644 "x"
+file-setup: file 644 "xe"
 	v=; unset v
 	trap 'echo EXtrap' EXIT
 	trap 'echo ERtrap' ERR
@@ -7940,15 +8134,16 @@ stdin:
 		) 2>&1 | sed \
 		    -e 's/parameter not set/parameter null or not set/' \
 		    -e 's/[[]6]//' -e 's/: eval: line 1//' -e 's/: line 6//' \
+		    -e 's/^x[etfu]: /E: &/' \
 		    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROG"
 	}
 	xe=-e
 	echo : $xe
-	runtest x $xe true
+	runtest xe $xe true
 	echo = eval-true $(<rc) .
-	runtest x $xe false
+	runtest xe $xe false
 	echo = eval-false $(<rc) .
-	runtest x $xe '${v?}'
+	runtest xe $xe '${v?}'
 	echo = eval-undef $(<rc) .
 	runtest xt $xe
 	echo = noeval-true $(<rc) .
@@ -7958,11 +8153,11 @@ stdin:
 	echo = noeval-undef $(<rc) .
 	xe=+e
 	echo : $xe
-	runtest x $xe true
+	runtest xe $xe true
 	echo = eval-true $(<rc) .
-	runtest x $xe false
+	runtest xe $xe false
 	echo = eval-false $(<rc) .
-	runtest x $xe '${v?}'
+	runtest xe $xe '${v?}'
 	echo = eval-undef $(<rc) .
 	runtest xt $xe
 	echo = noeval-true $(<rc) .
@@ -7981,7 +8176,7 @@ expected-stdout:
 	EXtrap
 	= eval-false 1 .
 	and run ${v?}
-	x: v: parameter null or not set
+	E: xe: v: parameter null or not set
 	EXtrap
 	= eval-undef 1 .
 	and run true
@@ -7993,7 +8188,7 @@ expected-stdout:
 	EXtrap
 	= noeval-false 1 .
 	and run ${v?}
-	xu: v: parameter null or not set
+	E: xu: v: parameter null or not set
 	EXtrap
 	= noeval-undef 1 .
 	: +e
@@ -8008,7 +8203,7 @@ expected-stdout:
 	EXtrap
 	= eval-false 0 .
 	and run ${v?}
-	x: v: parameter null or not set
+	E: xe: v: parameter null or not set
 	EXtrap
 	= eval-undef 1 .
 	and run true
@@ -8021,7 +8216,7 @@ expected-stdout:
 	EXtrap
 	= noeval-false 0 .
 	and run ${v?}
-	xu: v: parameter null or not set
+	E: xu: v: parameter null or not set
 	EXtrap
 	= noeval-undef 1 .
 ---
@@ -8474,7 +8669,7 @@ stdin:
 	[[ -o !sh ]] && echo nosh
 	[[ -o braceexpand ]] && echo brex
 	[[ -o !braceexpand ]] && echo nobrex
-	[[ $(exec -a -set "$__progname" -o) = *login+(' ')on* ]]; echo $?
+	:
 expected-stdout:
 	nosh
 	brex
@@ -8487,6 +8682,15 @@ expected-stdout:
 	a b c
 	sh
 	brex
+---
+name: sh-mode-1-exec-a
+description:
+	Was part of sh-mode-1 but exclude where selftest-exec-a fails
+	or better fix that
+category: !os:beos
+stdin:
+	[[ $(exec -a -set "$__progname" -o) = *login+(' ')on* ]]; echo $?
+expected-stdout:
 	0
 ---
 name: sh-mode-2a
@@ -8495,7 +8699,7 @@ description:
 category: !binsh
 stdin:
 	for shell in {,-}{,r}{,k,mk}sh {,-}{,R}{,K,MK}SH.EXE; do
-		ln -s "$__progname" ./$shell || cp "$__progname" ./$shell
+		ln -s "$__progname" ./$shell 2>/dev/null || cp "$__progname" ./$shell
 		print -- $shell $(./$shell +l -c '
 			[[ -o sh || -o posix ]] && echo sh
 			[[ -o !sh && -o !posix ]] && echo nosh
@@ -8534,7 +8738,7 @@ description:
 category: binsh
 stdin:
 	for shell in {,-}{,r}{,k,mk}sh {,-}{,R}{,K,MK}SH.EXE; do
-		ln -s "$__progname" ./$shell || cp "$__progname" ./$shell
+		ln -s "$__progname" ./$shell 2>/dev/null || cp "$__progname" ./$shell
 		print -- $shell $(./$shell +l -c '
 			[[ -o sh || -o posix ]] && echo sh
 			[[ -o !sh && -o !posix ]] && echo nosh
@@ -8641,8 +8845,8 @@ stdin:
 	(echo x; exit 12) | (cat; exit 23) | (cat; exit 42)
 	echo 5 $? , $PIPESTATUS , ${PIPESTATUS[0]} , ${PIPESTATUS[1]} , ${PIPESTATUS[2]} , ${PIPESTATUS[3]} .
 	echo 6 ${PIPESTATUS[0]} .
-	set | fgrep PIPESTATUS
-	echo 8 $(set | fgrep PIPESTATUS) .
+	set | grep PIPESTATUS
+	echo 8 $(set | grep PIPESTATUS) .
 expected-stdout:
 	1 0 .
 	2 0 .
@@ -8792,13 +8996,46 @@ expected-stdout:
 	<12345678910 345678920
 	<               .  aẞ> 2)
 ---
+name: typeset-unset
+description:
+	Check that typeset -p correctly distinguishes unset and empty
+stdin:
+	unset u
+	typeset -p u
+	echo 1 ${u-a} ${u:-b} .
+	x1=$(typeset -p u)
+	export u
+	typeset -p u
+	echo 2 ${u-a} ${u:-b} .
+	x2=$(typeset -p u)
+	u=
+	typeset -p u
+	echo 3 ${u-a} ${u:-b} .
+	x3=$(typeset -p u)
+	unset u
+	eval "$x1"
+	echo 4 ${u-a} ${u:-b} .
+	unset u
+	eval "$x2"
+	echo 5 ${u-a} ${u:-b} .
+	unset u
+	eval "$x3"
+	echo 6 ${u-a} ${u:-b} .
+expected-stdout:
+	1 a b .
+	typeset -x u
+	2 a b .
+	typeset -x u=''
+	3 b .
+	4 a b .
+	5 a b .
+	6 b .
+---
 name: utf8bom-1
 description:
-	Check that the UTF-8 Byte Order Mark is ignored as the first
-	multibyte character of the shell input (with -c, from standard
-	input, as file, or as eval argument), but nowhere else
+	Check that the UTF-8 Byte Order Mark is not ignored any more
 # breaks on Mac OSX (HFS+ non-standard UTF-8 canonical decomposition)
-category: !os:darwin,!shell:ebcdic-yes
+category: !os:darwin,!shell:ebcdic-yes,!noweirdfilenames
 stdin:
 	mkdir foo
 	print '#!/bin/sh\necho ohne' >foo/fnord
@@ -8823,33 +9060,33 @@ stdin:
 	rm -rf foo
 expected-stdout:
 	got 4 files
-	ohne
+	mit
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	ohne
+	mit
 	ohne
 	mit
 	ohne
 	=
-	﻿: ohne
+	﻿: mit
 ---
 name: utf8bom-2
 description:
-	Check that we can execute BOM-shebangs (failures not fatal)
+	Check that we cannot any more execute BOM-shebangs (failures not fatal)
 	XXX if the OS can already execute them, we lose
 	note: cygwin execve(2) doesn't return to us with ENOEXEC, we lose
 	note: Ultrix perl5 t4 returns 65280 (exit-code 255) and no text
@@ -8868,17 +9105,17 @@ stdin:
 	./t2
 	./t3
 	./t4
+	echo .
 expected-stdout:
 	1 a=/nonexistant{FOO}
-	2 a=/nonexistant{FOO}
 	3 a=BAR
-	4 a=BAR
+	.
 expected-stderr-pattern:
-	/(Unrecognized character .... ignored at \..t4 line 1)*/
+	/t2: not executable: magic EFBB.*\n.*t4: not executable: magic EFBB/
 ---
 name: utf8opt-1
 description:
-	Check that the utf8-mode flag is not set at non-interactive startup
+	Check that the utf8-mode flag *is* set at non-interactive startup
 env-setup: !PS1=!PS2=!LC_CTYPE=@utflocale@!
 stdin:
 	if [[ $- = *U* ]]; then
@@ -8887,12 +9124,12 @@ stdin:
 		echo is not set
 	fi
 expected-stdout:
-	is not set
+	is set
 ---
 name: utf8opt-2
 description:
 	Check that the utf8-mode flag is set at interactive startup.
-	If your OS is old, try passing HAVE_SETLOCALE_CTYPE=0 to Build.sh
+	If your OS is old and fails this, contact the mksh developer.
 need-pass: no
 category: !noutf8
 need-ctty: yes
@@ -9886,13 +10123,23 @@ name: varexpand-special-hash
 description:
 	Check special ${var@x} expansion for x=hash
 category: !shell:ebcdic-yes
+perl-setup: open XF,">xf" or die; print XF "a"x1000000 or die; close XF or die;
 stdin:
 	typeset -i8 foo=10
 	bar=baz
 	unset baz
 	print ${foo@#} ${bar@#} ${baz@#} .
+	set -e
+	set -A vec -- '' a abc 'message digest' abcdefghijklmnopqrstuvwxyz \
+	    abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq \
+	    ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 \
+	    12345678901234567890123456789012345678901234567890123456789012345678901234567890 \
+	    $(<xf)
+	print ${vec[0]@#} ${vec[1]@#} ${vec[2]@#} ${vec[3]@#} ${vec[4]@#} \
+	    ${vec[5]@#} ${vec[6]@#} ${vec[7]@#} ${vec[8]@#} .
 expected-stdout:
-	9B15FBFB CFBDD32B 00000000 .
+	D2F7C7B5 FE93FA63 03010102 .
+	03010102 4ACF470E 92FC2A8B E5030FFA ED69F029 9C0E532B C155BDD9 BE5117B7 2A9728CB .
 ---
 name: varexpand-special-hash-ebcdic
 description:
@@ -9904,12 +10151,11 @@ stdin:
 	unset baz
 	print ${foo@#} ${bar@#} ${baz@#} .
 expected-stdout:
-	016AE33D 9769C4AF 00000000 .
+	7819D62A E1FC0712 00000000 .
 ---
 name: varexpand-special-quote
 description:
 	Check special ${var@Q} expansion for quoted strings
-category: !shell:faux-ebcdic
 stdin:
 	set +U
 	i=x
@@ -9921,36 +10167,46 @@ stdin:
 	print -r -- "s=\"$s\""
 	eval "$s"
 	typeset -p u v w
+	set -o asis
+	typeset -p w
+	set -U
+	typeset -p w
 expected-stdout:
 	<i=x j=a b k=c
 	de€f>
-	s="u=x v='a b' w=$'c\nd\240e\u20ACf'"
+	s="u=x v='a b' w=$'c\nde\202f'"
 	typeset u=x
 	typeset v='a b'
-	typeset w=$'c\nd\240e\u20ACf'
+	typeset w=$'c\nde\202f'
+	typeset w=$'c\nde€f'
+	typeset w=$'c\nd\240e€f'
 ---
-name: varexpand-special-quote-faux-EBCDIC
+name: varexpand-special-caret
 description:
-	Check special ${var@Q} expansion for quoted strings
-category: shell:faux-ebcdic
+	Check special ${var@^} expansion for quoted strings
 stdin:
-	set +U
-	i=x
-	j=a\ b
-	k=$'c
-	d\xA0''e€f'
-	print -r -- "<i=$i j=$j k=$k>"
-	s="u=${i@Q} v=${j@Q} w=${k@Q}"
-	print -r -- "s=\"$s\""
-	eval "$s"
-	typeset -p u v w
-expected-stdout:
-	<i=x j=a b k=c
-	de€f>
-	s="u=x v='a b' w=$'c\nde\u20ACf'"
-	typeset u=x
-	typeset v='a b'
-	typeset w=$'c\nde\u20ACf'
+	if (( 1#1 == 49 )); then
+		CSI=$'\x9B'	# ISO-8859-1
+	else
+		CSI=$'\x3B'	# EBCDIC
+	fi
+	s=$'a\cbc d\te f\c?g h'$CSI$'0mi j\u009B''0mk l^m\n'
+	set +U +o asis
+	# this works because check.t is iconv’d to EBCDIC copying to OS/390
+	print -r -- "raw <$s> ."
+	print -r -- "Ai <${s@^}> ."
+	set -o asis
+	print -r -- "Aa <${s@^}> ."
+	set -U +o asis
+	print -r -- "Ui <${s@^}> ."
+	set -o asis
+	print -r -- "Ua <${s@^}> ."
+expected-stdout:
+	raw <ac d	e fg h0mi j0mk l^m\n> .
+	Ai <a^Bc d^Ie f^?g h^![0mi j^![0mk l\^m\\n> .
+	Aa <a^Bc d^Ie f^?g h0mi j0mk l\^m\\n> .
+	Ui <a^Bc d^Ie f^?g h\x9B0mi j^+[0mk l\^m\\n> .
+	Ua <a^Bc d^Ie f^?g h\x9B0mi j^+[0mk l\^m\\n> .
 ---
 name: varexpand-null-1
 description:
@@ -10027,7 +10283,6 @@ expected-stdout:
 name: varexpand-funny-chars
 description:
 	Check some characters
-	XXX \uEF80 is asymmetric, possibly buggy so we don’t check this
 stdin:
 	x=$'<\x00>'; typeset -p x
 	x=$'<\x01>'; typeset -p x
@@ -10105,6 +10360,9 @@ stdin:
 	./foo | while IFS= read -r line; do
 		print -r -- "{$line}"
 	done
+	print -n -- '<220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT\r>\n<220->> Bitte keine Werbung einwerfen! <<\r\r>\n<220 Who do you wanna pretend to be today'
+	print -n \?
+	print \>
 expected-stdout:
 	[220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
 	220->> Bitte keine Werbung einwerfen! <<

@@ -10112,6 +10370,9 @@ expected-stdout:
 	{220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
}
 	{220->> Bitte keine Werbung einwerfen! <<

}
 	{220 Who do you wanna pretend to be today?
}
+	<220-blau.mirbsd.org ESMTP ready at Thu, 25 Jul 2013 15:57:57 GMT
>
+	<220->> Bitte keine Werbung einwerfen! <<

>
+	<220 Who do you wanna pretend to be today?
>
 ---
 name: print-crlf
 description:
@@ -10407,6 +10668,18 @@ stdin:
 expected-stdout:
 	1 0 .
 ---
+name: dot-args
+description:
+	Ensure dot can take arguments
+file-setup: file 644 "t"
+	print -r -- "$#,${1-},${2-},${3-}"
+stdin:
+	"$__progname" -c '. ./t a b'
+	"$__progname" -c 'source t c d'
+expected-stdout:
+	2,a,b,
+	2,c,d,
+---
 name: alias-function-no-conflict
 description:
 	make aliases not conflict with function definitions
@@ -10709,11 +10982,14 @@ stdin:
 			lpos=0
 			while (( lpos < ${#line} )); do
 				wc=1#${line:(lpos++):1}
+				let hv=wc
 				if (( (wc < 32) || \
 				    ((wc > 126) && (wc < 160)) )); then
 					dch=.
-				elif (( (wc & 0xFF80) == 0xEF80 )); then
+				elif (( (wc & ~0x7F) == 0xEF80 )); then
 					dch=�
+					# OPTU-8 value mapping, to keep test
+					#(( hv = 0xEF80 | (hv & 0x7F) ))
 				else
 					dch=${wc#1#}
 				fi
@@ -10725,7 +11001,6 @@ stdin:
 					print -n "${pos#16#}  "
 					dasc=' |'
 				fi
-				let hv=wc
 				print -n "${hv#16#} "
 				(( (pos++ & 7) == 3 )) && \
 				    print -n -- '- '
@@ -10876,8 +11151,10 @@ stdin:
 				if (( (hv < 32) || \
 				    ((hv > 126) && (hv < 160)) )); then
 					dch=.
-				elif (( (hv & 0xFF80) == 0xEF80 )); then
+				elif (( (hv & ~0x7F) == 0xEF80 )); then
 					dch=�
+					# OPTU-8 value mapping, to keep test
+					#(( hv = 0xEF80 | (hv & 0x7F) ))
 				else
 					dch=${line[i-1]#1#}
 				fi
@@ -11103,11 +11380,11 @@ stdin:
 		echo tri >&3
 	}
 	threeout &>foo
-	echo ===
+	echo === "$("$__progname" -c "echo $(: &>/dev/null) ok")"
 	cat foo
 expected-stdout:
 	tri
-	===
+	=== ok
 	ras
 	dwa
 ---
@@ -11193,7 +11470,7 @@ stdin:
 expected-stdout:
 	===
 	mir
-expected-stderr-pattern: /.*: can't (create|overwrite) .*/
+expected-stderr-pattern: /.*: foo: (create: |cannot overwrite existing file).*/
 ---
 name: bashiop-3b
 description:
@@ -11416,6 +11693,20 @@ description:
 stdin:
 	set foo bar baz ; for out in ; do echo $out ; done
 ---
+name: for-without-list
+description:
+	LP#2002250
+stdin:
+	set -- a b
+	for x
+	do
+		echo $x
+		shift $#
+	done
+expected-stdout:
+	a
+	b
+---
 name: oksh-varfunction-mod1
 description:
 	(Inspired by PR 2450 on OpenBSD.) Calling
@@ -11490,6 +11781,8 @@ name: fd-cloexec-1
 description:
 	Verify that file descriptors > 2 are private for Korn shells
 	AT&T ksh93 does this still, which means we must keep it as well
+# broken on Xenix and BeOS
+category: !os:beos,!os:sco_xenix
 stdin:
 	cat >cld <<-EOF
 		#!$__perlname
@@ -11507,6 +11800,7 @@ name: fd-cloexec-2
 description:
 	Verify that file descriptors > 2 are not private for POSIX shells
 	See Debian Bug #154540, Closes: #499139
+category: !os:beos,!os:sco_xenix
 stdin:
 	cat >cld <<-EOF
 		#!$__perlname
@@ -11514,11 +11808,16 @@ stdin:
 		syswrite(FH, "Fowl\\n", 5) or die "E: write \$!";
 	EOF
 	chmod +x cld
+	./cld 9>&2
+	echo >&2 =
 	test -n "$POSH_VERSION" || set -o posix
 	exec 9>&1
 	./cld
 expected-stdout:
 	Fowl
+expected-stderr:
+	Fowl
+	=
 ---
 name: fd-cloexec-3
 description:
@@ -12728,7 +13027,6 @@ expected-stdout:
 name: funsub-2
 description:
 	You can now reliably use local and return in funsubs
-	(not exit though)
 stdin:
 	x=q; e=1; x=${ echo a; e=2; echo x$e;}; echo 1:y$x,$e,$?.
 	x=q; e=1; x=${ echo a; typeset e=2; echo x$e;}; echo 2:y$x,$e,$?.
@@ -12738,6 +13036,32 @@ expected-stdout:
 	2:ya x2,1,0.
 	3:ya,1,3.
 ---
+name: funsub-3
+description:
+	… not exit though, like in ksh93
+stdin:
+	function foo {
+		if [[ $1 = 2 ]]; then
+			print -u2 ERR
+			exit 42
+		fi
+		print -r -- "<$1>"
+	}
+	for i in 1 2 3; do
+		print $i ${ foo $i;} || {
+			print SUB=$?
+			exit 1
+		}
+	done
+	print END=$?
+expected-stdout:
+	1 <1>
+	2
+	3 <3>
+	END=0
+expected-stderr:
+	ERR
+---
 name: valsub-1
 description:
 	Check that "value substitutions" work as advertised
@@ -12770,6 +13094,51 @@ expected-stdout:
 	typeset t=$'foo\n\n'
 	this used to segfault.
 ---
+name: valsub-2
+description:
+	Can use exit here, in contrast to funsubs
+stdin:
+	function foo {
+		if [[ $1 = 2 ]]; then
+			print -u2 ERR
+			exit 42
+		fi
+		REPLY="<$1>"
+	}
+	for i in 1 2 3; do
+		print $i ${|foo $i;} || {
+			print SUB=$?
+			exit 1
+		}
+	done
+	print END=$?
+expected-exit: 42
+expected-stdout:
+	1 <1>
+expected-stderr:
+	ERR
+---
+name: funsub-valsub-1
+description:
+	This is what AT&T ksh93 does for shift
+stdin:
+	"$__progname" -c 'echo a. "$@"; : "${ shift;}"; echo b. "$@"' sh1 1a 1b
+	"$__progname" -c 'echo a. "$@"; : "${|shift;}"; echo b. "$@"' sh2 2a 2b
+	"$__progname" -c 'echo a. "$@"; : "${|shift;shift;}"; echo b. "$@"' sh3 3a 3b
+	echo >&2 =1
+	"$__progname" -c 'echo a. "$@"; : "${|shift;shift;shift;}"; echo b. "$@"' sh4 4a 4b
+	echo >&2 =2
+expected-stdout:
+	a. 1a 1b
+	b. 1b
+	a. 2a 2b
+	b. 2b
+	a. 3a 3b
+	b.
+	a. 4a 4b
+expected-stderr-pattern:
+	/^=1\n[^\n]*nothing to shift[^\n]*\n=2$/
+---
 name: event-subst-3
 description:
 	Check that '!' substitution in noninteractive mode is ignored
@@ -12875,22 +13244,26 @@ stdin:
 	echo =14
 	(mypid=$$; try mypid)
 	echo =15
-	) 2>&1 | sed -e 's/^[A-Za-z]://' -e 's/^[^]]*]//' -e 's/^[^:]*: *//'
+	) 2>&1 | sed \
+	    -e "s^${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROGl" \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: <stdin>\[[0-9]*]PROGl" \
+	    -e "s^${__progname%.exe}\.*e*x*e*: PROGn: " \
+	    -e "s^[EW]: ${__progname%.exe}\.*e*x*e*: PROGn: "
 	exit ${PIPESTATUS[0]}
 expected-stdout:
 	y
 	=1
-	y: parameter not set
+	PROGl: y: parameter not set
 	=2
 	x=nz
 	=3
-	y: parameter not set
+	PROGn: y: parameter not set
 	=4
 	0=nz
 	=5
-	2: parameter not set
+	PROGn: 2: parameter not set
 	=6
-	1: parameter not set
+	PROGl: 1: parameter not set
 	=7
 	at=
 	=8
@@ -12898,7 +13271,7 @@ expected-stdout:
 	=9
 	0
 	=10
-	!: parameter not set
+	PROGl: !: parameter not set
 	=11
 	ush
 	=12
@@ -13218,6 +13591,44 @@ expected-stdout:
 	2=\x7Cfoo-e \x4B
 	3=\x7Cfoo-e \x4B
 ---
+name: env-intvars
+description:
+	Check that importing integers fails except for numbers
+stdin:
+	print '#!'"$__perlname"'\n($k, $v) = split(/=/, shift(@ARGV),' \
+	    '2);\n$ENV{$k} = $v;\nexec { $ARGV[0] } @ARGV or die $!;' \
+	    >env; chmod +x env; PATH=.$PATHSEP$PATH
+	unset foo bar
+	print 1 $foo , $(typeset -p bar) .
+	print 2 $(foo=123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 3 $(foo='abc[$(echo >&2 fowled)0]' "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[$(echo >&2 fowled)0]=baz' "$__progname" -c 'typeset -p bar') .
+	print 4 $(foo=0123 "$__progname" +o posix -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[0123]=baz' "$__progname" +o posix -c 'typeset -p bar') .
+	# ksh93 does not do this:
+	print 5 $(foo=0123 "$__progname" -o posix -c 'integer foo; print -- $foo' 2>&1) .
+	# at import time FPOSIX is not yet set
+	print 6 $(foo=0x123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[0x123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 7 $(foo=12#123 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[12#123]=baz' "$__progname" -c 'typeset -p bar') .
+	print 8 $(foo=1+1 "$__progname" -c 'integer foo; print -- $foo' 2>&1) , \
+	    $(env 'bar[1+1]=baz' "$__progname" -c 'typeset -p bar') .
+	print 9 $(a=1 b=2 c=a "$__progname" -c 'typeset -p c; c=b; typeset -p c; integer c; typeset -p c') .
+	print 0 $(a=1 b=2 c=a "$__progname" -c 'typeset -p c;      typeset -p c; integer c; typeset -p c') .
+expected-stdout:
+	1 , .
+	2 123 , set -A bar typeset -x bar[123]=baz .
+	3 0 , .
+	4 123 , set -A bar typeset -x bar[123]=baz .
+	5 8#123 .
+	6 16#123 , set -A bar typeset -x bar[291]=baz .
+	7 12#123 , set -A bar typeset -x bar[171]=baz .
+	8 0 , .
+	9 typeset -x c=a typeset -x c=b typeset -i -x c=2 .
+	0 typeset -x c=a typeset -x c=a typeset -i -x c=0 .
+---
 name: utilities-getopts-1
 description:
 	getopts sets OPTIND correctly for unparsed option
@@ -13459,6 +13870,12 @@ stdin:
 expected-stdout:
 	bar
 ---
+name: crash-2
+stdin:
+	<<<`$((`
+expected-exit: e != 0
+expected-stderr-pattern: /.*: no closing quote$/
+---
 name: debian-117-1
 description:
 	Check test - bug#465250
@@ -13730,7 +14147,7 @@ name: duffs-device
 description:
 	Check that the compiler did not optimise-break them
 	(lex.c has got a similar one in SHEREDELIM)
-category: !shell:faux-ebcdic,!shell:ebcdic-yes
+category: !shell:ebcdic-yes
 stdin:
 	set +U
 	s=
@@ -13740,8 +14157,14 @@ stdin:
 	done
 	s+=$'\xC2\xA0\xE2\x82\xAC\xEF\xBF\xBD\xEF\xBF\xBE\xEF\xBF\xBF\xF0\x90\x80\x80.'
 	typeset -p s
+	set -o asis
+	typeset -p s
+	set -U
+	typeset -p s
 expected-stdout:
-	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\u00A0\u20AC\uFFFD\357\277\276\357\277\277\360\220\200\200.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237 \202�￾￿\220\200\200.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177 €�￾￿𐀀.'
+	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377 €�\357\277\276\357\277\277\360\220\200\200.'
 ---
 name: duffs-device-ebcdic
 description:
@@ -13759,52 +14182,41 @@ stdin:
 expected-stdout:
 	typeset s=$'\001\002\003\004\t\006\007\010\011\012\v\f\r\016\017\020\021\022\023\024\n\b\027\030\031\032\033\034\035\036\037\040\041\042\043\044\045\046\E\050\051\052\053\054\055\056\a\060\061\062\063\064\065\066\067\070\071\072\073\074\075\076\077 .<(+|&!$*);^-/Ѧ,%_>?`:#@\175="abcdefghijklmnopqrƤ~stuvwxyz[ޮݨ]{ABCDEFGHI}JKLMNOPQR\\STUVWXYZ0123456789\377'
 ---
-name: duffs-device-faux-EBCDIC
-description:
-	Check that the compiler did not optimise-break them
-category: shell:faux-ebcdic
+name: the-next-test-takes-very-long-on-retro-systems
+category: !system:fast-no
 stdin:
-	set +U
-	s=
-	typeset -i1 i=0
-	while (( ++i < 256 )); do
-		s+=${i#1#}
-	done
-	s+=$'\xC2\xA0\xE2\x82\xAC\xEF\xBF\xBD\xEF\xBF\xBE\xEF\xBF\xBF\xF0\x90\x80\x80.'
-	typeset -p s
-expected-stdout:
-	typeset s=$'\001\002\003\004\005\006\a\b\t\n\v\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\E\034\035\036\037 !"#$%&\047()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\u00A0\u20AC\uFFFD￾￿\220\200\200.'
+	:
 ---
 name: stateptr-underflow
 description:
 	This check overflows an Xrestpos stored in a short in R40
-category: fastbox
+category: !system:fast-no
 stdin:
 	function Lb64decode {
 		[[ -o utf8-mode ]]; local u=$?
 		set +U
 		local c s="$*" t=
-		[[ -n $s ]] || { s=$(cat;print x); s=${s%x}; }
-		local -i i=0 n=${#s} p=0 v x
+		[[ -n $s ]] || { s=$(cat;print .); s=${s%.}; }
+		local -i i=-1 n=${#s} p=0 v x
 		local -i16 o
 	
-		while (( i < n )); do
-			c=${s:(i++):1}
+		while ((# ++i < n )); do
+			c=${s:i:1}
 			case $c {
 			(=)	break ;;
-			([A-Z])	(( v = 1#$c - 65 )) ;;
-			([a-z])	(( v = 1#$c - 71 )) ;;
-			([0-9])	(( v = 1#$c + 4 )) ;;
+			([A-Z])	((# v = 1#$c - 65 )) ;;
+			([a-z])	((# v = 1#$c - 71 )) ;;
+			([0-9])	((# v = 1#$c + 4 )) ;;
 			(+)	v=62 ;;
 			(/)	v=63 ;;
 			(*)	continue ;;
 			}
-			(( x = (x << 6) | v ))
+			((# x = (x << 6) | v ))
 			case $((p++)) {
 			(0)	continue ;;
-			(1)	(( o = (x >> 4) & 255 )) ;;
-			(2)	(( o = (x >> 2) & 255 )) ;;
-			(3)	(( o = x & 255 ))
+			(1)	((# o = (x >> 4) & 255 )) ;;
+			(2)	((# o = (x >> 2) & 255 )) ;;
+			(3)	((# o = x & 255 ))
 				p=0
 				;;
 			}
@@ -13919,3 +14331,87 @@ expected-stdout:
 	2 eh .
 	3 eh .
 ---
+name: read-timeout-nexttesttakes15seconds
+description:
+	Check timeout functionality
+category: have:select:1
+time-limit: 5
+stdin:
+	sleep 2 | {
+		read -t1 foo
+		echo 1 $? "<$foo>"
+	}
+	: | {
+		read -t1 foo
+		echo 2 $? "<$foo>"
+	}
+	echo bla | {
+		read -t1 foo
+		echo 3 $? "<$foo>"
+	}
+expected-stdout:
+	1 142 <>
+	2 1 <>
+	3 0 <bla>
+---
+name: read-timeout-slow
+description:
+	Check timeout parser
+category: have:select:1
+time-limit: 20
+stdin:
+	(sleep 14; echo foo) | {
+		read -t12.3 foo
+		echo 1 $? "<$foo>"
+	} >o1 &
+	(sleep 11; echo foo) | {
+		read -t12.3 foo
+		echo 2 $? "<$foo>"
+	} > o2 &
+	wait
+	cat o1
+	cat o2
+expected-stdout:
+	1 142 <>
+	2 0 <foo>
+---
+name: optional-printf-builtin
+description:
+	printf(1) minimal tests
+category: printf-builtin
+stdin:
+	t() {
+		o=$(\\builtin printf "$@"; echo .)
+		r=$?
+		print -r -- "$((++n)) ${o%.} : $r"
+	}
+	t '<%s>' a b\	c
+	t '%s - %c %s %d %i %o %u %x %X %b' 3
+	t '%% %c %s %d %i %o %u %x %X' 72 73 74 75 76 77 78 79
+	t '\\\a\b\f\n\r\t\v\01234'
+	let n+=2
+	t '%b foo %s bar' '\\\a\b\f\n\r\t\v\01234\cdefg'
+	let ++n
+	t '<%d>' 1 +2 -3 0x1a 0X1B 010 -011 +012 \'1 \"2
+	t '<%d|%d><%+d|%+d><% d|% d><%+ d|%+ d>' 1 -1 1 -1 1 -1 1 -1
+	t '<%o|%#o><%x|%#x><%X|%#X>' 8 9 10 11 12 13
+	#XXX replace with below
+	t '|%3d|%-3d|%+3d|%-+3d|%03d|%-03d|%3d|%.3d|notyet|' \
+	    1 2 3 4 5 6 7777 8
+	#t '|%3d|%-3d|%+3d|%-+3d|%03d|%-03d|%3d|%.3d|%5.3d|' \
+	#    1 2 3 4 5 6 7777 8 9
+	#12 |  1|2  | +3|+4 |005|6  |7777|008|  009| : 0
+expected-stdout:
+	1 <a><b	c> : 0
+	2 3 -   0 0 0 0 0 0  : 0
+	3 % 7 73 74 75 114 77 4e 4F : 0
+	4 \
+	
	
+	34 : 0
+	7 \
+	
	S4 : 0
+	9 <1><2><-3><26><27><8><-9><10><49><50> : 0
+	10 <1|-1><+1|-1>< 1|-1><+1|-1> : 0
+	11 <10|011><a|0xb><C|0XD> : 0
+	12 |  1|2  | +3|+4 |005|6  |7777|008|notyet| : 0
+---
--- mksh-59c.orig/dot.mkshrc
+++ mksh-59c/dot.mkshrc
@@ -1,9 +1,9 @@
 # $Id$
-# $MirOS: src/bin/mksh/dot.mkshrc,v 1.128 2020/04/13 18:39:03 tg Exp $
+# $MirOS: src/bin/mksh/dot.mkshrc,v 1.144 2023/01/31 01:05:08 tg Exp $
 #-
 # Copyright (c) 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010,
 #		2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
-#		2020
+#		2020, 2021, 2022, 2023
 #	mirabilos <m@mirbsd.org>
 #
 # Provided that these terms and disclaimer and all copyright notices
@@ -38,24 +38,57 @@ function setenv {
 	fi
 }
 
+# internal helper function to cat all arguments if necessary
+function _dot_mkshrc_wrapped_cat {
+	\\builtin typeset fn=$1
+	\\builtin shift
+
+	if [[ $# = 0 || $#,$1 = 1,- ]]; then
+		"$fn"
+	else
+		\cat "$@" | "$fn"
+	fi
+}
+function _dot_mkshrc_cat_for_readNa {
+	\\builtin typeset fn=$1 s
+	\\builtin shift
+
+	if (( $# )); then
+		\\builtin read -raN-1 s <<<"$*" || \\builtin return $?
+		\\builtin unset s[${#s[*]}-1]
+	elif [[ -t 0 ]]; then
+		s=$(\cat || \\builtin exit $?; \\builtin print .) || \
+		    \\builtin return $?
+		\\builtin read -raN-1 s <<<"$s" || \\builtin return $?
+		\\builtin unset s[${#s[*]}-1]
+		\\builtin unset s[${#s[*]}-1]
+	else
+		\\builtin read -raN-1 s || \\builtin return $?
+	fi
+	"$fn"
+}
+
 # pager (not control character safe)
-smores() (
-	\\builtin set +m
-	\\builtin cat "$@" |&
-	\\builtin trap "rv=\$?; \\\\builtin kill $! >/dev/null 2>&1; \\\\builtin exit \$rv" EXIT
-	while IFS= \\builtin read -pr line; do
+function smores {
+	\_dot_mkshrc_wrapped_cat _dot_mkshrc_smores "$@"
+}
+function _dot_mkshrc_smores {
+	\\builtin set +e
+	\\builtin typeset line llen curlin=0 x
+
+	while IFS= \\builtin read -r line; do
 		llen=${%line}
-		(( llen == -1 )) && llen=${#line}
+		(( llen != -1 )) || llen=${#line}
 		(( llen = llen ? (llen + COLUMNS - 1) / COLUMNS : 1 ))
 		if (( (curlin += llen) >= LINES )); then
 			\\builtin print -nr -- $'\e[7m--more--\e[0m'
-			\\builtin read -u1 || \\builtin exit $?
-			[[ $REPLY = [Qq]* ]] && \\builtin exit 0
+			\\builtin read -u1 x || \\builtin return $?
+			[[ $x != [Qq]* ]] || \\builtin return 0
 			curlin=$llen
 		fi
 		\\builtin print -r -- "$line"
 	done
-)
+}
 
 # customise your favourite editor here; the first one found is used
 for EDITOR in "${EDITOR:-}" jupp jstar mcedit ed vi; do
@@ -82,10 +115,10 @@ fi
 
 # prompts
 PS4='[$EPOCHREALTIME] '; PS1='#'; (( USER_ID )) && PS1='$'; PS1=$'\001\r''${|
-	\\builtin typeset e=$?
+	\\builtin typeset e=$? hn=${HOSTNAME:-nil}
 
-	(( e )) && REPLY+="$e|"
-	REPLY+=${USER}@${HOSTNAME%%.*}:
+	(( !!e )) || REPLY+="$e|"
+	REPLY+=${USER:-?}@${hn%%.*}:
 
 	\\builtin typeset d=${PWD:-?}/ p=~; [[ $p = ?(*/) ]] || d=${d/#$p\//\~/}
 	d=${d%/}; \\builtin typeset m=${%d} n p=...; (( m > 0 )) || m=${#d}
@@ -104,12 +137,13 @@ if \\builtin command -v hd >/dev/null; t
 	\:
 elif \\builtin command -v hexdump >/dev/null; then
 	function hd {
-		hexdump -e '"%08.8_ax  " 8/1 "%02X " " - " 8/1 "%02X "' \
+		\hexdump -e '"%08.8_ax  " 8/1 "%02X " " - " 8/1 "%02X "' \
 		    -e '"  |" "%_p"' -e '"|\n"' "$@"
 	}
 else
 	function hd {
-		\\builtin cat "$@" | hd_mksh
+		# cannot use _dot_mkshrc_wrapped_cat as hd_mksh sets stdin raw
+		\cat "$@" | \hd_mksh
 	}
 fi
 
@@ -118,7 +152,7 @@ function hd_mksh {
 	\\builtin typeset -Uui16 -Z11 pos=0
 	\\builtin typeset -Uui16 -Z5 hv=2147483647
 	\\builtin typeset dasc dn line i
-	\\builtin set +U
+	\\builtin set +Ue
 
 	while \\builtin read -arn 512 line; do
 		\\builtin typeset -i1 'line[*]'
@@ -219,6 +253,7 @@ function cd_csh {
 	\cd "$t"
 }
 function dirs {
+	\\builtin set +e
 	\\builtin typeset d dwidth
 	\\builtin typeset -i fl=0 fv=0 fn=0 cpos=0
 
@@ -343,50 +378,56 @@ function pushd {
 
 # base64 encoder and decoder, RFC compliant, NUL safe, not EBCDIC safe
 function Lb64decode {
-	\\builtin set +U
-	\\builtin typeset c s="$*" t
-	[[ -n $s ]] || { s=$(\\builtin cat; \\builtin print x); s=${s%x}; }
-	\\builtin typeset -i i=0 j=0 n=${#s} p=0 v x
+	\\builtin set +Ue
+	\\builtin typeset c s t
+	if (( $# )); then
+		s="$*"
+	elif [[ -t 0 ]]; then
+		s=$(\cat || \\builtin exit $?; \\builtin print .) || \
+		    \\builtin return $?
+		s=${s%.}
+	else
+		\\builtin read -rN-1 s || \\builtin return $?
+	fi
+	\\builtin typeset -i i=-1 j=0 n=${#s} p=0 v x
 	\\builtin typeset -i16 o
 
-	while (( i < n )); do
-		c=${s:(i++):1}
+	while ((# ++i < n )); do
+		c=${s:i:1}
 		case $c {
 		(=)	\\builtin break ;;
-		([A-Z])	(( v = 1#$c - 65 )) ;;
-		([a-z])	(( v = 1#$c - 71 )) ;;
-		([0-9])	(( v = 1#$c + 4 )) ;;
+		([A-Z])	((# v = 1#$c - 65 )) ;;
+		([a-z])	((# v = 1#$c - 71 )) ;;
+		([0-9])	((# v = 1#$c + 4 )) ;;
 		(+)	v=62 ;;
 		(/)	v=63 ;;
 		(*)	\\builtin continue ;;
 		}
-		(( x = (x << 6) | v ))
+		((# x = (x << 6) | v ))
 		case $((p++)) {
 		(0)	\\builtin continue ;;
-		(1)	(( o = (x >> 4) & 255 )) ;;
-		(2)	(( o = (x >> 2) & 255 )) ;;
-		(3)	(( o = x & 255 ))
+		(1)	((# o = (x >> 4) & 255 )) ;;
+		(2)	((# o = (x >> 2) & 255 )) ;;
+		(3)	((# o = x & 255 ))
 			p=0
 			;;
 		}
 		t+=\\x${o#16#}
-		(( ++j & 4095 )) && \\builtin continue
-		\\builtin print -n $t
+		((# ++j & 4095 )) && \\builtin continue
+		\\builtin print -n -- "$t"
 		t=
 	done
-	\\builtin print -n $t
+	\\builtin print -n -- "$t"
 }
 function Lb64encode {
 	\\builtin set +U
-	\\builtin typeset c s t table
+	\_dot_mkshrc_cat_for_readNa _dot_mkshrc_b64encode "$@"
+}
+function _dot_mkshrc_b64encode {
+	\\builtin set +e
+	\\builtin typeset c t table
 	\\builtin set -A table -- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z \
 	    a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 + /
-	if (( $# )); then
-		\\builtin read -raN-1 s <<<"$*"
-		\\builtin unset s[${#s[*]}-1]
-	else
-		\\builtin read -raN-1 s
-	fi
 	\\builtin typeset -i i=0 n=${#s[*]} v
 
 	while (( i < n )); do
@@ -403,34 +444,34 @@ function Lb64encode {
 			t+===
 		fi
 		if (( ${#t} == 76 || i >= n )); then
-			\\builtin print -r $t
+			\\builtin print -r -- "$t"
 			t=
 		fi
 	done
+	\:
 }
 
-# Better Avalanche for the Jenkins Hash
+# Better Avalanche for the Jenkins Hash, IV=1 INC=0
 \\builtin typeset -Z11 -Uui16 Lbafh_v
 function Lbafh_init {
-	Lbafh_v=0
+	Lbafh_v=1
 }
 function Lbafh_add {
 	\\builtin set +U
-	\\builtin typeset s
-	if (( $# )); then
-		\\builtin read -raN-1 s <<<"$*"
-		\\builtin unset s[${#s[*]}-1]
-	else
-		\\builtin read -raN-1 s
-	fi
+	\_dot_mkshrc_cat_for_readNa _dot_mkshrc_bafh_add "$@"
+}
+function _dot_mkshrc_bafh_add {
+	\\builtin set +e
 	\\builtin typeset -i i=0 n=${#s[*]}
 
 	while (( i < n )); do
-		((# Lbafh_v = (Lbafh_v + s[i++] + 1) * 1025 ))
+		((# Lbafh_v = (Lbafh_v + s[i++]) * 1025 ))
 		((# Lbafh_v ^= Lbafh_v >> 6 ))
 	done
+	\:
 }
 function Lbafh_finish {
+	\\builtin set +e
 	\\builtin typeset -Ui t
 
 	((# t = (((Lbafh_v >> 7) & 0x01010101) * 0x1B) ^ \
@@ -443,11 +484,20 @@ function Lbafh_finish {
 # strip comments (and leading/trailing whitespace if IFS is set) from
 # any file(s) given as argument, or stdin if none, and spew to stdout
 function Lstripcom {
+	\_dot_mkshrc_wrapped_cat _dot_mkshrc_stripcom "$@"
+}
+function _dot_mkshrc_stripcom {
+	\\builtin typeset line x
 	\\builtin set -o noglob
-	\\builtin cat "$@" | while \\builtin read _line; do
-		_line=${_line%%#*}
-		[[ -n $_line ]] && \\builtin print -r -- $_line
+	while \\builtin read -r line; do
+		while [[ $line = *\\ && $line != *'#'* ]] && \
+		    \\builtin read -r x; do
+			line=${line%\\}$x
+		done
+		line=${line%%#*}
+		[[ -z $line ]] || \\builtin print -r -- $line
 	done
+	\:
 }
 
 # toggle built-in aliases and utilities, and aliases and functions from mkshrc
@@ -479,7 +529,6 @@ function enable {
 	i_func[nfunc++]=break
 	# \\builtin cannot, by design, be overridden
 	i_func[nfunc++]=builtin
-	i_func[nfunc++]=cat
 	i_func[nfunc++]=cd
 	i_func[nfunc++]=chdir
 	i_func[nfunc++]=command
@@ -522,8 +571,6 @@ function enable {
 	i_func[nfunc++]=bind
 	i_func[nfunc++]=mknod
 	i_func[nfunc++]=printf
-	i_func[nfunc++]=sleep
-	i_func[nfunc++]=domainname
 	i_func[nfunc++]=extproc
 
 	# accumulate aliases from dot.mkshrc, in definition order
@@ -585,7 +632,7 @@ function enable {
 		(*)
 			\\builtin print -ru2 enable: usage: \
 			    "enable [-adnps] [-f filename] [name ...]"
-			return 2
+			\\builtin return 2
 			;;
 		}
 	done
@@ -595,7 +642,7 @@ function enable {
 	if (( doprnt || ($# == 0) )); then
 		for x in "${i_all[@]}"; do
 			y=$(\\builtin alias "$x") || y=
-			[[ $y = "$x='\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -r mksh: $x: not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)'" ]]; z=$?
+			[[ $y = "$x='\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -ru2 E: mksh: $x: inaccessible or not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)'" ]]; z=$?
 			case $mode:$z {
 			(-1:0|0:0)
 				\\builtin print -r -- "enable -n $x"
@@ -622,7 +669,7 @@ function enable {
 		fi
 		if (( !mode )); then
 			# disable this
-			\\builtin alias "$x=\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -r mksh: $x: not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)"
+			\\builtin alias "$x=\\\\builtin whence -p $x >/dev/null || (\\\\builtin print -ru2 E: mksh: $x: inaccessible or not found; \\\\builtin exit 127) && \$(\\\\builtin whence -p $x)"
 		else
 			# find out if this is an alias or not, first
 			z=0
@@ -647,11 +694,11 @@ function enable {
 \: place customisations below this line
 
 # some defaults / samples which you are supposed to adjust to your
-# liking; by default we add ~/.etc/bin and ~/bin (whichever exist)
+# liking; by default we add user-local bin directories which exist
 # to $PATH, set $SHELL to mksh, set some defaults for man and less
 # and show a few more possible things for users to begin moving in
 
-for p in ~/.etc/bin ~/bin; do
+for p in ~/bin ~/.local/bin ~/.etc/bin; do
 	[[ -d $p/. ]] || \\builtin continue
 	[[ $PATHSEP$PATH$PATHSEP = *"$PATHSEP$p$PATHSEP"* ]] || \
 	    PATH=$p$PATHSEP$PATH
--- mksh-59c.orig/edit.c
+++ mksh-59c/edit.c
@@ -6,7 +6,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -29,7 +29,7 @@
 
 #ifndef MKSH_NO_CMDLINE_EDITING
 
-__RCSID("$MirOS: src/bin/mksh/edit.c,v 1.357 2020/10/31 05:02:17 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/edit.c,v 1.400 2022/12/01 23:55:29 tg Exp $");
 
 /*
  * in later versions we might use libtermcap for this, but since external
@@ -58,14 +58,8 @@ static struct {
 } edchars;
 
 #define isched(x,e) ((unsigned short)(unsigned char)(x) == (e))
-#define isedchar(x) (!((x) & ~0xFF))
-#ifndef _POSIX_VDISABLE
-#define toedchar(x) ((unsigned short)(unsigned char)(x))
-#else
-#define toedchar(x) (((_POSIX_VDISABLE != -1) && ((x) == _POSIX_VDISABLE)) ? \
-			((unsigned short)EDCHAR_DISABLED) : \
-			((unsigned short)(unsigned char)(x)))
-#endif
+#define isedchar(x) (!((x) & ~0xFFU))
+#define toedchar(x) ((unsigned short)KSH_ISVDIS(x, EDCHAR_DISABLED))
 
 /* x_cf_glob() flags */
 #define XCF_COMMAND	BIT(0)	/* Do command completion */
@@ -74,6 +68,7 @@ static struct {
 #define XCF_COMMAND_FILE (XCF_COMMAND | XCF_FILE)
 #define XCF_IS_COMMAND	BIT(3)	/* return flag: is command */
 #define XCF_IS_NOSPACE	BIT(4)	/* return flag: do not append a space */
+#define XCF_IS_HOMEDIR	BIT(5)	/* return flag: tilde needs slash */
 
 static char editmode;
 static int xx_cols;			/* for Emacs mode */
@@ -81,28 +76,32 @@ static int modified;			/* buffer has bee
 static char *holdbufp;			/* place to hold last edit buffer */
 
 /* 0=dumb 1=tmux (for now) */
-static uint8_t x_term_mode;
+static kby x_term_mode;
 
 static void x_adjust(void);
 static int x_getc(void);
 static void x_putcf(int);
 static void x_modified(void);
-static void x_mode(bool);
+static void x_mode(Wahr);
 static int x_do_comment(char *, ssize_t, ssize_t *);
-static void x_print_expansions(int, char * const *, bool);
+static void x_print_expansions(int, char * const *, Wahr);
 static int x_cf_glob(int *, const char *, int, int, int *, int *, char ***);
 static size_t x_longest_prefix(int, char * const *);
-static void x_glob_hlp_add_qchar(char *);
-static char *x_glob_hlp_tilde_and_rem_qchar(char *, bool);
+static char *x_glob_hlp_add_qchar(char *);
+static char *x_glob_hlp_tilde_and_rem_qchar(char *, Wahr);
 static size_t x_basename(const char *, const char *);
 static void x_free_words(int, char **);
 static int x_escape(const char *, size_t, int (*)(const char *, size_t));
-static int x_emacs(char *);
-static void x_init_prompt(bool);
+static ssize_t x_emacs(char *);
+#ifdef DF
+static void x_emacs_DF(const char *);
+#endif
+static void x_init_prompt(Wahr);
 #if !MKSH_S_NOVI
-static int x_vi(char *);
+static ssize_t x_vi(char *);
 #endif
 static void x_intr(int, int) MKSH_A_NORETURN;
+static void x_clrtoeol(int, Wahr);
 
 #define x_flush()	shf_flush(shl_out)
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
@@ -116,7 +115,7 @@ static void glob_table(const char *, XPt
 static void glob_path(int, const char *, XPtrV *, const char *);
 static int x_file_glob(int *, char *, char ***);
 static int x_command_glob(int, char *, char ***);
-static int x_locate_word(const char *, int, int, int *, bool *);
+static int x_locate_word(const char *, int, int, int *, Wahr *);
 
 static int x_e_getmbc(char *);
 
@@ -125,12 +124,12 @@ static int x_e_getmbc(char *);
 /*
  * read an edited command line
  */
-int
+char *
 x_read(char *buf)
 {
-	int i;
+	ssize_t i;
 
-	x_mode(true);
+	x_mode(Ja);
 	modified = 1;
 	if (Flag(FEMACS) || Flag(FGMACS))
 		i = x_emacs(buf);
@@ -142,8 +141,13 @@ x_read(char *buf)
 		/* internal error */
 		i = -1;
 	editmode = 0;
-	x_mode(false);
-	return (i);
+	x_mode(Nee);
+	if (i < 0) {
+		/* pdksh had no error handling here, just return null */
+		return (buf);
+	}
+	buf += i;
+	return (buf);
 }
 
 /* tty I/O */
@@ -159,7 +163,7 @@ x_getc(void)
 
 	while ((n = blocking_read(0, &c, 1)) < 0 && errno == EINTR)
 		if (trap) {
-			x_mode(false);
+			x_mode(Nee);
 			runtraps(0);
 #ifdef SIGWINCH
 			if (got_winch) {
@@ -167,12 +171,12 @@ x_getc(void)
 				if (x_cols != xx_cols && editmode == 1) {
 					/* redraw line in Emacs mode */
 					xx_cols = x_cols;
-					x_init_prompt(false);
+					x_init_prompt(Nee);
 					x_adjust();
 				}
 			}
 #endif
-			x_mode(true);
+			x_mode(Ja);
 		}
 	return ((n == 1) ? (int)(unsigned char)c : -1);
 #endif
@@ -208,7 +212,7 @@ x_do_comment(char *buf, ssize_t bsize, s
 
 	/* Already commented? */
 	if (buf[0] == '#') {
-		bool saw_nl = false;
+		Wahr saw_nl = Nee;
 
 		for (j = 0, i = 1; i < len; i++) {
 			if (!saw_nl || buf[i] != '#')
@@ -243,12 +247,14 @@ x_do_comment(char *buf, ssize_t bsize, s
  ****************************************************/
 
 static void
-x_print_expansions(int nwords, char * const *words, bool is_command)
+x_print_expansions(int nwords, char * const *words, Wahr is_command)
 {
-	bool use_copy = false;
-	size_t prefix_len;
-	XPtrV l = { NULL, 0, 0 };
+	int i;
+	char **w;
+	size_t prefix_len = 0;
+	Wahr prefix_trim = Nee;
 	struct columnise_opts co;
+	struct shf S;
 
 	/*
 	 * Check if all matches are in the same directory (in this
@@ -256,8 +262,6 @@ x_print_expansions(int nwords, char * co
 	 */
 	if (!is_command &&
 	    (prefix_len = x_longest_prefix(nwords, words)) > 0) {
-		int i;
-
 		/* Special case for 1 match (prefix is whole word) */
 		if (nwords == 1)
 			prefix_len = x_basename(words[0], NULL);
@@ -271,66 +275,70 @@ x_print_expansions(int nwords, char * co
 			while (prefix_len > 0 &&
 			    !mksh_cdirsep(words[0][prefix_len - 1]))
 				prefix_len--;
-			use_copy = true;
-			XPinit(l, nwords + 1);
-			for (i = 0; i < nwords; i++)
-				XPput(l, words[i] + prefix_len);
-			XPput(l, NULL);
+			prefix_trim = Ja;
 		}
 	}
 	/*
+	 * Escape words, trimming prefix_len if needed
+	 */
+	if (!prefix_trim)
+		prefix_len = 0;
+	w = alloc2((kui)nwords + 1U, sizeof(char *), ATEMP);
+	for (i = 0; i < nwords; ++i) {
+		shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &S);
+		uprntmbs(words[i] + prefix_len, Nee, &S);
+		w[i] = shf_sclose(&S);
+	}
+	w[nwords] = NULL;
+
+	/*
 	 * Enumerate expansions
 	 */
 	x_putc('\r');
 	x_putc('\n');
 	co.shf = shl_out;
 	co.linesep = '\n';
-	co.do_last = true;
-	co.prefcol = false;
-	pr_list(&co, use_copy ? (char **)XPptrv(l) : words);
-
-	if (use_copy)
-		/* not x_free_words() */
-		XPfree(l);
+	co.do_last = Ja;
+	co.prefcol = Nee;
+	pr_list(&co, w);
+	x_free_words(nwords, w);
 }
 
 /*
  * Convert backslash-escaped string to QCHAR-escaped
- * string useful for globbing; loses QCHAR unless it
- * can squeeze in, eg. by previous loss of backslash
+ * string useful for globbing
  */
-static void
+static char *
 x_glob_hlp_add_qchar(char *cp)
 {
-	char ch, *dp = cp;
-	bool escaping = false;
+	char ch, *dp;
+	Wahr escaping = Nee;
+	XString xs;
+	size_t n;
+
+	if (memchr(cp, QCHAR, (n = strlen(cp)))) {
+		Xinit(xs, dp, n, ATEMP);
+	} else {
+		xs.len = n + 1;
+		xs.areap = NULL; /* won’t be used */
+		xs.beg = dp = cp;
+		xs.end = xs.beg + xs.len;
+	}
 
 	while ((ch = *cp++)) {
 		if (ch == '\\' && !escaping) {
-			escaping = true;
+			escaping = Ja;
 			continue;
 		}
-		if (escaping || (ch == QCHAR && (cp - dp) > 1)) {
-			/*
-			 * empirically made list of chars to escape
-			 * for globbing as well as QCHAR itself
-			 */
-			switch (ord(ch)) {
-			case QCHAR:
-			case ORD('$'):
-			case ORD('*'):
-			case ORD('?'):
-			case ORD('['):
-			case ORD('\\'):
-			case ORD('`'):
-				*dp++ = QCHAR;
-				break;
-			}
-			escaping = false;
-		}
+		/* coverity[var_deref_model : SUPPRESS] */
+		XcheckN(xs, dp, 2);
+		if ((escaping && ctype(ch, C_EDGLB)) || ch == QCHAR)
+			*dp++ = QCHAR;
+		escaping = Nee;
 		*dp++ = ch;
 	}
 	*dp = '\0';
+	return (Xstring(xs, dp));
 }
 
 /*
@@ -340,7 +348,7 @@ x_glob_hlp_add_qchar(char *cp)
  * it is assumed QCHAR-escaped
  */
 static char *
-x_glob_hlp_tilde_and_rem_qchar(char *s, bool magic_flag)
+x_glob_hlp_tilde_and_rem_qchar(char *s, Wahr magic_flag)
 {
 	char ch, *cp, *dp;
 
@@ -349,7 +357,7 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 	 * and if so, discern "~foo/bar" and "~/baz" from "~blah";
 	 * if we have a directory part (the former), try to expand
 	 */
-	if (*s == '~' && (cp = /* not sdirsep */ strchr(s, '/')) != NULL) {
+	if (*s == '~' && (cp = /* not sdirsep */ ucstrchr(s, '/')) != NULL) {
 		/* ok, so split into "~foo"/"bar" or "~"/"baz" */
 		*cp++ = 0;
 		/* try to expand the tilde */
@@ -366,8 +374,12 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 	}
 
 	/* ... convert it from backslash-escaped via QCHAR-escaped... */
-	if (magic_flag)
-		x_glob_hlp_add_qchar(s);
+	if (magic_flag) {
+		cp = x_glob_hlp_add_qchar(s);
+		if (cp != s)
+			afree(s, ATEMP);
+		s = cp;
+	}
 	/* ... to unescaped, for comparison with the matches */
 	cp = dp = s;
 
@@ -390,25 +402,27 @@ x_glob_hlp_tilde_and_rem_qchar(char *s,
 static int
 x_file_glob(int *flagsp, char *toglob, char ***wordsp)
 {
-	char **words, *cp;
+	char **words, *cp, *qglob;
 	int nwords;
 	XPtrV w;
 	struct source *s, *sold;
 
 	/* remove all escaping backward slashes */
-	x_glob_hlp_add_qchar(toglob);
+	qglob = x_glob_hlp_add_qchar(toglob);
 
 	/*
 	 * Convert "foo*" (toglob) to an array of strings (words)
 	 */
 	sold = source;
 	s = pushs(SWSTR, ATEMP);
-	s->start = s->str = toglob;
+	s->start = s->str = qglob;
 	source = s;
 	if (yylex(ONEWORD | LQCHAR) != LWORD) {
 		source = sold;
-		internal_warningf(Tfg_badsubst);
-		return (0);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_ONEMSG | KWF_NOERRNO,
+		    Tfg_badsubst);
+		nwords = 0;
+		goto out;
 	}
 	source = sold;
 	afree(s, ATEMP);
@@ -425,15 +439,17 @@ x_file_glob(int *flagsp, char *toglob, c
 	}
 	expand(yylval.cp, &w, nwords);
 	XPput(w, NULL);
-	words = (char **)XPclose(w);
+	nwords = 0;
+	while (XPptrv(w)[nwords])
+		++nwords;
+	/* XPclose(w) except for nwords plus a trailing NULL for pr_list */
+	words = aresize2(XPptrv(w), (kui)nwords + 1U, sizeof(void *), ATEMP);
 
-	for (nwords = 0; words[nwords]; nwords++)
-		;
 	if (nwords == 1) {
 		struct stat statb;
 
 		/* Expand any tilde and drop all QCHAR for comparison */
-		toglob = x_glob_hlp_tilde_and_rem_qchar(toglob, false);
+		qglob = x_glob_hlp_tilde_and_rem_qchar(qglob, Nee);
 
 		/*
 		 * Check if globbing failed (returned glob pattern),
@@ -443,7 +459,7 @@ x_file_glob(int *flagsp, char *toglob, c
 		 * to glob something which evaluated to an empty
 		 * string (e.g., "$FOO" when there is no FOO, etc).
 		 */
-		if ((strcmp(words[0], toglob) == 0 &&
+		if ((strcmp(words[0], qglob) == 0 &&
 		    stat(words[0], &statb) < 0) ||
 		    words[0][0] == '\0') {
 			x_free_words(nwords, words);
@@ -455,6 +471,9 @@ x_file_glob(int *flagsp, char *toglob, c
 	if ((*wordsp = nwords ? words : NULL) == NULL && words != NULL)
 		x_free_words(nwords, words);
 
+ out:
+	if (qglob != toglob)
+		afree(qglob, ATEMP);
 	return (nwords);
 }
 
@@ -562,14 +581,14 @@ x_command_glob(int flags, char *toglob,
 
 static int
 x_locate_word(const char *buf, int buflen, int pos, int *startp,
-    bool *is_commandp)
+    Wahr *is_commandp)
 {
 	int start, end;
 
 	/* Bad call? Probably should report error */
 	if (pos < 0 || pos > buflen) {
 		*startp = pos;
-		*is_commandp = false;
+		*is_commandp = Nee;
 		return (0);
 	}
 	/* The case where pos == buflen happens to take care of itself... */
@@ -589,7 +608,7 @@ x_locate_word(const char *buf, int bufle
 	}
 
 	if (is_commandp) {
-		bool iscmd;
+		Wahr iscmd;
 		int p = start - 1;
 
 		/* Figure out if this is a command */
@@ -620,11 +639,11 @@ x_cf_glob(int *flagsp, const char *buf,
 {
 	int len, nwords = 0;
 	char **words = NULL;
-	bool is_command;
+	Wahr is_command;
 
 	len = x_locate_word(buf, buflen, pos, startp, &is_command);
 	if (!((*flagsp) & XCF_COMMAND))
-		is_command = false;
+		is_command = Nee;
 	/*
 	 * Don't do command globing on zero length strings - it takes too
 	 * long and isn't very useful. File globs are more likely to be
@@ -670,7 +689,7 @@ x_cf_glob(int *flagsp, const char *buf,
 
 		if (*toglob == '~' && /* not vdirsep */ !vstrchr(toglob, '/')) {
 			/* neither for '~foo' (but '~foo/bar') */
-			*flagsp |= XCF_IS_NOSPACE;
+			*flagsp |= XCF_IS_HOMEDIR;
 			goto dont_add_glob;
 		}
 
@@ -782,7 +801,7 @@ glob_table(const char *pat, XPtrV *wp, s
 
 	ktwalk(&ts, tp);
 	while ((te = ktnext(&ts)))
-		if (gmatchx(te->name, pat, false)) {
+		if (gmatchx(te->name, pat, Nee)) {
 			char *cp;
 
 			strdupx(cp, te->name, ATEMP);
@@ -829,7 +848,7 @@ glob_path(int flags, const char *pat, XP
 
 		oldsize = XPsize(*wp);
 		/* mark dirs */
-		glob_str(Xstring(xs, xp), wp, true);
+		glob_str(Xstring(xs, xp), wp, Ja);
 		newsize = XPsize(*wp);
 
 		/* Check that each match is executable... */
@@ -886,9 +905,63 @@ x_escape(const char *s, size_t len, int
 	return (rval);
 }
 
-
 /* +++ emacs editing mode +++ */
 
+/*-
+ * The input buffer "buf" is pointed to by "xbuf" and its end is
+ * pointed to by "xend".  The current position in "xbuf" and end of
+ * the edit line are pointed to by "xcp" and "xep" respectively.
+ * "xbp" points to the start of a display window within "xbuf", and
+ * "xlp" points to the last visible character on screen, if valid;
+ * "xdp" points to the end of x_displen, adding one-column bytes if
+ * necessary when the input line is shorter.
+ *
+ * [A] starting position
+ *
+ *      buf
+ * |<--------- $COLUMNS -------->|
+ *      |<---- x_displen ------->|
+ *  PS1 |
+ *      +=====+=========+........+.............................+
+ *      |\     \        |\        \                             \
+ *   xbuf xbp   xcp   xlp xep      xdp                           xend
+ *
+ * [B] larger input line
+ *
+ *      buf
+ * |<--------- $COLUMNS -------->|
+ *      |<---- x_displen ------->|
+ *  PS1 |
+ *      +===========+============+---------------------+.......+
+ *      |\          \             \                     \       \
+ *   xbuf xbp        xcp           xlp=xdp               xep     xend
+ *
+ * [C] scrolled
+ *
+ *      buf
+ *      |       |<--------- $COLUMNS -------->|
+ *      |       |<--------- x_displen ------->|
+ *      |
+ *      +-------+==============+==============+--------+.......+
+ *      |        \              \              \        \       \
+ *   xbuf         xbp            xcp            xlp=xdp  xep     xend
+ *
+ * In the above -------- represents the current edit line while
+ * ===== represents that portion which is visible on the screen;
+ * ....... is unused space in buf. Note that initially xbp == xbuf
+ * and PS1 is displayed. PS1 uses some of the screen width and thus
+ * "x_displen" is less than $COLUMNS.
+ *
+ * Any time that "xcp" moves outside the region bounded by "xbp"
+ * and "xbp" + "x_displen", the function x_adjust() is called to
+ * relocate "xbp" appropriately and redraw the line.
+ *
+ * Excessive I/O is avoided where possible.  x_goto() for instance
+ * calculates whether the destination is outside the visible
+ * region, and if so simply adjusts "xcp" and calls x_adjust()
+ * directly.  Normally though x_adjust() is called from x_putc().
+ */
+
 static	Area	aedit;
 #define	AEDIT	&aedit		/* area for kill ring and macro defns */
 
@@ -913,9 +986,6 @@ struct x_defbindings {
 #define	XF_NOBIND	2	/* not allowed to bind to function */
 #define	XF_PREFIX	4	/* function sets prefix */
 
-#define X_NTABS		4			/* normal, meta1, meta2, pc */
-#define X_TABSZ		256			/* size of keydef tables etc */
-
 /*-
  * Arguments for do_complete()
  * 0 = enumerate	M-=	complete as much as possible and then list
@@ -937,18 +1007,20 @@ static char *xcp;		/* current position *
 static char *xep;		/* current end */
 static char *xbp;		/* start of visible portion of input buffer */
 static char *xlp;		/* last char visible on screen */
-static bool x_adj_ok;
+static char *xdp;		/* xbuf + x_displen except multibyte-aware */
+static Wahr x_adj_ok;
 /*
  * we use x_adj_done so that functions can tell
  * whether x_adjust() has been called while they are active.
  */
-static int x_adj_done;		/* is incremented by x_adjust() */
+static kby x_adj_done;		/* is incremented by x_adjust() */
 
 static int x_displen;
 static int x_arg;		/* general purpose arg */
-static bool x_arg_defaulted;	/* x_arg not explicitly set; defaulted to 1 */
+static Wahr x_arg_defaulted;	/* x_arg not explicitly set; defaulted to 1 */
 
-static bool xlp_valid;		/* lastvis pointer was recalculated */
+/* indicates both xlp and xdp are valid (x_goto needs the latter) */
+static Wahr xlp_valid;		/* lastvis pointer was recalculated */
 
 static char **x_histp;		/* history position */
 static int x_nextcmd;		/* for newline-and-next */
@@ -956,18 +1028,16 @@ static char **x_histncp;	/* saved x_hist
 static char **x_histmcp;	/* saved x_histp for " */
 static char *xmp;		/* mark pointer */
 static unsigned char x_last_command;
-static unsigned char (*x_tab)[X_TABSZ];	/* key definition */
+static kby x_curprefix;
+static kby *x_btab;		/* bitmap of keys bound by the user */
+static kby *x_ktab;		/* key definitions */
 #ifndef MKSH_SMALL
-static char *(*x_atab)[X_TABSZ];	/* macro definitions */
+static char **x_mtab;		/* macro definitions */
+static char *macroptr;		/* bind key macro active? */
 #endif
-static unsigned char x_bound[(X_TABSZ * X_NTABS + 7) / 8];
 #define KILLSIZE	20
 static char *killstack[KILLSIZE];
 static int killsp, killtp;
-static int x_curprefix;
-#ifndef MKSH_SMALL
-static char *macroptr;		/* bind key macro active? */
-#endif
 #if !MKSH_S_NOVI
 static int winwidth;		/* width of window */
 static char *wbuf[2];		/* window buffers */
@@ -980,17 +1050,22 @@ static int pwidth;		/* width of prompt *
 static int prompt_trunc;	/* how much of prompt to truncate or -1 */
 static int x_col;		/* current column on line */
 
-static int x_ins(const char *);
-static void x_delete(size_t, bool);
-static size_t x_bword(void);
-static size_t x_fword(bool);
+/* normal, prefix1, prefix2, IBM PC, ^V (literal) */
+#define X_NTABS			4U
+#define X_NOTAB			0xFFU
+/* array indicēs; x_btab is inlined, bitmap at only two places */
+#define X_xTABidx(pfx,key)	((KBI(pfx) << 8) | KBI(key))
+#define X_KTAB(pfx,key)		x_ktab[X_xTABidx((pfx), (key))]
+#define X_MTAB(pfx,key)		x_mtab[X_xTABidx((pfx), (key))]
+
+static int x_ins(const void *);
+static void x_delete(size_t, Wahr);
+static void x_bword(kui, Wahr);
+static void x_fword(kui, Wahr);
 static void x_goto(char *);
-static char *x_bs0(char *, char *) MKSH_A_PURE;
 static void x_bs3(char **);
-static int x_size2(char *, char **);
-static void x_zots(char *);
-static void x_zotc3(char **);
-static void x_vi_zotc(int);
+static void x_uescs(char *);
+static void x_uescmb(char **);
 static void x_load_hist(char **);
 static int x_search(const char *, int, int);
 #ifndef MKSH_SMALL
@@ -999,19 +1074,18 @@ static int x_search_dir(int);
 static int x_match(const char *, const char *);
 static void x_redraw(int);
 static void x_push(size_t);
-static void x_bind_showone(int, int);
+static void x_bind_showone(kui, kui);
 static void x_e_ungetc(int);
 static int x_e_getc(void);
-static void x_e_putc2(int);
-static void x_e_putc3(const char **);
+static void x_e_putb(int);
 static void x_e_puts(const char *);
 #ifndef MKSH_SMALL
-static int x_fold_case(int);
+static int x_fold_case(int, kui);
 #endif
 static char *x_lastcp(void);
 static void x_lastpos(void);
 static void do_complete(int, Comp_type);
-static size_t x_nb2nc(size_t) MKSH_A_PURE;
+static size_t x_nb2nc(size_t);
 
 static int unget_char = -1;
 
@@ -1042,6 +1116,12 @@ static struct x_defbindings const x_defb
 	{ XFUNC_mv_bword,		1,	'b'	},
 	{ XFUNC_mv_fword,		1,	'f'	},
 	{ XFUNC_del_fword,		1,	'd'	},
+#ifndef MKSH_SMALL
+	{ XFUNC_del_bbigword,		1,	'H'	},
+	{ XFUNC_mv_bbigword,		1,	'B'	},
+	{ XFUNC_mv_fbigword,		1,	'F'	},
+	{ XFUNC_del_fbigword,		1,	'D'	},
+#endif
 	{ XFUNC_mv_back,		0,  CTRL_B	},
 	{ XFUNC_mv_forw,		0,  CTRL_F	},
 	{ XFUNC_search_char_forw,	0,  CTRL_BC	},
@@ -1079,7 +1159,7 @@ static struct x_defbindings const x_defb
 	{ XFUNC_list_comm,		2,	'?'	},
 	{ XFUNC_list_file,		2,  CTRL_Y	},
 	{ XFUNC_set_mark,		1,	' '	},
-	{ XFUNC_kill_region,		0,  CTRL_W	},
+	{ XFUNC_kill_region,		1,  CTRL_W	},
 	{ XFUNC_xchg_point_mark,	2,  CTRL_X	},
 	{ XFUNC_literal,		0,  CTRL_V	},
 	{ XFUNC_version,		1,  CTRL_V	},
@@ -1096,11 +1176,11 @@ static struct x_defbindings const x_defb
 	{ XFUNC_set_arg,		1,	'8'	},
 	{ XFUNC_set_arg,		1,	'9'	},
 #ifndef MKSH_SMALL
-	{ XFUNC_fold_upper,		1,	'U'	},
+	{ XFUNC_foldb_upper,		1,	'U'	},
 	{ XFUNC_fold_upper,		1,	'u'	},
-	{ XFUNC_fold_lower,		1,	'L'	},
+	{ XFUNC_foldb_lower,		1,	'L'	},
 	{ XFUNC_fold_lower,		1,	'l'	},
-	{ XFUNC_fold_capitalise,	1,	'C'	},
+	{ XFUNC_foldb_capitalise,	1,	'C'	},
 	{ XFUNC_fold_capitalise,	1,	'c'	},
 #endif
 	/*
@@ -1158,7 +1238,7 @@ x_nb2nc(size_t nb)
 	size_t nc = 0;
 
 	for (cp = xcp; cp < (xcp + nb); ++nc)
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 	return (nc);
 }
 
@@ -1175,39 +1255,45 @@ x_modified(void)
 #ifdef MKSH_SMALL
 #define XFUNC_VALUE(f) (f)
 #else
-#define XFUNC_VALUE(f) (f & 0x7F)
+#define XFUNC_VALUE(f) (f & 0x7FU)
 #endif
 
 static int
-x_e_getmbc(char *sbuf)
+x_e_getmbc(char *buf)
 {
-	int c, pos = 0;
-	unsigned char *buf = (unsigned char *)sbuf;
+	int c, pos;
+	kby f;
 
-	memset(buf, 0, 4);
-	buf[pos++] = c = x_e_getc();
-	if (c == -1)
+	if ((c = x_e_getc()) == -1)
 		return (-1);
-	if (UTFMODE) {
-		if ((rtt2asc(buf[0]) >= (unsigned char)0xC2) &&
-		    (rtt2asc(buf[0]) < (unsigned char)0xF0)) {
-			c = x_e_getc();
-			if (c == -1)
-				return (-1);
-			if ((rtt2asc(c) & 0xC0) != 0x80) {
-				x_e_ungetc(c);
-				return (1);
-			}
-			buf[pos++] = c;
+	buf[0] = c;
+	if (!UTFMODE) {
+		buf[1] = '\0';
+		return (1);
+	}
+
+	pos = 1;
+	f = rtt2asc(c);
+	if (f >= 0xC2U && f < 0xF0U) {
+		if ((c = x_e_getc()) == -1)
+			return (-1);
+		if ((rtt2asc(c) & 0xC0U) != 0x80U) {
+			x_e_ungetc(c);
+			goto out;
 		}
-		if ((rtt2asc(buf[0]) >= (unsigned char)0xE0) &&
-		    (rtt2asc(buf[0]) < (unsigned char)0xF0)) {
-			/* XXX x_e_ungetc is one-octet only */
-			buf[pos++] = c = x_e_getc();
-			if (c == -1)
+		buf[pos++] = c;
+		if (f >= 0xE0U) {
+			if ((c = x_e_getc()) == -1)
 				return (-1);
+			/* XXX x_e_ungetc is one-octet only */
+			if ((rtt2asc(c) & 0xC0U) != 0x80U)
+				x_e_ungetc(c);
+			else
+				buf[pos++] = c;
 		}
 	}
+ out:
+	buf[pos] = '\0';
 	return (pos);
 }
 
@@ -1218,7 +1304,7 @@ x_e_getmbc(char *sbuf)
 #define MIN_EDIT_SPACE	7
 
 static void
-x_init_prompt(bool doprint)
+x_init_prompt(Wahr doprint)
 {
 	prompt_trunc = pprompt(prompt, doprint ? 0 : -1);
 	pwidth = prompt_trunc % x_cols;
@@ -1228,11 +1314,11 @@ x_init_prompt(bool doprint)
 		prompt_trunc = -1;
 		pwidth = 0;
 		if (doprint)
-			x_e_putc2('\n');
+			x_e_putb('\n');
 	}
 }
 
-static int
+static ssize_t
 x_emacs(char *buf)
 {
 	int c, i;
@@ -1242,16 +1328,19 @@ x_emacs(char *buf)
 	xend = buf + LINE;
 	xlp = xcp = xep = buf;
 	*xcp = 0;
-	xlp_valid = true;
 	xmp = NULL;
 	x_curprefix = 0;
 	x_histmcp = x_histp = histptr + 1;
 	x_last_command = XFUNC_error;
 
-	x_init_prompt(true);
-	x_displen = (xx_cols = x_cols) - 2 - (x_col = pwidth);
+	xx_cols = x_cols;
+	x_adj_ok = Nee;
+	x_init_prompt(Ja);
+	x_displen = xx_cols - 2 - (x_col = pwidth);
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	x_adj_done = 0;
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 
 	x_histncp = NULL;
 	if (x_nextcmd >= 0) {
@@ -1266,10 +1355,10 @@ x_emacs(char *buf)
 	while (/* CONSTCOND */ 1) {
 		x_flush();
 		if ((c = x_e_getc()) < 0)
-			return (0);
+			return (-1);
 
-		f = x_curprefix == -1 ? XFUNC_insert :
-		    x_tab[x_curprefix][c];
+		f = x_curprefix == X_NOTAB ? XFUNC_insert :
+		    X_KTAB(x_curprefix, c);
 #ifndef MKSH_SMALL
 		if (f & 0x80) {
 			f &= 0x7F;
@@ -1285,9 +1374,9 @@ x_emacs(char *buf)
 		if (!(x_ftab[f].xf_flags & XF_PREFIX) &&
 		    x_last_command != XFUNC_set_arg) {
 			x_arg = 1;
-			x_arg_defaulted = true;
+			x_arg_defaulted = Ja;
 		}
-		i = c | (x_curprefix << 8);
+		i = (int)X_xTABidx(x_curprefix, c);
 		x_curprefix = 0;
 		switch ((*x_ftab[f].xf_func)(i)) {
 		case KSTD:
@@ -1295,8 +1384,7 @@ x_emacs(char *buf)
 				x_last_command = f;
 			break;
 		case KEOL:
-			i = xep - xbuf;
-			return (i);
+			return (xep - xbuf);
 		case KINTR:
 			/* special case for interrupt */
 			x_intr(SIGINT, c);
@@ -1309,57 +1397,55 @@ x_emacs(char *buf)
 static int
 x_insert(int c)
 {
-	static int left, pos, save_arg;
-	static char str[4];
+	static kby str[5], state;
+	static int save_arg;
+	kby b;
 
 	/*
 	 * Should allow tab and control chars.
 	 */
 	if (c == 0) {
- invmbs:
-		left = 0;
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
+		state = 0;
 		return (KSTD);
 	}
-	if (UTFMODE) {
-		if (((rtt2asc(c) & 0xC0) == 0x80) && left) {
-			str[pos++] = c;
-			if (!--left) {
-				str[pos] = '\0';
-				x_arg = save_arg;
-				while (x_arg--)
-					x_ins(str);
-			}
-			return (KSTD);
-		}
-		if (left) {
-			if (x_curprefix == -1) {
-				/* flush invalid multibyte */
-				str[pos] = '\0';
-				while (save_arg--)
-					x_ins(str);
-			}
-		}
-		if ((c >= 0xC2) && (c < 0xE0))
-			left = 1;
-		else if ((c >= 0xE0) && (c < 0xF0))
-			left = 2;
-		else if (c > 0x7F)
-			goto invmbs;
-		else
-			left = 0;
-		if (left) {
-			save_arg = x_arg;
-			pos = 1;
-			str[0] = c;
-			return (KSTD);
-		}
+	if (!UTFMODE) {
+ sbc:
+		str[0] = c;
+		str[1] = '\0';
+ mbc:
+		while (x_arg--)
+			x_ins(str);
+		state = 0;
+		return (KSTD);
 	}
-	left = 0;
+	b = rtt2asc(c);
+	if (state) {
+		/* this a continuation octet? */
+		if ((b & 0xC0U) == 0x80U) {
+			/* states: 1, 5, 6 */
+			str[state & 3] = c;
+			++state;
+			/* states: 2, 6, 7 */
+			if (state == 6)
+				/* another octet needed */
+				return (KSTD);
+			/* finishing up this multibyte character */
+			str[state & 3] = '\0';
+			x_arg = save_arg;
+			goto mbc;
+		}
+		/* flush invalid multibyte octets */
+		str[state & 3] = '\0';
+		while (save_arg--)
+			x_ins(str);
+		/* begin a new multibyte character */
+	}
+	if (b < 0xC2U || b >= 0xF0)
+		goto sbc;
+	state = b < 0xE0U ? 1 : 5;
 	str[0] = c;
-	str[1] = '\0';
-	while (x_arg--)
-		x_ins(str);
+	save_arg = x_arg;
 	return (KSTD);
 }
 
@@ -1367,7 +1453,7 @@ x_insert(int c)
 static int
 x_ins_string(int c)
 {
-	macroptr = x_atab[c >> 8][c & 255];
+	macroptr = x_mtab[KUI(c)];
 	/*
 	 * we no longer need to bother checking if macroptr is
 	 * not NULL but first char is NUL; x_e_getc() does it
@@ -1380,7 +1466,7 @@ static int
 x_do_ins(const char *cp, size_t len)
 {
 	if (xep + len >= xend) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (-1);
 	}
 	memmove(xcp + len, xcp, xep - xcp + 1);
@@ -1392,25 +1478,25 @@ x_do_ins(const char *cp, size_t len)
 }
 
 static int
-x_ins(const char *s)
+x_ins(const void *s)
 {
 	char *cp = xcp;
-	int adj = x_adj_done;
+	kby adj = x_adj_done;
 
 	if (x_do_ins(s, strlen(s)) < 0)
 		return (-1);
 	/*
-	 * x_zots() may result in a call to x_adjust()
-	 * we want xcp to reflect the new position.
+	 * x_uescs() may result in a call to x_adjust()
+	 * we want xcp to reflect the new position
 	 */
-	xlp_valid = false;
+	xlp_valid = Nee;
 	x_lastcp();
-	x_adj_ok = tobool(xcp >= xlp);
-	x_zots(cp);
+	x_adj_ok = isWahr(xcp >= xlp);
+	x_uescs(cp);
 	if (adj == x_adj_done)
 		/* x_adjust() has not been called */
 		x_lastpos();
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 	return (0);
 }
 
@@ -1420,13 +1506,13 @@ x_del_back(int c MKSH_A_UNUSED)
 	ssize_t i = 0;
 
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	do {
 		x_goto(xcp - 1);
 	} while ((++i < x_arg) && (xcp != xbuf));
-	x_delete(i, false);
+	x_delete(i, Nee);
 	return (KSTD);
 }
 
@@ -1438,7 +1524,7 @@ x_del_char(int c MKSH_A_UNUSED)
 
 	cp = xcp;
 	while (i < (size_t)x_arg) {
-		utf_ptradjx(cp, cp2);
+		cp2 = cp + ez_mbtoc(NULL, cp);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1446,16 +1532,16 @@ x_del_char(int c MKSH_A_UNUSED)
 	}
 
 	if (!i) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
-	x_delete(i, false);
+	x_delete(i, Nee);
 	return (KSTD);
 }
 
 /* Delete nc chars to the right of the cursor (including cursor position) */
 static void
-x_delete(size_t nc, bool push)
+x_delete(size_t nc, Wahr push)
 {
 	size_t i, nb, nw;
 	char *cp;
@@ -1469,7 +1555,7 @@ x_delete(size_t nc, bool push)
 		char *cp2;
 		int j;
 
-		j = x_size2(cp, &cp2);
+		j = uwidthmbT(cp, &cp2);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1494,9 +1580,9 @@ x_delete(size_t nc, bool push)
 	/* Copies the NUL */
 	memmove(xcp, xcp + nb, xep - xcp + 1);
 	/* don't redraw */
-	x_adj_ok = false;
-	xlp_valid = false;
-	x_zots(xcp);
+	x_adj_ok = Nee;
+	xlp_valid = Nee;
+	x_uescs(xcp);
 	/*
 	 * if we are already filling the line,
 	 * there is no need to ' ', '\b'.
@@ -1505,17 +1591,17 @@ x_delete(size_t nc, bool push)
 	if ((i = xx_cols - 2 - x_col) > 0 || xep - xlp == 0) {
 		nw = i = (nw < i) ? nw : i;
 		while (i--)
-			x_e_putc2(' ');
+			x_e_putb(' ');
 		if (x_col == xx_cols - 2) {
-			x_e_putc2((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
+			x_e_putb((xep > xlp) ? '>' : (xbp > xbuf) ? '<' : ' ');
 			++nw;
 		}
 		while (nw--)
-			x_e_putc2('\b');
+			x_e_putb('\b');
 	}
 	/*x_goto(xcp);*/
-	x_adj_ok = true;
-	xlp_valid = false;
+	x_adj_ok = Ja;
+	xlp_valid = Nee;
 	x_lastpos();
 	x_modified();
 	return;
@@ -1524,82 +1610,121 @@ x_delete(size_t nc, bool push)
 static int
 x_del_bword(int c MKSH_A_UNUSED)
 {
-	x_delete(x_bword(), true);
+	x_bword(C_MFS, Ja);
 	return (KSTD);
 }
 
 static int
 x_mv_bword(int c MKSH_A_UNUSED)
 {
-	x_bword();
+	x_bword(C_MFS, Nee);
 	return (KSTD);
 }
 
 static int
 x_mv_fword(int c MKSH_A_UNUSED)
 {
-	x_fword(true);
+	x_fword(C_MFS, Nee);
 	return (KSTD);
 }
 
 static int
 x_del_fword(int c MKSH_A_UNUSED)
 {
-	x_delete(x_fword(false), true);
+	x_fword(C_MFS, Ja);
 	return (KSTD);
 }
 
-static size_t
-x_bword(void)
+#ifndef MKSH_SMALL
+static int
+x_del_bbigword(int c MKSH_A_UNUSED)
+{
+	x_bword(C_BLANK, Ja);
+	return (KSTD);
+}
+
+static int
+x_mv_bbigword(int c MKSH_A_UNUSED)
+{
+	x_bword(C_BLANK, Nee);
+	return (KSTD);
+}
+
+static int
+x_mv_fbigword(int c MKSH_A_UNUSED)
+{
+	x_fword(C_BLANK, Nee);
+	return (KSTD);
+}
+
+static int
+x_del_fbigword(int c MKSH_A_UNUSED)
+{
+	x_fword(C_BLANK, Ja);
+	return (KSTD);
+}
+#endif
+
+static void
+x_bword(kui separator, Wahr erase)
 {
 	size_t nb = 0;
 	char *cp = xcp;
 
 	if (cp == xbuf) {
-		x_e_putc2(KSH_BEL);
-		return (0);
+		x_e_putb(KSH_BEL);
+		return;
 	}
 	while (x_arg--) {
-		while (cp != xbuf && ctype(cp[-1], C_MFS)) {
+		while (cp != xbuf && ctype(cp[-1], separator)) {
 			cp--;
 			nb++;
 		}
-		while (cp != xbuf && !ctype(cp[-1], C_MFS)) {
+		while (cp != xbuf && !ctype(cp[-1], separator)) {
 			cp--;
 			nb++;
 		}
 	}
 	x_goto(cp);
-	return (x_nb2nc(nb));
+	if (erase)
+		x_delete(x_nb2nc(nb), Ja);
 }
 
-static size_t
-x_fword(bool move)
+static void
+x_fword(kui separator, Wahr erase)
 {
-	size_t nc;
 	char *cp = xcp;
 
 	if (cp == xep) {
-		x_e_putc2(KSH_BEL);
-		return (0);
+		x_e_putb(KSH_BEL);
+		return;
 	}
 	while (x_arg--) {
-		while (cp != xep && ctype(*cp, C_MFS))
+		while (cp != xep && ctype(*cp, separator))
 			cp++;
-		while (cp != xep && !ctype(*cp, C_MFS))
+		while (cp != xep && !ctype(*cp, separator))
 			cp++;
 	}
-	nc = x_nb2nc(cp - xcp);
-	if (move)
+	if (erase)
+		x_delete(x_nb2nc(cp - xcp), Ja);
+	else
 		x_goto(cp);
-	return (nc);
+}
+
+static void
+x_uescmb(char **cp)
+{
+	unsigned char esc[5];
+
+	uescmbT(esc, (const char **)cp);
+	x_e_puts((const void *)esc);
 }
 
 static void
 x_goto(char *cp)
 {
-	cp = cp >= xep ? xep : x_bs0(cp, xbuf);
-	if (cp < xbp || cp >= utf_skipcols(xbp, x_displen, NULL)) {
+	cp = cp >= xep ? xep : ez_bs(cp, xbuf);
+	if (cp < xbp || (x_lastcp(), cp >= xdp)) {
 		/* we are heading off screen */
 		xcp = cp;
 		x_adjust();
@@ -1610,81 +1735,36 @@ x_goto(char *cp)
 	} else if (cp > xcp) {
 		/* move forward */
 		while (cp > xcp)
-			x_zotc3(&xcp);
+			x_uescmb(&xcp);
 	}
 }
 
-static char *
-x_bs0(char *cp, char *lower_bound)
-{
-	if (UTFMODE)
-		while ((!lower_bound || (cp > lower_bound)) &&
-		    ((rtt2asc(*cp) & 0xC0) == 0x80))
-			--cp;
-	return (cp);
-}
-
 static void
 x_bs3(char **p)
 {
 	int i;
 
-	*p = x_bs0((*p) - 1, NULL);
-	i = x_size2(*p, NULL);
+	*p = ez_bs((*p) - 1, xbuf);
+	i = uwidthmbT(*p, NULL);
 	while (i--)
-		x_e_putc2('\b');
-}
-
-static int
-x_size2(char *cp, char **dcp)
-{
-	uint8_t c = *(unsigned char *)cp;
-
-	if (UTFMODE && (rtt2asc(c) > 0x7F))
-		return (utf_widthadj(cp, (const char **)dcp));
-	if (dcp)
-		*dcp = cp + 1;
-	if (c == '\t')
-		/* Kludge, tabs are always four spaces. */
-		return (4);
-	if (ksh_isctrl(c))
-		/* control unsigned char */
-		return (2);
-	return (1);
+		x_e_putb('\b');
 }
 
 static void
-x_zots(char *str)
+x_uescs(char *str)
 {
-	int adj = x_adj_done;
+	kby adj = x_adj_done;
 
 	x_lastcp();
 	while (*str && str < xlp && x_col < xx_cols && adj == x_adj_done)
-		x_zotc3(&str);
-}
-
-static void
-x_zotc3(char **cp)
-{
-	unsigned char c = **(unsigned char **)cp;
-
-	if (c == '\t') {
-		/* Kludge, tabs are always four spaces. */
-		x_e_puts(T4spaces);
-		(*cp)++;
-	} else if (ksh_isctrl(c)) {
-		x_e_putc2('^');
-		x_e_putc2(ksh_unctrl(c));
-		(*cp)++;
-	} else
-		x_e_putc3((const char **)cp);
+		x_uescmb(&str);
 }
 
 static int
 x_mv_back(int c MKSH_A_UNUSED)
 {
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
@@ -1701,11 +1781,11 @@ x_mv_forw(int c MKSH_A_UNUSED)
 	char *cp = xcp, *cp2;
 
 	if (xcp == xep) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
-		utf_ptradjx(cp, cp2);
+		cp2 = cp + ez_mbtoc(NULL, cp);
 		if (cp2 > xep)
 			break;
 		cp = cp2;
@@ -1718,17 +1798,17 @@ static int
 x_search_char_forw(int c MKSH_A_UNUSED)
 {
 	char *cp = xcp;
-	char tmp[4];
+	char tmp[5];
 
 	*xep = '\0';
 	if (x_e_getmbc(tmp) < 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
-		if ((cp = (cp == xep) ? NULL : strstr(cp + 1, tmp)) == NULL &&
-		    (cp = strstr(xbuf, tmp)) == NULL) {
-			x_e_putc2(KSH_BEL);
+		if ((cp = (cp == xep) ? NULL : ucstrstr(cp + 1, tmp)) == NULL &&
+		    (cp = ucstrstr(xbuf, tmp)) == NULL) {
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 	}
@@ -1739,11 +1819,11 @@ x_search_char_forw(int c MKSH_A_UNUSED)
 static int
 x_search_char_back(int c MKSH_A_UNUSED)
 {
-	char *cp = xcp, *p, tmp[4];
-	bool b;
+	char *cp = xcp, *p, tmp[5];
+	Wahr b;
 
 	if (x_e_getmbc(tmp) < 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	for (; x_arg--; cp = p)
@@ -1751,19 +1831,19 @@ x_search_char_back(int c MKSH_A_UNUSED)
 			if (p-- == xbuf)
 				p = xep;
 			if (p == cp) {
-				x_e_putc2(KSH_BEL);
+				x_e_putb(KSH_BEL);
 				return (KSTD);
 			}
 			if ((tmp[1] && ((p+1) > xep)) ||
 			    (tmp[2] && ((p+2) > xep)))
 				continue;
-			b = true;
+			b = Ja;
 			if (*p != tmp[0])
-				b = false;
+				b = Nee;
 			if (b && tmp[1] && p[1] != tmp[1])
-				b = false;
+				b = Nee;
 			if (b && tmp[2] && p[2] != tmp[2])
-				b = false;
+				b = Nee;
 			if (b)
 				break;
 		}
@@ -1774,8 +1854,8 @@ x_search_char_back(int c MKSH_A_UNUSED)
 static int
 x_newline(int c MKSH_A_UNUSED)
 {
-	x_e_putc2('\r');
-	x_e_putc2('\n');
+	x_e_putb('\r');
+	x_e_putb('\n');
 	x_flush();
 	*xep++ = '\n';
 	return (KEOL);
@@ -1784,11 +1864,12 @@ x_newline(int c MKSH_A_UNUSED)
 static int
 x_end_of_text(int c MKSH_A_UNUSED)
 {
-	unsigned char tmp[1], *cp = tmp;
+	unsigned char tmp[2], *cp = tmp;
 
 	*tmp = isedchar(edchars.eof) ? (unsigned char)edchars.eof :
 	    (unsigned char)CTRL_D;
-	x_zotc3((char **)&cp);
+	tmp[1] = '\0';
+	x_uescmb((char **)&cp);
 	x_putc('\r');
 	x_putc('\n');
 	x_flush();
@@ -1847,7 +1928,7 @@ x_load_hist(char **hp)
 		sp = holdbufp;
 		modified = 0;
 	} else if (hp < history || hp > histptr) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return;
 	}
 	if (sp == NULL)
@@ -1901,12 +1982,12 @@ x_search_hist(int c)
 		x_flush();
 		if ((c = x_e_getc()) < 0)
 			return (KSTD);
-		f = x_tab[0][c];
-		if (c == CTRL_BO) {
+		f = X_KTAB(0, c);
+		if (ord(c) == CTRL_BO) {
 			if ((f & 0x7F) == XFUNC_meta1) {
 				if ((c = x_e_getc()) < 0)
 					return (KSTD);
-				f = x_tab[1][c] & 0x7F;
+				f = X_KTAB(1, c) & 0x7F;
 				if (f == XFUNC_meta1 || f == XFUNC_meta2)
 					x_meta1(CTRL_BO);
 				x_e_ungetc(c);
@@ -1928,7 +2009,7 @@ x_search_hist(int c)
 				break;
 			}
 			if (p > pat) {
-				p = x_bs0(p - 1, pat);
+				p = ez_bs(p - 1, pat);
 				*p = '\0';
 			}
 			if (p == pat)
@@ -1940,7 +2021,7 @@ x_search_hist(int c)
 			/* add char to pattern */
 			/* overflow check... */
 			if ((size_t)(p - pat) >= sizeof(pat) - 1) {
-				x_e_putc2(KSH_BEL);
+				x_e_putb(KSH_BEL);
 				continue;
 			}
 			*p++ = c, *p = '\0';
@@ -1983,13 +2064,13 @@ x_search(const char *pat, int sameline,
 		i = x_match(*hp, pat);
 		if (i >= 0) {
 			if (offset < 0)
-				x_e_putc2('\n');
+				x_e_putb('\n');
 			x_load_hist(hp);
 			x_goto(xbuf + i + patlen);
 			return (i);
 		}
 	}
-	x_e_putc2(KSH_BEL);
+	x_e_putb(KSH_BEL);
 	x_histp = histptr;
 	return (-1);
 }
@@ -2011,7 +2092,7 @@ x_search_hist_dn(int c MKSH_A_UNUSED)
 
 /* anchored search in the indicated direction */
 static int
-x_search_dir(int search_dir /* should've been bool */)
+x_search_dir(int search_dir /* should've been Wahr */)
 {
 	char **hp = x_histp + search_dir;
 	size_t curs = xcp - xbuf;
@@ -2035,7 +2116,7 @@ x_match(const char *str, const char *pat
 	if (*pat == '^') {
 		return ((strncmp(str, pat + 1, strlen(pat + 1)) == 0) ? 0 : -1);
 	} else {
-		char *q = strstr(str, pat);
+		const char *q = cstrstr(str, pat);
 		return ((q == NULL) ? -1 : q - str);
 	}
 }
@@ -2046,7 +2127,8 @@ x_del_line(int c MKSH_A_UNUSED)
 	*xep = 0;
 	x_push(xep - (xcp = xbuf));
 	xlp = xbp = xep = xbuf;
-	xlp_valid = true;
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	*xcp = 0;
 	xmp = NULL;
 	x_redraw('\r');
@@ -2079,6 +2161,11 @@ static int
 x_cls(int c MKSH_A_UNUSED)
 {
 	shf_puts(MKSH_CLS_STRING, shl_out);
+	if (prompt_trunc) {
+		/* multi-line prompt */
+		pprompt(prompt, 0);
+		/* x_redraw takes care of the last line */
+	}
 	x_redraw(0);
 	return (KSTD);
 }
@@ -2090,16 +2177,18 @@ x_cls(int c MKSH_A_UNUSED)
  * lastch MUST be an ASCII character with wcwidth(lastch) == 1
  */
 static void
-x_clrtoeol(int lastch, bool line_was_cleared)
+x_clrtoeol(int lastch, Wahr line_was_cleared)
 {
 	int col;
 
-	if (lastch == ' ' && !line_was_cleared && x_term_mode == 1) {
-		shf_puts(KSH_ESC_STRING "[K", shl_out);
-		line_was_cleared = true;
+	if (lastch == ' ') {
+		if (line_was_cleared)
+			return;
+		if (x_term_mode == 1) {
+			shf_puts(KSH_ESC_STRING "[K", shl_out);
+			return;
+		}
 	}
-	if (lastch == ' ' && line_was_cleared)
-		return;
 
 	col = x_col;
 	while (col < (xx_cols - 2)) {
@@ -2129,24 +2218,24 @@ x_redraw(int cr)
 {
 	int lch;
 
-	x_adj_ok = false;
+	x_adj_ok = Nee;
 	/* clear the line */
-	x_e_putc2(cr ? cr : '\r');
+	x_e_putb(cr ? cr : '\r');
 	x_flush();
 	/* display the prompt */
 	if (xbp == xbuf)
 		x_pprompt();
 	x_displen = xx_cols - 2 - x_col;
 	/* display the line content */
-	xlp_valid = false;
-	x_zots(xbp);
+	xlp_valid = Nee;
+	x_uescs(xbp);
 	/* check whether there is more off-screen */
 	lch = xep > xlp ? (xbp > xbuf ? '*' : '>') : (xbp > xbuf) ? '<' : ' ';
 	/* clear the rest of the line */
 	x_clrtoeol(lch, !cr || cr == '\n');
 	/* go back to actual cursor position */
 	x_lastpos();
-	x_adj_ok = true;
+	x_adj_ok = Ja;
 }
 
 static int
@@ -2161,19 +2250,20 @@ x_transpose(int c MKSH_A_UNUSED)
 	 *	Who			Before	After	Before	After
 	 *	AT&T ksh in emacs mode:	abCd	abdC	abcd_	(bell)
 	 *	AT&T ksh in gmacs mode:	abCd	baCd	abcd_	abdc_
-	 *	gnu emacs:		abCd	acbD	abcd_	abdc_
-	 * Pdksh currently goes with GNU behavior since I believe this is the
+	 *	GNU emacs:		abCd	acbD	abcd_	abdc_
+	 * pdksh currently goes with GNU behavior since I believe this is the
 	 * most common version of emacs, unless in gmacs mode, in which case
 	 * it does the AT&T ksh gmacs mode.
 	 * This should really be broken up into 3 functions so users can bind
 	 * to the one they want.
 	 */
 	if (xcp == xbuf) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
-	} else if (xcp == xep || Flag(FGMACS)) {
+	}
+	if (xcp == xep || Flag(FGMACS)) {
 		if (xcp - xbuf == 1) {
-			x_e_putc2(KSH_BEL);
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 		/*
@@ -2181,38 +2271,20 @@ x_transpose(int c MKSH_A_UNUSED)
 		 * the cursor, do not change cursor position
 		 */
 		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		utf_wctomb(xcp, tmpa);
-		x_zotc3(&xcp);
-		utf_wctomb(xcp, tmpb);
-		x_zotc3(&xcp);
-	} else {
-		/*
+	}
+	/* else
 		 * GNU emacs style: Swap the characters before and under the
 		 * cursor, move cursor position along one.
 		 */
-		if (utf_mbtowc(&tmpa, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		x_bs3(&xcp);
-		if (utf_mbtowc(&tmpb, xcp) == (size_t)-1) {
-			x_e_putc2(KSH_BEL);
-			return (KSTD);
-		}
-		utf_wctomb(xcp, tmpa);
-		x_zotc3(&xcp);
-		utf_wctomb(xcp, tmpb);
-		x_zotc3(&xcp);
-	}
+	ez_mbtoc(&tmpa, xcp);
+	x_bs3(&xcp);
+	ez_mbtoc(&tmpb, xcp);
+	/* ensure that swapping e.g. raw 0xA4 0xC3 doesn’t break separation */
+	xcp[ez_ctomb(xcp, tmpa)] = '\0';
+	x_uescmb(&xcp);
+	ez_ctomb(xcp, tmpb);
+	x_uescmb(&xcp);
+	/* though a ^L now re-recognises that, probably okay */
 	x_modified();
 	return (KSTD);
 }
@@ -2220,7 +2292,7 @@ x_transpose(int c MKSH_A_UNUSED)
 static int
 x_literal(int c MKSH_A_UNUSED)
 {
-	x_curprefix = -1;
+	x_curprefix = X_NOTAB;
 	return (KSTD);
 }
 
@@ -2259,7 +2331,7 @@ x_kill(int c MKSH_A_UNUSED)
 		ndel = col - narg;
 	} else
 		ndel = narg - col;
-	x_delete(x_nb2nc(ndel), true);
+	x_delete(x_nb2nc(ndel), Ja);
 	return (KSTD);
 }
 
@@ -2297,13 +2369,13 @@ x_meta_yank(int c MKSH_A_UNUSED)
 	if ((x_last_command != XFUNC_yank && x_last_command != XFUNC_meta_yank) ||
 	    killstack[killtp] == 0) {
 		killtp = killsp;
-		x_e_puts("\nyank something first");
+		x_e_puts(Tyankfirst);
 		x_redraw('\n');
 		return (KSTD);
 	}
 	len = strlen(killstack[killtp]);
 	x_goto(xcp - len);
-	x_delete(x_nb2nc(len), false);
+	x_delete(x_nb2nc(len), Nee);
 	do {
 		if (killtp == 0)
 			killtp = KILLSIZE - 1;
@@ -2318,18 +2390,19 @@ x_meta_yank(int c MKSH_A_UNUSED)
 static void
 x_intr(int signo, int c)
 {
-	x_vi_zotc(c);
+	uprntc(c, shl_out);
 	*xep = '\0';
 	strip_nuls(xbuf, xep - xbuf);
 	if (*xbuf)
-		histsave(&source->line, xbuf, HIST_STORE, true);
+		histsave(&source->line, xbuf, HIST_STORE, Ja);
 	xlp = xep = xcp = xbp = xbuf;
-	xlp_valid = true;
+	xdp = xbp + x_displen;
+	xlp_valid = Ja;
 	*xcp = 0;
 	x_modified();
 	x_flush();
 	trapsig(signo);
-	x_mode(false);
+	x_mode(Nee);
 	unwind(LSHELL);
 }
 
@@ -2342,7 +2415,7 @@ x_abort(int c MKSH_A_UNUSED)
 static int
 x_error(int c MKSH_A_UNUSED)
 {
-	x_e_putc2(KSH_BEL);
+	x_e_putb(KSH_BEL);
 	return (KSTD);
 }
 
@@ -2359,7 +2432,7 @@ x_vt_hack(int c)
 	switch ((c = x_e_getc())) {
 	case '~':
 		x_arg = 1;
-		x_arg_defaulted = true;
+		x_arg_defaulted = Ja;
 		return (x_mv_beg(0));
 	case ';':
 		/* "interesting" sequence detected */
@@ -2397,77 +2470,65 @@ x_vt_hack(int c)
 int
 x_bind_check(void)
 {
-	return (x_tab == NULL);
+	return (x_btab == NULL);
 }
 
-static XString x_bind_show_xs;
-static char *x_bind_show_xp;
+static char *x_bind_show_s;
+static size_t x_bind_show_n;
 
 static void
-x_bind_show_ch(unsigned char ch)
+x_bind_showone(kui prefix, kui key)
 {
-	Xcheck(x_bind_show_xs, x_bind_show_xp);
-	switch (ch) {
-	case ORD('^'):
-	case ORD('\\'):
-	case ORD('='):
-		*x_bind_show_xp++ = '\\';
-		*x_bind_show_xp++ = ch;
-		break;
-	default:
-		if (ksh_isctrl(ch)) {
-			*x_bind_show_xp++ = '^';
-			*x_bind_show_xp++ = ksh_unctrl(ch);
-		} else
-			*x_bind_show_xp++ = ch;
-		break;
-	}
-}
-
-static void
-x_bind_showone(int prefix, int key)
-{
-	unsigned char f = XFUNC_VALUE(x_tab[prefix][key]);
+	kby f = XFUNC_VALUE(X_KTAB(prefix, key));
+	struct shf shf;
 
-	if (!x_bind_show_xs.areap)
-		XinitN(x_bind_show_xs, 16, AEDIT);
+	if (!x_bind_show_n)
+		x_bind_show_s = aresize(x_bind_show_s,
+		    (x_bind_show_n = 12), AEDIT);
 
-	x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
 	shf_puts("bind ", shl_stdout);
 #ifndef MKSH_SMALL
 	if (f == XFUNC_ins_string)
 		shf_puts("-m ", shl_stdout);
 #endif
+
+	shf_sreopen(x_bind_show_s, x_bind_show_n, AEDIT, &shf);
 	switch (prefix) {
 	case 1:
-		x_bind_show_ch(CTRL_BO);
+		uprntc(CTRL_BO, &shf);
 		break;
 	case 2:
-		x_bind_show_ch(CTRL_X);
+		uprntc(CTRL_X, &shf);
 		break;
 	case 3:
-		x_bind_show_ch(0);
+		uprntc(CTRL_AT, &shf);
 		break;
 	}
-	x_bind_show_ch(key);
+	switch (key) {
+	case ORD('^'):
+	case ORD('\\'):
+	case ORD('='):
+		shf_putc('\\', &shf);
+		shf_putc(key, &shf);
+		break;
+	default:
+		uprntc(key, &shf);
+	}
 #ifndef MKSH_SMALL
-	if (x_tab[prefix][key] & 0x80)
-		*x_bind_show_xp++ = '~';
+	if (X_KTAB(prefix, key) & 0x80U)
+		shf_putc('~', &shf);
 #endif
-	*x_bind_show_xp = '\0';
-	x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
-	print_value_quoted(shl_stdout, x_bind_show_xp);
+	x_bind_show_n = shf.wbsize;
+	x_bind_show_s = shf_sclose(&shf);
+	print_value_quoted(shl_stdout, x_bind_show_s);
 	shf_putc('=', shl_stdout);
 #ifndef MKSH_SMALL
 	if (f == XFUNC_ins_string) {
-		const unsigned char *cp = (const void *)x_atab[prefix][key];
-		unsigned char c;
-
-		while ((c = *cp++))
-			x_bind_show_ch(c);
-		*x_bind_show_xp = '\0';
-		x_bind_show_xp = Xstring(x_bind_show_xs, x_bind_show_xp);
-		print_value_quoted(shl_stdout, x_bind_show_xp);
+		shf_sreopen(x_bind_show_s, x_bind_show_n, AEDIT, &shf);
+		uprntmbs(X_MTAB(prefix, key), Ja, &shf);
+		x_bind_show_n = shf.wbsize;
+		x_bind_show_s = shf_sclose(&shf);
+		print_value_quoted(shl_stdout, x_bind_show_s);
 	} else
 #endif
 	  shf_puts(x_ftab[f].xf_name, shl_stdout);
@@ -2488,11 +2549,11 @@ x_bind_list(void)
 int
 x_bind_showall(void)
 {
-	int prefix, key;
+	kui prefix, key;
 
-	for (prefix = 0; prefix < X_NTABS; prefix++)
-		for (key = 0; key < X_TABSZ; key++)
-			switch (XFUNC_VALUE(x_tab[prefix][key])) {
+	for (prefix = 0; prefix < X_NTABS; ++prefix)
+		for (key = 0; key <= 0xFF; ++key)
+			switch (XFUNC_VALUE(X_KTAB(prefix, key))) {
 			case XFUNC_error:	/* unset */
 			case XFUNC_insert:	/* auto-insert */
 				break;
@@ -2503,57 +2564,100 @@ x_bind_showall(void)
 	return (0);
 }
 
-static unsigned int
-x_bind_getc(const char **ccpp)
+struct x_bind_getc {
+	const char *cp;
+	kby next;
+};
+
+static kui
+x_bind_getc(struct x_bind_getc *ctx)
 {
-	unsigned int ch, ec;
+	kui ch;
+	kby tmp[4];
 
-	if ((ch = ord(**ccpp)))
-		++(*ccpp);
+	if ((ch = ctx->next)) {
+		ctx->next = 0;
+		return (ch);
+	}
+	if ((ch = ord(*(ctx->cp))))
+		++(ctx->cp);
 	switch (ch) {
 	case ORD('^'):
-		ch = ksh_toctrl(**ccpp) | 0x100U;
-		if (**ccpp)
-			++(*ccpp);
+		if ((ch = ord(*(ctx->cp))))
+			++(ctx->cp);
+		switch (ch) {
+		case ORD('!'):
+			if ((ch = ord(*(ctx->cp))))
+				++(ctx->cp);
+			ch = asc2rtt((rtt2asc(ch) & 0x1FU) + 0x80U);
+			break;
+		case ORD('+'):
+			if ((ch = ord(*(ctx->cp))))
+				++(ctx->cp);
+			utf_wctomb((char *)tmp, (rtt2asc(ch) & 0x1FU) + 0x80U);
+			ch = tmp[0];
+			ctx->next = tmp[1];
+			break;
+		case ORD('?'):
+			ch = CTRL_QM;
+			break;
+		default:
+			ch = asc2rtt(rtt2asc(ch) & 0x1FU);
+			break;
+		}
 		break;
 	case ORD('\\'):
-		switch ((ec = ord(**ccpp))) {
-		case ORD('^'):
-		case ORD('\\'):
-		case ORD('='):
-			ch = ec | 0x100U;
-			++(*ccpp);
-			break;
+		if ((ch = ord(*(ctx->cp))))
+			++(ctx->cp);
+		if (ch == ORD('x') && ctype(ctx->cp[0], C_SEDEC) &&
+		    ctype(ctx->cp[1], C_SEDEC)) {
+			if (ctype(ctx->cp[0], C_DIGIT))
+				ch = ksh_numdig(ctx->cp[0]);
+			else if (ctype(ctx->cp[0], C_UPPER))
+				ch = ksh_numuc(ctx->cp[0]) + 10;
+			else
+				ch = ksh_numlc(ctx->cp[0]) + 10;
+			ch <<= 4;
+			if (ctype(ctx->cp[1], C_DIGIT))
+				ch |= ksh_numdig(ctx->cp[1]);
+			else if (ctype(ctx->cp[1], C_UPPER))
+				ch |= ksh_numuc(ctx->cp[1]) + 10;
+			else
+				ch |= ksh_numlc(ctx->cp[1]) + 10;
+			ctx->cp += 2;
 		}
+		ch |= 0x100U;
 		break;
 	}
 	return (ch);
 }
 
 int
-x_bind(const char *s SMALLP(bool macro))
+x_bind(const char *s SMALLP(Wahr macro))
 {
-	const char *ccp = s;
-	int prefix, key;
-	unsigned int c;
+	register kui t;
+	struct x_bind_getc state;
+	kui c, key, prefix;
 #ifndef MKSH_SMALL
-	bool hastilde = false;
+	Wahr hastilde = Nee;
 	char *ms = NULL;
 #endif
 
+	state.cp = s;
+	state.next = 0;
 	prefix = 0;
-	c = x_bind_getc(&ccp);
+	c = x_bind_getc(&state);
 	if (!c || c == ORD('=')) {
 		bi_errorf("no key to bind");
 		return (1);
 	}
-	key = c & 0xFF;
-	while ((c = x_bind_getc(&ccp)) != ORD('=')) {
+	key = KBI(c);
+	while ((c = x_bind_getc(&state)) != ORD('=')) {
 		if (!c) {
 			x_bind_showone(prefix, key);
 			return (0);
 		}
-		switch (XFUNC_VALUE(x_tab[prefix][key])) {
+		switch (XFUNC_VALUE(X_KTAB(prefix, key))) {
 		case XFUNC_meta1:
 			prefix = 1;
 			if (0)
@@ -2564,12 +2668,12 @@ x_bind(const char *s SMALLP(bool macro))
 				/* FALLTHROUGH */
 		case XFUNC_meta3:
 			  prefix = 3;
-			key = c & 0xFF;
+			key = KBI(c);
 			continue;
 		}
 #ifndef MKSH_SMALL
 		if (c == ORD('~')) {
-			hastilde = true;
+			hastilde = Ja;
 			continue;
 		}
 #endif
@@ -2581,41 +2685,40 @@ x_bind(const char *s SMALLP(bool macro))
 	if (macro) {
 		char *cp;
 
-		cp = ms = alloc(strlen(ccp) + 1, AEDIT);
-		while ((c = x_bind_getc(&ccp)))
+		cp = ms = alloc(strlen(state.cp) + 1, AEDIT);
+		while ((c = x_bind_getc(&state)))
 			*cp++ = c;
 		*cp = '\0';
 		c = XFUNC_ins_string;
 	} else
 #endif
-	  if (!*ccp) {
+	  if (state.cp[0] == '\0') {
 		c = XFUNC_insert;
 	} else {
 		for (c = 0; c < NELEM(x_ftab); ++c)
-			if (!strcmp(x_ftab[c].xf_name, ccp))
+			if (!strcmp(x_ftab[c].xf_name, state.cp))
 				break;
 		if (c == NELEM(x_ftab) || x_ftab[c].xf_flags & XF_NOBIND) {
-			bi_errorf("%s: no such editing command", ccp);
+			bi_errorf("%s: no such editing command", state.cp);
 			return (1);
 		}
 	}
 
+	t = X_xTABidx(prefix, key);
 #ifndef MKSH_SMALL
-	if (XFUNC_VALUE(x_tab[prefix][key]) == XFUNC_ins_string)
-		afree(x_atab[prefix][key], AEDIT);
-	x_atab[prefix][key] = ms;
+	if (XFUNC_VALUE(x_ktab[t]) == XFUNC_ins_string)
+		afree(x_mtab[t], AEDIT);
+	x_mtab[t] = ms;
 	if (hastilde)
 		c |= 0x80U;
 #endif
-	x_tab[prefix][key] = c;
+	x_ktab[t] = c;
 
-	/* track what the user has bound, so x_mode(true) won't toast things */
+	/* track what the user has bound, so x_mode(Ja) won't toast things */
 	if (c == XFUNC_insert)
-		x_bound[(prefix * X_TABSZ + key) / 8] &=
-		    ~(1 << ((prefix * X_TABSZ + key) % 8));
+		x_btab[t >> 3] &= ~BIT(t & 7);
 	else
-		x_bound[(prefix * X_TABSZ + key) / 8] |=
-		    (1 << ((prefix * X_TABSZ + key) % 8));
+		x_btab[t >> 3] |= BIT(t & 7);
 
 	return (0);
 }
@@ -2623,17 +2726,15 @@ x_bind(const char *s SMALLP(bool macro))
 static void
 bind_if_not_bound(int p, int k, int func)
 {
-	int t;
+	register kui t = X_xTABidx(p, k);
 
 	/*
 	 * Has user already bound this key?
 	 * If so, do not override it.
 	 */
-	t = p * X_TABSZ + k;
-	if (x_bound[t >> 3] & (1 << (t & 7)))
+	if (x_btab[t >> 3] & BIT(t & 7))
 		return;
-
-	x_tab[p][k] = func;
+	x_ktab[t] = func;
 }
 
 static int
@@ -2650,7 +2751,7 @@ x_kill_region(int c MKSH_A_UNUSED)
 	char *xr;
 
 	if (xmp == NULL) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	if (xmp > xcp) {
@@ -2661,7 +2762,7 @@ x_kill_region(int c MKSH_A_UNUSED)
 		xr = xmp;
 	}
 	x_goto(xr);
-	x_delete(x_nb2nc(rsize), true);
+	x_delete(x_nb2nc(rsize), Ja);
 	xmp = xr;
 	return (KSTD);
 }
@@ -2672,7 +2773,7 @@ x_xchg_point_mark(int c MKSH_A_UNUSED)
 	char *tmp;
 
 	if (xmp == NULL) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	tmp = xmp;
@@ -2750,17 +2851,17 @@ x_expand(int c MKSH_A_UNUSED)
 	    &start, &end, &words);
 
 	if (nwords == 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	x_goto(xbuf + start);
-	x_delete(x_nb2nc(end - start), false);
+	x_delete(x_nb2nc(end - start), Nee);
 
 	i = 0;
 	while (i < nwords) {
 		if (x_escape(words[i], strlen(words[i]), x_do_ins) < 0 ||
 		    (++i < nwords && x_ins(T1space) < 0)) {
-			x_e_putc2(KSH_BEL);
+			x_e_putb(KSH_BEL);
 			return (KSTD);
 		}
 	}
@@ -2778,18 +2879,18 @@ do_complete(
 {
 	char **words;
 	int start, end, nlen, olen, nwords;
-	bool completed;
+	Wahr completed;
 
 	nwords = x_cf_glob(&flags, xbuf, xep - xbuf, xcp - xbuf,
 	    &start, &end, &words);
 	/* no match */
 	if (nwords == 0) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return;
 	}
 	if (type == CT_LIST) {
 		x_print_expansions(nwords, words,
-		    tobool(flags & XCF_IS_COMMAND));
+		    isWahr(flags & XCF_IS_COMMAND));
 		x_redraw(0);
 		x_free_words(nwords, words);
 		return;
@@ -2802,7 +2903,7 @@ do_complete(
 		 * any expansion of parameter substitution
 		 * is always at most one result, too
 		 */
-		completed = true;
+		completed = Ja;
 	} else {
 		char *unescaped;
 
@@ -2810,7 +2911,7 @@ do_complete(
 		strndupx(unescaped, xbuf + start, olen, ATEMP);
 
 		/* expand any tilde and unescape the string for comparison */
-		unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, true);
+		unescaped = x_glob_hlp_tilde_and_rem_qchar(unescaped, Ja);
 
 		/*
 		 * match iff entire original string is part of the
@@ -2827,12 +2928,11 @@ do_complete(
 		 * just a single match
 		 */
 		x_print_expansions(nwords, words,
-		    tobool(flags & XCF_IS_COMMAND));
+		    isWahr(flags & XCF_IS_COMMAND));
 	}
 	if (completed) {
 		/* expand on the command line */
-		xmp = NULL;
-		xcp = xbuf + start;
+		xmp = xcp = xbuf + start;
 		xep -= olen;
 		memmove(xcp, xcp + olen, xep - xcp + 1);
 		x_escape(words[0], nlen, x_do_ins);
@@ -2840,11 +2940,13 @@ do_complete(
 	x_adjust();
 	/*
 	 * append a space if this is a single non-directory match
-	 * and not a parameter or homedir substitution
+	 * and not a parameter substitution, slash for homedir
 	 */
-	if (nwords == 1 && !mksh_cdirsep(words[0][nlen - 1]) &&
-	    !(flags & XCF_IS_NOSPACE)) {
-		x_ins(T1space);
+	if (nwords == 1 && !mksh_cdirsep(words[0][nlen - 1])) {
+		if (flags & XCF_IS_HOMEDIR)
+			x_ins("/");
+		else if (!(flags & XCF_IS_NOSPACE))
+			x_ins(T1space);
 	}
 
 	x_free_words(nwords, words);
@@ -2867,43 +2969,53 @@ do_complete(
 static void
 x_adjust(void)
 {
-	int col_left, n;
+	int colcur, colmax;
 
 	/* flag the fact that we were called */
 	x_adj_done++;
 
+	/* fix up xcp to just past a character end first */
+	xcp = xcp >= xep ? xep : ez_bs(xcp, xbuf);
+	/* shortcut if going to beginning of line */
+	if (xcp == (xbp = xbuf))
+		goto x_adjust_out;
+
+	/* check if the entire line fits */
+	x_displen = xx_cols - 2 - pwidth;
+	xlp_valid = Nee;
+	x_lastcp();
+	/* accept if the cursor is still in the editable area */
+	if (xcp < xdp /*|| xdp >= xep */)
+		goto x_adjust_out;
+
+	/* ok, that was a failure so we need to proceed backwards from xcp */
+	xbp = xcp;
+	/* assert xbp > xbuf */
+
 	/*
-	 * calculate the amount of columns we need to "go back"
-	 * from xcp to set xbp to (but never < xbuf) to 2/3 of
-	 * the display width; take care of pwidth though
+	 * if we have enough space left on screen, we aim to
+	 * position the cursor at 3/4 of the display width;
+	 * if not we emergency-fit just one character before…
 	 */
-	if ((col_left = xx_cols * 2 / 3) < MIN_EDIT_SPACE) {
-		/*
-		 * cowardly refuse to do anything
-		 * if the available space is too small;
-		 * fall back to dumb pdksh code
-		 */
-		if ((xbp = xcp - (x_displen / 2)) < xbuf)
-			xbp = xbuf;
-		/* elide UTF-8 fixup as penalty */
+	if ((colmax = xx_cols * 3 / 4) < MIN_EDIT_SPACE) {
+		/* one backwards though */
+		xbp = ez_bs(xbp - 1, xbuf);
+		/* go for it */
 		goto x_adjust_out;
 	}
 
-	/* fix up xbp to just past a character end first */
-	xbp = xcp >= xep ? xep : x_bs0(xcp, xbuf);
-	/* walk backwards */
-	while (xbp > xbuf && col_left > 0) {
-		xbp = x_bs0(xbp - 1, xbuf);
-		col_left -= (n = x_size2(xbp, NULL));
-	}
-	/* check if we hit the prompt */
-	if (xbp == xbuf && xcp != xbuf && col_left >= 0 && col_left < pwidth) {
-		/* so we did; force scrolling occurs */
-		xbp += utf_ptradj(xbp);
+	/* go backwards until we reached the target width */
+	colcur = 0;
+	while (xbp > xbuf && colcur < colmax) {
+		xbp = ez_bs(xbp - 1, xbuf);
+		colcur += uwidthmbT(xbp, NULL);
 	}
+	/* check if we hit the prompt and force scrolling if so */
+	if (xbp == xbuf)
+		xbp += ez_mbtoc(NULL, xbp);
 
  x_adjust_out:
-	xlp_valid = false;
+	xlp_valid = Nee;
 	x_redraw('\r');
 	x_flush();
 }
@@ -2936,42 +3048,23 @@ x_e_getc(void)
 	return (x_getc());
 }
 
+/* takes single-column single-byte characters only */
 static void
-x_e_putc2(int c)
+x_e_putb(int c)
 {
-	int width = 1;
-
-	if (ctype(c, C_CR | C_LF))
+	if (ctype(c, C_CR | C_LF)) {
+		x_putc(c);
 		x_col = 0;
-	if (x_col < xx_cols) {
-#ifndef MKSH_EBCDIC
-		if (UTFMODE && (c > 0x7F)) {
-			char utf_tmp[3];
-			size_t x;
-
-			if (c < 0xA0)
-				c = 0xFFFD;
-			x = utf_wctomb(utf_tmp, c);
-			x_putc(utf_tmp[0]);
-			if (x > 1)
-				x_putc(utf_tmp[1]);
-			if (x > 2)
-				x_putc(utf_tmp[2]);
-			width = utf_wcwidth(c);
-		} else
-#endif
-			x_putc(c);
-		switch (c) {
-		case KSH_BEL:
-			break;
-		case '\r':
-		case '\n':
+	} else if (x_col < xx_cols) {
+		x_putc(c);
+		switch (ord(c)) {
+		case ORD(KSH_BEL):
 			break;
-		case '\b':
-			x_col--;
+		case ORD('\b'):
+			--x_col;
 			break;
 		default:
-			x_col += width;
+			++x_col;
 			break;
 		}
 	}
@@ -2980,58 +3073,50 @@ x_e_putc2(int c)
 }
 
 static void
-x_e_putc3(const char **cp)
+x_e_puts(const char *s)
 {
-	int width = 1, c = **(const unsigned char **)cp;
+	unsigned int c;
+	int width;
+	size_t len;
+	kby adj = x_adj_done;
 
-	if (ctype(c, C_CR | C_LF))
-		x_col = 0;
-	if (x_col < xx_cols) {
-		if (UTFMODE && (c > 0x7F)) {
-			char *cp2;
-
-			width = utf_widthadj(*cp, (const char **)&cp2);
-			if (cp2 == *cp + 1) {
-				(*cp)++;
-#ifdef MKSH_EBCDIC
-				x_putc(asc2rtt(0xEF));
-				x_putc(asc2rtt(0xBF));
-				x_putc(asc2rtt(0xBD));
-#else
-				shf_puts("\xEF\xBF\xBD", shl_out);
-#endif
-			} else
-				while (*cp < cp2)
-					x_putcf(*(*cp)++);
-		} else {
-			(*cp)++;
+	while ((c = ord(*s)) && adj == x_adj_done) {
+		if (ctype(c, C_CR | C_LF)) {
 			x_putc(c);
+			x_col = 0;
+			++s;
+		} else if (x_col < xx_cols) {
+			if (rtt2asc(c) < 0x80U || !UTFMODE) {
+				x_putc(c);
+				switch (c) {
+				case ORD(KSH_BEL):
+					break;
+				case ORD('\b'):
+					--x_col;
+					break;
+				default:
+					++x_col;
+					break;
+				}
+				++s;
+			} else if ((len = utf_mbtowc(&c, s)) == (size_t)-1) {
+				/* substitute U+FFFD */
+				x_putcf(asc2rtt(0xEF));
+				x_putcf(asc2rtt(0xBF));
+				x_putcf(asc2rtt(0xBD));
+				++x_col;
+				++s;
+			} else {
+				/* C1 control character? C0/DEL use 1 above */
+				if ((width = utf_wcwidth(c)) < 0)
+					width = /* for consistency */ 1;
+				shf_wr_sm(s, len, shl_out);
+				x_col += width;
+			}
 		}
-		switch (c) {
-		case KSH_BEL:
-			break;
-		case '\r':
-		case '\n':
-			break;
-		case '\b':
-			x_col--;
-			break;
-		default:
-			x_col += width;
-			break;
-		}
+		if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
+			x_adjust();
 	}
-	if (x_adj_ok && (x_col < 0 || x_col >= (xx_cols - 2)))
-		x_adjust();
-}
-
-static void
-x_e_puts(const char *s)
-{
-	int adj = x_adj_done;
-
-	while (*s && adj == x_adj_done)
-		x_e_putc3(&s);
 }
 
 /*-
@@ -3048,27 +3133,28 @@ static int
 x_set_arg(int c)
 {
 	unsigned int n = 0;
-	bool first = true;
+	Wahr first = Ja;
 
 	/* strip command prefix */
 	c &= 255;
-	while (c >= 0 && ctype(c, C_DIGIT)) {
+	/* loop to get digits */
+	while (cinttype(c, C_DIGIT)) {
 		n = n * 10 + ksh_numdig(c);
 		if (n > LINE)
 			/* upper bound for repeat */
 			goto x_set_arg_too_big;
 		c = x_e_getc();
-		first = false;
+		first = Nee;
 	}
 	if (c < 0 || first) {
  x_set_arg_too_big:
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_arg = 1;
-		x_arg_defaulted = true;
+		x_arg_defaulted = Ja;
 	} else {
 		x_e_ungetc(c);
 		x_arg = n;
-		x_arg_defaulted = false;
+		x_arg_defaulted = Nee;
 	}
 	return (KSTD);
 }
@@ -3081,7 +3167,7 @@ x_comment(int c MKSH_A_UNUSED)
 	int ret = x_do_comment(xbuf, xend - xbuf, &len);
 
 	if (ret < 0)
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 	else {
 		x_modified();
 		xep = xbuf + len;
@@ -3133,7 +3219,7 @@ x_edit_line(int c MKSH_A_UNUSED)
 	if (x_arg_defaulted) {
 		if (modified) {
 			*xep = '\0';
-			histsave(&source->line, xbuf, HIST_STORE, true);
+			histsave(&source->line, xbuf, HIST_STORE, Ja);
 			x_arg = 0;
 		} else
 			x_arg = source->line - (histptr - x_histp);
@@ -3149,12 +3235,12 @@ x_edit_line(int c MKSH_A_UNUSED)
 
 /*-
  * NAME:
- *	x_prev_histword - recover word from prev command
+ *	x_prev_histword - recover bigword from prev command
  *
  * DESCRIPTION:
- *	This function recovers the last word from the previous
+ *	This function recovers the last bigword from the previous
  *	command and inserts it into the current edit line. If a
- *	numeric arg is supplied then the n'th word from the
+ *	numeric arg is supplied then the n'th bigword from the
  *	start of the previous command is used.
  *	As a side effect, trashes the mark in order to achieve
  *	being called in a repeatable fashion.
@@ -3182,7 +3268,7 @@ x_prev_histword(int c MKSH_A_UNUSED)
 		last_arg = x_arg_defaulted ? -1 : x_arg;
 	xhp = histptr - (m - 1);
 	if ((xhp < history) || !(cp = *xhp)) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_modified();
 		return (KSTD);
 	}
@@ -3192,13 +3278,13 @@ x_prev_histword(int c MKSH_A_UNUSED)
 
 		rcp = &cp[strlen(cp) - 1];
 		/*
-		 * ignore white-space after the last word
+		 * ignore whitespace after the last bigword
 		 */
-		while (rcp > cp && ctype(*rcp, C_CFS))
+		while (rcp > cp && ctype(*rcp, C_BLANK))
 			rcp--;
-		while (rcp > cp && !ctype(*rcp, C_CFS))
+		while (rcp > cp && !ctype(*rcp, C_BLANK))
 			rcp--;
-		if (ctype(*rcp, C_CFS))
+		if (ctype(*rcp, C_BLANK))
 			rcp++;
 		x_ins(rcp);
 	} else {
@@ -3207,18 +3293,18 @@ x_prev_histword(int c MKSH_A_UNUSED)
 
 		rcp = cp;
 		/*
-		 * ignore white-space at start of line
+		 * ignore whitespace at start of line
 		 */
-		while (*rcp && ctype(*rcp, C_CFS))
+		while (*rcp && ctype(*rcp, C_BLANK))
 			rcp++;
 		while (x_arg-- > 0) {
-			while (*rcp && !ctype(*rcp, C_CFS))
+			while (*rcp && !ctype(*rcp, C_BLANK))
 				rcp++;
-			while (*rcp && ctype(*rcp, C_CFS))
+			while (*rcp && ctype(*rcp, C_BLANK))
 				rcp++;
 		}
 		cp = rcp;
-		while (*rcp && !ctype(*rcp, C_CFS))
+		while (*rcp && !ctype(*rcp, C_BLANK))
 			rcp++;
 		ch = *rcp;
 		*rcp = '\0';
@@ -3236,21 +3322,42 @@ x_prev_histword(int c MKSH_A_UNUSED)
 static int
 x_fold_upper(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('U'));
+	return (x_fold_case('U', C_MFS));
 }
 
 /* Lowercase N(1) words */
 static int
 x_fold_lower(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('L'));
+	return (x_fold_case('L', C_MFS));
 }
 
 /* Titlecase N(1) words */
 static int
 x_fold_capitalise(int c MKSH_A_UNUSED)
 {
-	return (x_fold_case('C'));
+	return (x_fold_case('C', C_MFS));
+}
+
+/* Uppercase N(1) bigwords */
+static int
+x_foldb_upper(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('U', C_BLANK));
+}
+
+/* Lowercase N(1) bigwords */
+static int
+x_foldb_lower(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('L', C_BLANK));
+}
+
+/* Titlecase N(1) bigwords */
+static int
+x_foldb_capitalise(int c MKSH_A_UNUSED)
+{
+	return (x_fold_case('C', C_BLANK));
 }
 
 /*-
@@ -3259,25 +3366,25 @@ x_fold_capitalise(int c MKSH_A_UNUSED)
  *
  * DESCRIPTION:
  *	This function is used to implement M-U/M-u, M-L/M-l, M-C/M-c
- *	to UPPER CASE, lower case or Capitalise Words.
+ *	to UPPER CASE, lower case or Capitalise words and bigwords.
  *
  * RETURN VALUE:
  *	None
  */
 static int
-x_fold_case(int c)
+x_fold_case(int c, kui separator)
 {
 	char *cp = xcp;
 
 	if (cp == xep) {
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		return (KSTD);
 	}
 	while (x_arg--) {
 		/*
 		 * first skip over any white-space
 		 */
-		while (cp != xep && ctype(*cp, C_MFS))
+		while (cp != xep && ctype(*cp, separator))
 			cp++;
 		/*
 		 * do the first char on its own since it may be
@@ -3295,7 +3402,7 @@ x_fold_case(int c)
 		/*
 		 * now for the rest of the word
 		 */
-		while (cp != xep && !ctype(*cp, C_MFS)) {
+		while (cp != xep && !ctype(*cp, separator)) {
 			if (c == 'U')
 				/* uppercase */
 				*cp = ksh_toupper(*cp);
@@ -3318,7 +3425,7 @@ x_fold_case(int c)
  * DESCRIPTION:
  *	This function returns a pointer to that char in the
  *	edit buffer that will be the last displayed on the
- *	screen.
+ *	screen. It also updates xlp and xdp.
  */
 static char *
 x_lastcp(void)
@@ -3329,14 +3436,20 @@ x_lastcp(void)
 
 		xlp = xbp;
 		while (xlp < xep) {
-			j = x_size2(xlp, &xlp2);
-			if ((i + j) > x_displen)
-				break;
+			j = uwidthmbT(xlp, &xlp2);
+			if ((i + j) > x_displen) {
+				/* don’t add (x_displen - i) here */
+				/* can be 2-column doesn’t-fit char */
+				xdp = xlp;
+				goto xlp_longline;
+			}
 			i += j;
 			xlp = xlp2;
 		}
+		xdp = xlp + (x_displen - i);
+ xlp_longline:
+		xlp_valid = Ja;
 	}
-	xlp_valid = true;
 	return (xlp);
 }
 
@@ -3351,16 +3464,16 @@ x_lastpos(void)
 }
 
 static void
-x_mode(bool onoff)
+x_mode(Wahr onoff)
 {
-	static bool x_cur_mode;
+	static Wahr x_cur_mode;
 
 	if (x_cur_mode == onoff)
 		return;
 	x_cur_mode = onoff;
 
 	if (onoff) {
-		x_mkraw(tty_fd, NULL, false);
+		x_mkraw(tty_fd, NULL, Nee);
 
 		edchars.erase = toedchar(tty_state.c_cc[VERASE]);
 		edchars.kill = toedchar(tty_state.c_cc[VKILL]);
@@ -3424,9 +3537,9 @@ static void yank_range(int, int);
 static int bracktype(int);
 static void save_cbuf(void);
 static void restore_cbuf(void);
-static int putbuf(const char *, ssize_t, bool);
+static int putbuf(const char *, ssize_t, Wahr);
 static void del_range(int, int);
-static int findch(int, int, bool, bool) MKSH_A_PURE;
+static int findch(int, int, Wahr, Wahr);
 static int forwword(int);
 static int backword(int);
 static int endword(int);
@@ -3434,13 +3547,13 @@ static int Forwword(int);
 static int Backword(int);
 static int Endword(int);
 static int grabhist(int, int);
-static int grabsearch(const char *, int, int, bool);
-static void redraw_line(bool);
-static void refresh(bool);
+static int grabsearch(const char *, int, int, Wahr);
+static void redraw_line(Wahr);
+static void refresh(Wahr);
 static int outofwin(void);
 static void rewindow(void);
 static int newcol(unsigned char, int);
-static void display(char *, char *, bool);
+static void display(char *, char *, Wahr);
 static void ed_mov_opt(int, char *);
 static int expand_word(int);
 static int complete_word(int, int);
@@ -3449,6 +3562,7 @@ static void vi_error(void);
 static void vi_macro_reset(void);
 static int x_vi_putbuf(const char *, size_t);
 #define char_len(c) (ksh_isctrl(c) ? 2 : 1)
+#define ksh_unctrl(c) asc2rtt(rtt2asc(c) ^ 0x40U)
 
 #define vC	0x01		/* a valid command that isn't a vM, vE, vU */
 #define vM	0x02		/* movement command (h, l, etc.) */
@@ -3534,17 +3648,17 @@ static struct edstate	*vs;		/* current V
 static struct edstate	*undo;
 
 static char *ibuf;			/* input buffer */
-static bool first_insert;		/* set when starting in insert mode */
+static Wahr first_insert;		/* set when starting in insert mode */
 static int saved_inslen;		/* saved inslen for first insert */
 static int inslen;			/* length of input buffer */
 static int srchlen;			/* length of current search pattern */
 static char *ybuf;			/* yank buffer */
 static int yanklen;			/* length of yank buffer */
-static uint8_t fsavecmd = ORD(' ');	/* last find command */
+static kby fsavecmd = ORD(' ');		/* last find command */
 static int fsavech;			/* character to find */
 static char lastcmd[MAXVICMD];		/* last non-move command */
 static int lastac;			/* argcnt for lastcmd */
-static uint8_t lastsearch = ORD(' ');	/* last search command */
+static kby lastsearch = ORD(' ');	/* last search command */
 static char srchpat[SRCHLEN];		/* last search pattern */
 static int insert;			/* <>0 in insert mode */
 static int hnum;			/* position in history */
@@ -3571,7 +3685,7 @@ static enum expand_mode {
 	NONE = 0, EXPAND, COMPLETE, PRINT
 } expanded;
 
-static int
+static ssize_t
 x_vi(char *buf)
 {
 	int c;
@@ -3580,7 +3694,7 @@ x_vi(char *buf)
 	ohnum = hnum = hlast = histnum(-1) + 1;
 	insert = INSERT;
 	saved_inslen = inslen;
-	first_insert = true;
+	first_insert = Ja;
 	inslen = 0;
 	vi_macro_reset();
 
@@ -3597,7 +3711,7 @@ x_vi(char *buf)
 	vs = &ebuf;
 	undo = &undobuf;
 
-	x_init_prompt(true);
+	x_init_prompt(Ja);
 	x_col = pwidth;
 
 	if (wbuf_len != x_cols - 3 && ((wbuf_len = x_cols - 3))) {
@@ -3646,7 +3760,11 @@ x_vi(char *buf)
 			} else if (isched(c, edchars.eof) &&
 			    state != VVERSION) {
 				if (vs->linelen == 0) {
-					x_vi_zotc(c);
+					if (ksh_isctrl(c)) {
+						x_putc('^');
+						c = ksh_unctrl(c);
+					}
+					x_putc(c);
 					c = -1;
 					break;
 				}
@@ -3712,7 +3830,7 @@ vi_hook(int ch)
 			case 0:
 				if (state == VLIT) {
 					vs->cursor--;
-					refresh(false);
+					refresh(Nee);
 				} else
 					refresh(insert != 0);
 				break;
@@ -3736,17 +3854,17 @@ vi_hook(int ch)
 					vs->cursor = 0;
 					vs->linelen = 0;
 					if (putbuf(ord(ch) == ORD('/') ?
-					    "/" : "?", 1, false) != 0)
+					    "/" : "?", 1, Nee) != 0)
 						return (-1);
-					refresh(false);
+					refresh(Nee);
 				}
 				if (state == VVERSION) {
 					save_cbuf();
 					vs->cursor = 0;
 					vs->linelen = 0;
 					putbuf(KSH_VERSION,
-					    strlen(KSH_VERSION), false);
-					refresh(false);
+					    strlen(KSH_VERSION), Nee);
+					refresh(Nee);
 				}
 			}
 		}
@@ -3758,14 +3876,14 @@ vi_hook(int ch)
 			vi_error();
 		} else
 			vs->cbuf[vs->cursor++] = ch;
-		refresh(true);
+		refresh(Ja);
 		state = VNORMAL;
 		break;
 
 	case VVERSION:
 		restore_cbuf();
 		state = VNORMAL;
-		refresh(false);
+		refresh(Nee);
 		break;
 
 	case VARG1:
@@ -3829,7 +3947,7 @@ vi_hook(int ch)
 				if (!srchpat[0]) {
 					vi_error();
 					state = VNORMAL;
-					refresh(false);
+					refresh(Nee);
 					return (0);
 				}
 			} else {
@@ -3842,17 +3960,17 @@ vi_hook(int ch)
 				srchlen--;
 				vs->linelen -= char_len(locpat[srchlen]);
 				vs->cursor = vs->linelen;
-				refresh(false);
+				refresh(Nee);
 				return (0);
 			}
 			restore_cbuf();
 			state = VNORMAL;
-			refresh(false);
+			refresh(Nee);
 		} else if (isched(ch, edchars.kill)) {
 			srchlen = 0;
 			vs->linelen = 1;
 			vs->cursor = 1;
-			refresh(false);
+			refresh(Nee);
 			return (0);
 		} else if (isched(ch, edchars.werase)) {
 			unsigned int i, n;
@@ -3871,7 +3989,7 @@ vi_hook(int ch)
 				vs->linelen -= char_len(locpat[i]);
 			srchlen = (int)n;
 			vs->cursor = vs->linelen;
-			refresh(false);
+			refresh(Nee);
 			return (0);
 		} else {
 			if (srchlen == SRCHLEN - 1)
@@ -3890,7 +4008,7 @@ vi_hook(int ch)
 					vs->cbuf[vs->linelen++] = ch;
 				}
 				vs->cursor = vs->linelen;
-				refresh(false);
+				refresh(Nee);
 			}
 			return (0);
 		}
@@ -3931,7 +4049,7 @@ vi_hook(int ch)
 		switch (vi_cmd(argc1, curcmd)) {
 		case -1:
 			vi_error();
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 0:
 			if (insert != 0)
@@ -3939,7 +4057,7 @@ vi_hook(int ch)
 			refresh(insert != 0);
 			break;
 		case 1:
-			refresh(false);
+			refresh(Nee);
 			return (1);
 		case 2:
 			/* back from a 'v' command - don't redraw the screen */
@@ -3954,12 +4072,12 @@ vi_hook(int ch)
 		switch (vi_cmd(lastac, lastcmd)) {
 		case -1:
 			vi_error();
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 0:
 			if (insert != 0) {
 				if (lastcmd[0] == 's' ||
-				    ksh_eq(lastcmd[0], 'C', 'c')) {
+				    isCh(lastcmd[0], 'C', 'c')) {
 					if (redo_insert(1) != 0)
 						vi_error();
 				} else {
@@ -3967,10 +4085,10 @@ vi_hook(int ch)
 						vi_error();
 				}
 			}
-			refresh(false);
+			refresh(Nee);
 			break;
 		case 1:
-			refresh(false);
+			refresh(Nee);
 			return (1);
 		case 2:
 			/* back from a 'v' command - can't happen */
@@ -4080,7 +4198,7 @@ vi_insert(int ch)
 	case CTRL_BO:
 		expanded = NONE;
 		if (first_insert) {
-			first_insert = false;
+			first_insert = Nee;
 			if (inslen == 0) {
 				inslen = saved_inslen;
 				return (redo_insert(0));
@@ -4088,7 +4206,7 @@ vi_insert(int ch)
 			lastcmd[0] = 'a';
 			lastac = 1;
 		}
-		if (lastcmd[0] == 's' || ksh_eq(lastcmd[0], 'C', 'c'))
+		if (lastcmd[0] == 's' || isCh(lastcmd[0], 'C', 'c'))
 			return (redo_insert(0));
 		else
 			return (redo_insert(lastac - 1));
@@ -4137,7 +4255,7 @@ vi_cmd(int argcnt, const char *cmd)
 	int ncursor;
 	int cur, c1, c2;
 	int any;
-	bool b;
+	Wahr b;
 	struct edstate *t;
 
 	if (argcnt == 0 && !is_zerocount(*cmd))
@@ -4164,7 +4282,7 @@ vi_cmd(int argcnt, const char *cmd)
 
 		case CTRL_L:
 		case CTRL_R:
-			redraw_line(true);
+			redraw_line(Ja);
 			break;
 
 		case ORD('@'):
@@ -4185,14 +4303,10 @@ vi_cmd(int argcnt, const char *cmd)
 						if (*++p == cmd[1])
 							return (-1);
 				/* insert alias into macro buffer */
-				nlen = strlen(ap->val.s) + 1;
+				nlen = strlen(ap->val.s) + 1U;
 				olen = !macro.p ? 2 :
 				    macro.len - (macro.p - macro.buf);
-				/*
-				 * at this point, it's fairly reasonable that
-				 * nlen + olen + 2 doesn't overflow
-				 */
-				nbuf = alloc(nlen + 1 + olen, AEDIT);
+				nbuf = alloc1(nlen + 1U, olen, AEDIT);
 				memcpy(nbuf, ap->val.s, nlen);
 				nbuf[nlen++] = cmd[1];
 				if (macro.p) {
@@ -4248,7 +4362,7 @@ vi_cmd(int argcnt, const char *cmd)
 			else {
 				if ((ncursor = domove(argcnt, &cmd[1], 1)) < 0)
 					return (-1);
-				if (*cmd == 'c' && ksh_eq(cmd[1], 'W', 'w') &&
+				if (*cmd == 'c' && isCh(cmd[1], 'W', 'w') &&
 				    !ctype(vs->cbuf[vs->cursor], C_SPACE)) {
 					do {
 						--ncursor;
@@ -4283,7 +4397,7 @@ vi_cmd(int argcnt, const char *cmd)
 			hnum = hlast;
 			if (vs->linelen != 0)
 				vs->cursor++;
-			while (putbuf(ybuf, yanklen, false) == 0 &&
+			while (putbuf(ybuf, yanklen, Nee) == 0 &&
 			    --argcnt > 0)
 				;
 			if (vs->cursor != 0)
@@ -4296,7 +4410,7 @@ vi_cmd(int argcnt, const char *cmd)
 			modified = 1;
 			hnum = hlast;
 			any = 0;
-			while (putbuf(ybuf, yanklen, false) == 0 &&
+			while (putbuf(ybuf, yanklen, Nee) == 0 &&
 			    --argcnt > 0)
 				any = 1;
 			if (any && vs->cursor != 0)
@@ -4411,7 +4525,7 @@ vi_cmd(int argcnt, const char *cmd)
 				if (modified) {
 					vs->cbuf[vs->linelen] = '\0';
 					histsave(&source->line, vs->cbuf,
-					    HIST_STORE, true);
+					    HIST_STORE, Ja);
 				} else
 					argcnt = source->line + 1 -
 					    (hlast - hnum);
@@ -4486,7 +4600,7 @@ vi_cmd(int argcnt, const char *cmd)
 			if ((c2 = grabsearch(srchpat, modified, hnum, b)) < 0) {
 				if (c1) {
 					restore_cbuf();
-					refresh(false);
+					refresh(Nee);
 				}
 				return (-1);
 			} else {
@@ -4502,7 +4616,7 @@ vi_cmd(int argcnt, const char *cmd)
 			break;
 		case ORD('_'):
 			{
-				bool inspace;
+				Wahr inspace;
 				char *p, *sp;
 
 				if (histnum(-1) < 0)
@@ -4522,12 +4636,12 @@ vi_cmd(int argcnt, const char *cmd)
 					sp = p;
 				} else {
 					sp = p;
-					inspace = false;
+					inspace = Nee;
 					while (*p) {
 						if (ctype(*p, C_SPACE))
-							inspace = true;
+							inspace = Ja;
 						else if (inspace) {
-							inspace = false;
+							inspace = Nee;
 							sp = p;
 						}
 						p++;
@@ -4542,8 +4656,8 @@ vi_cmd(int argcnt, const char *cmd)
 					argcnt++;
 					p++;
 				}
-				if (putbuf(T1space, 1, false) != 0 ||
-				    putbuf(sp, argcnt, false) != 0) {
+				if (putbuf(T1space, 1, Nee) != 0 ||
+				    putbuf(sp, argcnt, Nee) != 0) {
 					if (vs->cursor != 0)
 						vs->cursor--;
 					return (-1);
@@ -4592,7 +4706,6 @@ vi_cmd(int argcnt, const char *cmd)
 			print_expansions(vs, 1);
 			break;
 
-
 		/* Nonstandard vi/ksh */
 		case CTRL_I:
 			if (!Flag(FVITABCOMPLETE))
@@ -4612,7 +4725,6 @@ vi_cmd(int argcnt, const char *cmd)
 			complete_word(1, argcnt);
 			break;
 
-
 		/* AT&T ksh */
 		case ORD('*'):
 		/* Nonstandard vi/ksh */
@@ -4620,7 +4732,6 @@ vi_cmd(int argcnt, const char *cmd)
 			expand_word(1);
 			break;
 
-
 		/* mksh: cursor movement */
 		case ORD('['):
 		case ORD('O'):
@@ -4682,12 +4793,12 @@ domove(int argcnt, const char *cmd, int
 	case ORD(';'):
 		if (fsavecmd == ORD(' '))
 			return (-1);
-		i = ksh_eq(fsavecmd, 'F', 'f');
+		i = isCh(fsavecmd, 'F', 'f');
 		t = rtt2asc(fsavecmd) > rtt2asc('a');
 		if (*cmd == ',')
 			t = !t;
-		if ((ncursor = findch(fsavech, argcnt, tobool(t),
-		    tobool(i))) < 0)
+		if ((ncursor = findch(fsavech, argcnt, isWahr(t),
+		    isWahr(i))) < 0)
 			return (-1);
 		if (sub && t)
 			ncursor++;
@@ -4795,7 +4906,7 @@ static int
 redo_insert(int count)
 {
 	while (count-- > 0)
-		if (putbuf(ibuf, inslen, tobool(insert == REPLACE)) != 0)
+		if (putbuf(ibuf, inslen, isWahr(insert == REPLACE)) != 0)
 			return (-1);
 	if (vs->cursor > 0)
 		vs->cursor--;
@@ -4898,11 +5009,11 @@ free_edstate(struct edstate *old)
 static int
 x_vi_putbuf(const char *s, size_t len)
 {
-	return (putbuf(s, len, false));
+	return (putbuf(s, len, Nee));
 }
 
 static int
-putbuf(const char *buf, ssize_t len, bool repl)
+putbuf(const char *buf, ssize_t len, Wahr repl)
 {
 	if (len == 0)
 		return (0);
@@ -4932,7 +5043,7 @@ del_range(int a, int b)
 }
 
 static int
-findch(int ch, int cnt, bool forw, bool incl)
+findch(int ch, int cnt, Wahr forw, Wahr incl)
 {
 	int ncursor;
 
@@ -5095,9 +5206,10 @@ grabhist(int save, int n)
 		ohnum = n;
 		return (0);
 	}
-	(void)histnum(n);
+	histnum(n);
 	if ((hptr = *histpos()) == NULL) {
-		internal_warningf("grabhist: bad history array");
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_ONEMSG | KWF_NOERRNO,
+		    "grabhist: bad history array");
 		return (-1);
 	}
 	if (save)
@@ -5111,11 +5223,11 @@ grabhist(int save, int n)
 }
 
 static int
-grabsearch(const char *pat, int save, int start, bool fwd)
+grabsearch(const char *pat, int save, int start, Wahr fwd)
 {
 	char *hptr;
 	int hist;
-	bool anchored;
+	Wahr anchored;
 
 	if ((start == 0 && !fwd) || (start >= hlast - 1 && fwd))
 		return (-1);
@@ -5123,7 +5235,7 @@ grabsearch(const char *pat, int save, in
 		start++;
 	else
 		start--;
-	anchored = *pat == '^' ? (++pat, true) : false;
+	anchored = *pat == '^' ? (++pat, Ja) : Nee;
 	if ((hist = findhist(start, pat, fwd, anchored)) < 0) {
 		/* (start != 0 && fwd && match(holdbufp, pat) >= 0) */
 		if (start != 0 && fwd && strcmp(holdbufp, pat) >= 0) {
@@ -5144,7 +5256,7 @@ grabsearch(const char *pat, int save, in
 }
 
 static void
-redraw_line(bool newl)
+redraw_line(Wahr newl)
 {
 	if (wbuf_len)
 		memset(wbuf[win], ' ', wbuf_len);
@@ -5157,7 +5269,7 @@ redraw_line(bool newl)
 }
 
 static void
-refresh(bool leftside)
+refresh(Wahr leftside)
 {
 	if (outofwin())
 		rewindow();
@@ -5214,7 +5326,7 @@ newcol(unsigned char ch, int col)
 }
 
 static void
-display(char *wb1, char *wb2, bool leftside)
+display(char *wb1, char *wb2, Wahr leftside)
 {
 	unsigned char ch;
 	char *twb1, *twb2, mc;
@@ -5318,7 +5430,6 @@ ed_mov_opt(int col, char *wb)
 	x_col = col;
 }
 
-
 /* replace word with all expansions (ie, expand word*) */
 static int
 expand_word(int cmd)
@@ -5357,7 +5468,7 @@ expand_word(int cmd)
 			rval = -1;
 			break;
 		}
-		if (++i < nwords && putbuf(T1space, 1, false) != 0) {
+		if (++i < nwords && putbuf(T1space, 1, Nee) != 0) {
 			rval = -1;
 			break;
 		}
@@ -5369,7 +5480,7 @@ expand_word(int cmd)
 	hnum = hlast;
 	insert = INSERT;
 	lastac = 0;
-	refresh(false);
+	refresh(Nee);
 	return (rval);
 }
 
@@ -5381,7 +5492,7 @@ complete_word(int cmd, int count)
 	size_t match_len;
 	char **words;
 	char *match;
-	bool is_unique;
+	Wahr is_unique;
 
 	/* Undo previous completion */
 	if (cmd == 0 && expanded == COMPLETE && buf) {
@@ -5420,9 +5531,9 @@ complete_word(int cmd, int count)
 		if (count >= nwords) {
 			vi_error();
 			x_print_expansions(nwords, words,
-			    tobool(flags & XCF_IS_COMMAND));
+			    isWahr(flags & XCF_IS_COMMAND));
 			x_free_words(nwords, words);
-			redraw_line(false);
+			redraw_line(Nee);
 			return (-1);
 		}
 		/*
@@ -5442,7 +5553,7 @@ complete_word(int cmd, int count)
 		} else
 			match = words[count];
 		match_len = strlen(match);
-		is_unique = true;
+		is_unique = Ja;
 		/* expanded = PRINT;	next call undo */
 	} else {
 		match = words[0];
@@ -5471,11 +5582,14 @@ complete_word(int cmd, int count)
 
 		/*
 		 * append a space if this is a non-directory match
-		 * and not a parameter or homedir substitution
+		 * and not a parameter substitution, slash for homedir
 		 */
-		if (match_len > 0 && !mksh_cdirsep(match[match_len - 1]) &&
-		    !(flags & XCF_IS_NOSPACE))
-			rval = putbuf(T1space, 1, false);
+		if (match_len > 0 && !mksh_cdirsep(match[match_len - 1])) {
+			if (flags & XCF_IS_HOMEDIR)
+				rval = putbuf("/", 1, Nee);
+			else if (!(flags & XCF_IS_NOSPACE))
+				rval = putbuf(T1space, 1, Nee);
+		}
 	}
 	x_free_words(nwords, words);
 
@@ -5484,7 +5598,7 @@ complete_word(int cmd, int count)
 	insert = INSERT;
 	/* prevent this from being redone... */
 	lastac = 0;
-	refresh(false);
+	refresh(Nee);
 
 	return (rval);
 }
@@ -5502,25 +5616,12 @@ print_expansions(struct edstate *est, in
 		vi_error();
 		return (-1);
 	}
-	x_print_expansions(nwords, words, tobool(i & XCF_IS_COMMAND));
+	x_print_expansions(nwords, words, isWahr(i & XCF_IS_COMMAND));
 	x_free_words(nwords, words);
-	redraw_line(false);
+	redraw_line(Nee);
 	return (0);
 }
-#endif /* !MKSH_S_NOVI */
-
-/* Similar to x_zotc(emacs.c), but no tab weirdness */
-static void
-x_vi_zotc(int c)
-{
-	if (ksh_isctrl(c)) {
-		x_putc('^');
-		c = ksh_unctrl(c);
-	}
-	x_putc(c);
-}
 
-#if !MKSH_S_NOVI
 static void
 vi_error(void)
 {
@@ -5544,7 +5645,7 @@ vi_macro_reset(void)
 void
 x_init(void)
 {
-	int i, j;
+	size_t i;
 
 	/*
 	 * set edchars to force initial binding, except we need
@@ -5561,29 +5662,32 @@ x_init(void)
 	/* initialise Emacs command line editing mode */
 	x_nextcmd = -1;
 
-	x_tab = alloc2(X_NTABS, sizeof(*x_tab), AEDIT);
-	for (j = 0; j < X_TABSZ; j++)
-		x_tab[0][j] = XFUNC_insert;
-	for (i = 1; i < X_NTABS; i++)
-		for (j = 0; j < X_TABSZ; j++)
-			x_tab[i][j] = XFUNC_error;
-	for (i = 0; i < (int)NELEM(x_defbindings); i++)
-		x_tab[x_defbindings[i].xdb_tab][x_defbindings[i].xdb_char]
-		    = x_defbindings[i].xdb_func;
+	x_ktab = alloc2(X_NTABS << 8, sizeof(kby), AEDIT);
+	i = 0;
+	while (i <= 0xFF)
+		x_ktab[i++] = XFUNC_insert;
+	while (i < (X_NTABS << 8))
+		x_ktab[i++] = XFUNC_error;
+	for (i = 0; i < NELEM(x_defbindings); ++i)
+		X_KTAB(x_defbindings[i].xdb_tab,
+		    x_defbindings[i].xdb_char) = x_defbindings[i].xdb_func;
 
 #ifndef MKSH_SMALL
-	x_atab = alloc2(X_NTABS, sizeof(*x_atab), AEDIT);
-	for (i = 1; i < X_NTABS; i++)
-		for (j = 0; j < X_TABSZ; j++)
-			x_atab[i][j] = NULL;
+	x_mtab = alloc2(X_NTABS << 8, sizeof(char *), AEDIT);
+	i = 0;
+	while (i < (X_NTABS << 8))
+		x_mtab[i++] = NULL;
 #endif
+
+	x_btab = alloc2(X_NTABS << (8 - 3), sizeof(kby), AEDIT);
+	memset(x_btab, 0, (X_NTABS << (8 - 3)) * sizeof(kby));
 }
 
 #ifdef DEBUG_LEAKS
 void
 x_done(void)
 {
-	if (x_tab != NULL)
+	if (x_btab != NULL)
 		afreeall(AEDIT);
 }
 #endif
@@ -5597,12 +5701,12 @@ x_initterm(const char *termtype)
 	switch (*termtype) {
 	case 's':
 		if (!strncmp(termtype, "screen", 6) &&
-		    (termtype[6] == '\0' || termtype[6] == '-'))
+		    (!termtype[6] || ord(termtype[6]) == ORD('-')))
 			x_term_mode = 1;
 		break;
 	case 't':
 		if (!strncmp(termtype, "tmux", 4) &&
-		    (termtype[4] == '\0' || termtype[4] == '-'))
+		    (!termtype[4] || ord(termtype[4]) == ORD('-')))
 			x_term_mode = 1;
 		break;
 	}
@@ -5652,17 +5756,17 @@ x_operate_region(char *(*helper)(const c
 		rgend = xmp;
 	}
 
-	x_e_putc2('\r');
-	x_clrtoeol(' ', false);
+	x_e_putb('\r');
+	x_clrtoeol(' ', Nee);
 	x_flush();
-	x_mode(false);
+	x_mode(Nee);
 	cp = helper(rgbeg, rgend - rgbeg);
-	x_mode(true);
+	x_mode(Ja);
 
 	if (cp == NULL) {
 		/* error return from helper */
  x_eval_region_err:
-		x_e_putc2(KSH_BEL);
+		x_e_putb(KSH_BEL);
 		x_redraw('\r');
 		return (KSTD);
 	}
@@ -5699,9 +5803,7 @@ x_quote_region_helper(const char *cmd, s
 
 	strndupx(s, cmd, len, ATEMP);
 	newlen = len < 256 ? 256 : 4096;
-	shf_sopen(alloc(newlen, AEDIT), newlen, SHF_WR | SHF_DYNAMIC, &shf);
-	shf.areap = AEDIT;
-	shf.flags |= SHF_ALLOCB;
+	shf_sreopen(alloc(newlen, AEDIT), newlen, AEDIT, &shf);
 	print_value_quoted(&shf, s);
 	afree(s, ATEMP);
 	return (shf_sclose(&shf));
@@ -5713,4 +5815,88 @@ x_quote_region(int c MKSH_A_UNUSED)
 	return (x_operate_region(x_quote_region_helper));
 }
 #endif /* !MKSH_SMALL */
+
+#ifdef DF
+/* debug code to dump the Emacs buffer state */
+#define TL() do {							\
+	tmp = ofs & 0xFU;						\
+	if (tmp) {							\
+		while (tmp != 0x10U) {					\
+			shf_puts(tmp == 0x8U ? " -   " : "   ", &to);	\
+			++tmp;						\
+		}							\
+		tmp = ofs & (size_t)~(size_t)0xFU;			\
+	} else if (ofs)							\
+		tmp = ofs - 0x10U;					\
+	shf_puts("  ", &to);						\
+	while ((tmp & 0xFU) < lbeg) {					\
+		shf_putc(' ', &to);					\
+		++tmp;							\
+	}								\
+	shf_putc('|', &to);						\
+	while (tmp < ofs) {						\
+		kby c = xbuf[tmp++];					\
+		shf_putc(ctype(c, C_PRINT) ? c : '.', &to);		\
+	}								\
+	shf_putc('|', &to);						\
+	lbeg = ofs & 0xFU;						\
+	nl = 1;								\
+} while (/* CONSTCOND */ 0)
+
+#define DP(p) do { if ((xbuf + ofs) == p) {				\
+	if (!nl) TL();							\
+	shf_fprintf(&to, nl < 2 ? "\n   ↓ = %s" : " and %s", #p);	\
+	nl = 2;								\
+} } while (/* CONSTCOND */ 0)
+
+static void
+x_emacs_DF(const char *reason)
+{
+	struct shf to;
+	kby nl;
+	size_t ofs, end, tmp, lbeg = 0;
+
+	shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &to);
+	ofs = 0;
+	nl = 1;
+	if (xdp > xep)
+		end = xdp - xbuf + 1;
+	else
+		end = xep - xbuf + 1;
+	/* end is within xend + X_EXTRA */
+	while (ofs < end) {
+		DP(xbp);
+		DP(xmp);
+		DP(xcp);
+		DP(xlp);
+		DP(xdp);
+		DP(xep);
+		if (nl) {
+			shf_fprintf(&to, "\n%04zX ", ofs);
+			tmp = ofs & (size_t)~(size_t)0xFU;
+			while (tmp < ofs) {
+				shf_puts((tmp & 0xFU) == 0x8U ?
+				    " -   " : "   ", &to);
+				++tmp;
+			}
+			nl = 0;
+		}
+		shf_fprintf(&to, (ofs & 0xFU) == 0x8U ? " - %02X" : " %02X",
+		    ord(xbuf[ofs]));
+		++ofs;
+		if (!(ofs & 0xFU))
+			TL();
+	}
+	if (!nl)
+		TL();
+	DF("‣ xbuf: %s%s", reason, shf_sclose(&to));
+}
+
+static int
+x_debug_buf(int c MKSH_A_UNUSED)
+{
+	x_emacs_DF("from keyboard");
+	return (KSTD);
+}
+#endif
 #endif /* !MKSH_NO_CMDLINE_EDITING */
--- mksh-59c.orig/emacsfn.h
+++ mksh-59c/emacsfn.h
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2009, 2010, 2015, 2016, 2020
+ * Copyright (c) 2009, 2010, 2015, 2016, 2020, 2021
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -19,7 +19,7 @@
  */
 
 #if defined(EMACSFN_DEFNS)
-__RCSID("$MirOS: src/bin/mksh/emacsfn.h,v 1.11 2020/04/13 20:46:39 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/emacsfn.h,v 1.16 2021/10/16 01:28:06 tg Exp $");
 #define FN(cname,sname,flags)	static int x_##cname(int);
 #elif defined(EMACSFN_ENUMS)
 #define FN(cname,sname,flags)	XFUNC_##cname,
@@ -40,10 +40,19 @@ FN(comp_comm, "complete-command", 0)
 FN(comp_file, "complete-file", 0)
 FN(comp_list, "complete-list", 0)
 FN(complete, "complete", 0)
+#ifdef DF
+FN(debug_buf, "debug-buffer", 0)
+#endif
 FN(del_back, "delete-char-backward", XF_ARG)
 FN(del_bword, "delete-word-backward", XF_ARG)
+#ifndef MKSH_SMALL
+FN(del_bbigword, "delete-bigword-backward", XF_ARG)
+#endif
 FN(del_char, "delete-char-forward", XF_ARG)
 FN(del_fword, "delete-word-forward", XF_ARG)
+#ifndef MKSH_SMALL
+FN(del_fbigword, "delete-bigword-forward", XF_ARG)
+#endif
 FN(del_line, "kill-line", 0)
 FN(draw_line, "redraw", 0)
 #ifndef MKSH_SMALL
@@ -59,8 +68,11 @@ FN(eval_region, "evaluate-region", 0)
 #endif
 FN(expand, "expand-file", 0)
 #ifndef MKSH_SMALL
-FN(fold_capitalise, "capitalize-word", XF_ARG)
+FN(foldb_capitalise, "capitalise-bigword", XF_ARG)
+FN(fold_capitalise, "capitalise-word", XF_ARG)
+FN(foldb_lower, "downcase-bigword", XF_ARG)
 FN(fold_lower, "downcase-word", XF_ARG)
+FN(foldb_upper, "upcase-bigword", XF_ARG)
 FN(fold_upper, "upcase-word", XF_ARG)
 #endif
 FN(goto_hist, "goto-history", XF_ARG)
@@ -80,15 +92,21 @@ FN(meta_yank, "yank-pop", 0)
 FN(mv_back, "backward-char", XF_ARG)
 FN(mv_beg, "beginning-of-line", 0)
 FN(mv_bword, "backward-word", XF_ARG)
+#ifndef MKSH_SMALL
+FN(mv_bbigword, "backward-bigword", XF_ARG)
+#endif
 FN(mv_end, "end-of-line", 0)
 FN(mv_forw, "forward-char", XF_ARG)
 FN(mv_fword, "forward-word", XF_ARG)
+#ifndef MKSH_SMALL
+FN(mv_fbigword, "forward-bigword", XF_ARG)
+#endif
 FN(newline, "newline", 0)
 FN(next_com, "down-history", XF_ARG)
 FN(nl_next_com, "newline-and-next", 0)
 FN(noop, "no-op", 0)
 FN(prev_com, "up-history", XF_ARG)
-FN(prev_histword, "prev-hist-word", XF_ARG)
+FN(prev_histword, "prev-hist-bigword", XF_ARG)
 #ifndef MKSH_SMALL
 FN(quote_region, "quote-region", 0)
 #endif
--- mksh-59c.orig/eval.c
+++ mksh-59c/eval.c
@@ -3,7 +3,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -24,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/eval.c,v 1.231 2020/05/05 21:34:27 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/eval.c,v 1.262 2024/07/05 13:57:39 tg Exp $");
 
 /*
  * string expansion
@@ -48,7 +48,7 @@ typedef struct {
 	/* variable in ${var...} */
 	struct tbl *var;
 	/* split "$@" / call waitlast in $() */
-	bool split;
+	Wahr split;
 } Expand;
 
 #define XBASE		0	/* scanning original string */
@@ -79,17 +79,21 @@ typedef struct {
 static int varsub(Expand *, const char *, const char *, unsigned int *, int *);
 static int comsub(Expand *, const char *, int);
 static char *valsub(struct op *, Area *);
+static void funsub(struct op *);
 static char *trimsub(char *, char *, int);
-static void glob(char *, XPtrV *, bool);
+static void glob(char *, XPtrV *, Wahr);
 static void globit(XString *, char **, char *, XPtrV *, int);
-static const char *maybe_expand_tilde(const char *, XString *, char **, bool);
+static const char *maybe_expand_tilde(const char *, XString *, char **, Wahr);
 #ifndef MKSH_NOPWNAM
 static char *homedir(char *);
 #endif
 static void alt_expand(XPtrV *, char *, char *, char *, int);
-static int utflen(const char *) MKSH_A_PURE;
+static int utflen(const char *);
 static void utfincptr(const char *, mksh_ari_t *);
 
+/* null (sh.h) */
+char null_string[4] = { 0, 0, 0, 0 };
+
 /* UTFMODE functions */
 static int
 utflen(const char *s)
@@ -99,7 +103,7 @@ utflen(const char *s)
 	if (UTFMODE) {
 		n = 0;
 		while (*s) {
-			s += utf_ptradj(s);
+			s += ez_mbtoc(NULL, s);
 			++n;
 		}
 	} else
@@ -116,7 +120,7 @@ utfincptr(const char *s, mksh_ari_t *lp)
 	const char *cp = s;
 
 	while ((*lp)--)
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 	*lp = cp - s;
 }
 
@@ -131,7 +135,8 @@ substitute(const char *cp, int f)
 	s->start = s->str = cp;
 	source = s;
 	if (yylex(ONEWORD) != LWORD)
-		internal_errorf(Tbadsubst);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    Tbadsubst);
 	source = sold;
 	afree(s, ATEMP);
 	return (evalstr(yylval.cp, f));
@@ -212,8 +217,8 @@ typedef struct SubType {
 	size_t	base;		/* start position of expanded word */
 	unsigned short stype;	/* [=+-?%#] action after expanded word */
 	short	f;		/* saved value of f (DOPAT, etc) */
-	uint8_t	quotep;		/* saved value of quote (for ${..[%#]..}) */
-	uint8_t	quotew;		/* saved value of quote (for ${..[+-=]..}) */
+	kby	quotep;		/* saved value of quote (for ${..[%#]..}) */
+	kby	quotew;		/* saved value of quote (for ${..[+-=]..}) */
 } SubType;
 
 void
@@ -248,15 +253,16 @@ expand(
 	SubType st_head, *st;
 	/* record number of trailing newlines in COMSUB */
 	int newlines = 0;
-	bool saw_eq, make_magic;
+	Wahr saw_eq, make_magic;
 	unsigned int tilde_ok;
 	size_t len;
 	char *cp;
 
 	if (ccp == NULL)
-		internal_errorf("expand(NULL)");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "expand(NULL)");
 	/* for alias, readonly, set, typeset commands */
-	if ((f & DOVACHECK) && is_wdvarassign(ccp)) {
+	if ((f & DOVACHECK) && is_wdvarassign(ccp, Nee)) {
 		f &= ~(DOVACHECK | DOBLANK | DOGLOB | DOTILDE);
 		f |= DOASNTILDE | DOSCALAR;
 	}
@@ -272,11 +278,11 @@ expand(
 	type = XBASE;
 	sp = ccp;
 	fdo = 0;
-	saw_eq = false;
+	saw_eq = Nee;
 	/* must be 1/0 */
 	tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
 	doblank = 0;
-	make_magic = false;
+	make_magic = Nee;
 	word = (f&DOBLANK) ? IFS_WS : IFS_WORD;
 	/* clang doesn't know OSUBST comes before CSUBST */
 	memset(&st_head, 0, sizeof(st_head));
@@ -361,16 +367,17 @@ expand(
 					}
 					*dp++ = ')'; *dp++ = ')';
 				} else {
-					struct tbl v;
+					union tbl_static v;
 
-					v.flag = DEFINED|ISSET|INTEGER;
+					v.tbl.flag = DEFINED|ISSET|INTEGER;
 					/* not default */
-					v.type = 10;
-					v.name[0] = '\0';
-					v_evaluate(&v, substitute(sp, 0),
-					    KSH_UNWIND_ERROR, true);
+					v.tbl.type = 10;
+					v.tbl.name[0] = '\0';
+					v_evaluate((struct tbl *)&v,
+					    substitute(sp, 0),
+					    KSH_UNWIND_ERROR, Ja);
 					sp = strnul(sp) + 1;
-					x.str = str_val(&v);
+					x.str = str_val((struct tbl *)&v);
 					type = XSUB;
 					if (f & DOBLANK)
 						doblank++;
@@ -386,11 +393,11 @@ expand(
 			 */
 				/* skip the { or x (}) */
 				const char *varname = ++sp;
-				unsigned int stype;
+				unsigned int stype /* for GCC */ = 0;
 				int slen = 0;
 
 				/* skip variable */
-				sp = cstrchr(sp, '\0') + 1;
+				sp = strnul(sp) + 1;
 				type = varsub(&x, varname, sp, &stype, &slen);
 				if (type < 0) {
 					char *beg, *end, *str;
@@ -398,14 +405,16 @@ expand(
 					/* restore sp */
 					sp = varname - 2;
 					beg = wdcopy(sp, ATEMP);
-					end = (wdscan(cstrchr(sp, '\0') + 1,
-					    CSUBST) - sp) + beg;
+					end = (wdscan(strnul(sp) + 1, CSUBST) -
+					    sp) + beg;
 					/* ({) the } or x is already skipped */
 					if (end < wdscan(beg, EOS))
 						*end = EOS;
 					str = snptreef(NULL, 64, Tf_S, beg);
 					afree(beg, ATEMP);
-					errorf(Tf_sD_s, str, Tbadsubst);
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_TWOMSG |
+					    KWF_NOERRNO, str, Tbadsubst);
 				}
 				if (f & DOBLANK)
 					doblank++;
@@ -443,6 +452,7 @@ expand(
 					switch (stype & STYPE_SINGLE) {
 					case ORD('#') | STYPE_AT:
 					case ORD('Q') | STYPE_AT:
+					case ORD('^') | STYPE_AT:
 						break;
 					case ORD('0'): {
 						char *beg, *mid, *end, *stg;
@@ -465,11 +475,11 @@ expand(
 							sp += end - beg - 1;
 						}
 						evaluate(substitute(stg = wdstrip(beg, 0), 0),
-						    &from, KSH_UNWIND_ERROR, true);
+						    &from, KSH_UNWIND_ERROR, Ja);
 						afree(stg, ATEMP);
 						if (end) {
 							evaluate(substitute(stg = wdstrip(mid, 0), 0),
-							    &num, KSH_UNWIND_ERROR, true);
+							    &num, KSH_UNWIND_ERROR, Ja);
 							afree(stg, ATEMP);
 						}
 						afree(beg, ATEMP);
@@ -541,7 +551,7 @@ expand(
 							goto no_repl;
 						}
 						if ((stype & STYPE_MASK) &&
-						    gmatchx(null, pat, false)) {
+						    gmatchx(null, pat, Nee)) {
 							/*
 							 * pattern matches empty
 							 * string => don't loop
@@ -568,13 +578,13 @@ expand(
 						 * this would not be necessary if gmatchx would return
 						 * the start and end values of a match found, like re*
 						 */
-						if (!gmatchx(sbeg, tpat1, false))
+						if (!gmatchx(sbeg, tpat1, Nee))
 							goto end_repl;
 						d = strnul(s);
 						/* now anchor the beginning of the match */
 						if (ord(fpat) != ORD('#'))
 							while (sbeg <= d) {
-								if (gmatchx(sbeg, tpat2, false))
+								if (gmatchx(sbeg, tpat2, Nee))
 									break;
 								else
 									sbeg++;
@@ -583,11 +593,11 @@ expand(
 						p = d;
 						if (ord(fpat) != ORD('%'))
 							while (p >= sbeg) {
-								bool gotmatch;
+								Wahr gotmatch;
 
 								c = ord(*p);
 								*p = '\0';
-								gotmatch = tobool(gmatchx(sbeg, pat, false));
+								gotmatch = isWahr(gmatchx(sbeg, pat, Nee));
 								*p = c;
 								if (gotmatch)
 									break;
@@ -703,8 +713,10 @@ expand(
 						break;
 					case ORD('?'):
 						if (*sp == CSUBST)
-							errorf("%s: parameter null or not set",
-							    st->var->name);
+							kerrf(KWF_ERR(1) | KWF_PREFIX |
+							    KWF_FILELINE | KWF_TWOMSG |
+							    KWF_NOERRNO, st->var->name,
+							    "parameter null or not set");
 						f &= ~DOBLANK;
 						f |= DOTEMP;
 						/* FALLTHROUGH */
@@ -785,9 +797,9 @@ expand(
 					 * in AT&T ksh.
 					 */
 					/*
-					 * XXX POSIX says readonly is only
+					 * XXX POSIX says read-only is only
 					 * fatal for special builtins (setstr
-					 * does readonly check).
+					 * does read-only check).
 					 */
 					len = strlen(dp) + 1;
 					setstr(st->var,
@@ -803,11 +815,13 @@ expand(
 				case ORD('?'):
 					dp = Xrestpos(ds, dp, st->base);
 
-					errorf(Tf_sD_s, st->var->name,
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_TWOMSG |
+					    KWF_NOERRNO, st->var->name,
 					    debunk(dp, dp, strlen(dp) + 1));
 					break;
 				case ORD('#') | STYPE_AT:
-					x.str = shf_smprintf("%08X",
+					x.str = shf_smprintf(Thex32,
 					    (unsigned int)hash(str_val(st->var)));
 					goto common_CSUBST;
 				case ORD('Q') | STYPE_AT: {
@@ -818,6 +832,14 @@ expand(
 					x.str = shf_sclose(&shf);
 					goto common_CSUBST;
 				    }
+				case ORD('^') | STYPE_AT: {
+					struct shf shf;
+
+					shf_sopen(NULL, 0, SHF_WR|SHF_DYNAMIC, &shf);
+					uprntmbs(str_val(st->var), Ja, &shf);
+					x.str = shf_sclose(&shf);
+					goto common_CSUBST;
+				    }
 				case ORD('0'):
 				case ORD('/') | STYPE_AT:
 				case ORD('/'):
@@ -838,19 +860,19 @@ expand(
 			case OPAT:
 				/* open pattern: *(foo|bar) */
 				/* Next char is the type of pattern */
-				make_magic = true;
+				make_magic = Ja;
 				c = ord(*sp++) | 0x80U;
 				break;
 
 			case SPAT:
 				/* pattern separator (|) */
-				make_magic = true;
+				make_magic = Ja;
 				c = ORD('|');
 				break;
 
 			case CPAT:
 				/* close pattern */
-				make_magic = true;
+				make_magic = Ja;
 				c = ORD(/*(*/ ')');
 				break;
 			}
@@ -893,7 +915,7 @@ expand(
 				if (ord(*x.str) == ORD('('/*)*/)) {
 					++x.str;
 					c |= 0x80U;
-					make_magic = true;
+					make_magic = Ja;
 				}
 				break;
 			case ORD('('):
@@ -901,7 +923,7 @@ expand(
 				/* FALLTHROUGH */
 			case ORD('|'):
 			case ORD(')'):
-				make_magic = true;
+				make_magic = Ja;
 				break;
 			}
 			break;
@@ -1005,8 +1027,8 @@ expand(
 				c = ORD('\n');
 				--newlines;
 			} else {
-				while ((c = shf_getc(x.u.shf)) == 0 ||
-				    cinttype(c, C_NL)) {
+				while (c = shf_getc(x.u.shf),
+				    cinttype(c, C_NL | C_NUL)) {
 #ifdef MKSH_WITH_TEXTMODE
 					if (c == ORD('\r')) {
 						c = shf_getc(x.u.shf);
@@ -1063,25 +1085,26 @@ expand(
 			if ((word == IFS_WORD) || (word == IFS_QUOTE) || (c &&
 			    (word == IFS_IWS || word == IFS_NWS) &&
 			    !ctype(c, C_IFSWS))) {
+				size_t dlen;
  emit_word:
 				if (f & DOHERESTR)
 					*dp++ = '\n';
 				*dp++ = '\0';
+				dlen = Xlength(ds, dp);
 				cp = Xclose(ds, dp);
 				if (fdo & DOBRACE)
 					/* also does globbing */
 					alt_expand(wp, cp, cp,
-					    cp + Xlength(ds, (dp - 1)),
+					    cp + dlen - 1,
 					    fdo | (f & DOMARKDIRS));
 				else if (fdo & DOGLOB)
-					glob(cp, wp, tobool(f & DOMARKDIRS));
+					glob(cp, wp, isWahr(f & DOMARKDIRS));
 				else if ((f & DOPAT) || !(fdo & DOMAGIC))
 					XPput(*wp, cp);
 				else
-					XPput(*wp, debunk(cp, cp,
-					    strlen(cp) + 1));
+					XPput(*wp, debunk(cp, cp, dlen));
 				fdo = 0;
-				saw_eq = false;
+				saw_eq = Nee;
 				/* must be 1/0 */
 				tilde_ok = (f & (DOTILDE | DOASNTILDE)) ? 1 : 0;
 				if (c == 0)
@@ -1143,7 +1166,7 @@ expand(
 					/* Note first unquoted = for ~ */
 					if (!(f & DOTEMP) && (!Flag(FPOSIX) ||
 					    (f & DOASNTILDE)) && !saw_eq) {
-						saw_eq = true;
+						saw_eq = Ja;
 						tilde_ok = 1;
 					}
 					break;
@@ -1168,7 +1191,7 @@ expand(
 
 						tcp = maybe_expand_tilde(sp,
 						    &ds, &tdp,
-						    tobool(f & DOASNTILDE));
+						    isWahr(f & DOASNTILDE));
 						if (tcp) {
 							if (dp != tdp)
 								word = IFS_WORD;
@@ -1184,7 +1207,7 @@ expand(
 				quote &= ~2;
 
 			if (make_magic) {
-				make_magic = false;
+				make_magic = Nee;
 				fdo |= DOMAGIC | (f & DOGLOB);
 				*dp++ = MAGIC;
 			} else if (ISMAGIC(c)) {
@@ -1198,15 +1221,15 @@ expand(
 	}
 }
 
-static bool
+static Wahr
 hasnonempty(const char **strv)
 {
 	size_t i = 0;
 
 	while (strv[i])
 		if (*strv[i++])
-			return (true);
-	return (false);
+			return (Ja);
+	return (Nee);
 }
 
 /*
@@ -1225,7 +1248,7 @@ varsub(Expand *xp, const char *sp, const
 	int slen = 0;
 	const char *p;
 	struct tbl *vp;
-	bool zero_ok = false;
+	Wahr zero_ok = Nee;
 	int sc;
 	XPtrV wv;
 
@@ -1300,7 +1323,7 @@ varsub(Expand *xp, const char *sp, const
 			if (sc & 2) {
 				stype = 0;
 				XPinit(wv, 32);
-				vp = global(arrayname(sp));
+				vp = arraybase(sp);
 				do {
 					if (vp->flag & ISSET)
 						XPput(wv, shf_smprintf(Tf_lu,
@@ -1310,12 +1333,13 @@ varsub(Expand *xp, const char *sp, const
 			}
 			xp->var = global(sp);
 			/* use saved p from above */
-			xp->str = p ? shf_smprintf("%s[%lu]", xp->var->name,
+			xp->str = p ? shf_smprintf(Tf_sSQlu, xp->var->name,
 			    arrayindex(xp->var)) : xp->var->name;
 			break;
 #ifdef DEBUG
 		default:
-			internal_errorf("stype mismatch");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+			    "stype mismatch");
 			/* NOTREACHED */
 #endif
 		case ORD('%'):
@@ -1327,13 +1351,7 @@ varsub(Expand *xp, const char *sp, const
 			/* partial utf_mbswidth reimplementation */
 			sc = 0;
 			while (*p) {
-				if (!UTFMODE ||
-				    (wv.len = utf_mbtowc(&c, p)) == (size_t)-1)
-					/* not UTFMODE or not UTF-8 */
-					c = rtt2asc(*p++);
-				else
-					/* UTFMODE and UTF-8 */
-					p += wv.len;
+				p += ez_mbtowc(&c, p);
 				/* c == char or wchar at p++ */
 				if ((slen = utf_wcwidth(c)) == -1) {
 					/* 646, 8859-1, 10646 C0/C1 */
@@ -1347,9 +1365,9 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('#'):
 			  switch (sc & 3) {
 			case 3:
-				vp = global(arrayname(sp));
+				vp = arraybase(sp);
 				if (vp->flag & (ISSET|ARRAY))
-					zero_ok = true;
+					zero_ok = Ja;
 				sc = 0;
 				do {
 					if (vp->flag & ISSET)
@@ -1367,7 +1385,9 @@ varsub(Expand *xp, const char *sp, const
 			}
 			/* ${%var} also here */
 			if (Flag(FNOUNSET) && sc == 0 && !zero_ok)
-				errorf(Tf_parm, sp);
+				kerrf(KWF_ERR(1) | KWF_PREFIX |
+				    KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, sp, Tf_parm);
 			xp->str = shf_smprintf(Tf_d, sc);
 			break;
 		}
@@ -1414,6 +1434,7 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('#'):
 		case ORD('/'):
 		case ORD('Q'):
+		case ORD('^'):
 			break;
 		default:
 			return (-1);
@@ -1452,13 +1473,14 @@ varsub(Expand *xp, const char *sp, const
 		case ORD('0'):
 		case ORD('#') | STYPE_AT:
 		case ORD('Q') | STYPE_AT:
+		case ORD('^') | STYPE_AT:
 	*/	default:
 			return (-1);
 		}
 		/* do what we can */
 		if (sc & 2) {
 			XPinit(wv, 32);
-			vp = global(arrayname(sp));
+			vp = arraybase(sp);
 			do {
 				if (vp->flag & ISSET)
 					XPput(wv, str_val(vp));
@@ -1476,7 +1498,7 @@ varsub(Expand *xp, const char *sp, const
 			else
 				xp->u.strv = (const char **)e->loc->argv + 1;
 			/* POSIX 2009? */
-			zero_ok = true;
+			zero_ok = Ja;
 		}
 		/* have we got any elements? */
 		if (c) {
@@ -1487,7 +1509,7 @@ varsub(Expand *xp, const char *sp, const
 			/* yes → load first */
 			xp->str = *xp->u.strv++;
 			/* $@ or ${foo[@]} */
-			xp->split = tobool(sc & 4);
+			xp->split = isWahr(sc & 4);
 			state = XARG;
 		}
 	}
@@ -1502,12 +1524,14 @@ varsub(Expand *xp, const char *sp, const
 	    stype == (ORD('0') | STYPE_DBL) ||
 	    stype == (ORD('#') | STYPE_AT) ||
 	    stype == (ORD('Q') | STYPE_AT) ||
+	    stype == (ORD('^') | STYPE_AT) ||
 	    (stype & STYPE_CHAR) == ORD('/'))
 		/* expand word instead of variable value */
 		state = XBASE;
 	if (Flag(FNOUNSET) && xp->str == null && !zero_ok &&
 	    (ctype(c, C_SUB2) || (state != XBASE && c != ORD('+'))))
-		errorf(Tf_parm, sp);
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+		    KWF_NOERRNO, sp, Tf_parm);
 	*stypep = stype;
 	*slenp = slen;
 	return (state);
@@ -1522,8 +1546,8 @@ comsub(Expand *xp, const char *cp, int f
 	Source *s, *sold;
 	struct op *t;
 	struct shf *shf;
-	bool doalias = false;
-	uint8_t old_utfmode = UTFMODE;
+	Wahr doalias = Nee;
+	kby old_utfmode = UTFMODE;
 
 	switch (fn) {
 	case COMASUB:
@@ -1532,13 +1556,13 @@ comsub(Expand *xp, const char *cp, int f
 			/* FALLTHROUGH */
 	case FUNASUB:
 		  fn = FUNSUB;
-		doalias = true;
+		doalias = Ja;
 	}
 
 	s = pushs(SSTRING, ATEMP);
 	s->start = s->str = cp;
 	sold = source;
-	t = compile(s, true, doalias);
+	t = compile(s, doalias);
 	afree(s, ATEMP);
 	source = sold;
 
@@ -1548,7 +1572,7 @@ comsub(Expand *xp, const char *cp, int f
 		return (XBASE);
 
 	/* no waitlast() unless specifically enabled later */
-	xp->split = false;
+	xp->split = Nee;
 
 	if (t->type == TCOM &&
 	    *t->args == NULL && *t->vars == NULL && t->ioact != NULL) {
@@ -1561,9 +1585,9 @@ comsub(Expand *xp, const char *cp, int f
 			shf = shf_open(name = evalstr(io->ioname, DOTILDE),
 				O_RDONLY, 0, SHF_MAPHI | SHF_CLEXEC);
 			if (shf == NULL)
-				warningf(!Flag(FTALKING), Tf_sD_s_sD_s,
-				    name, Tcant_open, "$(<...) input",
-				    cstrerror(errno));
+				kwarnf(KWF_PREFIX | (Flag(FTALKING) ?
+				    KWF_FILELINE : 0) | KWF_TWOMSG,
+				    name, Tcant_filesub);
 			break;
 		case IOHERE:
 			if (!herein(io, &name)) {
@@ -1578,7 +1602,8 @@ comsub(Expand *xp, const char *cp, int f
 			shf = NULL;
 			break;
 		default:
-			errorf(Tf_sD_s, T_funny_command,
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG | KWF_NOERRNO, T_funny_command,
 			    snptreef(NULL, 32, Tft_R, io));
 		}
 	} else if (fn == FUNSUB) {
@@ -1590,22 +1615,21 @@ comsub(Expand *xp, const char *cp, int f
 		 * with an shf open for reading (buffered) but yet unused
 		 */
 		maketemp(ATEMP, TT_FUNSUB, &tf);
-		if (!tf->shf) {
-			errorf(Tf_temp,
-			    Tcreate, tf->tffn, cstrerror(errno));
-		}
+		if (!tf->shf)
+			kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+			    Tf_temp, Tcreate, tf->tffn);
 		/* extract shf from temporary file, unlink and free it */
 		shf = tf->shf;
 		unlink(tf->tffn);
 		afree(tf, ATEMP);
 		/* save stdout and let it point to the tempfile */
 		ofd1 = savefd(1);
-		ksh_dup2(shf_fileno(shf), 1, false);
+		ksh_dup2(shf_fileno(shf), 1, Nee);
 		/*
 		 * run tree, with output thrown into the tempfile,
 		 * in a new function block
 		 */
-		valsub(t, NULL);
+		funsub(t);
 		subst_exstat = exstat & 0xFF;
 		/* rewind the tempfile and restore regular stdout */
 		lseek(shf_fileno(shf), (off_t)0, SEEK_SET);
@@ -1621,14 +1645,14 @@ comsub(Expand *xp, const char *cp, int f
 		shf = shf_fdopen(pv[0], SHF_RD, NULL);
 		ofd1 = savefd(1);
 		if (pv[1] != 1) {
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			close(pv[1]);
 		}
 		execute(t, XXCOM | XPIPEO | XFORK, NULL);
 		restfd(1, ofd1);
 		startlast();
 		/* waitlast() */
-		xp->split = true;
+		xp->split = Ja;
 	}
 
 	xp->u.shf = shf;
@@ -1647,48 +1671,47 @@ trimsub(char *str, char *pat, int how)
 	switch (how & (STYPE_CHAR | STYPE_DBL)) {
 	case ORD('#'):
 		/* shortest match at beginning */
-		for (p = str; p <= end; p += utf_ptradj(p)) {
-			c = *p; *p = '\0';
-			if (gmatchx(str, pat, false)) {
+		p = str;
+		do {
+			c = *p;
+			*p = '\0';
+			if (gmatchx(str, pat, Nee)) {
 				record_match(str);
 				*p = c;
 				return (p);
 			}
 			*p = c;
-		}
+			p += ez_mbtoc(NULL, p);
+		} while (c != '\0');
 		break;
 	case ORD('#') | STYPE_DBL:
 		/* longest match at beginning */
-		for (p = end; p >= str; p--) {
-			c = *p; *p = '\0';
-			if (gmatchx(str, pat, false)) {
+		p = end;
+		while (p >= str) {
+			c = *p;
+			*p = '\0';
+			if (gmatchx(str, pat, Nee)) {
 				record_match(str);
 				*p = c;
 				return (p);
 			}
 			*p = c;
+			--p;
 		}
 		break;
 	case ORD('%'):
 		/* shortest match at end */
 		p = end;
 		while (p >= str) {
-			if (gmatchx(p, pat, false))
+			if (gmatchx(p, pat, Nee))
 				goto trimsub_match;
-			if (UTFMODE) {
-				char *op = p;
-				while ((p-- > str) && ((rtt2asc(*p) & 0xC0) == 0x80))
-					;
-				if ((p < str) || (p + utf_ptradj(p) != op))
-					p = op - 1;
-			} else
-				--p;
+			p = ez_bs(p - 1, str);
 		}
 		break;
 	case ORD('%') | STYPE_DBL:
 		/* longest match at end */
 		for (p = str; p <= end; p++)
-			if (gmatchx(p, pat, false)) {
+			if (gmatchx(p, pat, Nee)) {
  trimsub_match:
 				record_match(p);
 				strndupx(end, str, p - str, ATEMP);
@@ -1708,7 +1731,7 @@ trimsub(char *str, char *pat, int how)
 
 /* XXX cp not const 'cause slashes are temporarily replaced with NULs... */
 static void
-glob(char *cp, XPtrV *wp, bool markdirs)
+glob(char *cp, XPtrV *wp, Wahr markdirs)
 {
 	int oldsize = XPsize(*wp);
 
@@ -1729,7 +1752,7 @@ glob(char *cp, XPtrV *wp, bool markdirs)
  * the number of matches found.
  */
 int
-glob_str(char *cp, XPtrV *wp, bool markdirs)
+glob_str(char *cp, XPtrV *wp, Wahr markdirs)
 {
 	int oldsize = XPsize(*wp);
 	XString xs;
@@ -1753,6 +1776,8 @@ globit(XString *xs,	/* dest string */
 	char *xp = *xpp;
 	char *se;
 	char odirsep;
+	DIR *dirp;
+	size_t prefix_len;
 
 	/* This to allow long expansions to be interrupted */
 	intrcheck();
@@ -1811,6 +1836,7 @@ globit(XString *xs,	/* dest string */
 		Xcheck(*xs, xp);
 		*xp++ = *sp++;
 	}
+	*xp = '\0';
 	np = mksh_sdirsep(sp);
 	if (np != NULL) {
 		se = np;
@@ -1822,7 +1848,6 @@ globit(XString *xs,	/* dest string */
 		se = strnul(sp);
 	}
 
-
 	/*
 	 * Check if sp needs globbing - done to avoid pattern checks for strings
 	 * containing MAGIC characters, open [s without the matching close ],
@@ -1836,43 +1861,34 @@ globit(XString *xs,	/* dest string */
 		xp = strnul(xp);
 		*xpp = xp;
 		globit(xs, xpp, np, wp, check);
-	} else {
-		DIR *dirp;
+	} else if ((dirp = opendir((prefix_len = Xlength(*xs, xp)) ?
+	    Xstring(*xs, xp) : Tdot))) {
 		struct dirent *d;
-		char *name;
-		size_t len, prefix_len;
 
-		/* xp = *xpp;	copy_non_glob() may have re-alloc'd xs */
-		*xp = '\0';
-		prefix_len = Xlength(*xs, xp);
-		dirp = opendir(prefix_len ? Xstring(*xs, xp) : Tdot);
-		if (dirp == NULL)
-			goto Nodir;
 		while ((d = readdir(dirp)) != NULL) {
-			name = d->d_name;
-			if (name[0] == '.' &&
-			    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
+			size_t len;
+
+			if (isch(d->d_name[0], '.') && (!d->d_name[1] ||
+			    (isch(d->d_name[1], '.') && !d->d_name[2])))
 				/* always ignore . and .. */
 				continue;
-			if ((*name == '.' && *sp != '.') ||
-			    !gmatchx(name, sp, true))
+			if ((isch(d->d_name[0], '.') && !isch(*sp, '.')) ||
+			    !gmatchx(d->d_name, sp, Ja))
 				continue;
 
 			len = strlen(d->d_name) + 1;
 			XcheckN(*xs, xp, len);
-			memcpy(xp, name, len);
+			memcpy(xp, d->d_name, len);
 			*xpp = xp + len - 1;
 			globit(xs, xpp, np, wp, (check & GF_MARKDIR) |
 			    GF_GLOBBED | (np ? GF_EXCHECK : GF_NONE));
 			xp = Xstring(*xs, xp) + prefix_len;
 		}
 		closedir(dirp);
- Nodir:
-		;
 	}
 
 	if (np != NULL)
-		*--np = odirsep;
+		*(char *)(--np) = odirsep;
 }
 
 /* remove MAGIC from string */
@@ -1909,7 +1925,7 @@ debunk(char *dp, const char *sp, size_t
  * past the name, otherwise returns 0.
  */
 static const char *
-maybe_expand_tilde(const char *p, XString *dsp, char **dpp, bool isassign)
+maybe_expand_tilde(const char *p, XString *dsp, char **dpp, Wahr isassign)
 {
 	XString ts;
 	char *dp = *dpp;
@@ -1951,7 +1967,7 @@ do_tilde(char *cp)
 {
 	char *dp = null;
 #ifndef MKSH_NOPWNAM
-	bool do_simplify = true;
+	Wahr do_simplify = Ja;
 #endif
 
 	if (cp[0] == '\0')
@@ -1963,7 +1979,7 @@ do_tilde(char *cp)
 #ifndef MKSH_NOPWNAM
 	else {
 		dp = homedir(cp);
-		do_simplify = false;
+		do_simplify = Nee;
 	}
 #endif
 
@@ -2017,7 +2033,7 @@ alt_expand(XPtrV *wp, char *start, char
 	char *p = exp_start;
 
 	/* search for open brace */
-	while ((p = strchr(p, MAGIC)) && ord(p[1]) != ORD('{' /*}*/))
+	while ((p = ucstrchr(p, MAGIC)) && ord(p[1]) != ORD('{' /*}*/))
 		p += 2;
 	brace_start = p;
 
@@ -2046,7 +2062,7 @@ alt_expand(XPtrV *wp, char *start, char
 		 * expansion. }
 		 */
 		if (fdo & DOGLOB)
-			glob(start, wp, tobool(fdo & DOMARKDIRS));
+			glob(start, wp, isWahr(fdo & DOMARKDIRS));
 		else
 			XPput(*wp, debunk(start, start, end - start));
 		return;
@@ -2067,7 +2083,7 @@ alt_expand(XPtrV *wp, char *start, char
 			else if ((ord(*p) == ORD(/*{*/ '}') && --count == 0) ||
 			    (*p == ',' && count == 1)) {
 				char *news;
-				int l1, l2, l3;
+				size_t l1, l2, l3;
 
 				/*
 				 * addition safe since these operate on
@@ -2090,22 +2106,55 @@ alt_expand(XPtrV *wp, char *start, char
 	return;
 }
 
+static void
+subcpybk(struct block *l)
+{
+	/* did the valsub/funsub change $#/$*? */
+	if (e->loc->argc == l->argc &&
+	    e->loc->argv == l->argv)
+		return;
+
+	/* yes ⇒ copy back to parent Area */
+	l->argv = cpyargv(&l->argc, e->loc->argv, &l->area);
+}
+
 /* helper function due to setjmp/longjmp woes */
 static char *
 valsub(struct op *t, Area *ap)
 {
-	char * volatile cp = NULL;
-	struct tbl * volatile vp = NULL;
+	char *cp;
+	struct tbl * volatile vp;
+	struct block * volatile l;
+	int i;
 
+	l = e->loc;
 	newenv(E_FUNC);
 	newblock();
-	if (ap)
-		vp = local(TREPLY, false);
-	if (!kshsetjmp(e->jbuf))
-		execute(t, XXCOM | XERROK, NULL);
-	if (vp)
-		strdupx(cp, str_val(vp), ap);
+	vp = local(TREPLY, Nee);
+	if (!(i = kshsetjmp(e->jbuf))) {
+		execute(t, XXCOM, NULL);
+		i = LRETURN;
+	}
+	strdupx(cp, str_val(vp), ap);
+	subcpybk(l);
 	quitenv(NULL);
+	/* see CFUNC case in exec.c:comexec() */
+	if (i != LRETURN)
+		unwind(i);
 
 	return (cp);
 }
+
+static void
+funsub(struct op *t)
+{
+	struct block * volatile l;
+
+	l = e->loc;
+	newenv(E_FUNC);
+	newblock();
+	if (!kshsetjmp(e->jbuf))
+		execute(t, XXCOM | XERROK, NULL);
+	subcpybk(l);
+	quitenv(NULL);
+}
--- mksh-59c.orig/exec.c
+++ mksh-59c/exec.c
@@ -3,7 +3,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022, 2023, 2024
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -24,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/exec.c,v 1.224 2020/08/27 19:52:43 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/exec.c,v 1.248 2024/07/25 00:29:04 tg Exp $");
 
 #ifndef MKSH_DEFAULT_EXECSHELL
 #define MKSH_DEFAULT_EXECSHELL	MKSH_UNIXROOT "/bin/sh"
@@ -33,11 +33,11 @@ __RCSID("$MirOS: src/bin/mksh/exec.c,v 1
 static int comexec(struct op *, struct tbl * volatile, const char **,
     int volatile, volatile int *);
 static void scriptexec(struct op *, const char **) MKSH_A_NORETURN;
-static int call_builtin(struct tbl *, const char **, const char *, bool);
+static int call_builtin(struct tbl *, const char **, const char *, Wahr);
 static int iosetup(struct ioword *, struct tbl *);
-static const char *do_selectargs(const char **, bool);
+static const char *do_selectargs(const char **, Wahr);
 static Test_op dbteste_isa(Test_env *, Test_meta);
-static const char *dbteste_getopnd(Test_env *, Test_op, bool);
+static const char *dbteste_getopnd(Test_env *, Test_op, Wahr);
 static void dbteste_error(Test_env *, int, const char *);
 /* XXX: horrible kludge to fit within the framework */
 static void plain_fmt_entry(char *, size_t, unsigned int, const void *);
@@ -68,9 +68,18 @@ execute(struct op * volatile t,
 	if (xerrok == NULL)
 		xerrok = &dummy;
 
-	if ((flags&XFORK) && !(flags&XEXEC) && t->type != TPIPE)
-		/* run in sub-process */
-		return (exchild(t, flags & ~XTIME, xerrok, -1));
+	if (flags & XFORK)
+		switch (t->type) {
+		case TPIPE:
+			break;
+		default:
+			if (flags & XEXEC)
+				break;
+			/* FALLTHROUGH */
+		case TTIME:
+			/* run in sub-process */
+			return (exchild(t, flags & ~XTIME, xerrok, -1));
+		}
 
 	newenv(E_EXEC);
 	if (trap)
@@ -99,7 +108,7 @@ execute(struct op * volatile t,
 		    /* of type "here document" (or "here string") */
 		    (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
 		    /* the variable assignment begins with a valid varname */
-		    (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
+		    (ccp = skip_wdvarname(t->vars[0], Ja)) != t->vars[0] &&
 		    /* and has no right-hand side (i.e. "varname=") */
 		    ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
 		    /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
@@ -132,9 +141,9 @@ execute(struct op * volatile t,
 	flags &= ~XTIME;
 
 	if (t->ioact != NULL || t->type == TPIPE || t->type == TCOPROC) {
-		e->savefd = alloc2(NUFILE, sizeof(short), ATEMP);
+		e->savedfd = alloc2(NUFILE, sizeof(ksh_fdsave), ATEMP);
 		/* initialise to not redirected */
-		memset(e->savefd, 0, NUFILE * sizeof(short));
+		memset(e->savedfd, 0, NUFILE * sizeof(ksh_fdsave));
 	}
 
 	/* mark for replacement later (unless TPIPE) */
@@ -151,7 +160,9 @@ execute(struct op * volatile t,
 				 */
 				if (tp && tp->type == CSHELL &&
 				    (tp->flag & SPEC_BI))
-					errorfz();
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_FILELINE | KWF_ONEMSG |
+					    KWF_NOERRNO, "redirection failure");
 				/* Deal with FERREXIT, quitenv(), etc. */
 				goto Break;
 			}
@@ -169,12 +180,12 @@ execute(struct op * volatile t,
 	case TPIPE:
 		flags |= XFORK;
 		flags &= ~XEXEC;
-		e->savefd[0] = savefd(0);
-		e->savefd[1] = savefd(1);
+		FDSAVE(0, savefd(0));
+		FDSAVE(1, savefd(1));
 		while (t->type == TPIPE) {
 			openpipe(pv);
 			/* stdout of curr */
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			/**
 			 * Let exchild() close pv[0] in child
 			 * (if this isn't done, commands like
@@ -184,15 +195,15 @@ execute(struct op * volatile t,
 			exchild(t->left, flags | XPIPEO | XCCLOSE,
 			    NULL, pv[0]);
 			/* stdin of next */
-			ksh_dup2(pv[0], 0, false);
+			ksh_dup2(pv[0], 0, Nee);
 			closepipe(pv);
 			flags |= XPIPEI;
 			t = t->right;
 		}
 		/* stdout of last */
-		restfd(1, e->savefd[1]);
+		restfd(1, SAVEDFD(e, 1));
 		/* no need to re-restore this */
-		e->savefd[1] = 0;
+		e->savedfd[1] = 0;
 		/* Let exchild() close 0 in parent, after fork, before wait */
 		i = exchild(t, flags | XPCLOSE | XPIPEST, xerrok, 0);
 		if (!(flags&XBGND) && !(flags&XXCOM))
@@ -226,29 +237,31 @@ execute(struct op * volatile t,
 #endif
 		/* Already have a (live) co-process? */
 		if (coproc.job && coproc.write >= 0)
-			errorf("coprocess already exists");
+			kerrf(KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG |
+			    KWF_NOERRNO, "coprocess already exists");
 
 		/* Can we re-use the existing co-process pipe? */
-		coproc_cleanup(true);
+		coproc_cleanup(Ja);
 
 		/* do this before opening pipes, in case these fail */
-		e->savefd[0] = savefd(0);
-		e->savefd[1] = savefd(1);
+		FDSAVE(0, savefd(0));
+		FDSAVE(1, savefd(1));
 
 		openpipe(pv);
 		if (pv[0] != 0) {
-			ksh_dup2(pv[0], 0, false);
+			ksh_dup2(pv[0], 0, Nee);
 			close(pv[0]);
 		}
 		coproc.write = pv[1];
 		coproc.job = NULL;
 
 		if (coproc.readw >= 0)
-			ksh_dup2(coproc.readw, 1, false);
+			ksh_dup2(coproc.readw, 1, Nee);
 		else {
 			openpipe(pv);
 			coproc.read = pv[0];
-			ksh_dup2(pv[1], 1, false);
+			ksh_dup2(pv[1], 1, Nee);
 			/* closed before first read */
 			coproc.readw = pv[1];
 			coproc.njobs = 0;
@@ -316,11 +329,14 @@ execute(struct op * volatile t,
 
 	case TFOR:
 	case TSELECT: {
-		volatile bool is_first = true;
+		volatile Wahr is_first = Ja;
 
-		ap = (t->vars == NULL) ? e->loc->argv + 1 :
-		    (const char **)eval((const char **)t->vars,
-		    DOBLANK | DOGLOB | DOTILDE);
+		if (t->vars == NULL)
+			/* “for i; do” */
+			ap = cpyargv(NULL, e->loc->argv, ATEMP) + 1;
+		else
+			ap = (const char **)eval((const char **)t->vars,
+			    DOBLANK | DOGLOB | DOTILDE);
 		e->type = E_LOOP;
 		while ((i = kshsetjmp(e->jbuf))) {
 			if ((e->flags&EF_BRKCONT_PASS) ||
@@ -342,7 +358,7 @@ execute(struct op * volatile t,
 		} else {
  do_TSELECT:
 			if ((ccp = do_selectargs(ap, is_first))) {
-				is_first = false;
+				is_first = Nee;
 				setstr(global(t->str), ccp, KSH_UNWIND_ERROR);
 				execute(t->left, flags & XERROK, xerrok);
 				goto do_TSELECT;
@@ -387,7 +403,7 @@ execute(struct op * volatile t,
 		for (t = t->left; t != NULL && t->type == TPAT; t = t->right) {
 			for (ap = (const char **)t->vars; *ap; ap++) {
 				if (i || ((s = evalstr(*ap, DOTILDE|DOPAT)) &&
-				    gmatchx(ccp, s, false))) {
+				    gmatchx(ccp, s, Nee))) {
 					record_match(ccp);
 					rv = execute(t->left, flags & XERROK,
 					    xerrok);
@@ -433,8 +449,11 @@ execute(struct op * volatile t,
 		/* I/O redirection cleanup to be done in child process */
 		if (!Flag(FPOSIX) && !Flag(FSH) && t->left->ioact != NULL)
 			for (iowp = t->left->ioact; *iowp != NULL; iowp++)
-				if ((*iowp)->ioflag & IODUPSELF)
-					fcntl((*iowp)->unit, F_SETFD, 0);
+				if (((*iowp)->ioflag & IODUPSELF) &&
+				    fcntl((*iowp)->unit, F_SETFD, 0) == -1)
+					kwarnf0(KWF_INTERNAL | KWF_WARNING,
+					    Tcloexec_failed, "clear",
+					    (*iowp)->unit);
 		/* try to execute */
 		{
 			union mksh_ccphack cargs;
@@ -446,7 +465,8 @@ execute(struct op * volatile t,
 		if (rv == ENOEXEC)
 			scriptexec(t, (const char **)up);
 		else
-			errorfx(126, Tf_sD_s, t->str, cstrerror(rv));
+			kerrf(KWF_VERRNO | KWF_ERR(126) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG, rv, t->str);
 	}
  Break:
 	exstat = rv & 0xFF;
@@ -483,15 +503,17 @@ comexec(struct op *t, struct tbl * volat
 	volatile int rv = 0;
 	const char *cp;
 	const char **lastp;
-	/* Must be static (XXX but why?) */
-	static struct op texec;
 	int type_flags;
-	bool resetspec;
+	Wahr resetspec;
 	int fcflags = FC_BI | FC_FUNC | FC_PATH;
 	struct block *l_expand, *l_assign;
 	int optc;
 	const char *exec_argv0 = NULL;
-	bool exec_clrenv = false;
+	Wahr exec_clrenv = Nee;
+	volatile kui old_inuse;
+	const char * volatile old_kshname;
+	volatile kby old_flags[FNFLAGS];
+	static struct op texec; /* static for use by child process */
 
 	/* snag the last argument for $_ */
 	if (Flag(FTALKING) && *(lastp = ap)) {
@@ -521,7 +543,7 @@ comexec(struct op *t, struct tbl * volat
 	 *	FOO=bar command			FOO is neither kept nor exported
 	 *	PATH=... foobar			use new PATH in foobar search
 	 */
-	resetspec = false;
+	resetspec = Nee;
 	while (tp && tp->type == CSHELL) {
 		/* undo effects of command */
 		fcflags = FC_BI | FC_FUNC | FC_PATH;
@@ -532,7 +554,9 @@ comexec(struct op *t, struct tbl * volat
 				break;
 			}
 			if ((tp = findcom(cp, FC_BI)) == NULL)
-				errorf(Tf_sD_sD_s, Tbuiltin, cp, Tnot_found);
+				kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_THREEMSG | KWF_NOERRNO, Tbuiltin, cp,
+				    Tnot_found);
 			if (tp->type == CSHELL && (tp->flag & LOW_BI))
 				break;
 			continue;
@@ -546,9 +570,9 @@ comexec(struct op *t, struct tbl * volat
 					exec_argv0 = builtin_opt.optarg;
 					break;
 				case 'c':
-					exec_clrenv = true;
+					exec_clrenv = Ja;
 					/* ensure we can actually do this */
-					resetspec = true;
+					resetspec = Ja;
 					break;
 				default:
 					rv = 2;
@@ -560,7 +584,7 @@ comexec(struct op *t, struct tbl * volat
 			if (Flag(FPOSIX))
 				fcflags = FC_PATH;
 		} else if (tp->val.f == c_command) {
-			bool saw_p = false;
+			Wahr saw_p = Nee;
 
 			/*
 			 * Ugly dealing with options in two places (here
@@ -568,7 +592,7 @@ comexec(struct op *t, struct tbl * volat
 			 */
 			ksh_getopt_reset(&builtin_opt, 0);
 			while ((optc = ksh_getopt(ap, &builtin_opt, ":p")) == 'p')
-				saw_p = true;
+				saw_p = Ja;
 			if (optc != -1)
 				/* command -vV or something */
 				break;
@@ -576,7 +600,8 @@ comexec(struct op *t, struct tbl * volat
 			fcflags = FC_BI | FC_PATH;
 			if (saw_p) {
 				if (Flag(FRESTRICTED)) {
-					warningf(true, Tf_sD_s,
+					kwarnf(KWF_PREFIX | KWF_FILELINE |
+					    KWF_TWOMSG | KWF_NOERRNO,
 					    "command -p", "restricted");
 					rv = 1;
 					goto Leave;
@@ -588,7 +613,7 @@ comexec(struct op *t, struct tbl * volat
 			 * POSIX says special builtins lose their status
 			 * if accessed using command.
 			 */
-			resetspec = true;
+			resetspec = Ja;
 			if (!ap[0]) {
 				/* ensure command with no args exits with 0 */
 				subst_exstat = 0;
@@ -633,7 +658,7 @@ comexec(struct op *t, struct tbl * volat
 	if (Flag(FEXPORT))
 		type_flags |= EXPORT;
 	if (Flag(FXTRACE))
-		change_xtrace(2, false);
+		change_xtrace(2, Nee);
 	for (i = 0; t->vars[i]; i++) {
 		/* do NOT lookup in the new var/fn block just created */
 		e->loc = l_expand;
@@ -642,7 +667,7 @@ comexec(struct op *t, struct tbl * volat
 		if (Flag(FXTRACE)) {
 			const char *ccp;
 
-			ccp = skip_varname(cp, true);
+			ccp = skip_varname(cp, Ja);
 			if (*ccp == '+')
 				++ccp;
 			if (*ccp == '=')
@@ -656,7 +681,7 @@ comexec(struct op *t, struct tbl * volat
 	}
 
 	if (Flag(FXTRACE)) {
-		change_xtrace(2, false);
+		change_xtrace(2, Nee);
 		if (ap[rv = 0]) {
  xtrace_ap_loop:
 			print_value_quoted(shl_xtrace, ap[rv]);
@@ -665,7 +690,7 @@ comexec(struct op *t, struct tbl * volat
 				goto xtrace_ap_loop;
 			}
 		}
-		change_xtrace(1, false);
+		change_xtrace(1, Nee);
 	}
 
 	if ((cp = *ap) == NULL) {
@@ -673,7 +698,8 @@ comexec(struct op *t, struct tbl * volat
 		goto Leave;
 	} else if (!tp) {
 		if (Flag(FRESTRICTED) && mksh_vdirsep(cp)) {
-			warningf(true, Tf_sD_s, cp, "restricted");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, cp, "restricted");
 			rv = 1;
 			goto Leave;
 		}
@@ -691,25 +717,22 @@ comexec(struct op *t, struct tbl * volat
 		break;
 
 	/* function call */
-	case CFUNC: {
-		volatile uint32_t old_inuse;
-		const char * volatile old_kshname;
-		volatile uint8_t old_flags[FNFLAGS];
-
+	case CFUNC:
 		if (!(tp->flag & ISSET)) {
 			struct tbl *ftp;
 
 			if (!tp->u.fpath) {
  fpath_error:
 				rv = (tp->u2.errnov == ENOENT) ? 127 : 126;
-				warningf(true, Tf_sD_s_sD_s, cp,
-				    Tcant_find, Tfile_fd,
-				    cstrerror(tp->u2.errnov));
+				kwarnf(KWF_ERR(rv) | KWF_VERRNO |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG,
+				    tp->u2.errnov, cp,
+				    "function definition file");
 				break;
 			}
 			errno = 0;
-			if (include(tp->u.fpath, 0, NULL, false) < 0 ||
-			    !(ftp = findfunc(cp, hash(cp), false)) ||
+			if (include(tp->u.fpath, NULL, Nee) < 0 ||
+			    !(ftp = findfunc(cp, hash(cp), Nee)) ||
 			    !(ftp->flag & ISSET)) {
 				rv = errno;
 				if ((ftp = findcom(cp, FC_BI)) &&
@@ -723,7 +746,9 @@ comexec(struct op *t, struct tbl * volat
 					cp = tp->u.fpath;
 					goto fpath_error;
 				}
-				warningf(true, Tf_sD_s_s, cp,
+				kwarnf0(KWF_ERR(127) |
+				    KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+				    Tf_sD_s_s, cp,
 				    "function not defined by", tp->u.fpath);
 				rv = 127;
 				break;
@@ -757,7 +782,7 @@ comexec(struct op *t, struct tbl * volat
 		for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
 			old_flags[type_flags] = shell_flags[type_flags];
 		change_xtrace((Flag(FXTRACEREC) ? Flag(FXTRACE) : 0) |
-		    ((tp->flag & TRACE) ? 1 : 0), false);
+		    ((tp->flag & TRACE) ? 1 : 0), Nee);
 		old_inuse = tp->flag & FINUSE;
 		tp->flag |= FINUSE;
 
@@ -768,13 +793,22 @@ comexec(struct op *t, struct tbl * volat
 		}
 
 		kshname = old_kshname;
-		change_xtrace(old_flags[(int)FXTRACE], false);
+		change_xtrace(old_flags[(int)FXTRACE], Nee);
 #ifndef MKSH_LEGACY_MODE
 		if (tp->flag & FKSH) {
 			/* Korn style functions restore Flags on return */
 			old_flags[(int)FXTRACE] = Flag(FXTRACE);
+			/* some must not be restored / need special handling */
 			for (type_flags = 0; type_flags < FNFLAGS; ++type_flags)
-				shell_flags[type_flags] = old_flags[type_flags];
+#ifndef MKSH_UNEMPLOYED
+				if (type_flags == FMONITOR)
+					change_flag(type_flags, OF_INTERNAL,
+					    old_flags[type_flags]);
+				else
+#endif
+				  if (type_flags != FPRIVILEGED)
+					shell_flags[type_flags] =
+					    old_flags[type_flags];
 		}
 #endif
 		tp->flag = (tp->flag & ~FINUSE) | old_inuse;
@@ -805,10 +839,10 @@ comexec(struct op *t, struct tbl * volat
 			/* NOTREACHED */
 		default:
 			quitenv(NULL);
-			internal_errorf(Tunexpected_type, Tunwind, Tfunction, i);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    Tunexpected_type, Tunwind, Tfunction, i);
 		}
 		break;
-	}
 
 	/* executable command */
 	case CEXEC:
@@ -817,12 +851,14 @@ comexec(struct op *t, struct tbl * volat
 		if (!(tp->flag&ISSET)) {
 			if (tp->u2.errnov == ENOENT) {
 				rv = 127;
-				warningf(true, Tf_sD_s_s, cp,
-				    "inaccessible or", Tnot_found);
+				kwarnf(KWF_ERR(127) |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, cp, Tinacc_not_found);
 			} else {
 				rv = 126;
-				warningf(true, Tf_sD_sD_s, cp, "can't execute",
-				    cstrerror(tp->u2.errnov));
+				kwarnf(KWF_ERR(126) | KWF_VERRNO |
+				    KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG,
+				    tp->u2.errnov, cp, "can't execute");
 			}
 			break;
 		}
@@ -844,14 +880,6 @@ comexec(struct op *t, struct tbl * volat
 			if (exec_argv0)
 				texec.args[0] = exec_argv0;
 			j_exit();
-			if (!(flags & XBGND)
-#ifndef MKSH_UNEMPLOYED
-			    || Flag(FMONITOR)
-#endif
-			    ) {
-				setexecsig(&sigtraps[SIGINT], SS_RESTORE_ORIG);
-				setexecsig(&sigtraps[SIGQUIT], SS_RESTORE_ORIG);
-			}
 		}
 
 		rv = exchild(&texec, flags, xerrok, -1);
@@ -886,14 +914,9 @@ scriptexec(struct op *tp, const char **a
 #ifndef MKSH_SMALL
 	if ((fd = binopen2(tp->str, O_RDONLY | O_MAYEXEC)) >= 0) {
 		unsigned char *cp;
-#ifndef MKSH_EBCDIC
 		unsigned short m;
-#endif
 		ssize_t n;
 
-#if defined(__OS2__) && defined(MKSH_WITH_TEXTMODE)
-		setmode(fd, O_TEXT);
-#endif
 		/* read first couple of octets from file */
 		n = read(fd, buf, sizeof(buf) - 1);
 		close(fd);
@@ -903,31 +926,30 @@ scriptexec(struct op *tp, const char **a
 		/* terminate buffer */
 		buf[n] = '\0';
 
-		/* skip UTF-8 Byte Order Mark, if present */
-		cp = buf + (n = ((buf[0] == 0xEF) && (buf[1] == 0xBB) &&
-		    (buf[2] == 0xBF)) ? 3 : 0);
-
+		/* scan for shebang magic */
+		if (ord(buf[0]) == ORD('#') && ord(buf[1]) == ORD('!'))
+			n = 2;
+#ifdef __OS2__
+		else if (n > 8 && !strncmp(buf, Textproc, 7) &&
+		    ctype(buf[7], C_BLANK))
+			n = 8;
+#endif
+		else
+			goto noshebang;
 		/* scan for newline or NUL (end of buffer) */
+		cp = buf + n;
 		while (!ctype(*cp, C_NL | C_NUL))
 			++cp;
 		/* if the shebang line is longer than MAXINTERP, bail out */
 		if (!*cp)
-			goto noshebang;
+			kerrf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: shebang too long",
+			    tp->str);
 		/* replace newline by NUL */
 		*cp = '\0';
 
-		/* restore start of shebang position (buf+0 or buf+3) */
+		/* restore start of shebang position */
 		cp = buf + n;
-		/* bail out if no shebang magic found */
-		if (cp[0] == '#' && cp[1] == '!')
-			cp += 2;
-#ifdef __OS2__
-		else if (!strncmp(cp, Textproc, 7) &&
-		    ctype(cp[7], C_BLANK))
-			cp += 8;
-#endif
-		else
-			goto noshebang;
 		/* skip whitespace before shell name */
 		while (ctype(*cp, C_BLANK))
 			++cp;
@@ -966,11 +988,12 @@ scriptexec(struct op *tp, const char **a
 #endif
 		goto nomagic;
  noshebang:
-#ifndef MKSH_EBCDIC
-		m = buf[0] << 8 | buf[1];
-		if (m == 0x7F45 && buf[2] == 'L' && buf[3] == 'F')
-			errorf("%s: not executable: %d-bit ELF file", tp->str,
-			    32 * buf[4]);
+		m = ord(rtt2asc(buf[0])) << 8 | ord(rtt2asc(buf[1]));
+		if (m == 0x7F45 && ord(buf[2]) == ORD('L') &&
+		    ord(buf[3]) == ORD('F'))
+			kerrf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: %u-bit ELF file",
+			    tp->str, 32U * buf[4]);
 		if ((m == /* OMAGIC */ 0407) ||
 		    (m == /* NMAGIC */ 0410) ||
 		    (m == /* ZMAGIC */ 0413) ||
@@ -978,14 +1001,25 @@ scriptexec(struct op *tp, const char **a
 		    (m == /* ECOFF_I386 */ 0x4C01) ||
 		    (m == /* ECOFF_M68K */ 0x0150 || m == 0x5001) ||
 		    (m == /* ECOFF_SH */   0x0500 || m == 0x0005) ||
-		    (m == /* bzip */ 0x425A) || (m == /* "MZ" */ 0x4D5A) ||
+		    (m == /* "MZ" */ 0x4D5A && !( /* cosmo libc APE */
+		     ord(buf[2]) == ORD('q') && ord(buf[3]) == ORD('F') &&
+		     ord(buf[4]) == ORD('p') && ord(buf[5]) == ORD('D') &&
+		     ord(buf[6]) == ORD('=') && ord(buf[7]) == ORD('\''))) ||
 		    (m == /* "NE" */ 0x4E45) || (m == /* "LX" */ 0x4C58) ||
 		    (m == /* ksh93 */ 0x0B13) || (m == /* LZIP */ 0x4C5A) ||
-		    (m == /* xz */ 0xFD37 && buf[2] == 'z' && buf[3] == 'X' &&
-		    buf[4] == 'Z') || (m == /* 7zip */ 0x377A) ||
-		    (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D))
-			errorf("%s: not executable: magic %04X", tp->str, m);
-#endif
+		    (m == /* xz */ 0xFD37 && ord(buf[2]) == ORD('z') &&
+		     ord(buf[3]) == ORD('X') && ord(buf[4]) == ORD('Z')) ||
+		    (m == /* Zstd */ 0x28B5 && ord(rtt2asc(buf[2])) == 0x2FU &&
+		     ord(rtt2asc(buf[3])) == 0xFDU) ||
+		    (m == /* bzip */ 0x425A) || (m == /* 7zip */ 0x377A) ||
+		    (m == /* gzip */ 0x1F8B) || (m == /* .Z */ 0x1F9D) ||
+		    (m == /* UTF-8 BOM */ 0xEFBB &&
+		     ord(rtt2asc(buf[2])) == 0xBFU) ||
+		    (m == /* UCS-4, may also be general binary */ 0x0000) ||
+		    (m == /* UCS-2LE */ 0xFFFE) || (m == /* UCS-2BE */ 0xFEFF))
+			kerrf0(KWF_ERR(126) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_NOERRNO, "%s: not executable: magic %04X",
+			    tp->str, m);
 #ifdef __OS2__
 		cp = _getext(tp->str);
 		if (cp && (!stricmp(cp, ".cmd") || !stricmp(cp, ".bat"))) {
@@ -1010,14 +1044,14 @@ scriptexec(struct op *tp, const char **a
 	execve(args.rw[0], args.rw, cap.rw);
 
 	/* report both the program that was run and the bogus interpreter */
-	errorf(Tf_sD_sD_s, tp->str, sh, cstrerror(errno));
+	kerrf(KWF_ERR(127) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG, tp->str, sh);
 }
 
 /* actual 'builtin' built-in utility call is handled in comexec() */
 int
 c_builtin(const char **wp)
 {
-	return (call_builtin(get_builtin(*wp), wp, Tbuiltin, false));
+	return (call_builtin(get_builtin(*wp), wp, Tbuiltin, Nee));
 }
 
 struct tbl *
@@ -1031,7 +1065,7 @@ get_builtin(const char *s)
  * is created if none is found.
  */
 struct tbl *
-findfunc(const char *name, uint32_t h, bool create)
+findfunc(const char *name, k32 h, Wahr create)
 {
 	struct block *l;
 	struct tbl *tp = NULL;
@@ -1058,17 +1092,17 @@ findfunc(const char *name, uint32_t h, b
 int
 define(const char *name, struct op *t)
 {
-	uint32_t nhash;
+	k32 nhash;
 	struct tbl *tp;
-	bool was_set = false;
+	Wahr was_set = Nee;
 
 	nhash = hash(name);
 
 	while (/* CONSTCOND */ 1) {
-		tp = findfunc(name, nhash, true);
+		tp = findfunc(name, nhash, Ja);
 
 		if (tp->flag & ISSET)
-			was_set = true;
+			was_set = Ja;
 		/*
 		 * If this function is currently being executed, we zap
 		 * this table entry so findfunc() won't see it
@@ -1108,7 +1142,7 @@ const char *
 builtin(const char *name, int (*func) (const char **))
 {
 	struct tbl *tp;
-	uint32_t flag = DEFINED;
+	kui flag = DEFINED;
 
 	/* see if any flags should be set for this builtin */
  flags_loop:
@@ -1165,8 +1199,8 @@ builtin(const char *name, int (*func) (c
 struct tbl *
 findcom(const char *name, int flags)
 {
-	static struct tbl temp;
-	uint32_t h = hash(name);
+	static union tbl_static temp;
+	k32 h = hash(name);
 	struct tbl *tp = NULL, *tbi;
 	/* insert if not found */
 	unsigned char insert = Flag(FTRACKALL);
@@ -1188,7 +1222,7 @@ findcom(const char *name, int flags)
 	if ((flags & FC_SPECBI) && tbi && (tbi->flag & SPEC_BI))
 		tp = tbi;
 	if (!tp && (flags & FC_FUNC)) {
-		tp = findfunc(name, h, false);
+		tp = findfunc(name, h, Nee);
 		if (tp && !(tp->flag & ISSET)) {
 			if ((fpath = str_val(global(TFPATH))) == null) {
 				tp->u.fpath = NULL;
@@ -1220,7 +1254,7 @@ findcom(const char *name, int flags)
 				tp = ktenter(&taliases, name, h);
 				tp->type = CTALIAS;
 			} else {
-				tp = &temp;
+				tp = (struct tbl *)&temp;
 				tp->type = CEXEC;
 			}
 			/* make ~ISSET */
@@ -1244,7 +1278,7 @@ findcom(const char *name, int flags)
 			 * even if the command hasn't been set up as an
 			 * autoloaded function (ie, no typeset -uf).
 			 */
-			tp = &temp;
+			tp = (struct tbl *)&temp;
 			tp->type = CFUNC;
 			/* make ~ISSET */
 			tp->flag = DEFINED;
@@ -1259,7 +1293,7 @@ findcom(const char *name, int flags)
  * (just relative or all?)
  */
 void
-flushcom(bool all)
+flushcom(Wahr all)
 {
 	struct tbl *tp;
 	struct tstate ts;
@@ -1376,27 +1410,32 @@ search_path(const char *name, const char
 }
 
 static int
-call_builtin(struct tbl *tp, const char **wp, const char *where, bool resetspec)
+call_builtin(struct tbl *tp, const char **wp, const char *where, Wahr resetspec)
 {
 	int rv;
 
 	if (!tp)
-		internal_errorf(Tf_sD_s, where, wp[0]);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    where, wp[0]);
 	builtin_argv0 = wp[0];
-	builtin_spec = tobool(!resetspec && (tp->flag & SPEC_BI));
+	builtin_spec = isWahr(!resetspec && (tp->flag & SPEC_BI));
 	shf_reopen(1, SHF_WR, shl_stdout);
-	shl_stdout_ok = true;
+	shl_stdout_ok = Ja;
 	ksh_getopt_reset(&builtin_opt, GF_ERROR);
 	rv = (*tp->val.f)(wp);
-	shf_flush(shl_stdout);
-	shl_stdout_ok = false;
+	if (shf_flush(shl_stdout) < 0) {
+		bi_errorf(Tf_sD_s, Twrite, cstrerror(errno));
+		if (rv == 0)
+			rv = 1;
+	}
+	shl_stdout_ok = Nee;
 	builtin_argv0 = NULL;
-	builtin_spec = false;
+	builtin_spec = Nee;
 	return (rv);
 }
 
 /*
- * set up redirection, saving old fds in e->savefd
+ * set up redirection, saving old fds in e->savedfd
  */
 static int
 iosetup(struct ioword *iop, struct tbl *tp)
@@ -1404,7 +1443,7 @@ iosetup(struct ioword *iop, struct tbl *
 	int u = -1;
 	char *cp = iop->ioname;
 	int iotype = iop->ioflag & IOTYPE;
-	bool do_open = true, do_close = false, do_fstat = false;
+	Wahr do_open = Ja, do_close = Nee, do_fstat = Nee;
 	int flags = 0;
 	struct ioword iotmp;
 	struct stat statb;
@@ -1418,9 +1457,9 @@ iosetup(struct ioword *iop, struct tbl *
 	iotmp.ioflag |= IONAMEXP;
 
 	if (Flag(FXTRACE)) {
-		change_xtrace(2, false);
+		change_xtrace(2, Nee);
 		fptreef(shl_xtrace, 0, Tft_R, &iotmp);
-		change_xtrace(1, false);
+		change_xtrace(1, Nee);
 	}
 
 	switch (iotype) {
@@ -1448,7 +1487,7 @@ iosetup(struct ioword *iop, struct tbl *
 				 */
 				flags = O_WRONLY;
 				/* but check again after opening */
-				do_fstat = true;
+				do_fstat = Ja;
 			}
 		} else {
 			/* >|file or set +C */
@@ -1461,7 +1500,7 @@ iosetup(struct ioword *iop, struct tbl *
 		break;
 
 	case IOHERE:
-		do_open = false;
+		do_open = Nee;
 		/* herein() returns -2 if error has been printed */
 		u = herein(iop, NULL);
 		/* cp may have wrong name */
@@ -1470,18 +1509,19 @@ iosetup(struct ioword *iop, struct tbl *
 	case IODUP: {
 		const char *emsg;
 
-		do_open = false;
+		do_open = Nee;
 		if (ksh_isdash(cp)) {
 			/* prevent error return below */
 			u = 1009;
-			do_close = true;
+			do_close = Ja;
 		} else if ((u = check_fd(cp,
 		    X_OK | ((iop->ioflag & IORDUP) ? R_OK : W_OK),
 		    &emsg)) < 0) {
 			char *sp;
 
-			warningf(true, Tf_sD_s,
-			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)), emsg);
+			sp = snptreef(NULL, 32, Tft_R, &iotmp);
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, sp, emsg);
 			afree(sp, ATEMP);
 			return (-1);
 		}
@@ -1496,7 +1536,8 @@ iosetup(struct ioword *iop, struct tbl *
 
 	if (do_open) {
 		if (Flag(FRESTRICTED) && (flags & O_CREAT)) {
-			warningf(true, Tf_sD_s, cp, "restricted");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, cp, "restricted");
 			return (-1);
 		}
 		u = binopen3(cp, flags, 0666);
@@ -1513,44 +1554,39 @@ iosetup(struct ioword *iop, struct tbl *
 	if (u < 0) {
 		/* herein() may already have printed message */
 		if (u == -1) {
-			u = errno;
-			warningf(true, Tf_cant_ss_s,
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG, cp,
+			    (iotype == IOREAD || iotype == IOHERE) ? Topen :
 #if 0
 			    /* can't happen */
 			    iotype == IODUP ? "dup" :
 #endif
-			    (iotype == IOREAD || iotype == IOHERE) ?
-			    Topen : Tcreate, cp, cstrerror(u));
+			    Tcreate);
 		}
 		return (-1);
 	}
-	/* Do not save if it has already been redirected (i.e. "cat >x >y"). */
-	if (e->savefd[iop->unit] == 0) {
-		/* If these are the same, it means unit was previously closed */
-		if (u == (int)iop->unit)
-			e->savefd[iop->unit] = -1;
-		else
-			/*
-			 * c_exec() assumes e->savefd[fd] set for any
-			 * redirections. Ask savefd() not to close iop->unit;
-			 * this allows error messages to be seen if iop->unit
-			 * is 2; also means we can't lose the fd (eg, both
-			 * dup2 below and dup2 in restfd() failing).
-			 */
-			e->savefd[iop->unit] = savefd(iop->unit);
-	}
+	/* only save if it has not yet been redirected (e.g. by "cat >x >y") */
+	if (FDSVNUM(e, iop->unit) == 0U) {
+		/* c_exec() assumes e->savedfd[fd] set for any redirection */
+		FDSAVE(iop->unit, u == (int)iop->unit ?
+		    /* previously closed (exec >&-; ls >x; print e) */ -1 :
+		    savefd(iop->unit));
+	} else
+		/* clear previous fd-was-closed flag */
+		e->savedfd[iop->unit] &= FDNUMMASK;
 
-	if (do_close)
+	if (do_close) {
 		close(iop->unit);
-	else if (u != (int)iop->unit) {
-		if (ksh_dup2(u, iop->unit, true) < 0) {
+		e->savedfd[iop->unit] |= FDICLMASK;
+	} else if (u != (int)iop->unit) {
+		if (ksh_dup2(u, iop->unit, Ja) < 0) {
 			int eno;
 			char *sp;
 
 			eno = errno;
-			warningf(true, Tf_s_sD_s, Tredirection_dup,
-			    (sp = snptreef(NULL, 32, Tft_R, &iotmp)),
-			    cstrerror(eno));
+			sp = snptreef(NULL, 32, Tft_s_R, Tredirection_dup,
+			    &iotmp);
+			kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_FILELINE |
+			    KWF_ONEMSG, eno, sp);
 			afree(sp, ATEMP);
 			if (iotype != IODUP)
 				close(u);
@@ -1604,7 +1640,8 @@ hereinval(struct ioword *iop, int sub, c
 		s->start = s->str = ccp;
 		source = s;
 		if (yylex(sub) != LWORD)
-			internal_errorf("herein: yylex");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+			    "herein: yylex");
 		source = osource;
 		ccp = evalstr(yylval.cp, DOSCALAR | DOHEREDOC);
 	}
@@ -1639,9 +1676,8 @@ herein(struct ioword *iop, char **resbuf
 	 */
 	h = maketemp(ATEMP, TT_HEREDOC_EXP, &e->temps);
 	if (!(shf = h->shf) || (fd = binopen3(h->tffn, O_RDONLY, 0)) < 0) {
-		i = errno;
-		warningf(true, Tf_temp,
-		    !shf ? Tcreate : Topen, h->tffn, cstrerror(i));
+		kwarnf0(KWF_PREFIX | KWF_FILELINE, Tf_temp,
+		    !shf ? Tcreate : Topen, h->tffn);
 		if (shf)
 			shf_close(shf);
 		/* special to iosetup(): don't print error */
@@ -1657,8 +1693,8 @@ herein(struct ioword *iop, char **resbuf
 	if (shf_close(shf) == -1) {
 		i = errno;
 		close(fd);
-		warningf(true, Tf_temp,
-		    Twrite, h->tffn, cstrerror(i));
+		kwarnf1(KWF_VERRNO | KWF_PREFIX | KWF_FILELINE, i,
+		    Tf_temp, Twrite, h->tffn);
 		/* special to iosetup(): don't print error */
 		return (-2);
 	}
@@ -1671,7 +1707,7 @@ herein(struct ioword *iop, char **resbuf
  *	print the args in column form - assuming that we can
  */
 static const char *
-do_selectargs(const char **ap, bool print_menu)
+do_selectargs(const char **ap, Wahr print_menu)
 {
 	static const char *read_args[] = {
 		Tread, Tdr, TREPLY, NULL
@@ -1691,13 +1727,12 @@ do_selectargs(const char **ap, bool prin
 		if (print_menu || !*str_val(global(TREPLY)))
 			pr_menu(ap);
 		shellf(Tf_s, str_val(global("PS3")));
-		if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect,
-		    false))
+		if (call_builtin(findcom(Tread, FC_BI), read_args, Tselect, Nee))
 			return (NULL);
 		if (*(s = str_val(global(TREPLY))))
 			return ((getn(s, &i) && i >= 1 && i <= argct) ?
 			    ap[i - 1] : null);
-		print_menu = true;
+		print_menu = Ja;
 	}
 }
 
@@ -1758,7 +1793,7 @@ pr_menu(const char * const *ap)
 	smi.args = ap;
 	co.shf = shl_out;
 	co.linesep = '\n';
-	co.prefcol = co.do_last = true;
+	co.prefcol = co.do_last = Ja;
 	print_columns(&co, n, select_fmt_entry, (void *)&smi,
 	    smi.num_width + 2 + aocts, smi.num_width + 2 + acols);
 }
@@ -1802,7 +1837,7 @@ static Test_op
 dbteste_isa(Test_env *te, Test_meta meta)
 {
 	Test_op ret = TO_NONOP;
-	bool uqword;
+	Wahr uqword;
 	const char *p;
 
 	if (!*te->pos.wp)
@@ -1840,7 +1875,7 @@ dbteste_isa(Test_env *te, Test_meta meta
 }
 
 static const char *
-dbteste_getopnd(Test_env *te, Test_op op, bool do_eval)
+dbteste_getopnd(Test_env *te, Test_op op, Wahr do_eval)
 {
 	const char *s = *te->pos.wp;
 	int flags = DOTILDE | DOSCALAR;
@@ -1866,5 +1901,33 @@ static void
 dbteste_error(Test_env *te, int offset, const char *msg)
 {
 	te->flags |= TEF_ERROR;
-	internal_warningf("dbteste_error: %s (offset %d)", msg, offset);
+	kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+	    "dbteste_error: %s (offset %d)", msg, offset);
+}
+
+const char **
+cpyargv(int *i, const char **src, Area *ap)
+{
+	size_t n;
+	const char **wp, **dst;
+
+	wp = src - 1;
+	while (*++wp != NULL)
+		/* nothing */;
+	n = wp - src;
+	if (n < 1 || notoktoadd(n, 1) ||
+	    notok2add((size_t)INT_MAX, n, 1))
+		kerrf(KWF_VERRNO | KWF_INTERNAL | KWF_ERR(0xFF) |
+		    KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    EOVERFLOW, "cpyargv");
+	if (i)
+		*i = n - /* kshname */ 1U;
+	dst = alloc2(n + /* NULL */ 1U, sizeof(const char *), ap);
+
+	wp = dst;
+	*wp++ = *src++;
+	while (--n)
+		strdupx(*wp++, *src++, ap);
+	*wp = NULL;
+	return (dst);
 }
--- mksh-59c.orig/expr.c
+++ mksh-59c/expr.c
@@ -2,7 +2,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2014, 2016, 2017, 2018, 2019
+ *		 2011, 2012, 2013, 2014, 2016, 2017, 2018, 2019,
+ *		 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -21,9 +22,10 @@
  * of said person's immediate fault when using the work as intended.
  */
 
+#define MKSH_DO_MBI_CTAS
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/expr.c,v 1.108 2020/06/20 02:27:50 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/expr.c,v 1.127 2023/10/23 20:59:39 tg Exp $");
 
 #define EXPRTOK_DEFNS
 #include "exprtok.h"
@@ -56,12 +58,12 @@ static const char opname[][4] = {
 #include "exprtok.h"
 };
 
-static const uint8_t oplen[] = {
+static const kby oplen[] = {
 #define EXPRTOK_LEN
 #include "exprtok.h"
 };
 
-static const uint8_t opprec[] = {
+static const kby opprec[] = {
 #define EXPRTOK_PREC
 #include "exprtok.h"
 };
@@ -78,11 +80,11 @@ typedef struct expr_state {
 	/* token from token() */
 	enum token tok;
 	/* don't do assignments (for ?:, &&, ||) */
-	uint8_t noassign;
+	kby noassign;
 	/* evaluating an $(()) expression? */
-	bool arith;
+	Wahr arith;
 	/* unsigned arithmetic calculation */
-	bool natural;
+	Wahr natural;
 } Expr_state;
 
 enum error_type {
@@ -94,7 +96,7 @@ static void evalerr(Expr_state *, enum e
     MKSH_A_NORETURN;
 static struct tbl *evalexpr(Expr_state *, unsigned int);
 static void exprtoken(Expr_state *);
-static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, bool);
+static struct tbl *do_ppmm(Expr_state *, enum token, struct tbl *, Wahr);
 static void assign_check(Expr_state *, enum token, struct tbl *);
 static struct tbl *intvar(Expr_state *, struct tbl *);
 
@@ -102,15 +104,15 @@ static struct tbl *intvar(Expr_state *,
  * parse and evaluate expression
  */
 int
-evaluate(const char *expr, mksh_ari_t *rval, int error_ok, bool arith)
+evaluate(const char *expr, mksh_ari_t *rval, int error_ok, Wahr arith)
 {
-	struct tbl v;
+	union tbl_static v;
 	int ret;
 
-	v.flag = DEFINED | INTEGER;
-	v.type = 0;
-	ret = v_evaluate(&v, expr, error_ok, arith);
-	*rval = v.val.i;
+	v.tbl.flag = DEFINED | INTEGER;
+	v.tbl.type = 0;
+	ret = v_evaluate((struct tbl *)&v, expr, error_ok, arith);
+	*rval = v.tbl.val.i;
 	return (ret);
 }
 
@@ -119,7 +121,7 @@ evaluate(const char *expr, mksh_ari_t *r
  */
 int
 v_evaluate(struct tbl *vp, const char *expr, volatile int error_ok,
-    bool arith)
+    Wahr arith)
 {
 	struct tbl *v;
 	Expr_state curstate;
@@ -141,7 +143,11 @@ v_evaluate(struct tbl *vp, const char *e
 		if (i == LAEXPR) {
 			if (error_ok == KSH_RETURN_ERROR)
 				return (0);
-			errorfz();
+			/* error already printed */
+			/* (cf. syn.c for why) */
+			exstat = 1;
+			shl_stdout_ok = Nee;
+			i = LERROR;
 		}
 		unwind(i);
 		/* NOTREACHED */
@@ -162,7 +168,7 @@ v_evaluate(struct tbl *vp, const char *e
 	if (vp->flag & INTEGER)
 		setint_v(vp, v, es->arith);
 	else
-		/* can fail if readonly */
+		/* can fail if read-only */
 		setstr(vp, str_val(v), error_ok);
 
 	quitenv(NULL);
@@ -176,7 +182,7 @@ evalerr(Expr_state *es, enum error_type
 	char tbuf[2];
 	const char *s;
 
-	es->arith = false;
+	es->arith = Nee;
 	switch (type) {
 	case ET_UNEXPECTED:
 		switch (es->tok) {
@@ -197,33 +203,41 @@ evalerr(Expr_state *es, enum error_type
 		default:
 			s = opname[(int)es->tok];
 		}
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    Tunexpected, s);
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_qs, es->expression, Tunexpected, s);
 		break;
 
 	case ET_BADLIT:
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    Tbadnum, str);
+		if (!strcmp(es->expression, str))
+			kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG, es->expression, Tbadnum);
+		else
+			kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+			    Tf_sD_s_qs, es->expression, Tbadnum, str);
 		break;
 
 	case ET_RECURSIVE:
-		warningf(true, Tf_sD_s_qs, es->expression,
-		    "expression recurses on parameter", str);
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_qs,
+		    es->expression, "expression recurses on parameter", str);
 		break;
 
 	case ET_LVALUE:
-		warningf(true, Tf_sD_s_s,
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_s,
 		    es->expression, str, "requires lvalue");
 		break;
 
 	case ET_RDONLY:
-		warningf(true, Tf_sD_s_s,
+		kwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    Tf_sD_s_s,
 		    es->expression, str, "applied to read-only variable");
 		break;
 
 	default: /* keep gcc happy */
 	case ET_STR:
-		warningf(true, Tf_sD_s, es->expression, str);
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO |
+		    KWF_TWOMSG, es->expression, str);
 		break;
 	}
 	unwind(LAEXPR);
@@ -231,7 +245,7 @@ evalerr(Expr_state *es, enum error_type
 
 /* do a ++ or -- operation */
 static struct tbl *
-do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, bool is_prefix)
+do_ppmm(Expr_state *es, enum token op, struct tbl *vasn, Wahr is_prefix)
 {
 	struct tbl *vl;
 	mksh_uari_t oval;
@@ -262,7 +276,7 @@ evalexpr(Expr_state *es, unsigned int pr
 {
 	struct tbl *vl, *vr = NULL, *vasn;
 	enum token op;
-	mksh_uari_t res = 0, t1, t2, t3;
+	mksh_uari_t res = 0;
 
 	if (prec == P_PRIMARY) {
 		switch ((int)(op = es->tok)) {
@@ -299,7 +313,7 @@ evalexpr(Expr_state *es, unsigned int pr
 		case O_PLUSPLUS:
 		case O_MINUSMINUS:
 			exprtoken(es);
-			vl = do_ppmm(es, op, es->val, true);
+			vl = do_ppmm(es, op, es->val, Ja);
 			exprtoken(es);
 			break;
 
@@ -315,7 +329,7 @@ evalexpr(Expr_state *es, unsigned int pr
 		}
 
 		if (es->tok == O_PLUSPLUS || es->tok == O_MINUSMINUS) {
-			vl = do_ppmm(es, es->tok, vl, false);
+			vl = do_ppmm(es, es->tok, vl, Nee);
 			exprtoken(es);
 		}
 
@@ -344,7 +358,7 @@ evalexpr(Expr_state *es, unsigned int pr
 				assign_check(es, op, vasn);
 			vr = intvar(es, evalexpr(es, P_ASSIGN));
 		} else if (op == O_TERN) {
-			bool ev = vl->val.u != 0;
+			Wahr ev = vl->val.u != 0;
 
 			if (!ev)
 				es->noassign++;
@@ -365,118 +379,91 @@ evalexpr(Expr_state *es, unsigned int pr
 		} else if (op != O_LAND && op != O_LOR)
 			vr = intvar(es, evalexpr(es, prec - 1));
 
-		/* common ops setup */
+		/* op calculation */
+#ifndef MKSH_LEGACY_MODE
+#define ariop(op)	(vl->val.u op vr->val.u)
+#define cmpop(op)	(es->natural ?			\
+	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
+	(mksh_uari_t)mbiKcmp(mksh_uari_t, KUA_HM,	\
+	    vl->val.u, op, vr->val.u))
+#else
+#define ariop(op)	(es->natural ?			\
+	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
+	(mksh_uari_t)(vl->val.i op vr->val.i))
+#define cmpop(op)	ariop(op)
+#endif
 		switch ((int)op) {
+		case O_PLUS:
+		case O_PLUSASN:
+			res = ariop(+);
+			break;
+		case O_MINUS:
+		case O_MINUSASN:
+			res = ariop(-);
+			break;
+		case O_TIMES:
+		case O_TIMESASN:
+			res = ariop(*);
+			break;
 		case O_DIV:
 		case O_DIVASN:
-		case O_MOD:
-		case O_MODASN:
-			if (vr->val.u == 0) {
+			if (vr->val.i == 0) {
 				if (!es->noassign)
 					evalerr(es, ET_STR, "zero divisor");
-				vr->val.u = 1;
+				res = vl->val.u; /* dummy value, could be 1 */
+				break;
 			}
-			/* calculate the absolute values */
-			t1 = vl->val.i < 0 ? -vl->val.u : vl->val.u;
-			t2 = vr->val.i < 0 ? -vr->val.u : vr->val.u;
-			break;
 #ifndef MKSH_LEGACY_MODE
-		case O_LSHIFT:
-		case O_LSHIFTASN:
-		case O_RSHIFT:
-		case O_RSHIFTASN:
-		case O_ROL:
-		case O_ROLASN:
-		case O_ROR:
-		case O_RORASN:
-			t1 = vl->val.u;
-			t2 = vr->val.u & 31;
-			break;
+			if (!es->natural)
+				res = mbiKdiv(mksh_uari_t, KUA_HM,
+				    vl->val.u, vr->val.u);
+			else
 #endif
-		case O_LAND:
-		case O_LOR:
-			t1 = vl->val.u;
-			t2 = 0;	/* gcc */
-			break;
-		default:
-			t1 = vl->val.u;
-			t2 = vr->val.u;
-			break;
-		}
-
-#define cmpop(op)	(es->natural ?			\
-	(mksh_uari_t)(vl->val.u op vr->val.u) :		\
-	(mksh_uari_t)(vl->val.i op vr->val.i)		\
-)
-
-		/* op calculation */
-		switch ((int)op) {
-		case O_TIMES:
-		case O_TIMESASN:
-			res = t1 * t2;
+				res = ariop(/);
 			break;
 		case O_MOD:
 		case O_MODASN:
-			if (es->natural) {
-				res = vl->val.u % vr->val.u;
-				break;
-			}
-			goto signed_division;
-		case O_DIV:
-		case O_DIVASN:
-			if (es->natural) {
-				res = vl->val.u / vr->val.u;
+			if (vr->val.i == 0) {
+				if (!es->noassign)
+					evalerr(es, ET_STR, "zero divisor");
+				res = vl->val.u; /* dummy value, could be 1 */
 				break;
 			}
- signed_division:
-			/*
-			 * a / b = abs(a) / abs(b) * sgn((u)a^(u)b)
-			 */
-			t3 = t1 / t2;
 #ifndef MKSH_LEGACY_MODE
-			res = ((vl->val.u ^ vr->val.u) & 0x80000000) ? -t3 : t3;
-#else
-			res = ((t1 == vl->val.u ? 0 : 1) ^
-			    (t2 == vr->val.u ? 0 : 1)) ? -t3 : t3;
+			if (!es->natural)
+				res = mbiKrem(mksh_uari_t, KUA_HM,
+				    vl->val.u, vr->val.u);
+			else
 #endif
-			if (op == O_MOD || op == O_MODASN) {
-				/*
-				 * primitive modulo, to get the sign of
-				 * the result correct:
-				 * (a % b) = a - ((a / b) * b)
-				 * the subtraction and multiplication
-				 * are, amazingly enough, sign ignorant
-				 */
-				res = vl->val.u - (res * vr->val.u);
-			}
-			break;
-		case O_PLUS:
-		case O_PLUSASN:
-			res = t1 + t2;
-			break;
-		case O_MINUS:
-		case O_MINUSASN:
-			res = t1 - t2;
+				res = ariop(%);
 			break;
 #ifndef MKSH_LEGACY_MODE
 		case O_ROL:
 		case O_ROLASN:
-			res = (t1 << t2) | (t1 >> (32 - t2));
+			res = mbiKrol(mksh_uari_t, vl->val.u, vr->val.u);
 			break;
 		case O_ROR:
 		case O_RORASN:
-			res = (t1 >> t2) | (t1 << (32 - t2));
+			res = mbiKror(mksh_uari_t, vl->val.u, vr->val.u);
 			break;
 #endif
 		case O_LSHIFT:
 		case O_LSHIFTASN:
-			res = t1 << t2;
+#ifndef MKSH_LEGACY_MODE
+			res = mbiKshl(mksh_uari_t, vl->val.u, vr->val.u);
+#else
+			res = ariop(<<);
+#endif
 			break;
 		case O_RSHIFT:
 		case O_RSHIFTASN:
-			res = es->natural || vl->val.i >= 0 ?
-			    t1 >> t2 :
-			    ~(~t1 >> t2);
+#ifndef MKSH_LEGACY_MODE
+			res = mbiKsar(mksh_uari_t,
+			    !es->natural && vl->val.i < 0,
+			    vl->val.u, vr->val.u);
+#else
+			res = ariop(>>);
+#endif
 			break;
 		case O_LT:
 			res = cmpop(<);
@@ -491,47 +478,47 @@ evalexpr(Expr_state *es, unsigned int pr
 			res = cmpop(>=);
 			break;
 		case O_EQ:
-			res = t1 == t2;
+			res = ariop(==);
 			break;
 		case O_NE:
-			res = t1 != t2;
+			res = ariop(!=);
 			break;
 		case O_BAND:
 		case O_BANDASN:
-			res = t1 & t2;
+			res = ariop(&);
 			break;
 		case O_BXOR:
 		case O_BXORASN:
-			res = t1 ^ t2;
+			res = ariop(^);
 			break;
 		case O_BOR:
 		case O_BORASN:
-			res = t1 | t2;
+			res = ariop(|);
 			break;
 		case O_LAND:
-			if (!t1)
+			if (!vl->val.u)
 				es->noassign++;
 			exprtoken(es);
 			vr = intvar(es, evalexpr(es, prec - 1));
-			res = t1 && vr->val.u;
-			if (!t1)
+			res = vl->val.u && vr->val.u;
+			if (!vl->val.u)
 				es->noassign--;
 			break;
 		case O_LOR:
-			if (t1)
+			if (vl->val.u)
 				es->noassign++;
 			exprtoken(es);
 			vr = intvar(es, evalexpr(es, prec - 1));
-			res = t1 || vr->val.u;
-			if (t1)
+			res = vl->val.u || vr->val.u;
+			if (vl->val.u)
 				es->noassign--;
 			break;
 		case O_ASN:
 		case O_COMMA:
-			res = t2;
+			res = vr->val.u;
 			break;
 		}
-
+#undef ariop
 #undef cmpop
 
 		if (IS_ASSIGNOP(op)) {
@@ -565,7 +552,7 @@ exprtoken(Expr_state *es)
 	if (es->tokp == es->expression && (unsigned int)c == ORD('#')) {
 		/* expression begins with # */
 		/* switch to unsigned */
-		es->natural = true;
+		es->natural = Ja;
 		++cp;
 		goto skip_spaces;
 	}
@@ -597,7 +584,7 @@ exprtoken(Expr_state *es)
 	} else if (c == '1' && cp[1] == '#') {
 		cp += 2;
 		if (*cp)
-			cp += utf_ptradj(cp);
+			cp += ez_mbtoc(NULL, cp);
 		strndupx(tvar, es->tokp, cp - es->tokp, ATEMP);
 		goto process_tvar;
 #ifndef MKSH_SMALL
@@ -606,7 +593,7 @@ exprtoken(Expr_state *es)
 			es->tok = END;
 			evalerr(es, ET_UNEXPECTED, NULL);
 		}
-		cp += utf_ptradj(cp);
+		cp += ez_mbtoc(NULL, cp);
 		if (*cp++ != '\'')
 			evalerr(es, ET_STR,
 			    "multi-character character constant");
@@ -664,8 +651,9 @@ tempvar(const char *vname)
 	struct tbl *vp;
 	size_t vsize;
 
-	vsize = strlen(vname) + 1;
-	vp = alloc(offsetof(struct tbl, name[0]) + vsize, ATEMP);
+	/* vname is either "" or vtemp->name which maxes at 12 */
+	vsize = strlen(vname) + 1U;
+	vp = alloc(mbccFAMsz(struct tbl, name, vsize), ATEMP);
 	memcpy(vp->name, vname, vsize);
 	vp->flag = ISSET|INTEGER;
 	vp->type = 0;
@@ -699,11 +687,30 @@ intvar(Expr_state *es, struct tbl *vp)
 	return (vq);
 }
 
-
 /*
  * UTF-8 support code: high-level functions
  */
 
+char *
+ez_bs(char *cp, char *lower_bound)
+{
+	if (UTFMODE) {
+		char *bp = cp;
+		size_t n;
+
+		/* skip backwards knowing the UTF-8 encoding */
+		while (bp > lower_bound && (rtt2asc(*bp) & 0xC0U) == 0x80U)
+			--bp;
+		/* ensure we arrive back at the original point */
+		n = ez_mbtoc(NULL, bp);
+		/* back where we started? if so, this was indeed UTF-8 */
+		if (bp + n - 1 == cp)
+			return (bp);
+		/* no so some raw octet is at *cp */
+	}
+	return (cp);
+}
+
 int
 utf_widthadj(const char *src, const char **dst)
 {
@@ -711,15 +718,12 @@ utf_widthadj(const char *src, const char
 	unsigned int wc;
 	int width;
 
-	if (!UTFMODE || (len = utf_mbtowc(&wc, src)) == (size_t)-1 ||
-	    wc == 0)
+	if (!UTFMODE || !*src || (len = utf_mbtowc(&wc, src)) == (size_t)-1)
 		len = width = 1;
 	else if ((width = utf_wcwidth(wc)) < 0)
-		/* XXX use 2 for x_zotc3 here? */
 		width = 1;
 
-	if (dst)
-		*dst = src + len;
+	*dst = src + len;
 	return (width);
 }
 
@@ -745,41 +749,6 @@ utf_mbswidth(const char *s)
 	return (width);
 }
 
-const char *
-utf_skipcols(const char *p, int cols, int *colp)
-{
-	int c = 0;
-	const char *q;
-
-	while (c < cols) {
-		if (!*p) {
-			/* end of input; special handling for edit.c */
-			if (!colp)
-				return (p + cols - c);
-			*colp = c;
-			return (p);
-		}
-		c += utf_widthadj(p, &p);
-	}
-	if (UTFMODE)
-		while (utf_widthadj(p, &q) == 0)
-			p = q;
-	if (colp)
-		*colp = c;
-	return (p);
-}
-
-size_t
-utf_ptradj(const char *src)
-{
-	register size_t n;
-
-	if (!UTFMODE || rtt2asc(*src) < 0xC2 ||
-	    (n = utf_mbtowc(NULL, src)) == (size_t)-1)
-		n = 1;
-	return (n);
-}
-
 /*
  * UTF-8 support code: low-level functions
  */
@@ -850,6 +819,54 @@ utf_wctomb(char *dst, unsigned int wc)
 	return ((char *)d - dst);
 }
 
+/* “give me that character right now” */
+
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+/* as UCS codepoint; dst must not be NULL */
+size_t
+ez_mbtowc(unsigned int *dst, const char *src)
+{
+	size_t n;
+
+	if (UTFMODE) {
+		if ((n = utf_mbtowc(dst, src)) != (size_t)-1)
+			return (n);
+		*dst = OPTUMKRAW(rtt2asc(*src));
+	} else
+		*dst = ord(rtt2asc(*src));
+	return (*src ? 1 : 0);
+}
+/* identical to ez_mbtoc, unless EBCDIC… */
+#endif
+
+/* as kby if !UTFMODE, UCS codepoint or OPTURAW otherwise */
+size_t
+ez_mbtoc(unsigned int *dst, const char *src)
+{
+	size_t n;
+
+	if (UTFMODE) {
+		if ((n = utf_mbtowc(dst, src)) != (size_t)-1)
+			return (n);
+		if (dst)
+			*dst = OPTUMKRAW(rtt2asc(*src));
+	} else if (dst)
+		*dst = ord(*src);
+	return (*src ? 1 : 0);
+}
+
+size_t
+ez_ctomb(char *dst, unsigned int wc)
+{
+	if (!UTFMODE)
+		*dst = (kby)wc;
+	else if (OPTUISRAW(wc))
+		*dst = asc2rtt((kby)wc);
+	else
+		return (utf_wctomb(dst, wc));
+	return (1);
+}
+
 /*
  * Wrapper around access(2) because it says root can execute everything
  * on some operating systems. Does not set errno, no user needs it. Use
@@ -875,7 +892,7 @@ ksh_access(const char *fn, int mode)
 }
 
 #ifndef MIRBSD_BOOTFLOPPY
-/* From: X11/xc/programs/xterm/wcwidth.c,v 1.10 */
+/* From: X11/xc/programs/xterm/wcwidth.c,v 1.17 */
 
 struct mb_ucsrange {
 	unsigned short beg;
@@ -883,17 +900,17 @@ struct mb_ucsrange {
 };
 
 static int mb_ucsbsearch(const struct mb_ucsrange arr[], size_t elems,
-    unsigned int val) MKSH_A_PURE;
+    unsigned int val);
 
 /*
- * Generated from the UCD 13.0.0 - see /usr/share/doc/legal/LICENCE-BSD - by
+ * Generated from the UCD 15.0.0 - see /usr/share/doc/legal/LICENCE-BSD - by
  * MirOS: contrib/code/Snippets/eawparse,v 1.15 2020/06/15 20:31:13 tg Exp $
  */
 
 /*-
- * Parts Copyright © 1991–2020 Unicode, Inc. All rights reserved.
- * Distributed under the Terms of Use in
- *     https://www.unicode.org/copyright.html.
+ * Parts Copyright © 1991–2022 Unicode, Inc. All rights reserved.
+ * Distributed under the Terms of Use in:
+ *	https://www.unicode.org/copyright.html
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of the Unicode data files and any associated documentation
@@ -951,7 +968,8 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0825, 0x0827 },
 	{ 0x0829, 0x082D },
 	{ 0x0859, 0x085B },
-	{ 0x08D3, 0x08E1 },
+	{ 0x0898, 0x089F },
+	{ 0x08CA, 0x08E1 },
 	{ 0x08E3, 0x0902 },
 	{ 0x093A, 0x093A },
 	{ 0x093C, 0x093C },
@@ -992,6 +1010,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0BCD, 0x0BCD },
 	{ 0x0C00, 0x0C00 },
 	{ 0x0C04, 0x0C04 },
+	{ 0x0C3C, 0x0C3C },
 	{ 0x0C3E, 0x0C40 },
 	{ 0x0C46, 0x0C48 },
 	{ 0x0C4A, 0x0C4D },
@@ -1017,7 +1036,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x0E47, 0x0E4E },
 	{ 0x0EB1, 0x0EB1 },
 	{ 0x0EB4, 0x0EBC },
-	{ 0x0EC8, 0x0ECD },
+	{ 0x0EC8, 0x0ECE },
 	{ 0x0F18, 0x0F19 },
 	{ 0x0F35, 0x0F35 },
 	{ 0x0F37, 0x0F37 },
@@ -1042,7 +1061,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1160, 0x11FF },
 	{ 0x135D, 0x135F },
 	{ 0x1712, 0x1714 },
-	{ 0x1732, 0x1734 },
+	{ 0x1732, 0x1733 },
 	{ 0x1752, 0x1753 },
 	{ 0x1772, 0x1773 },
 	{ 0x17B4, 0x17B5 },
@@ -1050,7 +1069,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x17C6, 0x17C6 },
 	{ 0x17C9, 0x17D3 },
 	{ 0x17DD, 0x17DD },
-	{ 0x180B, 0x180E },
+	{ 0x180B, 0x180F },
 	{ 0x1885, 0x1886 },
 	{ 0x18A9, 0x18A9 },
 	{ 0x1920, 0x1922 },
@@ -1066,7 +1085,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1A65, 0x1A6C },
 	{ 0x1A73, 0x1A7C },
 	{ 0x1A7F, 0x1A7F },
-	{ 0x1AB0, 0x1AC0 },
+	{ 0x1AB0, 0x1ACE },
 	{ 0x1B00, 0x1B03 },
 	{ 0x1B34, 0x1B34 },
 	{ 0x1B36, 0x1B3A },
@@ -1089,8 +1108,7 @@ static const struct mb_ucsrange mb_ucs_c
 	{ 0x1CED, 0x1CED },
 	{ 0x1CF4, 0x1CF4 },
 	{ 0x1CF8, 0x1CF9 },
-	{ 0x1DC0, 0x1DF9 },
-	{ 0x1DFB, 0x1DFF },
+	{ 0x1DC0, 0x1DFF },
 	{ 0x200B, 0x200F },
 	{ 0x202A, 0x202E },
 	{ 0x2060, 0x2064 },
@@ -1220,8 +1238,12 @@ int
 utf_wcwidth(unsigned int wc)
 {
 	/* except NUL, C0/C1 control characters and DEL yield -1 */
-	if (wc < 0x20 || (wc >= 0x7F && wc < 0xA0))
+	if (wc < 0x20)
 		return (wc ? -1 : 0);
+	if (wc < 0x7F)
+		return (1);
+	if (wc < 0xA0)
+		return (-1);
 
 	/* combining characters use 0 screen columns */
 	if (mb_ucsbsearch(mb_ucs_combining, NELEM(mb_ucs_combining), wc))
--- mksh-59c.orig/funcs.c
+++ mksh-59c/funcs.c
@@ -5,7 +5,7 @@
 /*-
  * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022, 2023, 2024
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -26,19 +26,7 @@
 
 #include "sh.h"
 
-#if HAVE_SELECT
-#if HAVE_SYS_BSDTYPES_H
-#include <sys/bsdtypes.h>
-#endif
-#if HAVE_SYS_SELECT_H
-#include <sys/select.h>
-#endif
-#if HAVE_BSTRING_H
-#include <bstring.h>
-#endif
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.379 2020/08/27 19:52:44 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/funcs.c,v 1.415 2024/02/02 02:33:06 tg Exp $");
 
 #if HAVE_KILLPG
 /*
@@ -59,7 +47,8 @@ __RCSID("$MirOS: src/bin/mksh/funcs.c,v
 static int c_suspend(const char **);
 #endif
 
-static int do_whence(const char **, int, bool, bool);
+static int do_whence(const char **, int, Wahr, Wahr);
+static int do_evalcmd(const char **);
 
 /* getn() that prints error */
 static int
@@ -87,7 +76,9 @@ c_false(const char **wp MKSH_A_UNUSED)
 /*
  * A leading = means assignments before command are kept.
  * A leading * means a POSIX special builtin.
- * A leading ^ means declaration utility, - forwarder.
+ * A leading ^ means declaration utility, - declaration forwarder.
+ * A leading ~ means external utilities override this, ! with flags only.
+ * A leading # means is set or shift (for argc/argv bookkeeping).
  */
 const struct builtin mkshbuiltins[] = {
 	{Tsgdot, c_dot},
@@ -98,7 +89,6 @@ const struct builtin mkshbuiltins[] = {
 	{Tsgbreak, c_brkcont},
 	{T__builtin, c_builtin},
 	{Tbuiltin, c_builtin},
-	{Tbcat, c_cat},
 	{Tcd, c_cd},
 	/* dash compatibility hack */
 	{"chdir", c_cd},
@@ -120,7 +110,9 @@ const struct builtin mkshbuiltins[] = {
 	{Tread, c_read},
 	{Tdsgreadonly, c_typeset},
 	{"!realpath", c_realpath},
+#if HAVE_RENAME
 	{"~rename", c_rename},
+#endif
 	{"*=return", c_exitreturn},
 	{Tsghset, c_set},
 	{"*=#shift", c_shift},
@@ -129,6 +121,8 @@ const struct builtin mkshbuiltins[] = {
 	{Tsuspend, c_suspend},
 #endif
 	{"test", c_test},
+	/* normally a syntax element but as_builtin or 'x=y time foo' do: */
+	{Ttime, do_evalcmd},
 	{"*=times", c_times},
 	{"*=trap", c_trap},
 	{Ttrue, c_true},
@@ -152,13 +146,6 @@ const struct builtin mkshbuiltins[] = {
 #ifdef MKSH_PRINTF_BUILTIN
 	{"~printf", c_printf},
 #endif
-#if HAVE_SELECT
-	{"sleep", c_sleep},
-#endif
-#ifdef __MirBSD__
-	/* alias to "true" for historical reasons */
-	{"domainname", c_true},
-#endif
 #ifdef __OS2__
 	{Textproc, c_true},
 #endif
@@ -173,7 +160,7 @@ struct kill_info {
 const struct t_op u_ops[] = {
 /* 0*/	{"-a",	TO_FILAXST },
 	{"-b",	TO_FILBDEV },
-	{"-c",	TO_FILCDEV },
+/* 2*/	{"-c",	TO_FILCDEV },
 	{"-d",	TO_FILID },
 	{"-e",	TO_FILEXST },
 	{"-f",	TO_FILREG },
@@ -186,7 +173,7 @@ const struct t_op u_ops[] = {
 /*12*/	{"-n",	TO_STNZE },
 	{"-O",	TO_FILUID },
 /*14*/	{"-o",	TO_OPTION },
-	{"-p",	TO_FILFIFO },
+/*15*/	{"-p",	TO_FILFIFO },
 /*16*/	{"-r",	TO_FILRD },
 	{"-S",	TO_FILSOCK },
 	{"-s",	TO_FILGZ },
@@ -198,7 +185,9 @@ const struct t_op u_ops[] = {
 	{"-z",	TO_STZER },
 	{"",	TO_NONOP }
 };
-cta(u_ops_size, NELEM(u_ops) == 26);
+mbCTA_BEG(funcs_c);
+	mbCTA(u_ops_size, NELEM(u_ops) == 26);
+mbCTA_END(funcs_c);
 const struct t_op b_ops[] = {
 	{"=",	TO_STEQL },
 	{"==",	TO_STEQL },
@@ -217,31 +206,30 @@ const struct t_op b_ops[] = {
 	{"",	TO_NONOP }
 };
 
-static int test_oexpr(Test_env *, bool);
-static int test_aexpr(Test_env *, bool);
-static int test_nexpr(Test_env *, bool);
-static int test_primary(Test_env *, bool);
+static int test_oexpr(Test_env *, Wahr);
+static int test_aexpr(Test_env *, Wahr);
+static int test_nexpr(Test_env *, Wahr);
+static int test_primary(Test_env *, Wahr);
 static Test_op ptest_isa(Test_env *, Test_meta);
-static const char *ptest_getopnd(Test_env *, Test_op, bool);
+static const char *ptest_getopnd(Test_env *, Test_op, Wahr);
 static void ptest_error(Test_env *, int, const char *);
 static void kill_fmt_entry(char *, size_t, unsigned int, const void *);
-static void p_time(struct shf *, bool, long, int, int,
-    const char *, const char *);
 
 int
 c_pwd(const char **wp)
 {
 	int optc;
-	bool physical = tobool(Flag(FPHYSICAL));
-	char *p, *allocd = NULL;
+	Wahr physical = isWahr(Flag(FPHYSICAL));
+	const char *p;
+	char *allocd = NULL;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "LP")) != -1)
 		switch (optc) {
 		case 'L':
-			physical = false;
+			physical = Nee;
 			break;
 		case 'P':
-			physical = true;
+			physical = Ja;
 			break;
 		case '?':
 			return (1);
@@ -257,7 +245,7 @@ c_pwd(const char **wp)
 	/* LINTED use of access */
 	if (p && access(p, R_OK) < 0)
 		p = NULL;
-	if (!p && !(p = allocd = ksh_get_wd())) {
+	if (!p && !(p = ksh_getwd())) {
 		bi_errorf(Tf_sD_s, "can't determine current directory",
 		    cstrerror(errno));
 		return (1);
@@ -285,32 +273,30 @@ c_print(const char **wp)
 		mksh_ari_t wc;
 		/* output file descriptor (if any) */
 		int fd;
-		/* temporary storage for a multibyte character */
-		char ts[4];
 		/* output word separator */
 		char ws;
 		/* output line separator */
 		char ls;
 		/* output a trailing line separator? */
-		bool nl;
+		Wahr nl;
 		/* expand backslash sequences? */
-		bool exp;
+		Wahr exp;
 		/* columnise output? */
-		bool col;
+		Wahr col;
 		/* print to history instead of file descriptor / stdout? */
-		bool hist;
+		Wahr hist;
 		/* print words as wide characters? */
-		bool chars;
+		Wahr chars;
 		/* writing to a coprocess (SIGPIPE blocked)? */
-		bool coproc;
-		bool copipe;
+		Wahr coproc;
+		Wahr copipe;
 	} po;
 
 	memset(&po, 0, sizeof(po));
 	po.fd = 1;
 	po.ws = ' ';
 	po.ls = '\n';
-	po.nl = true;
+	po.nl = Ja;
 
 	if (wp[0][0] == 'e') {
 		/* "echo" builtin */
@@ -323,12 +309,12 @@ c_print(const char **wp)
 			++wp;
  bsd_echo:
 			if (*wp && !strcmp(*wp, Tdn)) {
-				po.nl = false;
+				po.nl = Nee;
 				++wp;
 			}
-			po.exp = false;
+			po.exp = Nee;
 		} else {
-			bool new_exp, new_nl = true;
+			Wahr new_exp, new_nl = Ja;
 
 			/*-
 			 * compromise between various historic echos: only
@@ -338,11 +324,11 @@ c_print(const char **wp)
 #ifdef MKSH_MIDNIGHTBSD01ASH_COMPAT
 			/* MidnightBSD /bin/sh needs -e supported but off */
 			if (Flag(FSH))
-				new_exp = false;
+				new_exp = Nee;
 			else
 #endif
 			/* otherwise compromise on -e enabled by default */
-			  new_exp = true;
+			  new_exp = Ja;
 			goto print_tradparse_beg;
 
  print_tradparse_arg:
@@ -350,13 +336,13 @@ c_print(const char **wp)
  print_tradparse_ch:
 				switch ((c = *s++)) {
 				case 'E':
-					new_exp = false;
+					new_exp = Nee;
 					goto print_tradparse_ch;
 				case 'e':
-					new_exp = true;
+					new_exp = Ja;
 					goto print_tradparse_ch;
 				case 'n':
-					new_nl = false;
+					new_nl = Nee;
 					goto print_tradparse_ch;
 				case '\0':
  print_tradparse_beg:
@@ -372,18 +358,18 @@ c_print(const char **wp)
 		const char *opts = "AcelNnpRrsu,";
 		const char *emsg;
 
-		po.exp = true;
+		po.exp = Ja;
 
 		while ((c = ksh_getopt(wp, &builtin_opt, opts)) != -1)
 			switch (c) {
 			case 'A':
-				po.chars = true;
+				po.chars = Ja;
 				break;
 			case 'c':
-				po.col = true;
+				po.col = Ja;
 				break;
 			case 'e':
-				po.exp = true;
+				po.exp = Ja;
 				break;
 			case 'l':
 				po.ws = '\n';
@@ -393,11 +379,11 @@ c_print(const char **wp)
 				po.ls = '\0';
 				break;
 			case 'n':
-				po.nl = false;
+				po.nl = Nee;
 				break;
 			case 'p':
 				if ((po.fd = coproc_getfd(W_OK, &emsg)) < 0) {
-					bi_errorf(Tf_coproc, emsg);
+					bi_errorf("%s: %s", Tdp, emsg);
 					return (1);
 				}
 				break;
@@ -406,10 +392,10 @@ c_print(const char **wp)
 				wp += builtin_opt.optind;
 				goto bsd_echo;
 			case 'r':
-				po.exp = false;
+				po.exp = Nee;
 				break;
 			case 's':
-				po.hist = true;
+				po.hist = Ja;
 				break;
 			case 'u':
 				if (!*(s = builtin_opt.optarg))
@@ -449,31 +435,24 @@ c_print(const char **wp)
 			s = *wp++;
 			if (*s == '\0')
 				break;
-			if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, true))
+			if (!evaluate(s, &po.wc, KSH_RETURN_ERROR, Ja))
 				return (1);
-			Xcheck(xs, xp);
-			if (UTFMODE) {
-				po.ts[utf_wctomb(po.ts, po.wc)] = 0;
-				c = 0;
-				do {
-					Xput(xs, xp, po.ts[c]);
-				} while (po.ts[++c]);
-			} else
-				Xput(xs, xp, po.wc & 0xFF);
+			XcheckN(xs, xp, 4);
+			xp += ez_ctomb(xp, po.wc);
 		}
 	} else {
 		s = *wp++;
 		while ((c = *s++) != '\0') {
-			Xcheck(xs, xp);
+			XcheckN(xs, xp, 4);
 			if (po.exp && c == '\\') {
 				s_ptr = s;
-				c = unbksl(false, s_get, s_put);
+				c = unbksl(Nee, s_get, s_put);
 				s = s_ptr;
 				if (c == -1) {
 					/* rejected by generic function */
 					switch ((c = *s++)) {
 					case 'c':
-						po.nl = false;
+						po.nl = Nee;
 						/* AT&T brain damage */
 						continue;
 					case '\0':
@@ -485,11 +464,7 @@ c_print(const char **wp)
 					}
 				} else if ((unsigned int)c > 0xFF) {
 					/* generic function returned UCS */
-					po.ts[utf_wctomb(po.ts, c - 0x100)] = 0;
-					c = 0;
-					do {
-						Xput(xs, xp, po.ts[c]);
-					} while (po.ts[++c]);
+					xp += utf_wctomb(xp, c - 0x100);
 					continue;
 				}
 			}
@@ -513,7 +488,7 @@ c_print(const char **wp)
 		XPput(po.words, NULL);
 		co.shf = shf_sopen(NULL, 128, SHF_WR | SHF_DYNAMIC, NULL);
 		co.linesep = po.ls;
-		co.prefcol = co.do_last = false;
+		co.prefcol = co.do_last = Nee;
 		pr_list(&co, (char **)XPptrv(po.words));
 		while (w--)
 			afree(XPptrv(po.words)[w], ATEMP);
@@ -531,7 +506,7 @@ c_print(const char **wp)
 	c = 0;
 	if (po.hist) {
 		Xput(xs, xp, '\0');
-		histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
+		histsave(&source->line, Xstring(xs, xp), HIST_STORE, Nee);
 	} else {
 		size_t len = Xlength(xs, xp);
 
@@ -542,10 +517,10 @@ c_print(const char **wp)
 		 * not enough).
 		 */
 		if (coproc.write >= 0 && coproc.write == po.fd) {
-			po.coproc = true;
+			po.coproc = Ja;
 			po.copipe = block_pipe();
 		} else
-			po.coproc = po.copipe = false;
+			po.coproc = po.copipe = Nee;
 
 		s = Xstring(xs, xp);
 		while (len > 0) {
@@ -562,6 +537,7 @@ c_print(const char **wp)
 						po.copipe = block_pipe();
 					continue;
 				}
+				bi_errorf(Tf_sD_s, Twrite, cstrerror(errno));
 				c = 1;
 				break;
 			}
@@ -592,15 +568,15 @@ int
 c_whence(const char **wp)
 {
 	int optc;
-	bool pflag = false, vflag = false;
+	Wahr pflag = Nee, vflag = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, Tpv)) != -1)
 		switch (optc) {
 		case 'p':
-			pflag = true;
+			pflag = Ja;
 			break;
 		case 'v':
-			vflag = true;
+			vflag = Ja;
 			break;
 		case '?':
 			return (1);
@@ -608,7 +584,7 @@ c_whence(const char **wp)
 	wp += builtin_opt.optind;
 
 	return (do_whence(wp, pflag ? FC_PATH :
-	    FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, false));
+	    FC_BI | FC_FUNC | FC_PATH | FC_WHENCE, vflag, Nee));
 }
 
 /* note: command without -vV is dealt with in comexec() */
@@ -616,7 +592,7 @@ int
 c_command(const char **wp)
 {
 	int optc, fcflags = FC_BI | FC_FUNC | FC_PATH | FC_WHENCE;
-	bool vflag = false;
+	Wahr vflag = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, TpVv)) != -1)
 		switch (optc) {
@@ -624,23 +600,23 @@ c_command(const char **wp)
 			fcflags |= FC_DEFPATH;
 			break;
 		case 'V':
-			vflag = true;
+			vflag = Ja;
 			break;
 		case 'v':
-			vflag = false;
+			vflag = Nee;
 			break;
 		case '?':
 			return (1);
 		}
 	wp += builtin_opt.optind;
 
-	return (do_whence(wp, fcflags, vflag, true));
+	return (do_whence(wp, fcflags, vflag, Ja));
 }
 
 static int
-do_whence(const char **wp, int fcflags, bool vflag, bool iscommand)
+do_whence(const char **wp, int fcflags, Wahr vflag, Wahr iscommand)
 {
-	uint32_t h;
+	k32 h;
 	int rv = 0;
 	struct tbl *tp;
 	const char *id;
@@ -692,9 +668,11 @@ do_whence(const char **wp, int fcflags,
 			break;
 		case CEXEC:
 		case CTALIAS:
+			if (vflag)
+				shf_puts(id, shl_stdout);
 			if (tp->flag & ISSET) {
 				if (vflag) {
-					shprintf("%s is ", id);
+					shf_puts(" is ", shl_stdout);
 					if (tp->type == CTALIAS)
 						shprintf("a tracked %s%s for ",
 						    (tp->flag & EXPORT) ?
@@ -703,10 +681,10 @@ do_whence(const char **wp, int fcflags,
 				}
 				if (!mksh_abspath(tp->val.s)) {
 					const char *xcwd = current_wd[0] ?
-					    current_wd : ".";
+					    current_wd : Tdot;
 					size_t xlen = strlen(xcwd);
 					size_t clen = strlen(tp->val.s) + 1;
-					char *xp = alloc(xlen + 1 + clen, ATEMP);
+					char *xp = alloc1(xlen + 1U, clen, ATEMP);
 
 					memcpy(xp, xcwd, xlen);
 					if (mksh_cdirsep(xp[xlen - 1]))
@@ -720,7 +698,7 @@ do_whence(const char **wp, int fcflags,
 					shf_puts(tp->val.s, shl_stdout);
 			} else {
 				if (vflag)
-					shprintf(Tnot_found_s, id);
+					shf_puts(Tsp_not_found, shl_stdout);
 				rv = 1;
 			}
 			break;
@@ -753,24 +731,24 @@ do_whence(const char **wp, int fcflags,
 	return (rv);
 }
 
-bool
+Wahr
 valid_alias_name(const char *cp)
 {
 	switch (ord(*cp)) {
 	case ORD('+'):
 	case ORD('-'):
-		return (false);
+		return (Nee);
 	case ORD('['):
 		if (ord(cp[1]) == ORD('[') && !cp[2])
-			return (false);
+			return (Nee);
 		break;
 	}
 	while (*cp)
 		if (ctype(*cp, C_ALIAS))
 			++cp;
 		else
-			return (false);
-	return (true);
+			return (Nee);
+	return (Ja);
 }
 
 int
@@ -778,8 +756,8 @@ c_alias(const char **wp)
 {
 	struct table *t = &aliases;
 	int rv = 0, prefix = 0;
-	bool rflag = false, tflag, Uflag = false, pflag = false, chkalias;
-	uint32_t xflag = 0;
+	Wahr rflag = Nee, tflag, Uflag = Nee, pflag = Nee, chkalias;
+	kui xflag = 0;
 	int optc;
 
 	builtin_opt.flags |= GF_PLUSOPT;
@@ -794,10 +772,10 @@ c_alias(const char **wp)
 #endif
 			break;
 		case 'p':
-			pflag = true;
+			pflag = Ja;
 			break;
 		case 'r':
-			rflag = true;
+			rflag = Ja;
 			break;
 		case 't':
 			t = &taliases;
@@ -807,7 +785,7 @@ c_alias(const char **wp)
 			 * kludge for tracked alias initialization
 			 * (don't do a path search, just make an entry)
 			 */
-			Uflag = true;
+			Uflag = Ja;
 			break;
 		case 'x':
 			xflag = EXPORT;
@@ -866,7 +844,7 @@ c_alias(const char **wp)
 		const char *alias = *wp, *val, *newval;
 		char *xalias = NULL;
 		struct tbl *ap;
-		uint32_t h;
+		k32 h;
 
 		if ((val = cstrchr(alias, '='))) {
 			strndupx(xalias, alias, val++ - alias, ATEMP);
@@ -930,12 +908,12 @@ c_unalias(const char **wp)
 	struct table *t = &aliases;
 	struct tbl *ap;
 	int optc, rv = 0;
-	bool all = false;
+	Wahr all = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "adt")) != -1)
 		switch (optc) {
 		case 'a':
-			all = true;
+			all = Ja;
 			break;
 		case 'd':
 #ifdef MKSH_NOPWNAM
@@ -997,7 +975,7 @@ c_let(const char **wp)
 		bi_errorf(Tno_args);
 	else
 		for (wp++; *wp; wp++)
-			if (!evaluate(*wp, &val, KSH_RETURN_ERROR, true)) {
+			if (!evaluate(*wp, &val, KSH_RETURN_ERROR, Ja)) {
 				/* distinguish error from zero result */
 				rv = 2;
 				break;
@@ -1045,7 +1023,7 @@ c_jobs(const char **wp)
 int
 c_fgbg(const char **wp)
 {
-	bool bg = strcmp(*wp, Tbg) == 0;
+	Wahr bg = strcmp(*wp, Tbg) == 0;
 	int rv = 0;
 
 	if (!Flag(FMONITOR)) {
@@ -1083,13 +1061,15 @@ c_kill(const char **wp)
 {
 	Trap *t = NULL;
 	const char *p;
-	bool lflag = false;
+	Wahr lflag = Nee;
 	int i, n, rv, sig;
 
 	/* assume old style options if -digits or -UPPERCASE */
-	if ((p = wp[1]) && *p == '-' && ctype(p[1], C_DIGIT | C_UPPER)) {
-		if (!(t = gettrap(p + 1, false, false))) {
-			bi_errorf(Tbad_sig_s, p + 1);
+	if ((p = wp[1]) && isch(*p, '-') && ctype(p[1], C_DIGIT | C_UPPER)) {
+		++p;
+		if (!(t = gettrap(p, Nee, Nee))) {
+			kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+			    Tbad_sig, p);
 			return (1);
 		}
 		i = (wp[2] && strcmp(wp[2], "--") == 0) ? 3 : 2;
@@ -1099,12 +1079,13 @@ c_kill(const char **wp)
 		while ((optc = ksh_getopt(wp, &builtin_opt, "ls:")) != -1)
 			switch (optc) {
 			case 'l':
-				lflag = true;
+				lflag = Ja;
 				break;
 			case 's':
 				if (!(t = gettrap(builtin_opt.optarg,
-				    true, false))) {
-					bi_errorf(Tbad_sig_s,
+				    Ja, Nee))) {
+					kwarnf(KWF_BIERR | KWF_TWOMSG |
+					    KWF_NOERRNO, Tbad_sig,
 					    builtin_opt.optarg);
 					return (1);
 				}
@@ -1120,7 +1101,7 @@ c_kill(const char **wp)
 		    " { job | pid | pgrp } ...\n"
 		    "\tkill -l [exit_status ...]\n", shl_out);
 #endif
-		bi_errorfz();
+		bi_unwind(1);
 		return (1);
 	}
 
@@ -1142,7 +1123,8 @@ c_kill(const char **wp)
 			n = 1;
 			while (n < ksh_NSIG) {
 				shf_puts(sigtraps[n].name, shl_stdout);
-				shf_putc(++n == ksh_NSIG ? '\n' : ' ',
+				++n;
+				shf_putc(n == ksh_NSIG ? '\n' : ' ',
 				    shl_stdout);
 			}
 		} else {
@@ -1169,7 +1151,7 @@ c_kill(const char **wp)
 
 			co.shf = shl_stdout;
 			co.linesep = '\n';
-			co.prefcol = co.do_last = true;
+			co.prefcol = co.do_last = Ja;
 
 			print_columns(&co, (unsigned int)(ksh_NSIG - 1),
 			    kill_fmt_entry, (void *)&ki,
@@ -1231,13 +1213,14 @@ c_getopts(const char **wp)
 		bi_errorf(Tf_sD_s, Tname, Tno_args);
 		return (1);
 	}
-	if (!*var || *skip_varname(var, true)) {
+	if (!*var || *skip_varname(var, Ja)) {
 		bi_errorf(Tf_sD_s, var, Tnot_ident);
 		return (1);
 	}
 
 	if (e->loc->next == NULL) {
-		internal_warningf(Tf_sD_s, Tgetopts, Tno_args);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+		    Tgetopts, Tno_args);
 		return (1);
 	}
 	/* Which arguments are we parsing... */
@@ -1305,7 +1288,7 @@ c_bind(const char **wp)
 {
 	int optc, rv = 0;
 #ifndef MKSH_SMALL
-	bool macro = false;
+	Wahr macro = Nee;
 #endif
 
 	if (x_bind_check()) {
@@ -1319,7 +1302,7 @@ c_bind(const char **wp)
 			return (x_bind_list());
 #ifndef MKSH_SMALL
 		case 'm':
-			macro = true;
+			macro = Ja;
 			break;
 #endif
 		default:
@@ -1359,9 +1342,9 @@ c_shift(const char **wp)
 
 	if (!arg)
 		n = 1;
-	else if (!evaluate(arg, &val, KSH_RETURN_ERROR, false)) {
+	else if (!evaluate(arg, &val, KSH_RETURN_ERROR, Nee)) {
 		/* error already printed */
-		bi_errorfz();
+		bi_unwind(1);
 		return (1);
 	} else if (!(n = val)) {
 		/* nothing to do */
@@ -1386,13 +1369,13 @@ c_umask(const char **wp)
 {
 	int i, optc;
 	const char *cp;
-	bool symbolic = false;
+	Wahr symbolic = Nee;
 	mode_t old_umask;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "S")) != -1)
 		switch (optc) {
 		case 'S':
-			symbolic = true;
+			symbolic = Ja;
 			break;
 		case '?':
 			return (1);
@@ -1521,7 +1504,7 @@ int
 c_dot(const char **wp)
 {
 	const char *file, *cp, **argv;
-	int argc, rv, errcode;
+	int rv, errcode;
 
 	if (ksh_getopt(wp, &builtin_opt, null) == '?')
 		return (1);
@@ -1544,15 +1527,11 @@ c_dot(const char **wp)
 		argv = wp + builtin_opt.optind;
 		/* preserve $0 */
 		argv[0] = e->loc->argv[0];
-		for (argc = 0; argv[argc + 1]; argc++)
-			;
-	} else {
-		argc = 0;
+	} else
 		argv = NULL;
-	}
 	/* SUSv4: OR with a high value never written otherwise */
 	exstat |= 0x4000;
-	if ((rv = include(file, argc, argv, false)) < 0) {
+	if ((rv = include(file, argv, Nee)) < 0) {
 		/* should not happen */
 		bi_errorf(Tf_sD_s, cp, cstrerror(errno));
 		return (1);
@@ -1590,11 +1569,11 @@ c_read(const char **wp)
 {
 #define is_ifsws(c) (ctype((c), C_IFS) && ctype((c), C_IFSWS))
 	int c, fd = 0, rv = 0;
-	bool savehist = false, intoarray = false, aschars = false;
-	bool rawmode = false, expanding = false;
-	bool lastparmmode = false, lastparmused = false;
+	Wahr savehist = Nee, intoarray = Nee, aschars = Nee;
+	Wahr rawmode = Nee, expanding = Nee;
+	Wahr lastparmmode = Nee, lastparmused = Nee;
 	enum { LINES, BYTES, UPTO, READALL } readmode = LINES;
-	char delim = '\n';
+	kby delim = ORD('\n');
 	size_t bytesleft = 128, bytesread;
 	struct tbl *vp /* FU gcc */ = NULL, *vq = NULL;
 	char *cp, *allocd = NULL, *xp;
@@ -1602,11 +1581,12 @@ c_read(const char **wp)
 	XString xs;
 	size_t xsave = 0;
 	mksh_ttyst tios;
-	bool restore_tios = false;
+	Wahr restore_tios = Nee;
 	/* to catch read -aN2 foo[i] */
-	bool subarray = false;
+	Wahr subarray = Nee;
+	k32 idx = 0;
 #if HAVE_SELECT
-	bool hastimeout = false;
+	Wahr hastimeout = Nee;
 	struct timeval tv, tvlim;
 #define c_read_opts "Aad:N:n:prst:u,"
 #else
@@ -1618,19 +1598,22 @@ c_read(const char **wp)
 #endif
 
 	while ((c = ksh_getopt(wp, &builtin_opt, c_read_opts)) != -1)
-	switch (c) {
-	case 'a':
-		aschars = true;
+	switch (ord(c)) {
+	case ORD('a'):
+		aschars = Ja;
 		/* FALLTHROUGH */
-	case 'A':
-		intoarray = true;
+	case ORD('A'):
+		intoarray = Ja;
 		break;
-	case 'd':
-		delim = builtin_opt.optarg[0];
+	case ORD('d'):
+		delim = ord(builtin_opt.optarg[0]);
 		break;
-	case 'N':
-	case 'n':
-		readmode = c == 'N' ? BYTES : UPTO;
+	case ORD('N'):
+		readmode = BYTES;
+		if (0)
+			/* FALLTHROUGH */
+	case ORD('n'):
+		  readmode = UPTO;
 		if (!bi_getn(builtin_opt.optarg, &c))
 			return (2);
 		if (c == -1) {
@@ -1641,15 +1624,15 @@ c_read(const char **wp)
 		break;
 	case 'p':
 		if ((fd = coproc_getfd(R_OK, &ccp)) < 0) {
-			bi_errorf(Tf_coproc, ccp);
+			bi_errorf("%s: %s", Tdp, ccp);
 			return (2);
 		}
 		break;
 	case 'r':
-		rawmode = true;
+		rawmode = Ja;
 		break;
 	case 's':
-		savehist = true;
+		savehist = Ja;
 		break;
 #if HAVE_SELECT
 	case 't':
@@ -1658,14 +1641,16 @@ c_read(const char **wp)
 			    builtin_opt.optarg);
 			return (2);
 		}
-		hastimeout = true;
+		hastimeout = Ja;
 		break;
 #endif
 	case 'u':
 		if (!builtin_opt.optarg[0])
 			fd = 0;
 		else if ((fd = check_fd(builtin_opt.optarg, R_OK, &ccp)) < 0) {
-			bi_errorf(Tf_sD_sD_s, Tdu, builtin_opt.optarg, ccp);
+			kwarnf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_BUILTIN | KWF_BIUNWIND | KWF_THREEMSG,
+			    Tdu, builtin_opt.optarg, ccp);
 			return (2);
 		}
 		break;
@@ -1682,8 +1667,7 @@ c_read(const char **wp)
 	}
 
 	if ((ccp = cstrchr(*wp, '?')) != NULL) {
-		strdupx(allocd, *wp, ATEMP);
-		allocd[ccp - *wp] = '\0';
+		strndupx(allocd, *wp, ccp - *wp, ATEMP);
 		*wp = allocd;
 		if (isatty(fd)) {
 			/*
@@ -1702,8 +1686,8 @@ c_read(const char **wp)
 	if (readmode == LINES)
 		bytesleft = 1;
 	else if (isatty(fd)) {
-		x_mkraw(fd, &tios, true);
-		restore_tios = true;
+		x_mkraw(fd, &tios, Ja);
+		restore_tios = Ja;
 	}
 
 #if HAVE_SELECT
@@ -1721,12 +1705,12 @@ c_read(const char **wp)
 		FD_ZERO(&fdset);
 		FD_SET((unsigned int)fd, &fdset);
 		mksh_TIME(tv);
-		timersub(&tvlim, &tv, &tv);
-		if (tv.tv_sec < 0) {
+		if (timercmp(&tvlim, &tv, <)) {
 			/* timeout expired globally */
 			rv = 3;
 			goto c_read_out;
 		}
+		timersub(&tvlim, &tv, &tv);
 
 		switch (select(fd + 1, &fdset, NULL, NULL, &tv)) {
 		case 1:
@@ -1806,13 +1790,13 @@ c_read(const char **wp)
 			rv = 1;
 			goto c_read_readdone;
 		}
-		if ((c = *xp) == '\0' && !aschars && delim != '\0') {
+		if ((c = ord(*xp)) == '\0' && !aschars && delim != '\0') {
 			/* skip any read NULs unless delimiter */
 			break;
 		}
 		if (expanding) {
-			expanding = false;
-			if (c == delim) {
+			expanding = Nee;
+			if (ord(c) == ord(delim)) {
 				if (Flag(FTALKING_I) && isatty(fd)) {
 					/*
 					 * set prompt in case this is
@@ -1826,10 +1810,10 @@ c_read(const char **wp)
 				/* and the delimiter */
 				break;
 			}
-		} else if (c == delim) {
+		} else if (ord(c) == ord(delim)) {
 			goto c_read_readdone;
-		} else if (!rawmode && c == '\\') {
-			expanding = true;
+		} else if (!rawmode && ord(c) == ORD('\\')) {
+			expanding = Ja;
 		}
 		Xcheck(xs, xp);
 		++xp;
@@ -1856,24 +1840,26 @@ c_read(const char **wp)
 	}
 
 	if (savehist)
-		histsave(&source->line, Xstring(xs, xp), HIST_STORE, false);
+		histsave(&source->line, Xstring(xs, xp), HIST_STORE, Nee);
 
 	ccp = cp = Xclose(xs, xp);
-	expanding = false;
+	expanding = Nee;
 	XinitN(xs, 128, ATEMP);
 	if (intoarray) {
 		vp = global(*wp);
 		subarray = last_lookup_was_array;
 		if (vp->flag & RDONLY) {
  c_read_splitro:
-			bi_errorf(Tf_ro, *wp);
+			kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+			    Tread_only, *wp);
  c_read_spliterr:
 			rv = 2;
 			afree(cp, ATEMP);
 			goto c_read_out;
 		}
 		/* counter for array index */
-		c = subarray ? arrayindex(vp) : 0;
+		if (subarray)
+			idx = arrayindex(vp);
 		/* exporting an array is currently pointless */
 		unset(vp, subarray ? 0 : 1);
 	}
@@ -1899,23 +1885,28 @@ c_read(const char **wp)
 		goto c_read_gotword;
 	}
 	if (aschars) {
+		bytesleft = ez_mbtoc(NULL, ccp);
+		if (!bytesleft) {
+			/* got a NUL byte */
+			Xput(xs, xp, '2');
+			Xput(xs, xp, '#');
+			Xput(xs, xp, '0');
+			++ccp;
+			--bytesread;
+			goto c_read_gotword;
+		}
 		Xput(xs, xp, '1');
 		Xput(xs, xp, '#');
-		bytesleft = utf_ptradj(ccp);
 		while (bytesleft && bytesread) {
 			*xp++ = *ccp++;
 			--bytesleft;
 			--bytesread;
 		}
-		if (xp[-1] == '\0') {
-			xp[-1] = '0';
-			xp[-3] = '2';
-		}
 		goto c_read_gotword;
 	}
 
 	if (!intoarray && wp[1] == NULL)
-		lastparmmode = true;
+		lastparmmode = Ja;
 
  c_read_splitlast:
 	/* copy until IFS character */
@@ -1924,12 +1915,12 @@ c_read(const char **wp)
 
 		ch = *ccp;
 		if (expanding) {
-			expanding = false;
+			expanding = Nee;
 			goto c_read_splitcopy;
 		} else if (ctype(ch, C_IFS)) {
 			break;
 		} else if (!rawmode && ch == '\\') {
-			expanding = true;
+			expanding = Ja;
 		} else {
  c_read_splitcopy:
 			Xcheck(xs, xp);
@@ -1940,7 +1931,7 @@ c_read(const char **wp)
 	}
 	xsave = Xsavepos(xs, xp);
 	/* copy word delimiter: IFSWS+IFS,IFSWS */
-	expanding = false;
+	expanding = Nee;
 	while (bytesread) {
 		char ch;
 
@@ -1948,7 +1939,7 @@ c_read(const char **wp)
 		if (!ctype(ch, C_IFS))
 			break;
 		if (lastparmmode && !expanding && !rawmode && ch == '\\') {
-			expanding = true;
+			expanding = Ja;
 		} else {
 			Xcheck(xs, xp);
 			Xput(xs, xp, ch);
@@ -1968,7 +1959,7 @@ c_read(const char **wp)
 	}
 	/* if no more parameters, rinse and repeat */
 	if (lastparmmode && bytesread) {
-		lastparmused = true;
+		lastparmused = Ja;
 		goto c_read_splitlast;
 	}
 	/* get rid of the delimiter unless we pack the rest */
@@ -1984,11 +1975,13 @@ c_read(const char **wp)
 				goto c_read_spliterr;
 			}
 			vq = vp;
-			if (c)
+			if (idx)
 				/* [0] doesn't */
 				vq->flag |= AINDEX;
-		} else
-			vq = arraysearch(vp, c++);
+		} else {
+			vq = arraysearch(vp, idx);
+			idx = mbiMO(k32, K32_FM, idx, +, 1U);
+		}
 	} else {
 		vq = global(*wp);
 		/* must be checked before exporting */
@@ -2000,7 +1993,7 @@ c_read(const char **wp)
 	if (!setstr(vq, Xstring(xs, xp), KSH_RETURN_ERROR))
 		goto c_read_spliterr;
 	if (aschars) {
-		setint_v(vq, vq, false);
+		setint_v(vq, vq, Nee);
 		/* protect from UTFMODE changes */
 		vq->type = 0;
 	}
@@ -2023,13 +2016,19 @@ c_read(const char **wp)
 int
 c_eval(const char **wp)
 {
+	if (ksh_getopt(wp, &builtin_opt, null) == '?')
+		return (1);
+	return (do_evalcmd(wp + builtin_opt.optind));
+}
+
+static int
+do_evalcmd(const char **wp)
+{
 	struct source *s, *saves = source;
 	int rv;
 
-	if (ksh_getopt(wp, &builtin_opt, null) == '?')
-		return (1);
 	s = pushs(SWORDS, ATEMP);
-	s->u.strv = wp + builtin_opt.optind;
+	s->u.strv = wp;
 	s->line = current_lineno;
 
 	/*-
@@ -2112,8 +2111,9 @@ c_trap(const char **wp)
 	/* set/clear the traps */
 	i = 0;
 	while (*wp)
-		if (!(p = gettrap(*wp++, true, true))) {
-			warningf(true, Tbad_sig_ss, builtin_argv0, wp[-1]);
+		if (!(p = gettrap(*wp++, Ja, Ja))) {
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_BUILTIN |
+			    KWF_TWOMSG | KWF_NOERRNO, Tbad_sig, wp[-1]);
 			i = 1;
 		} else
 			settrap(p, s);
@@ -2148,7 +2148,7 @@ c_exitreturn(const char **wp)
 	}
 
 	if (how == LEXIT && !really_exit && j_stopped_running()) {
-		really_exit = true;
+		really_exit = Ja;
 		how = LSHELL;
 	}
 
@@ -2201,7 +2201,8 @@ c_brkcont(const char **wp)
 		 * scripts, but don't generate an error (ie, keep going).
 		 */
 		if ((unsigned int)n == quit) {
-			warningf(true, Tf_cant_s, wp[0], wp[0]);
+			kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+			    Tf_cant_s, wp[0], wp[0]);
 			return (0);
 		}
 		/*
@@ -2211,7 +2212,8 @@ c_brkcont(const char **wp)
 		 */
 		if (last_ep)
 			last_ep->flags &= ~EF_BRKCONT_PASS;
-		warningf(true, "%s: can only %s %u level(s)",
+		kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+		    "%s: can only %s %u level(s)",
 		    wp[0], wp[0], (unsigned int)n - quit);
 	}
 
@@ -2226,7 +2228,7 @@ int
 c_set(const char **wp)
 {
 	int argi;
-	bool setargs;
+	Wahr setargs;
 	struct block *l = e->loc;
 
 	if ((l->flags & BF_RESETSPEC)) {
@@ -2245,18 +2247,10 @@ c_set(const char **wp)
 		return (2);
 	/* set $# and $* */
 	if (setargs) {
-		const char **owp;
-
 		wp += argi - 1;
-		owp = wp;
 		/* save $0 */
 		wp[0] = l->argv[0];
-		while (*++wp != NULL)
-			strdupx(*wp, *wp, &l->area);
-		l->argc = wp - owp - 1;
-		l->argv = alloc2(l->argc + 2, sizeof(char *), &l->area);
-		for (wp = l->argv; (*wp++ = *owp++) != NULL; )
-			;
+		l->argv = cpyargv(&l->argc, wp, &l->area);
 	}
 	/*-
 	 * POSIX says set exit status is 0, but old scripts that use
@@ -2280,18 +2274,18 @@ c_unset(const char **wp)
 {
 	const char *id;
 	int optc, rv = 0;
-	bool unset_var = true;
+	Wahr unset_var = Ja;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, "fv")) != -1)
 		switch (optc) {
 		case 'f':
-			unset_var = false;
+			unset_var = Nee;
 			break;
 		case 'v':
-			unset_var = true;
+			unset_var = Ja;
 			break;
 		case '?':
-			/*XXX not reached due to GF_ERROR */
+			/*XXX not reached due to GF_ERROR in spec_bi */
 			return (2);
 		}
 	wp += builtin_opt.optind;
@@ -2316,7 +2310,8 @@ c_unset(const char **wp)
 			afree(cp, ATEMP);
 
 			if ((vp->flag&RDONLY)) {
-				warningf(true, Tf_ro, vp->name);
+				kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+				    KWF_NOERRNO, Tread_only, vp->name);
 				rv = 1;
 			} else
 				unset(vp, optc);
@@ -2327,36 +2322,45 @@ c_unset(const char **wp)
 }
 
 static void
-p_time(struct shf *shf, bool posix, long tv_sec, int tv_usec, int width,
-    const char *prefix, const char *suffix)
+c_times_i(int what)
 {
-	tv_usec /= 10000;
-	if (posix)
-		shf_fprintf(shf, "%s%*ld.%02d%s", prefix, width,
-		    tv_sec, tv_usec, suffix);
-	else
-		shf_fprintf(shf, "%s%*ldm%02d.%02ds%s", prefix, width,
-		    tv_sec / 60, (int)(tv_sec % 60), tv_usec, suffix);
+	struct rusage usage;
+
+	if (ksh_getrusage(what, &usage))
+		kwarnf(KWF_BIERR | KWF_ONEMSG, "getrusage");
+	shf_fprintf(shl_stdout,
+	    "%ldm%02d.%02ds %ldm%02d.%02ds\n",
+	    (long)(usage.ru_utime.tv_sec / 60),
+	    (int)(usage.ru_utime.tv_sec % 60),
+	    (int)(usage.ru_utime.tv_usec / 10000),
+	    (long)(usage.ru_stime.tv_sec / 60),
+	    (int)(usage.ru_stime.tv_sec % 60),
+	    (int)(usage.ru_stime.tv_usec / 10000));
 }
 
 int
 c_times(const char **wp MKSH_A_UNUSED)
 {
-	struct rusage usage;
+	c_times_i(RUSAGE_SELF);
+	c_times_i(RUSAGE_CHILDREN);
+	return (0);
+}
 
-	getrusage(RUSAGE_SELF, &usage);
-	p_time(shl_stdout, false, usage.ru_utime.tv_sec,
-	    usage.ru_utime.tv_usec, 0, null, T1space);
-	p_time(shl_stdout, false, usage.ru_stime.tv_sec,
-	    usage.ru_stime.tv_usec, 0, null, "\n");
-
-	getrusage(RUSAGE_CHILDREN, &usage);
-	p_time(shl_stdout, false, usage.ru_utime.tv_sec,
-	    usage.ru_utime.tv_usec, 0, null, T1space);
-	p_time(shl_stdout, false, usage.ru_stime.tv_sec,
-	    usage.ru_stime.tv_usec, 0, null, "\n");
+static void
+p_time_psx(struct timeval *tv, const char *prefix)
+{
+	shf_fprintf(shl_out, "%s%ld.%02d\n", prefix,
+	    (long)(tv->tv_sec),
+	    (int)(tv->tv_usec / 10000));
+}
 
-	return (0);
+static void
+p_time_ksh(struct timeval *tv, const char *suffix)
+{
+	shf_fprintf(shl_out, "%5ldm%02d.%02ds%s",
+	    (long)(tv->tv_sec / 60),
+	    (int)(tv->tv_sec % 60),
+	    (int)(tv->tv_usec / 10000), suffix);
 }
 
 /*
@@ -2373,8 +2377,12 @@ timex(struct op *t, int f, volatile int
 	struct timeval usrtime, systime, tv0, tv1;
 
 	mksh_TIME(tv0);
-	getrusage(RUSAGE_SELF, &ru0);
-	getrusage(RUSAGE_CHILDREN, &cru0);
+	if (ksh_getrusage(RUSAGE_SELF, &ru0) ||
+	    ksh_getrusage(RUSAGE_CHILDREN, &cru0)) {
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    Ttime_getrusage);
+		return (125);
+	}
 	if (t->left) {
 		/*
 		 * Two ways of getting cpu usage of a command: just use t0
@@ -2390,8 +2398,12 @@ timex(struct op *t, int f, volatile int
 		if (t->left->type == TCOM)
 			tf |= t->left->str[0];
 		mksh_TIME(tv1);
-		getrusage(RUSAGE_SELF, &ru1);
-		getrusage(RUSAGE_CHILDREN, &cru1);
+		if (ksh_getrusage(RUSAGE_SELF, &ru1) ||
+		    ksh_getrusage(RUSAGE_CHILDREN, &cru1)) {
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+			    Ttime_getrusage);
+			return (rv);
+		}
 	} else
 		tf = TF_NOARGS;
 
@@ -2407,27 +2419,21 @@ timex(struct op *t, int f, volatile int
 		timeradd(&systime, &j_systime, &systime);
 	}
 
-	if (!(tf & TF_NOREAL)) {
-		timersub(&tv1, &tv0, &tv1);
-		if (tf & TF_POSIX)
-			p_time(shl_out, true, tv1.tv_sec, tv1.tv_usec,
-			    5, Treal_sp1, "\n");
-		else
-			p_time(shl_out, false, tv1.tv_sec, tv1.tv_usec,
-			    5, null, Treal_sp2);
+	if (tf & TF_POSIX) {
+		if (!(tf & TF_NOREAL)) {
+			timersub(&tv1, &tv0, &tv1);
+			p_time_psx(&tv1, Treal_sp1);
+		}
+		p_time_psx(&usrtime, Tuser_sp1);
+		p_time_psx(&systime, "sys ");
+	} else {
+		if (!(tf & TF_NOREAL)) {
+			timersub(&tv1, &tv0, &tv1);
+			p_time_ksh(&tv1, Treal_sp2);
+		}
+		p_time_ksh(&usrtime, Tuser_sp2);
+		p_time_ksh(&systime, " system\n");
 	}
-	if (tf & TF_POSIX)
-		p_time(shl_out, true, usrtime.tv_sec, usrtime.tv_usec,
-		    5, Tuser_sp1, "\n");
-	else
-		p_time(shl_out, false, usrtime.tv_sec, usrtime.tv_usec,
-		    5, null, Tuser_sp2);
-	if (tf & TF_POSIX)
-		p_time(shl_out, true, systime.tv_sec, systime.tv_usec,
-		    5, "sys  ", "\n");
-	else
-		p_time(shl_out, false, systime.tv_sec, systime.tv_usec,
-		    5, null, " system\n");
 	shf_flush(shl_out);
 
 	return (rv);
@@ -2449,11 +2455,13 @@ timex_hook(struct op *t, char **volatile
 			t->str[0] |= TF_POSIX;
 			break;
 		case '?':
-			errorf(Tf_optfoo, Ttime, Tcolsp,
-			    opt.optarg[0], Tunknown_option);
+			ksh_getopt_opterr(opt.optarg[0], Ttime,
+			    Tunknown_option);
+			unwind(LERROR);
 		case ':':
-			errorf(Tf_optfoo, Ttime, Tcolsp,
-			    opt.optarg[0], Treq_arg);
+			ksh_getopt_opterr(opt.optarg[0], Ttime,
+			    Treq_arg);
+			unwind(LERROR);
 		}
 	/* Copy command words down over options. */
 	if (opt.optind != 0) {
@@ -2472,22 +2480,35 @@ int
 c_exec(const char **wp MKSH_A_UNUSED)
 {
 	int i;
+	kui sfd;
+
+	if (e->savedfd == NULL)
+		return (0);
 
 	/* make sure redirects stay in place */
-	if (e->savefd != NULL) {
+
+	/* for ksh, keep file descriptors private (except stdin/out/err)… */
+	if (!Flag(FPOSIX) && !Flag(FSH)) {
 		for (i = 0; i < NUFILE; i++) {
-			if (e->savefd[i] > 0)
-				close(e->savefd[i]);
-			/*
-			 * keep all file descriptors > 2 private for ksh,
-			 * but not for POSIX or legacy/kludge sh
-			 */
-			if (!Flag(FPOSIX) && !Flag(FSH) && i > 2 &&
-			    e->savefd[i])
-				fcntl(i, F_SETFD, FD_CLOEXEC);
+			if (!(sfd = FDSVNUM(e, i)))
+				continue;
+			if (sfd > (kui)FDBASE)
+				close((int)sfd);
+			if (i > 2 && !(e->savedfd[i] & FDICLMASK) &&
+			    fcntl(i, F_SETFD, FD_CLOEXEC) == -1)
+				kwarnf0(KWF_INTERNAL | KWF_WARNING,
+				    Tcloexec_failed, "set", i);
+		}
+	} else {
+		/* … but not for POSIX or legacy/kludge sh */
+		for (i = 0; i < NUFILE; i++) {
+			sfd = FDSVNUM(e, i);
+			if (sfd > (kui)FDBASE)
+				close((int)sfd);
 		}
-		e->savefd = NULL;
 	}
+
+	e->savedfd = NULL;
 	return (0);
 }
 
@@ -2496,7 +2517,7 @@ int
 c_mknod(const char **wp)
 {
 	int argc, optc, rv = 0;
-	bool ismkfifo = false;
+	Wahr ismkfifo = Nee;
 	const char **argv;
 	void *set = NULL;
 	mode_t mode = 0, oldmode = 0;
@@ -2522,7 +2543,7 @@ c_mknod(const char **wp)
 	for (argc = 0; argv[argc]; argc++)
 		;
 	if (argc == 2 && argv[1][0] == 'p')
-		ismkfifo = true;
+		ismkfifo = Ja;
 	else if (argc != 4 || (argv[1][0] != 'b' && argv[1][0] != 'c'))
 		goto c_mknod_usage;
 
@@ -2541,21 +2562,21 @@ c_mknod(const char **wp)
 
 		majnum = strtoul(argv[2], &c, 0);
 		if ((c == argv[2]) || (*c != '\0')) {
-			bi_errorf(Tf_nonnum, "device", "major", argv[2]);
+			bi_errorf("%s: %s: %s", "major", "non-numeric", argv[2]);
 			goto c_mknod_err;
 		}
 		minnum = strtoul(argv[3], &c, 0);
 		if ((c == argv[3]) || (*c != '\0')) {
-			bi_errorf(Tf_nonnum, "device", "minor", argv[3]);
+			bi_errorf("%s: %s: %s", "minor", "non-numeric", argv[3]);
 			goto c_mknod_err;
 		}
 		dv = makedev(majnum, minnum);
 		if ((unsigned long)(major(dv)) != majnum) {
-			bi_errorf(Tf_toolarge, "device", "major", majnum);
+			bi_errorf(Tf_toolarge, "major", majnum);
 			goto c_mknod_err;
 		}
 		if ((unsigned long)(minor(dv)) != minnum) {
-			bi_errorf(Tf_toolarge, "device", "minor", minnum);
+			bi_errorf(Tf_toolarge, "minor", minnum);
 			goto c_mknod_err;
 		}
 		if (mknod(argv[0], mode, dv))
@@ -2650,7 +2671,7 @@ c_test(const char **wp)
 		}
 		if ((op = ptest_isa(&te, TM_UNOP))) {
  ptest_unary:
-			rv = test_eval(&te, op, *te.pos.wp++, NULL, true);
+			rv = test_eval(&te, op, *te.pos.wp++, NULL, Ja);
  ptest_out:
 			if (te.flags & TEF_ERROR)
 				return (T_ERR_EXIT);
@@ -2665,13 +2686,13 @@ c_test(const char **wp)
 		lhs = *te.pos.wp++;
 		if ((op = ptest_isa(&te, TM_BINOP))) {
 			/* test lhs op rhs */
-			rv = test_eval(&te, op, lhs, *te.pos.wp++, true);
+			rv = test_eval(&te, op, lhs, *te.pos.wp++, Ja);
 			goto ptest_out;
 		}
 		if (ptest_isa(&te, tm = TM_AND) || ptest_isa(&te, tm = TM_OR)) {
 			/* XSI */
-			argc = test_eval(&te, TO_STNZE, lhs, NULL, true);
-			rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, true);
+			argc = test_eval(&te, TO_STNZE, lhs, NULL, Ja);
+			rv = test_eval(&te, TO_STNZE, *te.pos.wp++, NULL, Ja);
 			if (tm == TM_AND)
 				rv = argc && rv;
 			else
@@ -2757,11 +2778,6 @@ test_isop(Test_meta meta, const char *s)
 #define test_lstat(name,buffer)	lstat((name), (buffer))
 #endif
 
-#if HAVE_ST_MTIM
-#undef st_mtimensec
-#define st_mtimensec st_mtim.tv_nsec
-#endif
-
 static int
 mtimecmp(const struct stat *sb1, const struct stat *sb2)
 {
@@ -2769,7 +2785,7 @@ mtimecmp(const struct stat *sb1, const s
 		return (-1);
 	if (sb1->st_mtime > sb2->st_mtime)
 		return (1);
-#if (HAVE_ST_MTIMENSEC || HAVE_ST_MTIM)
+#if HAVE_ST_MTIMENSEC
 	if (sb1->st_mtimensec < sb2->st_mtimensec)
 		return (-1);
 	if (sb1->st_mtimensec > sb2->st_mtimensec)
@@ -2780,7 +2796,7 @@ mtimecmp(const struct stat *sb1, const s
 
 int
 test_eval(Test_env *te, Test_op op, const char *opnd1, const char *opnd2,
-    bool do_eval)
+    Wahr do_eval)
 {
 	int i, s;
 	size_t k;
@@ -2835,7 +2851,7 @@ test_eval(Test_env *te, Test_op op, cons
 
 	/* -v */
 	case TO_ISSET:
-		return ((vp = isglobal(opnd1, false)) && (vp->flag & ISSET));
+		return ((vp = isglobal(opnd1, Nee)) && (vp->flag & ISSET));
 
 	/* -o */
 	case TO_OPTION:
@@ -2972,7 +2988,7 @@ test_eval(Test_env *te, Test_op op, cons
 	/* =, == */
 	case TO_STEQL:
 		if (te->flags & TEF_DBRACKET) {
-			if ((i = gmatchx(opnd1, opnd2, false)))
+			if ((i = gmatchx(opnd1, opnd2, Nee)))
 				record_match(opnd1);
 			return (i);
 		}
@@ -2981,7 +2997,7 @@ test_eval(Test_env *te, Test_op op, cons
 	/* != */
 	case TO_STNEQ:
 		if (te->flags & TEF_DBRACKET) {
-			if ((i = gmatchx(opnd1, opnd2, false)))
+			if ((i = gmatchx(opnd1, opnd2, Nee)))
 				record_match(opnd1);
 			return (!i);
 		}
@@ -3039,8 +3055,8 @@ test_eval(Test_env *te, Test_op op, cons
 	case TO_INTLE:
 	/* -lt */
 	case TO_INTLT:
-		if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, false) ||
-		    !evaluate(opnd2, &v2, KSH_RETURN_ERROR, false)) {
+		if (!evaluate(opnd1, &v1, KSH_RETURN_ERROR, Nee) ||
+		    !evaluate(opnd2, &v2, KSH_RETURN_ERROR, Nee)) {
 			/* error already printed.. */
 			te->flags |= TEF_ERROR;
 			return (1);
@@ -3082,31 +3098,31 @@ test_parse(Test_env *te)
 }
 
 static int
-test_oexpr(Test_env *te, bool do_eval)
+test_oexpr(Test_env *te, Wahr do_eval)
 {
 	int rv;
 
 	if ((rv = test_aexpr(te, do_eval)))
-		do_eval = false;
+		do_eval = Nee;
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_OR))
 		return (test_oexpr(te, do_eval) || rv);
 	return (rv);
 }
 
 static int
-test_aexpr(Test_env *te, bool do_eval)
+test_aexpr(Test_env *te, Wahr do_eval)
 {
 	int rv;
 
 	if (!(rv = test_nexpr(te, do_eval)))
-		do_eval = false;
+		do_eval = Nee;
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_AND))
 		return (test_aexpr(te, do_eval) && rv);
 	return (rv);
 }
 
 static int
-test_nexpr(Test_env *te, bool do_eval)
+test_nexpr(Test_env *te, Wahr do_eval)
 {
 	if (!(te->flags & TEF_ERROR) && (*te->isa)(te, TM_NOT))
 		return (!test_nexpr(te, do_eval));
@@ -3114,7 +3130,7 @@ test_nexpr(Test_env *te, bool do_eval)
 }
 
 static int
-test_primary(Test_env *te, bool do_eval)
+test_primary(Test_env *te, Wahr do_eval)
 {
 	const char *opnd1, *opnd2;
 	int rv;
@@ -3204,7 +3220,7 @@ ptest_isa(Test_env *te, Test_meta meta)
 }
 
 static const char *
-ptest_getopnd(Test_env *te, Test_op op, bool do_eval MKSH_A_UNUSED)
+ptest_getopnd(Test_env *te, Test_op op, Wahr do_eval MKSH_A_UNUSED)
 {
 	if (te->pos.wp >= te->wp_end)
 		return (op == TO_FILTT ? "1" : NULL);
@@ -3223,6 +3239,7 @@ ptest_error(Test_env *te, int ofs, const
 		bi_errorf(Tf_s, msg);
 }
 
+#if HAVE_RENAME
 int
 c_rename(const char **wp)
 {
@@ -3246,6 +3263,7 @@ c_rename(const char **wp)
 
 	return (rv);
 }
+#endif
 
 int
 c_realpath(const char **wp)
@@ -3276,167 +3294,6 @@ c_realpath(const char **wp)
 	return (rv);
 }
 
-int
-c_cat(const char **wp)
-{
-	int fd = 0, rv;
-	ssize_t n, w;
-	const char *fn = "<stdin>";
-	char *buf, *cp;
-	bool opipe;
-#define MKSH_CAT_BUFSIZ 4096
-
-	/* parse options: POSIX demands we support "-u" as no-op */
-	while ((rv = ksh_getopt(wp, &builtin_opt, Tu)) != -1) {
-		switch (rv) {
-		case 'u':
-			/* we already operate unbuffered */
-			break;
-		default:
-			bi_errorf(Tsynerr);
-			return (1);
-		}
-	}
-	wp += builtin_opt.optind;
-	rv = 0;
-
-	if ((buf = malloc_osfunc(MKSH_CAT_BUFSIZ)) == NULL) {
-		bi_errorf(Toomem, (size_t)MKSH_CAT_BUFSIZ);
-		return (1);
-	}
-
-	/* catch SIGPIPE */
-	opipe = block_pipe();
-
-	do {
-		if (*wp) {
-			fn = *wp++;
-			if (ksh_isdash(fn))
-				fd = 0;
-			else if ((fd = binopen2(fn, O_RDONLY)) < 0) {
-				bi_errorf(Tf_sD_s, fn, cstrerror(errno));
-				rv = 1;
-				continue;
-			}
-		}
-		while (/* CONSTCOND */ 1) {
-			if ((n = blocking_read(fd, (cp = buf),
-			    MKSH_CAT_BUFSIZ)) == -1) {
-				if (errno == EINTR) {
-					if (opipe)
-						restore_pipe();
-					/* give the user a chance to ^C out */
-					intrcheck();
-					/* interrupted, try again */
-					opipe = block_pipe();
-					continue;
-				}
-				/* an error occurred during reading */
-				bi_errorf(Tf_sD_s, fn, cstrerror(errno));
-				rv = 1;
-				break;
-			} else if (n == 0)
-				/* end of file reached */
-				break;
-			while (n) {
-				if (intrsig)
-					goto has_intrsig;
-				if ((w = write(1, cp, n)) != -1) {
-					n -= w;
-					cp += w;
-					continue;
-				}
-				if (errno == EINTR) {
- has_intrsig:
-					if (opipe)
-						restore_pipe();
-					/* give the user a chance to ^C out */
-					intrcheck();
-					/* interrupted, try again */
-					opipe = block_pipe();
-					continue;
-				}
-				if (errno == EPIPE) {
-					/* fake receiving signal */
-					rv = ksh_sigmask(SIGPIPE);
-				} else {
-					/* an error occurred during writing */
-					bi_errorf(Tf_sD_s, "<stdout>",
-					    cstrerror(errno));
-					rv = 1;
-				}
-				if (fd != 0)
-					close(fd);
-				goto out;
-			}
-		}
-		if (fd != 0)
-			close(fd);
-	} while (*wp);
-
- out:
-	if (opipe)
-		restore_pipe();
-	free_osfunc(buf);
-	return (rv);
-}
-
-#if HAVE_SELECT
-int
-c_sleep(const char **wp)
-{
-	struct timeval tv;
-	int rv = 1;
-
-	/* skip argv[0] */
-	++wp;
-	if (wp[0] && !strcmp(wp[0], "--"))
-		/* skip "--" (options separator) */
-		++wp;
-
-	if (!wp[0] || wp[1])
-		bi_errorf(Tsynerr);
-	else if (parse_usec(wp[0], &tv))
-		bi_errorf(Tf_sD_s_qs, Tsynerr, cstrerror(errno), wp[0]);
-	else {
-#ifndef MKSH_NOPROSPECTOFWORK
-		sigset_t omask, bmask;
-
-		/* block a number of signals from interrupting us, though */
-		(void)sigemptyset(&bmask);
-		(void)sigaddset(&bmask, SIGPIPE);
-		(void)sigaddset(&bmask, SIGCHLD);
-#ifdef SIGWINCH
-		(void)sigaddset(&bmask, SIGWINCH);
-#endif
-#ifdef SIGINFO
-		(void)sigaddset(&bmask, SIGINFO);
-#endif
-#ifdef SIGUSR1
-		(void)sigaddset(&bmask, SIGUSR1);
-#endif
-#ifdef SIGUSR2
-		(void)sigaddset(&bmask, SIGUSR2);
-#endif
-		sigprocmask(SIG_BLOCK, &bmask, &omask);
-#endif
-		if (select(1, NULL, NULL, NULL, &tv) == 0 || errno == EINTR)
-			/*
-			 * strictly speaking only for SIGALRM, but the
-			 * execution may be interrupted by other signals
-			 */
-			rv = 0;
-		else
-			bi_errorf(Tf_sD_s, Tselect, cstrerror(errno));
-#ifndef MKSH_NOPROSPECTOFWORK
-		/* this will re-schedule signal delivery */
-		sigprocmask(SIG_SETMASK, &omask, NULL);
-#endif
-	}
-	return (rv);
-}
-#endif
-
 #if !defined(MKSH_UNEMPLOYED) && HAVE_GETSID
 static int
 c_suspend(const char **wp)
--- mksh-59c.orig/histrap.c
+++ mksh-59c/histrap.c
@@ -3,7 +3,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019
+ *		 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019,
+ *		 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -23,14 +24,11 @@
  */
 
 #include "sh.h"
-#if HAVE_SYS_FILE_H
-#include <sys/file.h>
-#endif
+#include "mirhash.h"
 
-__RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.170 2020/10/01 22:53:20 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/histrap.c,v 1.190 2023/08/22 22:31:32 tg Exp $");
 
 Trap sigtraps[ksh_NSIG + 1];
-static struct sigaction Sigact_ign;
 
 #if HAVE_PERSISTENT_HISTORY
 static int histload(Source *, unsigned char *, size_t);
@@ -39,10 +37,10 @@ static void writehistfile(int, const cha
 #endif
 
 static int hist_execute(char *, Area *);
-static char **hist_get(const char *, bool, bool);
+static char **hist_get(const char *, Wahr, Wahr);
 static char **hist_get_oldest(void);
 
-static bool hstarted;		/* set after hist_init() called */
+static Wahr hstarted;		/* set after hist_init() called */
 static Source *hist_source;
 
 #if HAVE_PERSISTENT_HISTORY
@@ -86,8 +84,7 @@ c_fc(const char **wp)
 {
 	struct shf *shf;
 	struct temp *tf;
-	bool gflag = false, lflag = false, nflag = false, rflag = false,
-	    sflag = false;
+	Wahr gflag = Nee, lflag = Nee, nflag = Nee, rflag = Nee, sflag = Nee;
 	int optc;
 	const char *p, *first = NULL, *last = NULL;
 	char **hfirst, **hlast, **hp, *editor = NULL;
@@ -104,37 +101,37 @@ c_fc(const char **wp)
 		case 'e':
 			p = builtin_opt.optarg;
 			if (ksh_isdash(p))
-				sflag = true;
+				sflag = Ja;
 			else {
 				size_t len = strlen(p);
 
 				/* almost certainly not overflowing */
-				editor = alloc(len + 4, ATEMP);
+				editor = alloc(len + 6U, ATEMP);
 				memcpy(editor, p, len);
-				memcpy(editor + len, Tspdollaru, 4);
+				memcpy(editor + len, Tspdollaru, 6U);
 			}
 			break;
 
 		/* non-AT&T ksh */
 		case 'g':
-			gflag = true;
+			gflag = Ja;
 			break;
 
 		case 'l':
-			lflag = true;
+			lflag = Ja;
 			break;
 
 		case 'n':
-			nflag = true;
+			nflag = Ja;
 			break;
 
 		case 'r':
-			rflag = true;
+			rflag = Ja;
 			break;
 
 		/* POSIX version of -e - */
 		case 's':
-			sflag = true;
+			sflag = Ja;
 			break;
 
 		/* kludge city - accept -num as -- -num (kind of) */
@@ -181,8 +178,7 @@ c_fc(const char **wp)
 			return (1);
 		}
 
-		hp = first ? hist_get(first, false, false) :
-		    hist_get_newest(false);
+		hp = first ? hist_get(first, Nee, Nee) : hist_get_newest(Nee);
 		if (!hp)
 			return (1);
 		/* hist_replace */
@@ -193,14 +189,14 @@ c_fc(const char **wp)
 			size_t len, pat_len, rep_len;
 			XString xs;
 			char *xp;
-			bool any_subst = false;
+			Wahr any_subst = Nee;
 
 			pat_len = strlen(pat);
 			rep_len = strlen(rep);
 			Xinit(xs, xp, 128, ATEMP);
-			for (s = *hp; (s1 = strstr(s, pat)) &&
+			for (s = *hp; (s1 = ucstrstr(s, pat)) &&
 			    (!any_subst || gflag); s = s1 + pat_len) {
-				any_subst = true;
+				any_subst = Ja;
 				len = s1 - s;
 				XcheckN(xs, xp, len + rep_len);
 				/*; first part */
@@ -237,23 +233,22 @@ c_fc(const char **wp)
 		return (1);
 	}
 	if (!first) {
-		hfirst = lflag ? hist_get("-16", true, true) :
-		    hist_get_newest(false);
+		hfirst = lflag ? hist_get("-16", Ja, Ja) : hist_get_newest(Nee);
 		if (!hfirst)
 			return (1);
 		/* can't fail if hfirst didn't fail */
-		hlast = hist_get_newest(false);
+		hlast = hist_get_newest(Nee);
 	} else {
 		/*
 		 * POSIX says not an error if first/last out of bounds
 		 * when range is specified; AT&T ksh and pdksh allow out
 		 * of bounds for -l as well.
 		 */
-		hfirst = hist_get(first, tobool(lflag || last), lflag);
+		hfirst = hist_get(first, isWahr(lflag || last), lflag);
 		if (!hfirst)
 			return (1);
-		hlast = last ? hist_get(last, true, lflag) :
-		    (lflag ? hist_get_newest(false) : hfirst);
+		hlast = last ? hist_get(last, Ja, lflag) :
+		    (lflag ? hist_get_newest(Nee) : hfirst);
 		if (!hlast)
 			return (1);
 	}
@@ -278,7 +273,7 @@ c_fc(const char **wp)
 			shf_putc('\t', shl_stdout);
 			/* print multi-line commands correctly */
 			s = *hp;
-			while ((t = strchr(s, '\n'))) {
+			while ((t = ucstrchr(s, '\n'))) {
 				*t = '\0';
 				shf_fprintf(shl_stdout, "%s\n\t", s);
 				*t++ = '\n';
@@ -294,19 +289,19 @@ c_fc(const char **wp)
 
 	tf = maketemp(ATEMP, TT_HIST_EDIT, &e->temps);
 	if (!(shf = tf->shf)) {
-		bi_errorf(Tf_temp, Tcreate, tf->tffn, cstrerror(errno));
+		kwarnf0(KWF_BIERR, Tf_temp, Tcreate, tf->tffn);
 		return (1);
 	}
 	for (hp = rflag ? hlast : hfirst;
 	    hp >= hfirst && hp <= hlast; hp += rflag ? -1 : 1)
 		shf_fprintf(shf, Tf_sN, *hp);
 	if (shf_close(shf) == -1) {
-		bi_errorf(Tf_temp, Twrite, tf->tffn, cstrerror(errno));
+		kwarnf0(KWF_BIERR, Tf_temp, Twrite, tf->tffn);
 		return (1);
 	}
 
 	/* Ignore setstr errors here (arbitrary) */
-	setstr(local("_", false), tf->tffn, KSH_RETURN_ERROR);
+	setstr(local("_", Nee), tf->tffn, KSH_RETURN_ERROR);
 
 	if ((optc = command(editor ? editor : TFCEDIT_dollaru, 0)))
 		return (optc);
@@ -318,15 +313,15 @@ c_fc(const char **wp)
 		ssize_t n;
 
 		if (!(shf = shf_open(tf->tffn, O_RDONLY, 0, 0))) {
-			bi_errorf(Tf_temp, Topen, tf->tffn, cstrerror(errno));
+			kwarnf0(KWF_BIERR, Tf_temp, Topen, tf->tffn);
 			return (1);
 		}
 
 		if (stat(tf->tffn, &statb) < 0)
 			n = 128;
 		else if ((off_t)statb.st_size > MKSH_MAXHISTFSIZE) {
-			bi_errorf(Tf_toolarge, Thistory,
-			    Tfile, (unsigned long)statb.st_size);
+			bi_errorf(Tf_toolarge, Tfile,
+			    (unsigned long)statb.st_size);
 			goto errout;
 		} else
 			n = (size_t)statb.st_size + 1;
@@ -337,8 +332,8 @@ c_fc(const char **wp)
 				XcheckN(xs, xp, Xlength(xs, xp));
 		}
 		if (n < 0) {
-			bi_errorf(Tf_temp, Tread, tf->tffn,
-			    cstrerror(shf_errno(shf)));
+			kwarnf1(KWF_VERRNO | KWF_BIERR, shf_errno(shf),
+			    Tf_temp, Tread, tf->tffn);
  errout:
 			shf_close(shf);
 			return (1);
@@ -364,7 +359,7 @@ hist_execute(char *cmd, Area *areap)
 		last_line = hist_source->line;
 	}
 
-	histsave(&hist_source->line, cmd, HIST_STORE, true);
+	histsave(&hist_source->line, cmd, HIST_STORE, Ja);
 	/* now *histptr == cmd without all trailing newlines */
 	afree(cmd, areap);
 	cmd = *histptr;
@@ -386,7 +381,7 @@ hist_execute(char *cmd, Area *areap)
  * pattern is a number or string
  */
 static char **
-hist_get(const char *str, bool approx, bool allow_cur)
+hist_get(const char *str, Wahr approx, Wahr allow_cur)
 {
 	char **hp = NULL;
 	int n;
@@ -412,11 +407,10 @@ hist_get(const char *str, bool approx, b
 			hp = NULL;
 		}
 	} else {
-		bool anchored = *str == '?' ? (++str, false) : true;
+		Wahr anchd = *str == '?' ? (++str, Nee) : Ja;
 
 		/* the -1 is to avoid the current fc command */
-		if ((n = findhist(histptr - history - 1, str, false,
-		    anchored)) < 0)
+		if ((n = findhist(histptr - history - 1, str, Nee, anchd)) < 0)
 			bi_errorf(Tf_sD_s, str, Tnot_in_history);
 		else
 			hp = &history[n];
@@ -426,7 +420,7 @@ hist_get(const char *str, bool approx, b
 
 /* Return a pointer to the newest command in the history */
 char **
-hist_get_newest(bool allow_cur)
+hist_get_newest(Wahr allow_cur)
 {
 	if (histptr < history || (!allow_cur && histptr == history)) {
 		bi_errorf("no history (yet)");
@@ -480,7 +474,7 @@ histnum(int n)
  * direction.
  */
 int
-findhist(int start, const char *str, bool fwd, bool anchored)
+findhist(int start, const char *str, Wahr fwd, Wahr anchored)
 {
 	char **hp;
 	int maxhist = histptr - history;
@@ -493,7 +487,7 @@ findhist(int start, const char *str, boo
 	hp = &history[start];
 	for (; hp >= history && hp <= histptr; hp += incr)
 		if ((anchored && strncmp(*hp, str, len) == 0) ||
-		    (!anchored && strstr(*hp, str)))
+		    (!anchored && vstrstr(*hp, str)))
 			return (hp - history);
 
 	return (-1);
@@ -532,7 +526,7 @@ void
 sethistfile(const char *name)
 {
 	/* if not started then nothing to do */
-	if (hstarted == false)
+	if (!hstarted)
 		return;
 
 	/* if the name is the same as the name we have */
@@ -544,13 +538,13 @@ sethistfile(const char *name)
 	 */
 	if (histfd != -1) {
 		/* yes the file is open */
-		(void)close(histfd);
+		close(histfd);
 		histfd = -1;
 		histfsize = 0;
 		afree(hname, APERM);
 		hname = NULL;
 		/* let's reset the history */
-		histsave(NULL, NULL, HIST_DISCARD, true);
+		histsave(NULL, NULL, HIST_DISCARD, Ja);
 		histptr = history - 1;
 		hist_source->line = 0;
 	}
@@ -573,17 +567,16 @@ init_histvec(void)
 	}
 }
 
-
 /*
  * It turns out that there is a lot of ghastly hackery here
  */
 
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
 /* do not save command in history but possibly sync */
-bool
+Wahr
 histsync(void)
 {
-	bool changed = false;
+	Wahr changed = Nee;
 
 	/* called by histsave(), may not HIST_DISCARD, caller should flush */
 
@@ -595,7 +588,7 @@ histsync(void)
 		hist_source->line--;
 
 		if (lno != hist_source->line)
-			changed = true;
+			changed = Ja;
 	}
 
 	return (changed);
@@ -606,7 +599,7 @@ histsync(void)
  * save command in history
  */
 void
-histsave(int *lnp, const char *cmd, int svmode, bool ignoredups)
+histsave(int *lnp, const char *cmd, int svmode, Wahr ignoredups)
 {
 	static char *enqueued = NULL;
 	char **hp, *c;
@@ -625,7 +618,7 @@ histsave(int *lnp, const char *cmd, int
 		c = enqueued;
 		enqueued = NULL;
 		--*lnp;
-		histsave(lnp, c, HIST_STORE, true);
+		histsave(lnp, c, HIST_STORE, Ja);
 		afree(c, APERM);
 	}
 
@@ -669,7 +662,7 @@ histsave(int *lnp, const char *cmd, int
 
 		nenq = strlen(enqueued);
 		ncmd = strlen(c);
-		enqueued = aresize(enqueued, nenq + 1 + ncmd + 1, APERM);
+		enqueued = aresize1(enqueued, nenq + 1, ncmd + 1, APERM);
 		enqueued[nenq] = '\n';
 		memcpy(enqueued + nenq + 1, c, ncmd + 1);
 		afree(c, APERM);
@@ -788,8 +781,10 @@ hist_persist_init(void)
 	/* we have a file and are interactive */
 	if ((fd = binopen3(hname, O_RDWR | O_CREAT | O_APPEND, 0600)) < 0)
 		return;
-	if ((histfd = savefd(fd)) < 0)
+	if ((histfd = savefd(fd)) < 0) {
+		close(fd);
 		return;
+	}
 	if (histfd != fd)
 		close(fd);
 
@@ -827,7 +822,7 @@ hist_persist_init(void)
 				goto hist_trunc_dont;
 			}
 			if (fstat(histfd, &sb) >= 0 &&
-			    chown(nhname, sb.st_uid, sb.st_gid)) {
+			    fchown(fd, sb.st_uid, sb.st_gid)) {
 				/* abort the truncation then, meh. */
 				goto hist_trunc_abort;
 			}
@@ -870,7 +865,7 @@ hist_persist_init(void)
 			goto retry;
 		}
 		if (hs != hist_init_retry)
-			bi_errorf(Tf_cant_ss_s,
+			bi_errorf("can't %s %s: %s",
 			    "unlink HISTFILE", hname, cstrerror(errno));
 		histfsize = 0;
 		return;
@@ -892,12 +887,12 @@ hist_persist_init(void)
 void
 hist_init(Source *s)
 {
-	histsave(NULL, NULL, HIST_DISCARD, true);
+	histsave(NULL, NULL, HIST_DISCARD, Ja);
 
 	if (Flag(FTALKING) == 0)
 		return;
 
-	hstarted = true;
+	hstarted = Ja;
 	hist_source = s;
 
 #if HAVE_PERSISTENT_HISTORY
@@ -941,7 +936,7 @@ histload(Source *s, unsigned char *base,
 		}
 	} else {
 		s->line = lno--;
-		histsave(&lno, (char *)(base + 4), HIST_NOTE, false);
+		histsave(&lno, (char *)(base + 4), HIST_NOTE, Nee);
 	}
 	/* advance base pointer past NUL */
 	bytes -= ++cp - base;
@@ -1028,14 +1023,15 @@ hist_finish(void)
 {
 	if (histfd >= 0) {
 		mksh_unlkfd(histfd);
-		(void)close(histfd);
+		close(histfd);
 	}
 	histfd = -1;
 }
 #endif
 
+/* +++ signals +++ */
 
-#if !HAVE_SYS_SIGNAME
+#if !HAVE_SIGABBREV_NP && !HAVE_SYS_SIGNAME
 static const struct mksh_sigpair {
 	const char * const name;
 	int nr;
@@ -1045,18 +1041,12 @@ static const struct mksh_sigpair {
 };
 #endif
 
-#if HAVE_SYS_SIGLIST
-#if !HAVE_SYS_SIGLIST_DECL
-extern const char * const sys_siglist[];
-#endif
-#endif
-
 void
 inittraps(void)
 {
 	int i;
 	const char *cs;
-#if !HAVE_SYS_SIGNAME
+#if !HAVE_SIGABBREV_NP && !HAVE_SYS_SIGNAME
 	const struct mksh_sigpair *pair;
 #endif
 
@@ -1065,7 +1055,9 @@ inittraps(void)
 	/* populate sigtraps based on sys_signame and sys_siglist */
 	for (i = 1; i < ksh_NSIG; i++) {
 		sigtraps[i].signal = i;
-#if HAVE_SYS_SIGNAME
+#if HAVE_SIGABBREV_NP
+		cs = sigabbrev_np(i);
+#elif HAVE_SYS_SIGNAME
 		cs = sys_signame[i];
 #else
 		pair = mksh_sigpairs;
@@ -1080,9 +1072,9 @@ inittraps(void)
 			char *s;
 
 			/* this is not optimal, what about SIGSIG1? */
-			if (ksh_eq(cs[0], 'S', 's') &&
-			    ksh_eq(cs[1], 'I', 'i') &&
-			    ksh_eq(cs[2], 'G', 'g') &&
+			if (isCh(cs[0], 'S', 's') &&
+			    isCh(cs[1], 'I', 'i') &&
+			    isCh(cs[2], 'G', 'g') &&
 			    cs[3] != '\0') {
 				/* skip leading "SIG" */
 				cs += 3;
@@ -1095,23 +1087,16 @@ inittraps(void)
 			if (!strcmp(sigtraps[i].name, "EXIT") ||
 			    !strcmp(sigtraps[i].name, "ERR")) {
 #ifndef MKSH_SMALL
-				internal_warningf(Tinvname, sigtraps[i].name,
-				    "signal");
+				kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+				    Tinvname, sigtraps[i].name, "signal");
 #endif
 				sigtraps[i].name = null;
 			}
 		}
 		if (sigtraps[i].name == null)
 			sigtraps[i].name = shf_smprintf(Tf_d, i);
-#if HAVE_SYS_SIGLIST
-		sigtraps[i].mess = sys_siglist[i];
-#elif HAVE_STRSIGNAL
-		sigtraps[i].mess = strsignal(i);
-#else
-		sigtraps[i].mess = NULL;
-#endif
-		if ((sigtraps[i].mess == NULL) ||
-		    (sigtraps[i].mess[0] == '\0'))
+		sigtraps[i].mess = ksh_sigmess(i);
+		if (ksh_sigmessf(sigtraps[i].mess))
 			sigtraps[i].mess = shf_smprintf(Tf_sd,
 			    "Signal", i);
 	}
@@ -1122,10 +1107,6 @@ inittraps(void)
 	sigtraps[ksh_SIGERR].name = "ERR";
 	sigtraps[ksh_SIGERR].mess = "Error handler";
 
-	(void)sigemptyset(&Sigact_ign.sa_mask);
-	Sigact_ign.sa_flags = 0; /* interruptible */
-	Sigact_ign.sa_handler = SIG_IGN;
-
 	sigtraps[SIGINT].flags |= TF_DFL_INTR | TF_TTY_INTR;
 	sigtraps[SIGQUIT].flags |= TF_DFL_INTR | TF_TTY_INTR;
 	/* SIGTERM is not fatal for interactive */
@@ -1168,7 +1149,7 @@ alarm_catcher(int sig MKSH_A_UNUSED)
 }
 
 Trap *
-gettrap(const char *cs, bool igncase, bool allsigs)
+gettrap(const char *cs, Wahr igncase, Wahr allsigs)
 {
 	int i;
 	Trap *p;
@@ -1183,9 +1164,9 @@ gettrap(const char *cs, bool igncase, bo
 	/* do a lookup by name then */
 
 	/* this breaks SIGSIG1, but we do that above anyway */
-	if (ksh_eq(cs[0], 'S', 's') &&
-	    ksh_eq(cs[1], 'I', 'i') &&
-	    ksh_eq(cs[2], 'G', 'g') &&
+	if (isCh(cs[0], 'S', 's') &&
+	    isCh(cs[1], 'I', 'i') &&
+	    isCh(cs[2], 'G', 'g') &&
 	    cs[3] != '\0') {
 		/* skip leading "SIG" */
 		cs += 3;
@@ -1222,15 +1203,48 @@ gettrap(const char *cs, bool igncase, bo
 	return (p);
 }
 
+static k32
+traphash(int signo, int extra)
+{
+	register k32 h;
+	static volatile k32 state;
+	k32 o;
+	struct {
+		struct timeval tv;
+		void *sp;
+		int i;
+		int j;
+	} z;
+
+	memset(&z, 0, sizeof(z));
+	mksh_TIME(z.tv);
+	z.sp = &z;
+	z.i = signo;
+	z.j = extra;
+
+	o = state;
+	h = o ? o : (k32)1U;
+	BAFHUpdateMem(h, &z, sizeof(z));
+	while (state != o) {
+		o = state;
+		BAFHUpdateMem(h, &o, sizeof(o));
+	}
+	state = h;
+	return (h);
+}
+
 /*
  * trap signal handler
  */
 void
 trapsig(int i)
 {
-	Trap *p = &sigtraps[i];
-	int eno = errno;
+	Trap *p;
+	int eno;
 
+	eno = errno;
+	traphash(i, eno);
+	p = &sigtraps[i];
 	trap = p->set = 1;
 	if (p->flags & TF_DFL_INTR)
 		intrsig = 1;
@@ -1303,10 +1317,15 @@ runtraps(int flag)
 {
 	Trap *p = sigtraps;
 	int i = ksh_NSIG + 1;
+	k32 h;
+
+	h = traphash(-666, (int)ksh_tmout_state);
+	rndpush(&h, sizeof(h));
 
 	if (ksh_tmout_state == TMOUT_LEAVING) {
 		ksh_tmout_state = TMOUT_EXECUTING;
-		warningf(false, "timed out waiting for input");
+		kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
+		    "timed out waiting for input");
 		unwind(LEXIT);
 	} else
 		/*
@@ -1324,15 +1343,15 @@ runtraps(int flag)
 	do {
 		if (p->set && (!flag ||
 		    ((p->flags & flag) && p->trap == NULL)))
-			runtrap(p, false);
+			runtrap(p, Nee);
 		++p;
 	} while (--i);
 	if (!--trap_nested)
-		runtrap(NULL, true);
+		runtrap(NULL, Ja);
 }
 
 void
-runtrap(Trap *p, bool is_last)
+runtrap(Trap *p, Wahr is_last)
 {
 	int old_changed = 0, i;
 	char *trapstr;
@@ -1464,20 +1483,20 @@ settrap(Trap *p, const char *s)
  * called by c_print() when writing to a co-process to ensure
  * SIGPIPE won't kill shell (unless user catches it and exits)
  */
-bool
+Wahr
 block_pipe(void)
 {
-	bool restore_dfl = false;
+	Wahr restore_dfl = Nee;
 	Trap *p = &sigtraps[SIGPIPE];
 
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
 		if (p->flags & TF_ORIG_DFL)
-			restore_dfl = true;
+			restore_dfl = Ja;
 	} else if (p->cursig == SIG_DFL) {
 		setsig(p, SIG_IGN, SS_RESTORE_CURR);
 		/* restore to SIG_DFL */
-		restore_dfl = true;
+		restore_dfl = Ja;
 	}
 	return (restore_dfl);
 }
@@ -1496,20 +1515,18 @@ restore_pipe(void)
 int
 setsig(Trap *p, sig_t f, int flags)
 {
-	struct sigaction sigact;
-
 	if (p->signal == ksh_SIGEXIT || p->signal == ksh_SIGERR)
 		return (1);
 
-	memset(&sigact, 0, sizeof(sigact));
-
 	/*
 	 * First time setting this signal? If so, get and note the current
 	 * setting.
 	 */
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL))) {
-		sigaction(p->signal, &Sigact_ign, &sigact);
-		p->flags |= sigact.sa_handler == SIG_IGN ?
+		ksh_sigsaved ohandler;
+
+		ksh_sigset(p->signal, SIG_IGN, &ohandler);
+		p->flags |= ksh_sighandler(ohandler) == SIG_IGN ?
 		    TF_ORIG_IGN : TF_ORIG_DFL;
 		p->cursig = SIG_IGN;
 	}
@@ -1540,11 +1557,7 @@ setsig(Trap *p, sig_t f, int flags)
 
 	if (p->cursig != f) {
 		p->cursig = f;
-		(void)sigemptyset(&sigact.sa_mask);
-		/* interruptible */
-		sigact.sa_flags = 0;
-		sigact.sa_handler = f;
-		sigaction(p->signal, &sigact, NULL);
+		ksh_sigset(p->signal, f, NULL);
 	}
 
 	return (1);
@@ -1556,8 +1569,8 @@ setexecsig(Trap *p, int restore)
 {
 	/* XXX debugging */
 	if (!(p->flags & (TF_ORIG_IGN|TF_ORIG_DFL)))
-		internal_errorf("setexecsig: unset signal %d(%s)",
-		    p->signal, p->name);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    "setexecsig: unset signal %d(%s)", p->signal, p->name);
 
 	/* restore original value for exec'd kids */
 	p->flags &= ~(TF_EXEC_IGN|TF_EXEC_DFL);
@@ -1590,7 +1603,7 @@ mksh_lockfd(int fd)
 {
 #if defined(__OpenBSD__)
 	/* flock is not interrupted by signals */
-	(void)flock(fd, LOCK_EX);
+	flock(fd, LOCK_EX);
 #elif HAVE_FLOCK
 	int rv;
 
@@ -1615,7 +1628,7 @@ mksh_lockfd(int fd)
 void
 mksh_unlkfd(int fd)
 {
-	(void)flock(fd, LOCK_UN);
+	flock(fd, LOCK_UN);
 }
 #elif HAVE_LOCK_FCNTL
 void
@@ -1625,7 +1638,76 @@ mksh_unlkfd(int fd)
 
 	memset(&lks, 0, sizeof(lks));
 	lks.l_type = F_UNLCK;
-	(void)fcntl(fd, F_SETLKW, &lks);
+	fcntl(fd, F_SETLKW, &lks);
 }
 #endif
 #endif
+
+/*
+ * On handling errors when setting signals
+ *
+ * The signal management calls fail with:
+ * - EFAULT: (sigaction only) &sa or old point to invalid memory,
+ *   which is not bloody likely
+ * - E?????: (sigaction only) if SA_SIGINFO is set and […]
+ *   but we don’t ever set SA_SIGINFO
+ * - EINVAL: on invalid signal number; operating on uncatchable
+ *   respectively unignorable signals (SIGKILL, SIGSTOP)
+ *
+ * The signal number is already verified in higher-up code. We
+ * deliberately do not error nor even warn for SIGKILL or SIGSTOP
+ * because startx on Debian for example attempts that (POSIX says
+ * undefined); therefore silently ignoring invalid signal numbers
+ * that otherwise pass muster is acceptable.
+ */
+
+#if HAVE_SIGACTION
+#ifndef SIG_ERR
+static void
+ksh_sigerr(int sig MKSH_A_UNUSED)
+{
+}
+#define SIG_ERR (&ksh_sigerr)
+#endif
+
+/* masks the signal, does not (may) restart, not oneshot */
+void
+ksh_sigset(int sig, sig_t act, ksh_sigsaved *old)
+{
+	int rv;
+
+	if (act != SIG_ERR) {
+		struct sigaction sa;
+
+		memset(&sa, '\0', sizeof(sa));
+		sigemptyset(&sa.sa_mask);
+		sa.sa_handler = act;
+		rv = sigaction(sig, &sa, old);
+	} else if (!old)
+		return;
+	else
+		rv = sigaction(sig, NULL, old);
+	if (rv && old) {
+		memset(old, '\0', sizeof(*old));
+		old->sa_handler = SIG_ERR;
+	}
+}
+
+void
+ksh_sigrestore(int sig, ksh_sigsaved *savedp)
+{
+	if (savedp->sa_handler != SIG_ERR)
+		sigaction(sig, savedp, NULL);
+}
+#elif defined(MKSH_USABLE_SIGNALFUNC)
+/* masks the signal, may (probably will, not always) restart, not oneshot */
+void
+ksh_sigset(int sig, sig_t act, ksh_sigsaved *old)
+{
+	sig_t res;
+
+	res = act == SIG_ERR ? SIG_ERR : MKSH_USABLE_SIGNALFUNC(sig, act);
+	if (old)
+		*old = res;
+}
+#endif
--- mksh-59c.orig/jobs.c
+++ mksh-59c/jobs.c
@@ -2,7 +2,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
- *		 2012, 2013, 2014, 2015, 2016, 2018, 2019
+ *		 2012, 2013, 2014, 2015, 2016, 2018, 2019, 2021,
+ *		 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -23,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.128 2019/12/11 19:46:20 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/jobs.c,v 1.162 2024/04/02 03:33:48 tg Exp $");
 
 #if HAVE_KILLPG
 #define mksh_killpg		killpg
@@ -38,28 +39,30 @@ __RCSID("$MirOS: src/bin/mksh/jobs.c,v 1
 #define PSIGNALLED	2
 #define PSTOPPED	3
 
+#define PROC_TGTSZ	256U
+
 typedef struct proc Proc;
 /* to take alignment into consideration */
 struct proc_dummy {
 	Proc *next;
-	pid_t pid;
 	int state;
 	int status;
-	char command[128];
+	pid_t pid;
+	char command[PROC_TGTSZ - (ALLOC_OVERHEAD + 14U)];
 };
+#define PROC_OFS (offsetof(struct proc_dummy, command))
 /* real structure */
 struct proc {
 	/* next process in pipeline (if any) */
 	Proc *next;
-	/* process id of this Unix process in the job */
-	pid_t pid;
 	/* one of the four P… above */
 	int state;
 	/* wait status */
 	int status;
+	/* process ID of this Unix process in the job */
+	pid_t pid;
 	/* process command string from vistree */
-	char command[256 - (ALLOC_OVERHEAD +
-	    offsetof(struct proc_dummy, command[0]))];
+	char command[PROC_TGTSZ - (ALLOC_OVERHEAD + PROC_OFS)];
 };
 
 /* Notify/print flag - j_print() argument */
@@ -120,6 +123,8 @@ struct job {
 #define JL_AMBIG	1	/* %foo or %?foo is ambiguous */
 #define JL_INVALID	2	/* non-pid, non-% job id */
 
+const char Tpipest[] = "PIPESTATUS";
+
 static const char * const lookup_msgs[] = {
 	"no such job",
 	"ambiguous",
@@ -145,7 +150,7 @@ static volatile sig_atomic_t held_sigchl
 
 #ifndef MKSH_UNEMPLOYED
 static struct shf	*shl_j;
-static bool		ttypgrp_ok;	/* set if can use tty pgrps */
+static Wahr		ttypgrp_ok;	/* set if can use tty pgrps */
 static pid_t		restore_ttypgrp = -1;
 static int const	tt_sigs[] = { SIGTSTP, SIGTTIN, SIGTTOU };
 #endif
@@ -166,16 +171,19 @@ static int		kill_job(Job *, int);
 static void tty_init_talking(void);
 static void tty_init_state(void);
 
+static void vistree(char *, size_t, struct op *)
+    MKSH_A_BOUNDED(__string__, 1, 2);
+
 /* initialise job control */
 void
 j_init(void)
 {
 #ifndef MKSH_NOPROSPECTOFWORK
-	(void)sigemptyset(&sm_default);
+	sigemptyset(&sm_default);
 	sigprocmask(SIG_SETMASK, &sm_default, NULL);
 
-	(void)sigemptyset(&sm_sigchld);
-	(void)sigaddset(&sm_sigchld, SIGCHLD);
+	sigemptyset(&sm_sigchld);
+	sigaddset(&sm_sigchld, SIGCHLD);
 
 	setsig(&sigtraps[SIGCHLD], j_sigchld,
 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
@@ -227,6 +235,7 @@ proc_errorlevel(Proc *p)
 	case PEXITED:
 		return ((WEXITSTATUS(p->status)) & 255);
 	case PSIGNALLED:
+		/* coverity[result_independent_of_operands : SUPPRESS] */
 		return (ksh_sigmask(WTERMSIG(p->status)));
 	default:
 		return (0);
@@ -238,7 +247,7 @@ proc_errorlevel(Proc *p)
 void
 j_suspend(void)
 {
-	struct sigaction sa, osa;
+	ksh_sigsaved ohandler;
 
 	/* Restore tty and pgrp. */
 	if (ttypgrp_ok) {
@@ -246,34 +255,31 @@ j_suspend(void)
 			mksh_tcset(tty_fd, &tty_state);
 		if (restore_ttypgrp >= 0) {
 			if (tcsetpgrp(tty_fd, restore_ttypgrp) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "tcsetpgrp");
 			} else if (setpgid(0, restore_ttypgrp) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "setpgid", cstrerror(errno));
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "setpgid");
 			}
 		}
 	}
 
 	/* Suspend the shell. */
-	memset(&sa, 0, sizeof(sa));
-	sigemptyset(&sa.sa_mask);
-	sa.sa_handler = SIG_DFL;
-	sigaction(SIGTSTP, &sa, &osa);
+	ksh_sigset(SIGTSTP, SIG_DFL, &ohandler);
 	kill(0, SIGTSTP);
 
 	/* Back from suspend, reset signals, pgrp and tty. */
-	sigaction(SIGTSTP, &osa, NULL);
+	ksh_sigrestore(SIGTSTP, &ohandler);
 	if (ttypgrp_ok) {
 		if (restore_ttypgrp >= 0) {
 			if (setpgid(0, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "setpgid", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "setpgid");
+				ttypgrp_ok = Nee;
 			} else if (tcsetpgrp(tty_fd, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    Tj_suspend, "tcsetpgrp", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    Tj_suspend, "tcsetpgrp");
+				ttypgrp_ok = Nee;
 			}
 		}
 		tty_init_state();
@@ -287,7 +293,7 @@ j_exit(void)
 {
 	/* kill stopped, and possibly running, jobs */
 	Job *j;
-	bool killed = false;
+	Wahr killed = Nee;
 
 	for (j = job_list; j != NULL; j = j->next) {
 		if (j->ppid == procpid &&
@@ -295,7 +301,7 @@ j_exit(void)
 		    (j->state == PRUNNING &&
 		    ((j->flags & JF_FG) ||
 		    (Flag(FLOGIN) && !Flag(FNOHUP) && procpid == kshpid))))) {
-			killed = true;
+			killed = Ja;
 			if (j->pgrp == 0)
 				kill_job(j, SIGHUP);
 			else
@@ -342,14 +348,13 @@ j_change(void)
 	int i;
 
 	if (Flag(FMONITOR)) {
-		bool use_tty = Flag(FTALKING);
-
 		/* don't call mksh_tcget until we own the tty process group */
-		if (use_tty)
+		if (Flag(FTALKING))
 			tty_init_talking();
 
 		/* no controlling tty, no SIGT* */
-		if ((ttypgrp_ok = (use_tty && tty_fd >= 0 && tty_devtty))) {
+		ttypgrp_ok = (Flag(FTALKING) && tty_fd >= 0 && tty_devtty);
+		if (ttypgrp_ok) {
 			setsig(&sigtraps[SIGTTIN], SIG_DFL,
 			    SS_RESTORE_ORIG|SS_FORCE);
 			/* wait to be given tty (POSIX.1, B.2, job control) */
@@ -357,10 +362,9 @@ j_change(void)
 				pid_t ttypgrp;
 
 				if ((ttypgrp = tcgetpgrp(tty_fd)) < 0) {
-					warningf(false, Tf_ssfaileds,
-					    "j_init", "tcgetpgrp",
-					    cstrerror(errno));
-					ttypgrp_ok = false;
+					kwarnf0(KWF_PREFIX, Tf_ssfailed,
+					    "j_init", "tcgetpgrp");
+					ttypgrp_ok = Nee;
 					break;
 				}
 				if (ttypgrp == kshpgrp)
@@ -373,27 +377,26 @@ j_change(void)
 			    SS_RESTORE_DFL|SS_FORCE);
 		if (ttypgrp_ok && kshpgrp != kshpid) {
 			if (setpgid(0, kshpid) < 0) {
-				warningf(false, Tf_ssfaileds,
-				    "j_init", "setpgid", cstrerror(errno));
-				ttypgrp_ok = false;
+				kwarnf0(KWF_PREFIX, Tf_ssfailed,
+				    "j_init", "setpgid");
+				ttypgrp_ok = Nee;
 			} else {
 				if (tcsetpgrp(tty_fd, kshpid) < 0) {
-					warningf(false, Tf_ssfaileds,
-					    "j_init", "tcsetpgrp",
-					    cstrerror(errno));
-					ttypgrp_ok = false;
+					kwarnf0(KWF_PREFIX, Tf_ssfailed,
+					    "j_init", "tcsetpgrp");
+					ttypgrp_ok = Nee;
 				} else
 					restore_ttypgrp = kshpgrp;
 				kshpgrp = kshpid;
 			}
 		}
 #ifndef MKSH_DISABLE_TTY_WARNING
-		if (use_tty && !ttypgrp_ok)
-			warningf(false, Tf_sD_s, "warning",
+		if (Flag(FTALKING) && !ttypgrp_ok)
+			kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
 			    "won't have full job control");
 #endif
 	} else {
-		ttypgrp_ok = false;
+		ttypgrp_ok = Nee;
 		if (Flag(FTALKING))
 			for (i = NELEM(tt_sigs); --i >= 0; )
 				setsig(&sigtraps[tt_sigs[i]], SIG_IGN,
@@ -408,7 +411,10 @@ j_change(void)
 					    SS_RESTORE_ORIG|SS_FORCE);
 			}
 	}
-	tty_init_state();
+	if (Flag(FTALKING))
+		tty_init_state();
+	else
+		tty_hasstate = Nee;
 }
 #endif
 
@@ -423,9 +429,9 @@ ksh_nice(int ness)
 	errno = 0;
 	/* this is gonna annoy users; complain to your distro, people! */
 	if (nice(ness) == -1 && (eno = errno) != 0)
-		warningf(false, Tf_sD_s, "bgnice", cstrerror(eno));
+		kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_ONEMSG, eno, "bgnice");
 #else
-	(void)nice(ness);
+	nice(ness);
 #endif
 }
 #endif
@@ -441,6 +447,7 @@ exchild(struct op *t, int flags,
 	static Proc *last_proc;
 
 	int rv = 0, forksleep, jwflags = JW_NONE;
+	int eno = /* stupid GCC */ 0;
 #ifndef MKSH_NOPROSPECTOFWORK
 	sigset_t omask;
 #endif
@@ -475,8 +482,9 @@ exchild(struct op *t, int flags,
 	if (flags & XPIPEI) {
 		/* continuing with a pipe */
 		if (!last_job)
-			internal_errorf("exchild: XPIPEI and no last_job - pid %d",
-			    (int)procpid);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    "exchild: XPIPEI and no last_job - pid %ld",
+			    (long)procpid);
 		j = last_job;
 		if (last_proc)
 			last_proc->next = p;
@@ -507,15 +515,14 @@ exchild(struct op *t, int flags,
 
 	/* create child process */
 	forksleep = 1;
-	while ((cldpid = fork()) < 0 && errno == EAGAIN && forksleep < 32) {
+	while ((cldpid = fork()) < 0 && (eno = errno) == EAGAIN &&
+	    forksleep < 32) {
 		if (intrsig)
 			/* allow user to ^C out... */
 			break;
 		sleep(forksleep);
 		forksleep <<= 1;
 	}
-	/* ensure $RANDOM changes between parent and child */
-	rndset((unsigned long)cldpid);
 	/* fork failed? */
 	if (cldpid < 0) {
 		kill_job(j, SIGKILL);
@@ -523,19 +530,22 @@ exchild(struct op *t, int flags,
 #ifndef MKSH_NOPROSPECTOFWORK
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
-		errorf("can't fork - try again");
+		kerrf(KWF_VERRNO | KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_ONEMSG, eno, "can't fork - try again");
 	}
 	p->pid = cldpid ? cldpid : (procpid = getpid());
+	/* ensure $RANDOM changes between parent and child */
+	rndset((unsigned long)cldpid);
 
 #ifndef MKSH_UNEMPLOYED
 	/* job control set up */
 	if (Flag(FMONITOR) && !(flags&XXCOM)) {
-		bool dotty = false;
+		Wahr dotty = Nee;
 
 		if (j->pgrp == 0) {
 			/* First process */
 			j->pgrp = p->pid;
-			dotty = true;
+			dotty = Ja;
 		}
 
 		/*
@@ -557,7 +567,7 @@ exchild(struct op *t, int flags,
 
 		/* Do this before restoring signal */
 		if (flags & XCOPROC)
-			coproc_cleanup(false);
+			coproc_cleanup(Nee);
 		cleanup_parents_env();
 #ifndef MKSH_UNEMPLOYED
 		/*
@@ -585,8 +595,8 @@ exchild(struct op *t, int flags,
 			setsig(&sigtraps[SIGQUIT], SIG_IGN,
 			    SS_RESTORE_IGN|SS_FORCE);
 			if ((!(flags & (XPIPEI | XCOPROC))) &&
-			    ((forksleep = open("/dev/null", 0)) > 0)) {
-				(void)ksh_dup2(forksleep, 0, true);
+			    ((forksleep = open("/dev/null", 0, 0)) > 0)) {
+				ksh_dup2(forksleep, 0, Ja);
 				close(forksleep);
 			}
 		}
@@ -598,7 +608,7 @@ exchild(struct op *t, int flags,
 #endif
 		nzombie = 0;
 #ifndef MKSH_UNEMPLOYED
-		ttypgrp_ok = false;
+		ttypgrp_ok = Nee;
 		Flag(FMONITOR) = 0;
 #endif
 		Flag(FTALKING) = 0;
@@ -608,7 +618,8 @@ exchild(struct op *t, int flags,
 #ifndef MKSH_SMALL
 		if (t->type == TPIPE)
 			unwind(LLEAVE);
-		internal_warningf("%s: execute() returned", "exchild");
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG,
+		    "exchild", "execute() returned");
 		fptreef(shl_out, 8, "%s: tried to execute {\n\t%T\n}\n",
 		    "exchild", t);
 		shf_flush(shl_out);
@@ -635,7 +646,7 @@ exchild(struct op *t, int flags,
 				for (p = j->proc_list; p; p = p->next)
 					shf_fprintf(shl_out, Tf__d,
 					    (int)p->pid);
-				shf_putchar('\n', shl_out);
+				shf_putc('\n', shl_out);
 				shf_flush(shl_out);
 			}
 		} else
@@ -685,9 +696,11 @@ waitlast(void)
 	j = last_job;
 	if (!j || !(j->flags & JF_STARTED)) {
 		if (!j)
-			warningf(true, Tf_sD_s, "waitlast", "no last job");
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+			    KWF_NOERRNO, "waitlast", "no last job");
 		else
-			internal_warningf(Tf_sD_s, "waitlast", Tnot_started);
+			kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+			    "waitlast", Tnot_started);
 #ifndef MKSH_NOPROSPECTOFWORK
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
@@ -817,7 +830,7 @@ j_resume(const char *cp, int bg)
 	Job *j;
 	Proc *p;
 	int ecode, rv = 0;
-	bool running;
+	Wahr running;
 	sigset_t omask;
 
 	sigprocmask(SIG_BLOCK, &sm_sigchld, &omask);
@@ -834,19 +847,21 @@ j_resume(const char *cp, int bg)
 		return (1);
 	}
 
-	if (bg)
-		shprintf("[%d] ", j->job);
+	if (bg) {
+		shprintf("[%d]", j->job);
+		shf_putc(' ', shl_stdout);
+	}
 
-	running = false;
+	running = Nee;
 	for (p = j->proc_list; p != NULL; p = p->next) {
 		if (p->state == PSTOPPED) {
 			p->state = PRUNNING;
 			p->status = 0;
-			running = true;
+			running = Ja;
 		}
 		shf_puts(p->command, shl_stdout);
 		if (p->next)
-			shf_puts("| ", shl_stdout);
+			shf_puts(" | ", shl_stdout);
 	}
 	shf_putc('\n', shl_stdout);
 	shf_flush(shl_stdout);
@@ -869,11 +884,10 @@ j_resume(const char *cp, int bg)
 				if (j->flags & JF_SAVEDTTY)
 					mksh_tcset(tty_fd, &tty_state);
 				sigprocmask(SIG_SETMASK, &omask, NULL);
-				bi_errorf(Tf_ldfailed,
-				    "fg: 1st", "tcsetpgrp", tty_fd,
+				kwarnf1(KWF_VERRNO | KWF_BIERR, rv,
+				    Tf_ldfailed, Tfirst, tty_fd,
 				    (long)((j->flags & JF_SAVEDTTYPGRP) ?
-				    j->saved_ttypgrp : j->pgrp),
-				    cstrerror(rv));
+				    j->saved_ttypgrp : j->pgrp));
 				return (1);
 			}
 		}
@@ -891,9 +905,9 @@ j_resume(const char *cp, int bg)
 			if (ttypgrp_ok && (j->flags & JF_SAVEDTTY))
 				mksh_tcset(tty_fd, &tty_state);
 			if (ttypgrp_ok && tcsetpgrp(tty_fd, kshpgrp) < 0)
-				warningf(true, Tf_ldfailed,
-				    "fg: 2nd", "tcsetpgrp", tty_fd,
-				    (long)kshpgrp, cstrerror(errno));
+				kwarnf0(KWF_PREFIX | KWF_FILELINE,
+				    Tf_ldfailed, "second", tty_fd,
+				    (long)kshpgrp);
 		}
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 		bi_errorf(Tf_s_sD_s, "can't continue job",
@@ -938,7 +952,6 @@ j_stopped_running(void)
 	return (0);
 }
 
-
 /* list jobs for jobs built-in */
 int
 j_jobs(const char *cp, int slp,
@@ -1065,7 +1078,8 @@ j_set_async(Job *j)
 	if (async_job && (async_job->flags & (JF_KNOWN|JF_ZOMBIE)) == JF_ZOMBIE)
 		remove_job(async_job, "async");
 	if (!(j->flags & JF_STARTED)) {
-		internal_warningf(Tf_sD_s, "j_async", Tjob_not_started);
+		kwarnf(KWF_INTERNAL | KWF_WARNING | KWF_TWOMSG | KWF_NOERRNO,
+		    "j_async", Tjob_not_started);
 		return;
 	}
 	async_job = j;
@@ -1077,10 +1091,11 @@ j_set_async(Job *j)
 			    (!oldest || jl->age < oldest->age))
 				oldest = jl;
 		if (!oldest) {
-			/* XXX debugging */
 			if (!(async_job->flags & JF_ZOMBIE) || nzombie != 1) {
-				internal_warningf("%s: bad nzombie (%d)",
-				    "j_async", nzombie);
+#ifdef DEBUG
+				kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+				    "%s: bad nzombie (%d)", "j_async", nzombie);
+#endif
 				nzombie = 0;
 			}
 			break;
@@ -1126,7 +1141,7 @@ j_waitj(Job *j,
 {
 	Proc *p;
 	int rv;
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigset_t omask;
 #endif
 
@@ -1147,7 +1162,11 @@ j_waitj(Job *j,
 #ifndef MKSH_NOPROSPECTOFWORK
 #ifdef MKSH_NO_SIGSUSPEND
 		sigprocmask(SIG_SETMASK, &sm_default, &omask);
+#ifdef MKSH_POLL_FOR_PAUSE
+		poll(NULL, 0, -1);
+#else
 		pause();
+#endif
 		/* note that handlers may run here so they need to know */
 		sigprocmask(SIG_SETMASK, &omask, NULL);
 #else
@@ -1189,9 +1208,9 @@ j_waitj(Job *j,
 			    (j->saved_ttypgrp = tcgetpgrp(tty_fd)) >= 0)
 				j->flags |= JF_SAVEDTTYPGRP;
 			if (tcsetpgrp(tty_fd, kshpgrp) < 0)
-				warningf(true, Tf_ldfailed,
-				    "j_waitj:", "tcsetpgrp", tty_fd,
-				    (long)kshpgrp, cstrerror(errno));
+				kwarnf0(KWF_PREFIX | KWF_FILELINE,
+				    Tf_ldfailed, "wait", tty_fd,
+				    (long)kshpgrp);
 			if (j->state == PSTOPPED) {
 				j->flags |= JF_SAVEDTTY;
 				mksh_tcget(tty_fd, &j->ttystat);
@@ -1255,8 +1274,9 @@ j_waitj(Job *j,
 	if (!(p = j->proc_list)) {
 		;	/* nothing */
 	} else if (flags & JW_PIPEST) {
-		uint32_t num = 0;
+		k32 num = 0;
 		struct tbl *vp;
+		kby *vt;
 
 		unset(vp_pipest, 1);
 		vp = vp_pipest;
@@ -1264,19 +1284,15 @@ j_waitj(Job *j,
 		goto got_array;
 
 		while (p != NULL) {
-			{
-				struct tbl *vq;
-
-				/* strlen(vp_pipest->name) == 10 */
-				vq = alloc(offsetof(struct tbl, name[0]) + 11,
-				    vp_pipest->areap);
-				memset(vq, 0, offsetof(struct tbl, name[0]));
-				memcpy(vq->name, vp_pipest->name, 11);
-				vp->u.array = vq;
-				vp = vq;
-			}
+			vt = alloc(mbccFAMSZ(struct tbl, name,
+			    sizeof(Tpipest)), vp_pipest->areap);
+			memset(vt, 0, offsetof(struct tbl, name));
+			memcpy(vt + offsetof(struct tbl, name),
+			    Tpipest, sizeof(Tpipest));
+			vp->u.array = (void *)vt;
+			vp = (void *)vt;
 			vp->areap = vp_pipest->areap;
-			vp->ua.index = ++num;
+			vp->ua.index = num = mbiMO(k32, K32_FM, num, +, 1U);
 			vp->flag = DEFINED | ISSET | INTEGER | RDONLY |
 			    ARRAY | INT_U | AINDEX;
  got_array:
@@ -1327,7 +1343,7 @@ j_sigchld(int sig MKSH_A_UNUSED)
 	pid_t pid;
 	int status;
 	struct rusage ru0, ru1;
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigset_t omask;
 
 	/* this handler can run while SIGCHLD is not blocked, so block it now */
@@ -1348,7 +1364,8 @@ j_sigchld(int sig MKSH_A_UNUSED)
 		}
 #endif
 
-	getrusage(RUSAGE_CHILDREN, &ru0);
+	if (ksh_getrusage(RUSAGE_CHILDREN, &ru0))
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, Tgetrusage);
 	do {
 #ifndef MKSH_NOPROSPECTOFWORK
 		pid = waitpid(-1, &status, (WNOHANG |
@@ -1367,7 +1384,9 @@ j_sigchld(int sig MKSH_A_UNUSED)
 		if (pid <= 0)
 			goto j_sigchld_out;
 
-		getrusage(RUSAGE_CHILDREN, &ru1);
+		if (ksh_getrusage(RUSAGE_CHILDREN, &ru1))
+			kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+			    Tgetrusage);
 
 		/* find job and process structures for this pid */
 		for (j = job_list; j != NULL; j = j->next)
@@ -1377,8 +1396,8 @@ j_sigchld(int sig MKSH_A_UNUSED)
  found:
 		if (j == NULL) {
 			/* Can occur if process has kids, then execs shell
-			warningf(true, "bad process waited for (pid = %d)",
-				pid);
+			kwarnf0(KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+			    "bad process waited for (pid = %d)", pid);
 			 */
 			ru0 = ru1;
 			continue;
@@ -1417,7 +1436,7 @@ j_sigchld(int sig MKSH_A_UNUSED)
 #endif
 
  j_sigchld_out:
-#ifdef MKSH_NO_SIGSUSPEND
+#if !defined(MKSH_NOPROSPECTOFWORK) && defined(MKSH_NO_SIGSUSPEND)
 	sigprocmask(SIG_SETMASK, &omask, NULL);
 #endif
 	errno = saved_errno;
@@ -1439,7 +1458,8 @@ check_job(Job *j)
 
 	/* XXX debugging (nasty - interrupt routine using shl_out) */
 	if (!(j->flags & JF_STARTED)) {
-		internal_warningf("check_job: job started (flags 0x%X)",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "check_job: job started (flags 0x%X)",
 		    (unsigned int)j->flags);
 		return;
 	}
@@ -1492,16 +1512,17 @@ check_job(Job *j)
 			put_job(j, PJ_ON_FRONT);
 		if (Flag(FNOTIFY) &&
 		    (j->flags & (JF_WAITING|JF_W_ASYNCNOTIFY)) != JF_WAITING) {
-			/* Look for the real file descriptor 2 */
-			{
-				struct env *ep;
-				int fd = 2;
-
-				for (ep = e; ep; ep = ep->oenv)
-					if (ep->savefd && ep->savefd[2])
-						fd = ep->savefd[2];
-				shf_reopen(fd, SHF_WR, shl_j);
+			struct env *ep = e;
+			int fd = 2, nfd;
+
+			/* look for the real file descriptor 2 */
+			while (ep) {
+				if (ep->savedfd && (nfd = SAVEDFD(ep, 2)))
+					fd = nfd;
+				ep = ep->oenv;
 			}
+			shf_reopen(fd, SHF_WR, shl_j);
+
 			/*
 			 * Can't call j_notify() as it removes jobs. The job
 			 * must stay in the job list as j_waitj() may be
@@ -1541,12 +1562,13 @@ j_print(Job *j, int how, struct shf *shf
 	int state;
 	int status;
 #ifdef WCOREDUMP
-	bool coredumped;
+	Wahr coredumped;
 #endif
-	char jobchar = ' ';
-	char buf[64];
+	char jobchar;
+	Wahr output = Nee;
+	const char *msg;
 	const char *filler;
-	int output = 0;
+	char msgbuf[sizeof("Done (255)")];
 
 	if (how == JP_PGRP) {
 		/*
@@ -1558,108 +1580,110 @@ j_print(Job *j, int how, struct shf *shf
 		    (j->last_proc ? j->last_proc->pid : 0)));
 		return;
 	}
+	/* how is one of JP_SHORT, JP_MEDIUM, JP_LONG from here */
 	j->flags &= ~JF_CHANGED;
 	filler = j->job > 10 ? "\n       " : "\n      ";
 	if (j == job_list)
 		jobchar = '+';
 	else if (j == job_list->next)
 		jobchar = '-';
+	else
+		jobchar = ' ';
 
 	for (p = j->proc_list; p != NULL;) {
 #ifdef WCOREDUMP
-		coredumped = false;
+		coredumped = Nee;
 #endif
 		switch (p->state) {
 		case PRUNNING:
-			memcpy(buf, "Running", 8);
+			msg = "Running";
 			break;
-		case PSTOPPED: {
-			int stopsig = WSTOPSIG(p->status);
-
-			strlcpy(buf, stopsig > 0 && stopsig < ksh_NSIG ?
-			    sigtraps[stopsig].mess : "Stopped", sizeof(buf));
+		case PSTOPPED:
+			status = WSTOPSIG(p->status);
+			msg = status > 0 && status < ksh_NSIG ?
+			    sigtraps[status].mess : "Stopped";
 			break;
-		}
-		case PEXITED: {
-			int exitstatus = (WEXITSTATUS(p->status)) & 255;
-
+		case PEXITED:
 			if (how == JP_SHORT)
-				buf[0] = '\0';
-			else if (exitstatus == 0)
-				memcpy(buf, "Done", 5);
-			else
-				shf_snprintf(buf, sizeof(buf), "Done (%d)",
-				    exitstatus);
+				msg = null;
+			else if ((status = (WEXITSTATUS(p->status)) & 255) == 0)
+				msg = "Done";
+			else {
+				shf_snprintf(msgbuf, sizeof(msgbuf),
+				    TDone, status);
+				msg = msgbuf;
+			}
 			break;
-		}
-		case PSIGNALLED: {
-			int termsig = WTERMSIG(p->status);
+		case PSIGNALLED:
 #ifdef WCOREDUMP
 			if (WCOREDUMP(p->status))
-				coredumped = true;
+				coredumped = Ja;
 #endif
-			/*
-			 * kludge for not reporting 'normal termination
-			 * signals' (i.e. SIGINT, SIGPIPE)
-			 */
-			if (how == JP_SHORT &&
+			status = WTERMSIG(p->status);
+			/* only report “abnormal” termination signals short */
+			if (how != JP_SHORT ||
 #ifdef WCOREDUMP
-			    !coredumped &&
+			    coredumped ||
 #endif
-			    (termsig == SIGINT || termsig == SIGPIPE)) {
-				buf[0] = '\0';
-			} else
-				strlcpy(buf, termsig > 0 && termsig < ksh_NSIG ?
-				    sigtraps[termsig].mess : "Signalled",
-				    sizeof(buf));
-			break;
-		}
+			    (status != SIGINT && status != SIGPIPE)) {
+				msg = status > 0 && status < ksh_NSIG ?
+				    sigtraps[status].mess : "Signalled";
+				break;
+			}
+			/* FALLTHROUGH */
 		default:
-			buf[0] = '\0';
+			msg = null;
 		}
 
-		if (how != JP_SHORT) {
-			if (p == j->proc_list)
-				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
-			else
-				shf_puts(filler, shf);
-		}
-
-		if (how == JP_LONG)
-			shf_fprintf(shf, "%5d ", (int)p->pid);
-
 		if (how == JP_SHORT) {
-			if (buf[0]) {
-				output = 1;
+			if (msg[0]) {
+				output = Ja;
+				shf_puts(msg, shf);
 #ifdef WCOREDUMP
-				shf_fprintf(shf, "%s%s ",
-				    buf, coredumped ? " (core dumped)" : null);
-#else
-				shf_puts(buf, shf);
-				shf_putchar(' ', shf);
+				if (coredumped)
+					shf_puts(" (core dumped)", shf);
 #endif
+				shf_putc(' ', shf);
 			}
 		} else {
-			output = 1;
-			shf_fprintf(shf, "%-20s %s%s%s", buf, p->command,
-			    p->next ? "|" : null,
+			/* JP_MEDIUM or JP_LONG */
+			if (p == j->proc_list)
+				shf_fprintf(shf, "[%d] %c ", j->job, jobchar);
+			else
+				shf_puts(filler, shf);
+			if (how == JP_LONG)
+				shf_fprintf(shf, "%5d ", (int)p->pid);
+			output = Ja;
+			shf_fprintf(shf, "%-20s %s", msg, p->command);
+			if (p->next) {
+				shf_putc(' ', shf);
+				shf_putc('|', shf);
+			}
 #ifdef WCOREDUMP
-			    coredumped ? " (core dumped)" :
+			if (coredumped)
+				shf_puts(" (core dumped)", shf);
 #endif
-			     null);
 		}
 
 		state = p->state;
 		status = p->status;
 		p = p->next;
 		while (p && p->state == state && p->status == status) {
-			if (how == JP_LONG)
-				shf_fprintf(shf, "%s%5d %-20s %s%s", filler,
-				    (int)p->pid, T1space, p->command,
-				    p->next ? "|" : null);
-			else if (how == JP_MEDIUM)
-				shf_fprintf(shf, Tf__ss, p->command,
-				    p->next ? "|" : null);
+			switch (how) {
+			case JP_LONG:
+				shf_puts(filler, shf);
+				shf_fprintf(shf, "%5d %-20s",
+				    (int)p->pid, T1space);
+				/* FALLTHROUGH */
+			case JP_MEDIUM:
+				shf_putc(' ', shf);
+				shf_puts(p->command, shf);
+				if (p->next) {
+					shf_putc(' ', shf);
+					shf_putc('|', shf);
+				}
+				break;
+			}
 			p = p->next;
 		}
 	}
@@ -1727,7 +1751,7 @@ j_lookup(const char *cp, int *ecodep)
 		last_match = NULL;
 		for (j = job_list; j != NULL; j = j->next)
 			for (p = j->proc_list; p != NULL; p = p->next)
-				if (strstr(p->command, cp+1) != NULL) {
+				if (vstrstr(p->command, cp + 1)) {
 					if (last_match) {
 						if (ecodep)
 							*ecodep = JL_AMBIG;
@@ -1842,7 +1866,8 @@ remove_job(Job *j, const char *where)
 		curr = *prev;
 	}
 	if (curr != j) {
-		internal_warningf("remove_job: job %s (%s)", Tnot_found, where);
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "remove_job: job %s (%s)", Tnot_found, where);
 		return;
 	}
 	*prev = curr->next;
@@ -1931,23 +1956,21 @@ tty_init_talking(void)
 		break;
 	case 1:
 #ifndef MKSH_DISABLE_TTY_WARNING
-		warningf(false, Tf_sD_s_sD_s,
-		    "No controlling tty", Topen, T_devtty, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_ONEMSG, "can't find controlling tty");
 #endif
 		break;
 	case 2:
 #ifndef MKSH_DISABLE_TTY_WARNING
-		warningf(false, Tf_s_sD_s, Tcant_find, Ttty_fd,
-		    cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_ONEMSG, "can't find tty fd");
 #endif
 		break;
 	case 3:
-		warningf(false, Tf_ssfaileds, "j_ttyinit",
-		    Ttty_fd_dupof, cstrerror(errno));
+		kwarnf0(KWF_PREFIX, Tf_ssfailed,
+		    "j_ttyinit", "dup of tty fd");
 		break;
 	case 4:
-		warningf(false, Tf_sD_sD_s, "j_ttyinit",
-		    "can't set close-on-exec flag", cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, "j_ttyinit",
+		    "can't set close-on-exec flag");
 		break;
 	}
 }
@@ -1957,6 +1980,20 @@ tty_init_state(void)
 {
 	if (tty_fd >= 0) {
 		mksh_tcget(tty_fd, &tty_state);
-		tty_hasstate = true;
+		tty_hasstate = Ja;
 	}
 }
+
+static void
+vistree(char *dst, size_t sz, struct op *t)
+{
+	char buf[PROC_TGTSZ - 12];
+	struct shf shf;
+
+	snptreef(buf, sizeof(buf), Tf_T, t);
+	shf_sopen(dst, sz, SHF_WR, &shf);
+	uprntmbs(buf, Nee, &shf);
+	while ((char *)shf.wp > dst && ctype(shf.wp[-1], C_IFSWS))
+		--shf.wp;
+	shf_sclose(&shf);
+}
--- mksh-59c.orig/lalloc.c
+++ mksh-59c/lalloc.c
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2009, 2010, 2011, 2013, 2014, 2016
+ * Copyright (c) 2009, 2010, 2011, 2013, 2014, 2016, 2021, 2022
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -18,12 +18,12 @@
  * of said person's immediate fault when using the work as intended.
  */
 
-#include "sh.h"
 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
 #include <err.h>
 #endif
+#include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/lalloc.c,v 1.26 2016/02/26 21:53:36 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/lalloc.c,v 1.35 2023/08/16 13:46:04 tg Exp $");
 
 /* build with CPPFLAGS+= -DUSE_REALLOC_MALLOC=0 on ancient systems */
 #if defined(USE_REALLOC_MALLOC) && (USE_REALLOC_MALLOC == 0)
@@ -32,7 +32,6 @@ __RCSID("$MirOS: src/bin/mksh/lalloc.c,v
 #define remalloc(p,n)	realloc_osi((p), (n))
 #endif
 
-
 static struct lalloc_common *findptr(struct lalloc_common **, char *, Area *);
 
 #ifndef MKSH_ALLOC_CATCH_UNDERRUNS
@@ -56,7 +55,7 @@ remalloc(void *ptr, size_t size)
 {
 	struct lalloc_item *lp, *lold = ptr;
 
-	size = (size + 4095) & ~(size_t)4095;
+	size = (size_t)(size + 4095U) & (size_t)~(size_t)4095U;
 
 	if (lold && lold->len >= size)
 		return (ptr);
@@ -81,6 +80,7 @@ remalloc(void *ptr, size_t size)
 }
 #endif
 
+/* pre-initio() */
 void
 ainit(Area *ap)
 {
@@ -100,6 +100,9 @@ static struct lalloc_common *
 findptr(struct lalloc_common **lpp, char *ptr, Area *ap)
 {
 	void *lp;
+#ifdef DEBUG
+	Area *oap = ap;
+#endif
 
 #ifndef MKSH_SMALL
 	if (ALLOC_ISUNALIGNED(ptr))
@@ -118,31 +121,43 @@ findptr(struct lalloc_common **lpp, char
  fail:
 #endif
 #ifdef DEBUG
-			internal_warningf("rogue pointer %zX in ap %zX",
-			    (size_t)ptr, (size_t)ap);
+			kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+			    "rogue pointer %zX in ap %zX",
+			    (size_t)ptr, (size_t)oap);
 			/* try to get a coredump */
 			abort();
 #else
-			internal_errorf("rogue pointer %zX", (size_t)ptr);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    "rogue pointer %zX", (size_t)ptr);
 #endif
 		}
 	return (ap);
 }
 
 void *
+aresize1(void *ptr, size_t len1, size_t len2, Area *ap)
+{
+	checkoktoadd(len1, len2);
+	return (aresize(ptr, len1 + len2, ap));
+}
+
+/* pre-initio() */
+void *
 aresize2(void *ptr, size_t fac1, size_t fac2, Area *ap)
 {
 	if (notoktomul(fac1, fac2))
-		internal_errorf(Tintovfl, fac1, '*', fac2);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tintovfl, fac1, '*', fac2);
 	return (aresize(ptr, fac1 * fac2, ap));
 }
 
+/* pre-initio() ptr=NULL */
 void *
 aresize(void *ptr, size_t numb, Area *ap)
 {
 	struct lalloc_common *lp = NULL;
 
-	/* resizing (true) or newly allocating? */
+	/* resizing or newly allocating? */
 	if (ptr != NULL) {
 		struct lalloc_common *pp;
 
@@ -150,14 +165,29 @@ aresize(void *ptr, size_t numb, Area *ap
 		pp->next = lp->next;
 	}
 
-	if (notoktoadd(numb, sizeof(ALLOC_ITEM)) ||
-	    (lp = remalloc(lp, numb + sizeof(ALLOC_ITEM))) == NULL
+	if (notoktoadd(numb, sizeof(ALLOC_ITEM))) {
+		errno = E2BIG;
+ alloc_fail:
+		if (!initio_done) {
+			SHIKATANAI write(2, SC("mksh: out of memory early\n"));
+			exit(255);
+		}
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF),
+		    "can't allocate %zu data bytes", numb);
+	}
+	if ((lp = remalloc(lp, numb + sizeof(ALLOC_ITEM))) == NULL)
+		goto alloc_fail;
 #ifndef MKSH_SMALL
-	    || ALLOC_ISUNALIGNED(lp)
+	if (ALLOC_ISUNALIGNED(lp)) {
+#ifdef EPROTO
+		errno = EPROTO;
 #endif
-	    )
-		internal_errorf(Toomem, numb);
+		goto alloc_fail;
+	}
+#endif
+
 	/* area pointer and items share struct lalloc_common */
+	/*XXX C99 §6.5(6) and footnote 72 may dislike this? */
 	lp->next = ap->next;
 	ap->next = lp;
 	/* return user item address */
--- mksh-59c.orig/lex.c
+++ mksh-59c/lex.c
@@ -2,7 +2,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
+ *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
+ *		 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -23,7 +24,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/lex.c,v 1.251 2020/03/10 23:48:40 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/lex.c,v 1.267 2023/04/16 00:40:13 tg Exp $");
 
 /*
  * states while lexing word
@@ -62,9 +63,9 @@ typedef struct lex_state {
 		struct lex_state *base;
 		/* marks start of state output in output string */
 		size_t start;
-		/* SBQUOTE: true if in double quotes: "`...`" */
+		/* SBQUOTE: Ja if in double quotes: "`...`" */
 		/* SEQUOTE: got NUL, ignore rest of string */
-		bool abool;
+		Wahr sxqflag;
 		/* SADELIM information */
 		struct {
 			/* character to search for */
@@ -76,13 +77,13 @@ typedef struct lex_state {
 	/* count open parentheses */
 	short nparen;
 	/* type of this state */
-	uint8_t type;
+	kby type;
 	/* extra flags */
-	uint8_t ls_flags;
+	kby ls_flags;
 } Lex_state;
 #define ls_base		u.base
 #define ls_start	u.start
-#define ls_bool		u.abool
+#define ls_flag		u.sxqflag
 #define ls_adelim	u.adelim
 
 /* ls_flags */
@@ -101,7 +102,7 @@ static void getsc_line(Source *);
 static int getsc_bn(void);
 static int getsc_i(void);
 static char *get_brace_var(XString *, char *);
-static bool arraysub(char **);
+static Wahr arraysub(char **);
 static void gethere(void);
 static Lex_state *push_state_i(State_info *, Lex_state *);
 static Lex_state *pop_state_i(State_info *, Lex_state *);
@@ -152,7 +153,7 @@ getsc_r(int c)
 #define STATE_BSIZE	8
 
 #define PUSH_STATE(s)	do {					\
-	uint8_t state_flags = statep->ls_flags;			\
+	kby state_flags = statep->ls_flags;			\
 	if (++statep == state_info.end)				\
 		statep = push_state_i(&state_info, statep);	\
 	state = statep->type = (s);				\
@@ -193,7 +194,6 @@ getsc_r(int c)
  * for example, "${var:-${PWD}}", and "$(size $(whence ksh))".
  * hence the state stack. Note "$(...)" are now parsed recursively.
  */
-
 int
 yylex(int cf)
 {
@@ -252,13 +252,18 @@ yylex(int cf)
 	statep->ls_flags = (cf & HEREDOC) ? LS_HEREDOC : 0;
 
 	/* collect non-special or quoted characters to form word */
-	while (!((c = getsc()) == 0 ||
-	    ((state == SBASE || state == SHEREDELIM) && ctype(c, C_LEX1)))) {
-		if (state == SBASE &&
-		    subshell_nesting_type == ORD(/*{*/ '}') &&
-		    (unsigned int)c == ORD(/*{*/ '}'))
-			/* possibly end ${ :;} */
+	while ((c = getsc())) {
+		switch (state) {
+		case SBASE:
+			/* possibly end "${ :;}" */
+			if ((unsigned int)c == subshell_nesting_type)
+				goto Done;
+			/* FALLTHROUGH */
+		case SHEREDELIM:
+			if (ctype(c, C_LEX1))
+				goto Done;
 			break;
+		}
 		Xcheck(ws, wp);
 		switch (state) {
 		case SADELIM:
@@ -283,7 +288,7 @@ yylex(int cf)
 			if ((unsigned int)c == ORD('[') && (cf & CMDASN)) {
 				/* temporary */
 				*wp = EOS;
-				if (is_wdvarname(Xstring(ws, wp), false)) {
+				if (is_wdvarname(Xstring(ws, wp), Nee)) {
 					char *p, *tmp;
 
 					if (arraysub(&tmp)) {
@@ -552,15 +557,15 @@ yylex(int cf)
 				 * "…`…\"…`…" because, unlike for COMSUBs, the
 				 * outer double quoteing changes the backslash
 				 * meaning for the inside. For more details:
-				 * http://austingroupbugs.net/view.php?id=1015
+				 * https://www.austingroupbugs.net/view.php?id=1015
 				 */
-				statep->ls_bool = false;
+				statep->ls_flag = Nee;
 				s2 = statep;
 				base = state_info.base;
 				while (/* CONSTCOND */ 1) {
 					for (; s2 != base; s2--) {
 						if (s2->type == SDQUOTE) {
-							statep->ls_bool = true;
+							statep->ls_flag = Ja;
 							break;
 						}
 					}
@@ -591,27 +596,26 @@ yylex(int cf)
 				*wp++ = CQUOTE;
 				ignore_backslash_newline--;
 			} else if ((unsigned int)c == ORD('\\')) {
-				if ((c2 = unbksl(true, getsc_i, ungetsc)) == -1)
+				if ((c2 = unbksl(Ja, getsc_i, ungetsc)) == -1)
 					c2 = getsc();
 				if (c2 == 0)
-					statep->ls_bool = true;
-				if (!statep->ls_bool) {
-					char ts[4];
-
+					statep->ls_flag = Ja;
+				if (!statep->ls_flag) {
 					if ((unsigned int)c2 < 0x100) {
 						*wp++ = QCHAR;
 						*wp++ = c2;
 					} else {
+						char ts[4];
+
 						cz = utf_wctomb(ts, c2 - 0x100);
-						ts[cz] = 0;
-						cz = 0;
-						do {
+						c2 = 0;
+						while ((size_t)c2 < cz) {
 							*wp++ = QCHAR;
-							*wp++ = ts[cz];
-						} while (ts[++cz]);
+							*wp++ = ts[c2++];
+						}
 					}
 				}
-			} else if (!statep->ls_bool) {
+			} else if (!statep->ls_flag) {
 				*wp++ = QCHAR;
 				*wp++ = c;
 			}
@@ -752,7 +756,7 @@ yylex(int cf)
 					*wp++ = c;
 					break;
 				case ORD('"'):
-					if (statep->ls_bool) {
+					if (statep->ls_flag) {
 						*wp++ = c;
 						break;
 					}
@@ -830,7 +834,7 @@ yylex(int cf)
 					*wp++ = OQUOTE;
 					ignore_backslash_newline++;
 					PUSH_STATE(SEQUOTE);
-					statep->ls_bool = false;
+					statep->ls_flag = Nee;
 					break;
 				} else if ((unsigned int)c2 == ORD('"')) {
 					/* FALLTHROUGH */
@@ -1041,7 +1045,7 @@ yylex(int cf)
 
 	if (*ident != '\0' && (cf & (KEYWORD | ALIAS))) {
 		struct tbl *p;
-		uint32_t h = hash(ident);
+		k32 h = hash(ident);
 
 		if ((cf & KEYWORD) && (p = ktsearch(&keywords, ident, h)) &&
 		    (!(cf & ESACONLY) || p->val.i == ESAC ||
@@ -1098,7 +1102,7 @@ yylex(int cf)
 	} else if (*ident == '\0') {
 		/* retain typeset et al. even when quoted */
 		struct tbl *tt = get_builtin((dp = wdstrip(yylval.cp, 0)));
-		uint32_t flag = tt ? tt->flag : 0;
+		kui flag = tt ? tt->flag : 0U;
 
 		if (flag & (DECL_UTIL | DECL_FWDR))
 			strlcpy(ident, dp, sizeof(ident));
@@ -1122,7 +1126,6 @@ gethere(void)
 /*
  * read "<<word" text into temp file
  */
-
 static void
 readhere(struct ioword *iop)
 {
@@ -1157,7 +1160,7 @@ readhere(struct ioword *iop)
 		/* end of here document marker, what to do? */
 		switch (c) {
 		case ORD(/*(*/ ')'):
-			if (!subshell_nesting_type)
+			if (subshell_nesting_type != ORD(/*(*/ ')'))
 				/*-
 				 * not allowed outside $(...) or (...)
 				 * => mismatch
@@ -1209,29 +1212,9 @@ readhere(struct ioword *iop)
 		ignore_backslash_newline--;
 }
 
-void
-yyerror(const char *fmt, ...)
-{
-	va_list va;
-
-	/* pop aliases and re-reads */
-	while (source->type == SALIAS || source->type == SREREAD)
-		source = source->next;
-	/* zap pending input */
-	source->str = null;
-
-	error_prefix(true);
-	va_start(va, fmt);
-	shf_vfprintf(shl_out, fmt, va);
-	shf_putc('\n', shl_out);
-	va_end(va);
-	errorfz();
-}
-
 /*
  * input for yylex with alias expansion
  */
-
 Source *
 pushs(int type, Area *areap)
 {
@@ -1357,8 +1340,8 @@ static void
 getsc_line(Source *s)
 {
 	char *xp = Xstring(s->xs, xp), *cp;
-	bool interactive = Flag(FTALKING) && s->type == SSTDIN;
-	bool have_tty = interactive && (s->flags & SF_TTY) && tty_hasstate;
+	Wahr interactive = Flag(FTALKING) && s->type == SSTDIN;
+	Wahr have_tty = interactive && (s->flags & SF_TTY) && tty_hasstate;
 
 	/* Done here to ensure nothing odd happens when a timeout occurs */
 	XcheckN(s->xs, xp, LINE);
@@ -1371,7 +1354,7 @@ getsc_line(Source *s)
 	}
 	if (interactive) {
 		if (cur_prompt == PS1)
-			histsave(&s->line, NULL, HIST_FLUSH, true);
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 		change_winsz();
 	}
 #ifndef MKSH_NO_CMDLINE_EDITING
@@ -1380,14 +1363,8 @@ getsc_line(Source *s)
 	    Flag(FVI) ||
 #endif
 	    Flag(FEMACS) || Flag(FGMACS))) {
-		int nread;
-
-		nread = x_read(xp);
-		if (nread < 0)
-			/* read error */
-			nread = 0;
-		xp[nread] = '\0';
-		xp += nread;
+		xp = x_read(xp);
+		*xp = '\0';
 	} else
 #endif
 	  {
@@ -1435,7 +1412,6 @@ getsc_line(Source *s)
 		alarm(0);
 	}
 	cp = Xstring(s->xs, xp);
-	rndpush(cp);
 	s->start = s->str = cp;
 	strip_nuls(Xstring(s->xs, xp), Xlength(s->xs, xp));
 	/* Note: if input is all nulls, this is not eof */
@@ -1446,9 +1422,9 @@ getsc_line(Source *s)
 		s->str = NULL;
 	} else if (interactive && *s->str) {
 		if (cur_prompt != PS1)
-			histsave(&s->line, s->str, HIST_APPEND, true);
+			histsave(&s->line, s->str, HIST_APPEND, Ja);
 		else if (!ctype(*s->str, C_IFS | C_IFSWS))
-			histsave(&s->line, s->str, HIST_QUEUE, true);
+			histsave(&s->line, s->str, HIST_QUEUE, Ja);
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
 		else
 			goto check_for_sole_return;
@@ -1458,7 +1434,7 @@ getsc_line(Source *s)
 		while (ctype(*cp, C_IFSWS))
 			++cp;
 		if (!*cp) {
-			histsave(&s->line, NULL, HIST_FLUSH, true);
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 			histsync();
 		}
 #endif
@@ -1470,7 +1446,7 @@ getsc_line(Source *s)
 void
 set_prompt(int to, Source *s)
 {
-	cur_prompt = (uint8_t)to;
+	cur_prompt = (kby)to;
 
 	switch (to) {
 	/* command */
@@ -1482,26 +1458,29 @@ set_prompt(int to, Source *s)
 		 * substitutions, POSIX doesn't say which is to be done.
 		 */
 		{
+			char ch;
 			struct shf *shf;
 			char * volatile ps1;
 			Area *saved_atemp;
 			int saved_lineno;
 
+			saved_atemp = ATEMP;
+			newenv(E_ERRH);
 			ps1 = str_val(global("PS1"));
 			shf = shf_sopen(NULL, strlen(ps1) * 2,
 			    SHF_WR | SHF_DYNAMIC, NULL);
-			while (*ps1)
-				if (*ps1 != '!' || *++ps1 == '!')
-					shf_putchar(*ps1++, shf);
-				else
+			while ((ch = *ps1++))
+				if (ch != '!' || *ps1++ == '!')
+					shf_putc(ch, shf);
+				else {
+					--ps1;
 					shf_fprintf(shf, Tf_lu, s ?
 					    (unsigned long)s->line + 1 : 0UL);
+				}
 			ps1 = shf_sclose(shf);
 			saved_lineno = current_lineno;
 			if (s)
 				current_lineno = s->line + 1;
-			saved_atemp = ATEMP;
-			newenv(E_ERRH);
 			if (kshsetjmp(e->jbuf)) {
 				prompt = safe_prompt;
 				/*
@@ -1516,6 +1495,7 @@ set_prompt(int to, Source *s)
 				strdupx(prompt, cp, saved_atemp);
 			}
 			current_lineno = saved_lineno;
+			/* frees everything in post-newenv ATEMP */
 			quitenv(NULL);
 		}
 		break;
@@ -1530,8 +1510,8 @@ int
 pprompt(const char *cp, int ntruncate)
 {
 	char delimiter = 0;
-	bool doprint = (ntruncate != -1);
-	bool indelimit = false;
+	Wahr doprint = (ntruncate != -1);
+	Wahr indelimit = Nee;
 	int columns = 0, lines = 0;
 
 	/*
@@ -1545,7 +1525,7 @@ pprompt(const char *cp, int ntruncate)
 		delimiter = *cp;
 		cp += 2;
 	}
-	for (; *cp; cp++) {
+	while (*cp) {
 		if (indelimit && *cp != delimiter)
 			;
 		else if (ctype(*cp, C_CR | C_LF)) {
@@ -1560,17 +1540,19 @@ pprompt(const char *cp, int ntruncate)
 			indelimit = !indelimit;
 		else if (UTFMODE && (rtt2asc(*cp) > 0x7F)) {
 			const char *cp2;
+
 			columns += utf_widthadj(cp, &cp2);
 			if (doprint && (indelimit ||
 			    (ntruncate < (x_cols * lines + columns))))
 				shf_write(cp, cp2 - cp, shl_out);
-			cp = cp2 - /* loop increment */ 1;
+			cp = cp2;
 			continue;
 		} else
 			columns++;
 		if (doprint && (*cp != delimiter) &&
 		    (indelimit || (ntruncate < (x_cols * lines + columns))))
 			shf_putc(*cp, shl_out);
+		++cp;
 	}
 	if (doprint)
 		shf_flush(shl_out);
@@ -1600,10 +1582,8 @@ get_brace_var(XString *wsp, char *wp)
 
 				c2 = getsc();
 				ungetsc(c2);
-				if (ord(c2) != ORD(/*{*/ '}')) {
-					ungetsc(c);
+				if (ord(c2) != ORD(/*{*/ '}'))
 					goto out;
-				}
 			}
 			goto ps_common;
 		case PS_SAW_BANG:
@@ -1678,11 +1658,11 @@ get_brace_var(XString *wsp, char *wp)
 }
 
 /*
- * Save an array subscript - returns true if matching bracket found, false
- * if eof or newline was found.
- * (Returned string double null terminated)
+ * Save an array subscript
+ * Returns Ja if matching bracket found, Nee if EOF or newline was found.
+ * (Returned string is double-NUL-terminated.)
  */
-static bool
+static Wahr
 arraysub(char **strp)
 {
 	XString ws;
@@ -1705,7 +1685,7 @@ arraysub(char **strp)
 	*wp++ = '\0';
 	*strp = Xclose(ws, wp);
 
-	return (tobool(depth == 0));
+	return (isWahr(depth == 0));
 }
 
 /* Unget a char: handles case when we are already at the start of the buffer */
@@ -1742,7 +1722,6 @@ ungetsc_i(int c)
 	}
 }
 
-
 /* Called to get a char that isn't a \newline sequence. */
 static int
 getsc_bn(void)
@@ -1772,29 +1751,6 @@ getsc_bn(void)
 	}
 }
 
-void
-yyskiputf8bom(void)
-{
-	int c;
-
-	if (rtt2asc((c = o_getsc_u())) != 0xEF) {
-		ungetsc_i(c);
-		return;
-	}
-	if (rtt2asc((c = o_getsc_u())) != 0xBB) {
-		ungetsc_i(c);
-		ungetsc_i(asc2rtt(0xEF));
-		return;
-	}
-	if (rtt2asc((c = o_getsc_u())) != 0xBF) {
-		ungetsc_i(c);
-		ungetsc_i(asc2rtt(0xBB));
-		ungetsc_i(asc2rtt(0xEF));
-		return;
-	}
-	UTFMODE |= 8;
-}
-
 static Lex_state *
 push_state_i(State_info *si, Lex_state *old_end)
 {
--- mksh-59c.orig/lksh.1
+++ mksh-59c/lksh.1
@@ -1,6 +1,7 @@
-.\" $MirOS: src/bin/mksh/lksh.1,v 1.26 2020/09/04 22:37:01 tg Exp $
+.\" $MirOS: src/bin/mksh/lksh.1,v 1.33 2024/01/05 02:08:45 tg Exp $
 .\"-
-.\" Copyright (c) 2008, 2009, 2010, 2012, 2013, 2015, 2016, 2017, 2018
+.\" Copyright © 2008, 2009, 2010, 2012, 2013, 2015, 2016, 2017,
+.\"		2018, 2023
 .\"	mirabilos <m@mirbsd.org>
 .\"
 .\" Provided that these terms and disclaimer and all copyright notices
@@ -18,7 +19,12 @@
 .\" damage or existence of a defect, except proven that it results out
 .\" of said person’s immediate fault when using the work as intended.
 .\"-
-.\" Try to make GNU groff and AT&T nroff more compatible
+.\" $miros: contrib/samples/portmdoc,v 1.23 2024/01/04 22:52:50 tg Exp $
+.\"-
+.\" Copyright © 2008, 2009, 2010, 2016, 2018, 2020, 2023
+.\"	mirabilos <m@mirbsd.org>
+.\"
+.\" Glue GNU groff (BSD and GNU mdoc both) to AT&T nroff (UCB mdoc).
 .\" * ` generates ‘ in gnroff, so use \`
 .\" * ' generates ’ in gnroff, \' generates ´, so use \*(aq
 .\" * - generates ‐ in gnroff, \- generates −, so .tr it to -
@@ -31,18 +37,36 @@
 .\" Also make sure to use \& *before* a punctuation char that is to not
 .\" be interpreted as punctuation, and especially with two-letter words
 .\" but also (after) a period that does not end a sentence (“e.g.\&”).
-.\" The section after the "doc" macropackage has been loaded contains
-.\" additional code to convene between the UCB mdoc macropackage (and
-.\" its variant as BSD mdoc in groff) and the GNU mdoc macropackage.
+.\"-
+.\"
+.\" Implement .Dd with the Mdocdate RCS keyword
+.\"
+.rn Dd xD
+.de Dd
+.ie \\$1$Mdocdate: \{\
+.	xD \\$2 \\$3, \\$4
+.\}
+.el .xD \\$1 \\$2 \\$3
+..
+.\"
+.\" .Dd must come before most everything, because when called
+.\" with -mandoc it loads -mdoc via .so in .Dd (first macro).
+.\"
+.Dd $Mdocdate: January 5 2024 $
+.\"
+.\" Check which macro package we use, and do other -mdoc setup.
 .\"
 .ie \n(.g \{\
+.	if n .ss \n[.ss] 0
 .	if \*[.T]ascii .tr \-\N'45'
 .	if \*[.T]latin1 .tr \-\N'45'
 .	if \*[.T]utf8 .tr \-\N'45'
-.	ds <= \[<=]
-.	ds >= \[>=]
-.	ds Rq \[rq]
-.	ds Lq \[lq]
+.	if \*[.T]utf8 .tr \(la\*(Lt
+.	if \*[.T]utf8 .tr \(ra\*(Gt
+.	ds <= \(<=
+.	ds >= \(>=
+.	ds Rq \(rq
+.	ds Lq \(lq
 .	ds sL \(aq
 .	ds sR \(aq
 .	if \*[.T]utf8 .ds sL `
@@ -53,56 +77,36 @@
 .	ds TI \(ti
 .	ds ha \(ha
 .	ds en \(en
+.	ie d volume-ds-1 .ds tT gnu
+.	el .ie d doc-volume-ds-1 .ds tT gnp
+.	el .ds tT bsd
 .\}
 .el \{\
 .	ds aq '
 .	ds TI ~
 .	ds ha ^
 .	ds en \(em
+.	ds tT ucb
 .\}
 .ie n \{\
-.	ds EM \ \*(en\ \&
+.	ds EM \ \(em\ \&
 .\}
 .el \{\
-.	ds EM \f(TR\^\(em\^\fP
+.	ds EM \f(TR\|\(em\|\fP
 .\}
 .\"
-.\" Implement .Dd with the Mdocdate RCS keyword
-.\"
-.rn Dd xD
-.de Dd
-.ie \\$1$Mdocdate: \{\
-.	xD \\$2 \\$3, \\$4
-.\}
-.el .xD \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8
-..
-.\"
-.\" .Dd must come before definition of .Mx, because when called
-.\" with -mandoc, it might implement .Mx itself, but we want to
-.\" use our own definition. And .Dd must come *first*, always.
-.\"
-.Dd $Mdocdate: September 4 2020 $
-.\"
-.\" Check which macro package we use, and do other -mdoc setup.
-.\"
-.ie \n(.g \{\
-.	if \*[.T]utf8 .tr \[la]\*(Lt
-.	if \*[.T]utf8 .tr \[ra]\*(Gt
-.	ie d volume-ds-1 .ds tT gnu
-.	el .ie d doc-volume-ds-1 .ds tT gnp
-.	el .ds tT bsd
-.\}
-.el .ds tT ucb
-.\"
+.\" Add UCB mdoc compatibility to GNU mdoc
 .\" Implement .Mx (MirBSD)
 .\"
 .ie "\*(tT"gnu" \{\
+.	ds sP \s0
+.	ds tN \*[Tn-font-size]
 .	eo
 .	de Mx
 .	nr curr-font \n[.f]
 .	nr curr-size \n[.ps]
 .	ds str-Mx \f[\n[curr-font]]\s[\n[curr-size]u]
-.	ds str-Mx1 \*[Tn-font-size]\%MirBSD\*[str-Mx]
+.	ds str-Mx1 \*(tN\%MirBSD\*[str-Mx]
 .	if !\n[arg-limit] \
 .	if \n[.$] \{\
 .	ds macro-name Mx
@@ -111,7 +115,7 @@
 .	if (\n[arg-limit] > \n[arg-ptr]) \{\
 .	nr arg-ptr +1
 .	ie (\n[type\n[arg-ptr]] == 2) \
-.	as str-Mx1 \~\*[arg\n[arg-ptr]]
+.	ds str-Mx1 \*(tN\%MirBSD\~#\*[arg\n[arg-ptr]]\*[str-Mx]
 .	el \
 .	nr arg-ptr -1
 .	\}
@@ -124,17 +128,31 @@
 .	parse-space-vector
 .	print-recursive
 ..
+.	de Aq
+.	if !\n[arg-limit] \
+.	ds macro-name Aq
+.	ie \n[in-authors-section] \{\
+.		ds quote-left \*(Lt
+.		ds quote-right \*(Gt
+.	\}
+.	el \{\
+.		ds quote-left \[la]
+.		ds quote-right \[ra]
+.	\}
+.	enclose-string \$@
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[Tn-font-size]
 .\}
 .el .ie "\*(tT"gnp" \{\
+.	ds sP \s0
+.	ie t .ds tN \s[(\n[.ps]u-1z)]
+.	el .ds tN
 .	eo
 .	de Mx
 .	nr doc-curr-font \n[.f]
 .	nr doc-curr-size \n[.ps]
 .	ds doc-str-Mx \f[\n[doc-curr-font]]\s[\n[doc-curr-size]u]
-.	ds doc-str-Mx1 \*[doc-Tn-font-size]\%MirBSD\*[doc-str-Mx]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\*[doc-str-Mx]
 .	if !\n[doc-arg-limit] \
 .	if \n[.$] \{\
 .	ds doc-macro-name Mx
@@ -143,7 +161,7 @@
 .	if (\n[doc-arg-limit] > \n[doc-arg-ptr]) \{\
 .	nr doc-arg-ptr +1
 .	ie (\n[doc-type\n[doc-arg-ptr]] == 2) \
-.	as doc-str-Mx1 \~\*[doc-arg\n[doc-arg-ptr]]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\~#\*[doc-arg\n[doc-arg-ptr]]\*[doc-str-Mx]
 .	el \
 .	nr doc-arg-ptr -1
 .	\}
@@ -157,8 +175,6 @@
 .	doc-print-recursive
 ..
 .	ec
-.	ds sP \s0
-.	ds tN \*[doc-Tn-font-size]
 .\}
 .el \{\
 .	de Mx
@@ -166,13 +182,18 @@
 .	nr cZ \\n(.s
 .	ds aa \&\f\\n(cF\s\\n(cZ
 .	if \\n(aC==0 \{\
-.		ie \\n(.$==0 \&MirBSD\\*(aa
+.		ie \\n(.$==0 \&\\*(tNMirBSD\\*(aa
 .		el .aV \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9
 .	\}
 .	if \\n(aC>\\n(aP \{\
 .		nr aP \\n(aP+1
 .		ie \\n(C\\n(aP==2 \{\
-.			as b1 \&MirBSD\ #\&\\*(A\\n(aP\\*(aa
+.			nr xX 0
+.			nr xX 1+\\*(A\\n(aP
+.			as b1 \&\\*(tNMirBSD\ \&
+.			if \\n(xX>0 .as b1 #\&
+.			as b1 \&\\*(A\\n(aP\\*(aa
+.			rr xX
 .			ie \\n(aC>\\n(aP \{\
 .				nr aP \\n(aP+1
 .				nR
@@ -180,12 +201,13 @@
 .			el .aZ
 .		\}
 .		el \{\
-.			as b1 \&MirBSD\\*(aa
+.			as b1 \&\\*(tNMirBSD\\*(aa
 .			nR
 .		\}
 .	\}
 ..
 .\}
+.\" </MirCVS://contrib/samples/portmdoc>
 .\"-
 .Dt LKSH 1
 .Os MirBSD
@@ -346,16 +368,12 @@ Talk to the
 .Mx
 development team and users using the mailing list at
 .Aq Mt miros\-mksh@mirbsd.org
-(please note the EU-DSGVO/GDPR notice on
-.Pa http://www.mirbsd.org/rss.htm#lists
-and in the SMTP banner!) or the
+or in the
 .Li \&#\&!/bin/mksh
-.Pq or Li \&#ksh
-IRC channel at
-.Pa irc.freenode.net
-.Pq Port 6697 SSL, 6667 unencrypted
-if you need any further quirks or assistance,
-and consider migrating your legacy scripts to work with
+IRC channel; mind the infos from
+.Pa http://www.mirbsd.org/mksh\-faq.htm#contact
+for either.
+Consider migrating your legacy scripts to work with
 .Nm mksh
 instead of requiring
 .Nm .
--- mksh-59c.orig/main.c
+++ mksh-59c/main.c
@@ -6,7 +6,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -28,14 +28,10 @@
 #define EXTERN
 #include "sh.h"
 
-#if HAVE_LANGINFO_CODESET
-#include <langinfo.h>
-#endif
-#if HAVE_SETLOCALE_CTYPE
-#include <locale.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/main.c,v 1.374 2020/10/01 20:28:54 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/main.c,v 1.438 2023/10/06 21:56:49 tg Exp $");
+__IDSTRING(mbsdcc_h_rcsid, SYSKERN_MBSDCC_H);
+__IDSTRING(mbsdint_h_rcsid, SYSKERN_MBSDINT_H);
+__IDSTRING(sh_h_rcsid, MKSH_SH_H_ID);
 
 #ifndef MKSHRC_PATH
 #define MKSHRC_PATH	"~/.mkshrc"
@@ -45,17 +41,31 @@ __RCSID("$MirOS: src/bin/mksh/main.c,v 1
 #define MKSH_DEFAULT_TMPDIR	MKSH_UNIXROOT "/tmp"
 #endif
 
-static uint8_t isuc(const char *);
-static int main_init(int, const char *[], Source **, struct block **);
+#if !HAVE_POSIX_UTF8_LOCALE
+/* this is the “implementation-defined default locale” */
+#ifdef MKSH_DEFAULT_UTFLOC
+#define MKSH_DEFAULT_LOCALE	"UTF-8"
+#else
+#define MKSH_DEFAULT_LOCALE	"C"
+#endif
+#endif
+
+static void main_init(int, const char *[], Source **);
 void chvt_reinit(void);
 static void reclaim(void);
 static void remove_temps(struct temp *);
-static mksh_uari_t rndsetup(void);
+static void rndsetup(void);
 static void init_environ(void);
 #ifdef SIGWINCH
 static void x_sigwinch(int);
 #endif
 
+#ifdef DEBUG
+static void reclim_trace(void);
+#else
+#define reclim_trace() /* nothing */
+#endif
+
 static const char initsubs[] =
     "${PS2=> }"
     "${PS3=#? }"
@@ -84,75 +94,81 @@ static const char *initcoms[] = {
 	NULL,
 	 /* this is what AT&T ksh seems to track, with the addition of emacs */
 	Talias, "-tU",
-	Tcat, "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
+	"cat", "cc", "chmod", "cp", "date", "ed", "emacs", "grep", "ls",
 	"make", "mv", "pr", "rm", "sed", Tsh, "vi", "who", NULL,
 	NULL
 };
 
 static const char *restr_com[] = {
-	Ttypeset, Tdr, TPATH, TENV, TSHELL, NULL
+	Ttypeset, Tdr, TENV, "HISTFILE", TPATH, TSHELL, NULL
 };
 
-static bool initio_done;
+extern const char Tpipest[];
 
 /* top-level parsing and execution environment */
 static struct env env;
 struct env *e = &env;
 
-/* compile-time assertions */
+/* buffer */
+#if !HAVE_GET_CURRENT_DIR_NAME
+static size_t getwd_bufsz = 448U;
+#endif
+static char *getwd_bufp = NULL;
+
+/* many compile-time assertions */
+mbCTA_BEG(main_c);
+
+ /* require char to be 8 bit long */
+ mbCTA(char_8bit, (CHAR_BIT) == 8 &&
+    (((unsigned int)(unsigned char)255U) == 255U) &&
+    (((unsigned int)(unsigned char)256U) == 0U) &&
+    mbiTYPE_UBITS(unsigned char) == 8U &&
+    mbiMASK_BITS(SCHAR_MAX) == 7U);
+
+ /* the next assertion is probably not really needed */
+ mbCTA(short_is_2_char, sizeof(short) == 2);
+ /* the next assertion is probably not really needed */
+ mbCTA(int_is_4_char, sizeof(int) == 4);
 
-/* this one should be defined by the standard */
-cta(char_is_1_char, (sizeof(char) == 1) && (sizeof(signed char) == 1) &&
-    (sizeof(unsigned char) == 1));
-cta(char_is_8_bits, ((CHAR_BIT) == 8) && ((int)(unsigned char)0xFF == 0xFF) &&
-    ((int)(unsigned char)0x100 == 0) && ((int)(unsigned char)(int)-1 == 0xFF));
-/* the next assertion is probably not really needed */
-cta(short_is_2_char, sizeof(short) == 2);
-cta(short_size_no_matter_of_signedness, sizeof(short) == sizeof(unsigned short));
-/* the next assertion is probably not really needed */
-cta(int_is_4_char, sizeof(int) == 4);
-cta(int_size_no_matter_of_signedness, sizeof(int) == sizeof(unsigned int));
+#ifndef MKSH_LEGACY_MODE
+ mbiCTA_TYPE_MBIT(sari, mksh_ari_t);
+ mbiCTA_TYPE_MBIT(uari, mksh_uari_t);
+ mbCTA(basic_int32_smask, mbiMASK_CHK(INT32_MAX));
+ mbCTA(basic_int32_umask, mbiMASK_CHK(UINT32_MAX));
+ mbCTA(basic_int32_ari,
+    mbiTYPE_UMAX(mksh_uari_t) == (UINT32_MAX) &&
+    /* require two’s complement */
+    ((INT32_MIN)+1 == -(INT32_MAX)));
+ /* the next assertion is probably not really needed */
+ mbCTA(ari_is_4_char, sizeof(mksh_ari_t) == 4);
+ /* but this is */
+ mbCTA(ari_has_31_bit, mbiMASK_BITS(INT32_MAX) == 31);
+ /* the next assertion is probably not really needed */
+ mbCTA(uari_is_4_char, sizeof(mksh_uari_t) == 4);
+ mbCTA(uari_is_32_bit, mbiTYPE_UBITS(mksh_uari_t) == 32);
+#else
+ mbCTA(long_complement, (LONG_MIN)+1 == -(LONG_MAX));
+#endif
+ /* these are always required */
+ mbCTA(ari_is_signed, !mbiTYPE_ISU(mksh_ari_t));
+ mbCTA(uari_is_unsigned, mbiTYPE_ISU(mksh_uari_t));
+ /* we require these to have the precisely same size and assume 2s complement */
+ mbCTA(ari_size_no_matter_of_signedness,
+    sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
 
-cta(long_ge_int, sizeof(long) >= sizeof(int));
-cta(long_size_no_matter_of_signedness, sizeof(long) == sizeof(unsigned long));
+ /* our formatting routines assume this */
+ mbCTA(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
 
-#ifndef MKSH_LEGACY_MODE
-/* the next assertion is probably not really needed */
-cta(ari_is_4_char, sizeof(mksh_ari_t) == 4);
-/* but this is */
-cta(ari_has_31_bit, 0 < (mksh_ari_t)(((((mksh_ari_t)1 << 15) << 15) - 1) * 2 + 1));
-/* the next assertion is probably not really needed */
-cta(uari_is_4_char, sizeof(mksh_uari_t) == 4);
-/* but the next three are; we REQUIRE unsigned integer wraparound */
-cta(uari_has_31_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 2 + 1));
-cta(uari_has_32_bit, 0 < (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3));
-cta(uari_wrap_32_bit,
-    (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 3) >
-    (mksh_uari_t)(((((mksh_uari_t)1 << 15) << 15) - 1) * 4 + 4));
-#endif
-/* these are always required */
-cta(ari_is_signed, (mksh_ari_t)-1 < (mksh_ari_t)0);
-cta(uari_is_unsigned, (mksh_uari_t)-1 > (mksh_uari_t)0);
-/* we require these to have the precisely same size and assume 2s complement */
-cta(ari_size_no_matter_of_signedness, sizeof(mksh_ari_t) == sizeof(mksh_uari_t));
-
-cta(sizet_size_no_matter_of_signedness, sizeof(ssize_t) == sizeof(size_t));
-cta(sizet_voidptr_same_size, sizeof(size_t) == sizeof(void *));
-cta(sizet_funcptr_same_size, sizeof(size_t) == sizeof(void (*)(void)));
-/* our formatting routines assume this */
-cta(ptr_fits_in_long, sizeof(size_t) <= sizeof(long));
-cta(ari_fits_in_long, sizeof(mksh_ari_t) <= sizeof(long));
+mbCTA_END(main_c);
+/* end of compile-time asserts */
 
-static mksh_uari_t
+static void
 rndsetup(void)
 {
-	register uint32_t h;
 	struct {
 		ALLOC_ITEM alloc_INT;
-		void *dataptr, *stkptr, *mallocptr;
-#if defined(__GLIBC__) && (__GLIBC__ >= 2)
-		sigjmp_buf jbuf;
-#endif
+		void *bssptr, *dataptr, *stkptr, *mallocptr;
+		kshjmp_buf jbuf;
 		struct timeval tv;
 	} *bufptr;
 	char *cp;
@@ -163,27 +179,29 @@ rndsetup(void)
 	/* undo what alloc() did to the malloc result address */
 	bufptr = (void *)(cp - sizeof(ALLOC_ITEM));
 	/* PIE or something similar provides us with deltas here */
-	bufptr->dataptr = &rndsetupstate;
+	bufptr->bssptr = &rndsetupstate;
+	bufptr->dataptr = &e;
 	/* ASLR in at least Windows, Linux, some BSDs */
 	bufptr->stkptr = &bufptr;
 	/* randomised malloc in BSD (and possibly others) */
 	bufptr->mallocptr = bufptr;
-#if defined(__GLIBC__) && (__GLIBC__ >= 2)
 	/* glibc pointer guard */
+#ifdef MKSH_NO_SIGSETJMP
+	setjmp(bufptr->jbuf);
+#else
 	sigsetjmp(bufptr->jbuf, 1);
 #endif
-	/* introduce variation (and yes, second arg MBZ for portability) */
+	/* introduce variation (cannot use gettimeofday *tzp portably) */
 	mksh_TIME(bufptr->tv);
 
 #ifdef MKSH_ALLOC_CATCH_UNDERRUNS
 	mprotect(((char *)bufptr) + 4096, 4096, PROT_READ | PROT_WRITE);
 #endif
-	h = chvt_rndsetup(bufptr, sizeof(*bufptr));
-
+	chvt_rndsetup(bufptr, sizeof(*bufptr));
 	afree(cp, APERM);
-	return ((mksh_uari_t)h);
 }
 
+/* pre-initio() */
 void
 chvt_reinit(void)
 {
@@ -197,35 +215,58 @@ static const char *empty_argv[] = {
 	Tmksh, NULL
 };
 
-static uint8_t
+#ifndef MKSH_EARLY_LOCALE_TRACKING
+static kby
 isuc(const char *cx) {
-	char *cp, *x;
-	uint8_t rv = 0;
+	const char *cp;
 
 	if (!cx || !*cx)
 		return (0);
 
-	/* uppercase a string duplicate */
-	strdupx(x, cx, ATEMP);
-	cp = x;
-	while ((*cp = ksh_toupper(*cp)))
+	if ((cp = cstrchr(cx, '.')))
 		++cp;
+	else
+		cp = cx;
+	if (!isCh(cp[0], 'U', 'u') ||
+	    !isCh(cp[1], 'T', 't') ||
+	    !isCh(cp[2], 'F', 'f'))
+		return (0);
+	cp += isch(cp[3], '-') ? 4 : 3;
+	return (isch(*cp, '8') && (isch(cp[1], '@') || !cp[1]));
+}
+#endif
 
-	/* check for UTF-8 */
-	if (strstr(x, "UTF-8") || strstr(x, "UTF8"))
-		rv = 1;
+kby
+kshname_islogin(const char **kshbasenamep)
+{
+	const char *cp;
+	size_t o;
+	kby rv;
 
-	/* free copy and out */
-	afree(x, ATEMP);
+	/* determine the basename (without '-' or path) of the executable */
+	cp = kshname;
+	o = 0;
+	while ((rv = cp[o++])) {
+		if (mksh_cdirsep(rv)) {
+			cp += o;
+			o = 0;
+		}
+	}
+	rv = isch(*cp, '-') || isch(*kshname, '-');
+	if (isch(*cp, '-'))
+		++cp;
+	if (!*cp)
+		cp = empty_argv[0];
+	*kshbasenamep = cp;
 	return (rv);
 }
 
-static int
-main_init(int argc, const char *argv[], Source **sp, struct block **lp)
+/* pre-initio() */
+static void
+main_init(int argc, const char *argv[], Source **sp)
 {
-	int argi, i;
+	int argi = 1, i;
 	Source *s = NULL;
-	struct block *l;
 	unsigned char restricted_shell = 0, errexit, utf_flag;
 	char *cp;
 	const char *ccp, **wp;
@@ -236,6 +277,7 @@ main_init(int argc, const char *argv[],
 #endif
 
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+	/* this must come *really* early due to locale use */
 	ebcdic_init();
 #endif
 	set_ifs(TC_IFSWS);
@@ -260,7 +302,11 @@ main_init(int argc, const char *argv[],
 	/* initialise permanent Area */
 	ainit(&aperm);
 	/* max. name length: -2147483648 = 11 (+ NUL) */
-	vtemp = alloc(offsetof(struct tbl, name[0]) + 12, APERM);
+	vtemp = alloc(mbccFAMSZ(struct tbl, name, 12), APERM);
+#if !HAVE_GET_CURRENT_DIR_NAME
+	getwd_bufp = alloc(getwd_bufsz + 1U, APERM);
+	getwd_bufp[getwd_bufsz] = '\0';
+#endif
 
 	/* set up base environment */
 	env.type = E_NONE;
@@ -268,24 +314,11 @@ main_init(int argc, const char *argv[],
 	/* set up global l->vars and l->funs */
 	newblock();
 
-	/* Do this first so output routines (eg, errorf, shellf) can work */
+	/* Do this first so output routines (eg. kwarnf, shellf) can work */
 	initio();
 
-	/* determine the basename (without '-' or path) of the executable */
-	ccp = kshname;
-	goto begin_parsing_kshname;
-	while ((i = ccp[argi++])) {
-		if (mksh_cdirsep(i)) {
-			ccp += argi;
- begin_parsing_kshname:
-			argi = 0;
-		}
-	}
-	Flag(FLOGIN) = (ord(*ccp) == ORD('-')) || (ord(*kshname) == ORD('-'));
-	if (ord(*ccp) == ORD('-'))
-		++ccp;
-	if (!*ccp)
-		ccp = empty_argv[0];
+	/* check kshname: leading dash, determine basename */
+	Flag(FLOGIN) = kshname_islogin(&ccp);
 
 	/*
 	 * Turn on nohup by default. (AT&T ksh does not have a nohup
@@ -306,7 +339,7 @@ main_init(int argc, const char *argv[],
 
 	/* define built-in commands and see if we were called as one */
 	ktinit(APERM, &builtins,
-	    /* currently up to 52 builtins: 75% of 128 = 2^7 */
+	    /* currently up to 50 builtins: 75% of 128 = 2^7 */
 	    7);
 	for (i = 0; mkshbuiltins[i].name != NULL; ++i) {
 		const char *builtin_name;
@@ -316,7 +349,7 @@ main_init(int argc, const char *argv[],
 		if (!builtin_name_cmp(ccp, builtin_name)) {
 			/* canonicalise argv[0] */
 			ccp = builtin_name;
-			as_builtin = true;
+			as_builtin = Ja;
 		}
 	}
 
@@ -324,24 +357,24 @@ main_init(int argc, const char *argv[],
 		/* check for -T option early */
 		argi = parse_args(argv, OF_FIRSTTIME, NULL);
 		if (argi < 0)
-			return (1);
+			unwind(LERROR);
 		/* called as rsh, rmksh, -rsh, RKSH.EXE, etc.? */
-		if (ksh_eq(*ccp, 'R', 'r')) {
+		if (isCh(*ccp, 'R', 'r')) {
 			++ccp;
 			++restricted_shell;
 		}
 #if defined(MKSH_BINSHPOSIX) || defined(MKSH_BINSHREDUCED)
 		/* are we called as -rsh or /bin/sh or SH.EXE or so? */
-		if (ksh_eq(ccp[0], 'S', 's') &&
-		    ksh_eq(ccp[1], 'H', 'h')) {
+		if (isCh(ccp[0], 'S', 's') &&
+		    isCh(ccp[1], 'H', 'h')) {
 			/* either also turns off braceexpand */
 #ifdef MKSH_BINSHPOSIX
 			/* enable better POSIX conformance */
-			change_flag(FPOSIX, OF_FIRSTTIME, true);
+			change_flag(FPOSIX, OF_FIRSTTIME, Ja);
 #endif
 #ifdef MKSH_BINSHREDUCED
 			/* enable kludge/compat mode */
-			change_flag(FSH, OF_FIRSTTIME, true);
+			change_flag(FSH, OF_FIRSTTIME, Ja);
 #endif
 		}
 #endif
@@ -393,7 +426,8 @@ main_init(int argc, const char *argv[],
 
 	/*
 	 * Set PATH to def_path (will set the path global variable).
-	 * (import of environment below will probably change this setting).
+	 * Import of environment below will probably change this setting;
+	 * the EXPORT flag is only added via initcoms for this to work.
 	 */
 	vp = global(TPATH);
 	/* setstr can't fail here */
@@ -405,7 +439,7 @@ main_init(int argc, const char *argv[],
 	 * by the environment or the user. Also, we want tab completion
 	 * on in vi by default.
 	 */
-	change_flag(FEMACS, OF_SPECIAL, true);
+	change_flag(FEMACS, OF_INTERNAL, Ja);
 #if !MKSH_S_NOVI
 	Flag(FVITABCOMPLETE) = 1;
 #endif
@@ -426,7 +460,7 @@ main_init(int argc, const char *argv[],
 	cp = str_val(vp);
 	/* Try to use existing $PWD if it is valid */
 	set_current_wd((mksh_abspath(cp) && test_eval(NULL, TO_FILEQ, cp,
-	    Tdot, true)) ? cp : NULL);
+	    Tdot, Ja)) ? cp : NULL);
 	if (current_wd[0])
 		simplify_path(current_wd);
 	/* Only set pwd if we know where we are or if it had a bogus value */
@@ -444,14 +478,16 @@ main_init(int argc, const char *argv[],
 	kshuid = getuid();
 	kshgid = getgid();
 	kshegid = getegid();
+	rndsetup();
 
 	safe_prompt = ksheuid ? "$ " : "# ";
 	vp = global("PS1");
 	/* Set PS1 if unset or we are root and prompt doesn't contain a # */
 	if (!(vp->flag & ISSET) ||
-	    (!ksheuid && !strchr(str_val(vp), '#')))
+	    (!ksheuid && !vstrchr(str_val(vp), '#')))
 		/* setstr can't fail here */
 		setstr(vp, safe_prompt, KSH_RETURN_ERROR);
+	/* ensure several variables will be (unsigned) integers */
 	setint_n((vp = global("BASHPID")), 0, 10);
 	vp->flag |= INT_U;
 	setint_n((vp = global("PGRP")), (mksh_uari_t)kshpgrp, 10);
@@ -466,9 +502,13 @@ main_init(int argc, const char *argv[],
 	vp->flag |= INT_U;
 	setint_n((vp = global("KSHGID")), (mksh_uari_t)kshgid, 10);
 	vp->flag |= INT_U;
-	setint_n((vp = global("RANDOM")), rndsetup(), 10);
-	vp->flag |= INT_U;
-	setint_n((vp_pipest = global("PIPESTATUS")), 0, 10);
+	/* this is needed globally */
+	setint_n((vp_pipest = global(Tpipest)), 0, 10);
+	/* unsigned integer, but avoid rndset call: done farther below */
+	vp = global("RANDOM");
+	vp->flag &= ~SPECIAL;
+	setint_n(vp, 0, 10);
+	vp->flag |= SPECIAL | INT_U;
 
 	/* Set this before parsing arguments */
 	Flag(FPRIVILEGED) = (kshuid != ksheuid || kshgid != kshegid) ? 2 : 0;
@@ -478,14 +518,17 @@ main_init(int argc, const char *argv[],
 	Flag(FMONITOR) = 127;
 #endif
 	/* this to note if utf-8 mode is set on command line (see below) */
+/*XXX this and the below can probably go away */
+/*XXX UTFMODE should be set from env here if locale tracking, just keep it */
 	UTFMODE = 2;
 
 	if (!as_builtin) {
 		argi = parse_args(argv, OF_CMDLINE, NULL);
 		if (argi < 0)
-			return (1);
+			unwind(LERROR);
 	}
 
+/*XXX drop this and the entire cases below */
 	/* process this later only, default to off (hysterical raisins) */
 	utf_flag = UTFMODE;
 	UTFMODE = 0;
@@ -496,7 +539,8 @@ main_init(int argc, const char *argv[],
 	} else if (Flag(FCOMMAND)) {
 		s = pushs(SSTRINGCMDLINE, ATEMP);
 		if (!(s->start = s->str = argv[argi++]))
-			errorf(Tf_optfoo, "", "", 'c', Treq_arg);
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_TWOMSG | KWF_NOERRNO, Tdc, Treq_arg);
 		while (*s->str) {
 			if (ctype(*s->str, C_QUOTE))
 				break;
@@ -532,10 +576,9 @@ main_init(int argc, const char *argv[],
 		s->u.shf = shf_open(s->file, O_RDONLY | O_MAYEXEC, 0,
 		    SHF_MAPHI | SHF_CLEXEC);
 		if (s->u.shf == NULL) {
-			shl_stdout_ok = false;
-			warningf(true, Tf_sD_s, s->file, cstrerror(errno));
-			/* mandated by SUSv4 */
-			exstat = 127;
+			shl_stdout_ok = Nee;
+			kwarnf(KWF_ERR(127) |
+			    KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, s->file);
 			unwind(LERROR);
 		}
 		kshname = s->file;
@@ -556,7 +599,7 @@ main_init(int argc, const char *argv[],
 
 	/* this bizarreness is mandated by POSIX */
 	if (Flag(FTALKING) && fstat(0, &s_stdin) >= 0 &&
-	    S_ISCHR(s_stdin.st_mode))
+	    (S_ISCHR(s_stdin.st_mode) || S_ISFIFO(s_stdin.st_mode)))
 		reset_nonblock(0);
 
 	/* initialise job control */
@@ -587,45 +630,48 @@ main_init(int argc, const char *argv[],
 	    SS_RESTORE_ORIG|SS_FORCE|SS_SHTRAP);
 #endif
 
-	l = e->loc;
-	if (as_builtin) {
-		l->argc = argc;
-		l->argv = argv;
-		l->argv[0] = ccp;
-	} else {
-		l->argc = argc - argi;
-		/*
-		 * allocate a new array because otherwise, when we modify
-		 * it in-place, ps(1) output changes; the meaning of argc
-		 * here is slightly different as it excludes kshname, and
-		 * we add a trailing NULL sentinel as well
-		 */
-		l->argv = alloc2(l->argc + 2, sizeof(void *), APERM);
-		l->argv[0] = kshname;
-		memcpy(&l->argv[1], &argv[argi], l->argc * sizeof(void *));
-		l->argv[l->argc + 1] = NULL;
+	/*
+	 * allocate a new array because otherwise, when we modify
+	 * it in-place, ps(1) output changes; the meaning of argc
+	 * here is slightly different as it excludes kshname, and
+	 * we add a trailing NULL sentinel as well
+	 */
+	e->loc->argc = argc - argi;
+	e->loc->argv = alloc2(e->loc->argc + 2, sizeof(char *), APERM);
+	memcpy(&e->loc->argv[1], &argv[argi], e->loc->argc * sizeof(char *));
+	e->loc->argv[e->loc->argc + 1] = NULL;
+	if (as_builtin)
+		e->loc->argv[0] = ccp;
+	else {
+		e->loc->argv[0] = kshname;
 		getopts_reset(1);
 	}
 
+/*XXX to go away entirely with locale tracking */
 	/* divine the initial state of the utf8-mode Flag */
 	ccp = null;
 	switch (utf_flag) {
 
+#ifdef MKSH_EARLY_LOCALE_TRACKING
+	/* not set on command line, not FTALKING */
+	case 2:
+#endif
 	/* auto-detect from locale or environment */
 	case 4:
-#if HAVE_SETLOCALE_CTYPE
+#ifndef MKSH_EARLY_LOCALE_TRACKING
+#if HAVE_POSIX_UTF8_LOCALE
 		ccp = setlocale(LC_CTYPE, "");
-#if HAVE_LANGINFO_CODESET
 		if (!isuc(ccp))
 			ccp = nl_langinfo(CODESET);
-#endif
 		if (!isuc(ccp))
 			ccp = null;
 #endif
+#endif
 		/* FALLTHROUGH */
 
 	/* auto-detect from environment */
 	case 3:
+#ifndef MKSH_EARLY_LOCALE_TRACKING
 		/* these were imported from environ earlier */
 		if (ccp == null)
 			ccp = str_val(global("LC_ALL"));
@@ -634,10 +680,15 @@ main_init(int argc, const char *argv[],
 		if (ccp == null)
 			ccp = str_val(global("LANG"));
 		UTFMODE = isuc(ccp);
+#else
+		recheck_ctype(); /*XXX probably unnecessary here */
+#endif
 		break;
 
+#ifndef MKSH_EARLY_LOCALE_TRACKING
 	/* not set on command line, not FTALKING */
 	case 2:
+#endif
 	/* unknown values */
 	default:
 		utf_flag = 0;
@@ -668,6 +719,8 @@ main_init(int argc, const char *argv[],
 	/* mark as initialised */
 	baseline_flags[(int)FNFLAGS] = 1;
 #endif
+	rndpush(shell_flags, sizeof(shell_flags));
+	rndset(hash(/*=current_wd*/ cp) ^ hash(argv[0]));
 	if (as_builtin)
 		goto skip_startup_files;
 
@@ -676,28 +729,29 @@ main_init(int argc, const char *argv[],
 	 * user will know why things broke.
 	 */
 	if (!current_wd[0] && Flag(FTALKING))
-		warningf(false, "can't determine current directory");
+		kwarnf(KWF_PREFIX | KWF_ONEMSG | KWF_NOERRNO,
+		    "can't determine current directory");
 
 	if (Flag(FLOGIN))
-		include(MKSH_SYSTEM_PROFILE, 0, NULL, true);
+		include(MKSH_SYSTEM_PROFILE, NULL, Ja);
 	if (Flag(FPRIVILEGED)) {
-		include(MKSH_SUID_PROFILE, 0, NULL, true);
+		include(MKSH_SUID_PROFILE, NULL, Ja);
 		/* note whether -p was enabled during startup */
 		if (Flag(FPRIVILEGED) == 1)
 			/* allow set -p to setuid() later */
 			Flag(FPRIVILEGED) = 3;
 		else
 			/* turn off -p if not set explicitly */
-			change_flag(FPRIVILEGED, OF_INTERNAL, false);
+			change_flag(FPRIVILEGED, OF_INTERNAL, Nee);
 		/* track shell-imposed changes */
 		baseline_flags[(int)FPRIVILEGED] = Flag(FPRIVILEGED);
 	} else {
 		if (Flag(FLOGIN))
-			include(substitute("$HOME/.profile", 0), 0, NULL, true);
+			include(substitute("$HOME/.profile", 0), NULL, Ja);
 		if (Flag(FTALKING)) {
 			cp = substitute("${ENV:-" MKSHRC_PATH "}", DOTILDE);
 			if (cp[0] != '\0')
-				include(cp, 0, NULL, true);
+				include(cp, NULL, Ja);
 		}
 	}
 	if (restricted_shell) {
@@ -722,8 +776,6 @@ main_init(int argc, const char *argv[],
 	alarm_init();
 
 	*sp = s;
-	*lp = l;
-	return (0);
 }
 
 /* this indirection barrier reduces stack usage during normal operation */
@@ -733,21 +785,22 @@ main(int argc, const char *argv[])
 {
 	int rv;
 	Source *s;
-	struct block *l;
 
-	if ((rv = main_init(argc, argv, &s, &l)) == 0) {
-		if (as_builtin) {
-			rv = c_builtin(l->argv);
-		} else {
-			shell(s, 0);
-			/* NOTREACHED */
-		}
+	main_init(argc, argv, &s);
+	if (as_builtin) {
+		rv = c_builtin(e->loc->argv) & 0xFF;
+		exstat = rv;
+		unwind(LEXIT);
+		/* NOTREACHED */
+	} else {
+		rv = shell(s, 0) & 0xFF;
+		/* NOTREACHED */
 	}
 	return (rv);
 }
 
 int
-include(const char *name, int argc, const char **argv, bool intr_ok)
+include(const char *name, const char **argv, Wahr intr_ok)
 {
 	Source *volatile s = NULL;
 	struct shf *shf;
@@ -793,13 +846,16 @@ include(const char *name, int argc, cons
 			unwind(i);
 			/* NOTREACHED */
 		default:
-			internal_errorf(Tunexpected_type, Tunwind, Tsource, i);
+			kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+			    Tunexpected_type, Tunwind, Tsource, i);
 			/* NOTREACHED */
 		}
 	}
 	if (argv) {
 		e->loc->argv = argv;
-		e->loc->argc = argc;
+		e->loc->argc = 0;
+		while (argv[e->loc->argc + 1])
+			++e->loc->argc;
 	}
 	s = pushs(SFILE, ATEMP);
 	s->u.shf = shf;
@@ -836,10 +892,9 @@ int
 shell(Source * volatile s, volatile int level)
 {
 	struct op *t;
-	volatile bool wastty = tobool(s->flags & SF_TTY);
-	volatile uint8_t attempts = 13;
-	volatile bool interactive = (level == 0) && Flag(FTALKING);
-	volatile bool sfirst = true;
+	volatile Wahr wastty = isWahr(s->flags & SF_TTY);
+	volatile kby attempts = 13;
+	volatile Wahr interactive = (level == 0) && Flag(FTALKING);
 	Source *volatile old_source = source;
 	int i;
 
@@ -847,13 +902,13 @@ shell(Source * volatile s, volatile int
 	if (level == 2)
 		e->flags |= EF_IN_EVAL;
 	if (interactive)
-		really_exit = false;
+		really_exit = Nee;
 	switch ((i = kshsetjmp(e->jbuf))) {
 	case 0:
 		break;
 	case LBREAK:
 	case LCONTIN:
-		/* assert: interactive == false */
+		/* assert: interactive == Nee */
 		source = old_source;
 		quitenv(NULL);
 		if (level == 2) {
@@ -861,8 +916,8 @@ shell(Source * volatile s, volatile int
 			unwind(i);
 			/* NOTREACHED */
 		}
-		internal_errorf(Tf_cant_s, Tshell,
-		    i == LBREAK ? Tbreak : Tcontinue);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tf_cant_s, Tshell, i == LBREAK ? Tbreak : Tcontinue);
 		/* NOTREACHED */
 	case LINTR:
 		/* we get here if SIGINT not caught or ignored */
@@ -871,7 +926,7 @@ shell(Source * volatile s, volatile int
 	case LSHELL:
 		if (interactive) {
 			if (i == LINTR)
-				shellf("\n");
+				shellf(Tnl);
 			/*
 			 * Reset any eof that was read as part of a
 			 * multiline command.
@@ -886,7 +941,7 @@ shell(Source * volatile s, volatile int
 			 * needs FMONITOR set (not FTALKING/SF_TTY)...
 			 */
 			/* toss any input we have so far */
-			yyrecursive_pop(true);
+			yyrecursive_pop(Ja);
 			s->start = s->str = null;
 			retrace_info = NULL;
 			herep = heres;
@@ -906,7 +961,8 @@ shell(Source * volatile s, volatile int
 	default:
 		source = old_source;
 		quitenv(NULL);
-		internal_errorf(Tunexpected_type, Tunwind, Tshell, i);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tunexpected_type, Tunwind, Tshell, i);
 		/* NOTREACHED */
 	}
 	while (/* CONSTCOND */ 1) {
@@ -923,10 +979,9 @@ shell(Source * volatile s, volatile int
 			j_notify();
 			set_prompt(PS1, s);
 		}
-		t = compile(s, sfirst, true);
+		t = compile(s, Ja);
 		if (interactive)
-			histsave(&s->line, NULL, HIST_FLUSH, true);
-		sfirst = false;
+			histsave(&s->line, NULL, HIST_FLUSH, Ja);
 		if (!t)
 			goto source_no_tree;
 		if (t->type == TEOF) {
@@ -935,7 +990,7 @@ shell(Source * volatile s, volatile int
 				s->type = SSTDIN;
 			} else if (wastty && !really_exit &&
 			    j_stopped_running()) {
-				really_exit = true;
+				really_exit = Ja;
 				s->type = SSTDIN;
 			} else {
 				/*
@@ -954,7 +1009,7 @@ shell(Source * volatile s, volatile int
 			exstat = execute(t, 0, NULL) & 0xFF;
 
 		if (t->type != TEOF && interactive && really_exit)
-			really_exit = false;
+			really_exit = Nee;
 
  source_no_tree:
 		reclaim();
@@ -1015,6 +1070,7 @@ newenv(int type)
 	struct env *ep;
 	char *cp;
 
+	reclim_trace();
 	/*
 	 * struct env includes ALLOC_ITEM for alignment constraints
 	 * so first get the actually used memory, then assign it
@@ -1026,7 +1082,7 @@ newenv(int type)
 	ainit(&ep->area);
 	ep->oenv = e;
 	ep->loc = e->loc;
-	ep->savefd = NULL;
+	ep->savedfd = NULL;
 	ep->temps = NULL;
 	ep->yyrecursive_statep = NULL;
 	ep->type = type;
@@ -1039,29 +1095,28 @@ quitenv(struct shf *shf)
 {
 	struct env *ep = e;
 	char *cp;
-	int fd;
+	int fd, i;
 
-	yyrecursive_pop(true);
+	yyrecursive_pop(Ja);
 	while (ep->oenv && ep->oenv->loc != ep->loc)
 		popblock();
-	if (ep->savefd != NULL) {
+	if (ep->savedfd != NULL) {
 		for (fd = 0; fd < NUFILE; fd++)
-			/* if ep->savefd[fd] < 0, means fd was closed */
-			if (ep->savefd[fd])
-				restfd(fd, ep->savefd[fd]);
-		if (ep->savefd[2])
+			if ((i = SAVEDFD(ep, fd)))
+				restfd(fd, i);
+		if (SAVEDFD(ep, 2))
 			/* Clear any write errors */
 			shf_reopen(2, SHF_WR, shl_out);
 	}
+	if (ep->type == E_EXEC) {
+		/* could be set, would be reclaim()ed below */
+		builtin_argv0 = NULL;
+	}
 	/*
 	 * Bottom of the stack.
 	 * Either main shell is exiting or cleanup_parents_env() was called.
 	 */
 	if (ep->oenv == NULL) {
-#ifdef DEBUG_LEAKS
-		int i;
-#endif
-
 		if (ep->type == E_NONE) {
 			/* Main shell exiting? */
 #if HAVE_PERSISTENT_HISTORY
@@ -1098,6 +1153,9 @@ quitenv(struct shf *shf)
 		sigprocmask(SIG_BLOCK, &sm_sigchld, NULL);
 #endif
 		afreeall(APERM);
+#if HAVE_GET_CURRENT_DIR_NAME
+		free_gnu_gcdn(getwd_bufp);
+#endif
 		for (fd = 3; fd < NUFILE; fd++)
 			if ((i = fcntl(fd, F_GETFD, 0)) != -1 &&
 			    (i & FD_CLOEXEC))
@@ -1132,14 +1190,14 @@ cleanup_parents_env(void)
 	 * anywhere.
 	 */
 
-	/* close all file descriptors hiding in savefd */
+	/* close all file descriptors hiding in savedfd */
 	for (ep = e; ep; ep = ep->oenv) {
-		if (ep->savefd) {
+		if (ep->savedfd) {
 			for (fd = 0; fd < NUFILE; fd++)
-				if (ep->savefd[fd] > 0)
-					close(ep->savefd[fd]);
-			afree(ep->savefd, &ep->area);
-			ep->savefd = NULL;
+				if (FDSVNUM(ep, fd) > (kui)FDBASE)
+					close((int)FDSVNUM(ep, fd));
+			afree(ep->savedfd, &ep->area);
+			ep->savedfd = NULL;
 		}
 #ifdef DEBUG_LEAKS
 		if (ep->type != E_NONE)
@@ -1182,6 +1240,7 @@ reclaim(void)
 	 */
 	if (source && source->areap == &e->area)
 		source = NULL;
+	retrace_info = NULL;
 	afreeall(&e->area);
 }
 
@@ -1211,7 +1270,7 @@ int
 tty_init_fd(void)
 {
 	int fd, rv, eno = 0;
-	bool do_close = false, is_devtty = true;
+	Wahr do_close = Nee, is_devtty = Ja;
 
 	if (tty_devtty) {
 		/* already got a tty which is /dev/tty */
@@ -1226,8 +1285,8 @@ tty_init_fd(void)
 		goto got_fd;
 	}
 #endif
-	if ((fd = open(T_devtty, O_RDWR, 0)) >= 0) {
-		do_close = true;
+	if ((fd = open("/dev/tty", O_RDWR, 0)) >= 0) {
+		do_close = Ja;
 		goto got_fd;
 	}
 	eno = errno;
@@ -1237,13 +1296,13 @@ tty_init_fd(void)
 		rv = 1;
 		goto out;
 	}
-	is_devtty = false;
+	is_devtty = Nee;
 
 	if (isatty((fd = 0)) || isatty((fd = 2)))
 		goto got_fd;
 	/* cannot find one */
 	rv = 2;
-	/* assert: do_close == false */
+	/* assert: do_close == Nee */
 	goto out;
 
  got_fd:
@@ -1268,186 +1327,12 @@ tty_init_fd(void)
 	return (rv);
 }
 
-/* A shell error occurred (eg, syntax error, etc.) */
-
-#define VWARNINGF_ERRORPREFIX	1
-#define VWARNINGF_FILELINE	2
-#define VWARNINGF_BUILTIN	4
-#define VWARNINGF_INTERNAL	8
-
-static void vwarningf(unsigned int, const char *, va_list)
-    MKSH_A_FORMAT(__printf__, 2, 0);
-
-static void
-vwarningf(unsigned int flags, const char *fmt, va_list ap)
-{
-	if (fmt) {
-		if (flags & VWARNINGF_INTERNAL)
-			shf_fprintf(shl_out, Tf_sD_, "internal error");
-		if (flags & VWARNINGF_ERRORPREFIX)
-			error_prefix(tobool(flags & VWARNINGF_FILELINE));
-		if ((flags & VWARNINGF_BUILTIN) &&
-		    /* not set when main() calls parse_args() */
-		    builtin_argv0 && builtin_argv0 != kshname)
-			shf_fprintf(shl_out, Tf_sD_, builtin_argv0);
-		shf_vfprintf(shl_out, fmt, ap);
-		shf_putchar('\n', shl_out);
-	}
-	shf_flush(shl_out);
-}
-
-void
-errorfx(int rc, const char *fmt, ...)
-{
-	va_list va;
-
-	exstat = rc;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-void
-errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	exstat = 1;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-/* like errorf(), but no unwind is done */
-void
-warningf(bool fileline, const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | (fileline ? VWARNINGF_FILELINE : 0),
-	    fmt, va);
-	va_end(va);
-}
-
-/*
- * Used by built-in utilities to prefix shell and utility name to message
- * (also unwinds environments for special builtins).
- */
-void
-bi_errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	exstat = 1;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
-	    VWARNINGF_BUILTIN, fmt, va);
-	va_end(va);
-
-	/* POSIX special builtins cause non-interactive shells to exit */
-	if (builtin_spec) {
-		builtin_argv0 = NULL;
-		/* may not want to use LERROR here */
-		unwind(LERROR);
-	}
-}
-
-/*
- * Used by functions called by builtins and not:
- * identical to errorfx if first argument is nil,
- * like bi_errorf storing the errorlevel into it otherwise
- */
-void
-maybe_errorf(int *ep, int rc, const char *fmt, ...)
-{
-	va_list va;
-
-	/* debugging: note that stdout not valid */
-	shl_stdout_ok = false;
-
-	exstat = rc;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_ERRORPREFIX | VWARNINGF_FILELINE |
-	    (ep ? VWARNINGF_BUILTIN : 0), fmt, va);
-	va_end(va);
-
-	if (!ep)
-		goto and_out;
-	*ep = rc;
-
-	/* POSIX special builtins cause non-interactive shells to exit */
-	if (builtin_spec) {
-		builtin_argv0 = NULL;
-		/* may not want to use LERROR here */
- and_out:
-		unwind(LERROR);
-	}
-}
-
-/* Called when something that shouldn't happen does */
-void
-internal_errorf(const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_INTERNAL, fmt, va);
-	va_end(va);
-	unwind(LERROR);
-}
-
-void
-internal_warningf(const char *fmt, ...)
-{
-	va_list va;
-
-	va_start(va, fmt);
-	vwarningf(VWARNINGF_INTERNAL, fmt, va);
-	va_end(va);
-}
-
-/* used by error reporting functions to print "ksh: .kshrc[25]: " */
-void
-error_prefix(bool fileline)
-{
-	/* Avoid foo: foo[2]: ... */
-	if (!fileline || !source || !source->file ||
-	    strcmp(source->file, kshname) != 0)
-		shf_fprintf(shl_out, Tf_sD_, kshname +
-		    (*kshname == '-' ? 1 : 0));
-	if (fileline && source && source->file != NULL) {
-		shf_fprintf(shl_out, "%s[%lu]: ", source->file,
-		    (unsigned long)(source->errline ?
-		    source->errline : source->line));
-		source->errline = 0;
-	}
-}
-
 /* printf to shl_out (stderr) with flush */
 void
 shellf(const char *fmt, ...)
 {
 	va_list va;
 
-	if (!initio_done)
-		/* shl_out may not be set up yet... */
-		return;
 	va_start(va, fmt);
 	shf_vfprintf(shl_out, fmt, va);
 	va_end(va);
@@ -1461,7 +1346,8 @@ shprintf(const char *fmt, ...)
 	va_list va;
 
 	if (!shl_stdout_ok)
-		internal_errorf("shl_stdout not valid");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "shl_stdout not valid");
 	va_start(va, fmt);
 	shf_vfprintf(shl_stdout, fmt, va);
 	va_end(va);
@@ -1485,6 +1371,7 @@ int shl_dbg_fd;
 #endif
 struct shf shf_iob[NSHF_IOB];
 
+/* pre-initio() */
 void
 initio(void)
 {
@@ -1496,38 +1383,43 @@ initio(void)
 	shf_fdopen(1, SHF_WR, shl_stdout);
 	shf_fdopen(2, SHF_WR, shl_out);
 	shf_fdopen(2, SHF_WR, shl_xtrace);
+	initio_done = Ja;
 #ifdef DF
 	if ((lfp = getenv("SDMKSH_PATH")) == NULL) {
 		if ((lfp = getenv("HOME")) == NULL || !mksh_abspath(lfp))
-			errorf("can't get home directory");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG |
+			    KWF_NOERRNO, "can't get home directory");
 		strpathx(lfp, lfp, "mksh-dbg.txt", 1);
 	}
 
 	if ((shl_dbg_fd = open(lfp, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0)
-		errorf("can't open debug output file %s", lfp);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG,
+		    lfp, "can't open debug output file");
 	if (shl_dbg_fd < FDBASE) {
 		int nfd;
 
-		nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE);
+		if ((nfd = fcntl(shl_dbg_fd, F_DUPFD, FDBASE)) == -1)
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG,
+			    "can't dup debug output file");
 		close(shl_dbg_fd);
-		if ((shl_dbg_fd = nfd) == -1)
-			errorf("can't dup debug output file");
+		shl_dbg_fd = nfd;
 	}
 	fcntl(shl_dbg_fd, F_SETFD, FD_CLOEXEC);
 	shf_fdopen(shl_dbg_fd, SHF_WR, shl_dbg);
 	DF("=== open ===");
+	initio_done = 2;
 #endif
-	initio_done = true;
 }
 
 /* A dup2() with error checking */
 int
-ksh_dup2(int ofd, int nfd, bool errok)
+ksh_dup2(int ofd, int nfd, Wahr errok)
 {
 	int rv;
 
 	if (((rv = dup2(ofd, nfd)) < 0) && !errok && (errno != EBADF))
-		errorf(Ttoo_many_files);
+		kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+		    Ttoo_many_files, ofd, nfd);
 
 #ifdef __ultrix
 	/*XXX imake style */
@@ -1539,21 +1431,25 @@ ksh_dup2(int ofd, int nfd, bool errok)
 }
 
 /*
- * Move fd from user space (0 <= fd < 10) to shell space (fd >= 10),
- * set close-on-exec flag. See FDBASE in sh.h, maybe 24 not 10 here.
+ * Move fd from user space (0 <= fd < FDBASE) to shell space (fd >= FDBASE)
+ * set moved fd’s close-on-exec flag (see sh.h for FDBASE).
  */
-short
+int
 savefd(int fd)
 {
 	int nfd = fd;
 
+	errno = 0;
 	if (fd < FDBASE && (nfd = fcntl(fd, F_DUPFD, FDBASE)) < 0 &&
 	    (errno == EBADF || errno == EPERM))
 		return (-1);
-	if (nfd < 0 || nfd > SHRT_MAX)
-		errorf(Ttoo_many_files);
-	fcntl(nfd, F_SETFD, FD_CLOEXEC);
-	return ((short)nfd);
+	if (nfd < FDBASE || nfd > (int)(kui)FDMAXNUM)
+		kerrf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE,
+		    Ttoo_many_files, fd, nfd);
+	if (fcntl(nfd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed,
+		    "set", nfd);
+	return (nfd);
 }
 
 void
@@ -1566,7 +1462,7 @@ restfd(int fd, int ofd)
 		close(fd);
 	else if (fd != ofd) {
 		/*XXX: what to do if this dup fails? */
-		ksh_dup2(ofd, fd, true);
+		ksh_dup2(ofd, fd, Ja);
 		close(ofd);
 	}
 }
@@ -1577,7 +1473,8 @@ openpipe(int *pv)
 	int lpv[2];
 
 	if (pipe(lpv) < 0)
-		errorf("can't create pipe - try again");
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG,
+		    "pipe");
 	pv[0] = savefd(lpv[0]);
 	if (pv[0] != lpv[0])
 		close(lpv[0]);
@@ -1614,6 +1511,7 @@ check_fd(const char *name, int mode, con
  illegal_fd_name:
 		if (emsgp)
 			*emsgp = "illegal file descriptor name";
+		errno = EINVAL;
 		return (-1);
 	}
 
@@ -1635,6 +1533,11 @@ check_fd(const char *name, int mode, con
 			*emsgp = (fl == O_WRONLY) ?
 			    "fd not open for reading" :
 			    "fd not open for writing";
+#ifdef ENXIO
+		errno = ENXIO;
+#else
+		errno = EBADF;
+#endif
 		return (-1);
 	}
 	return (fd);
@@ -1699,6 +1602,7 @@ coproc_getfd(int mode, const char **emsg
 		return (fd);
 	if (emsgp)
 		*emsgp = "no coprocess";
+	errno = EBADF;
 	return (-1);
 }
 
@@ -1726,6 +1630,8 @@ coproc_cleanup(int reuse)
 	}
 }
 
+static const char temp_tpl[] = "/shXXXXXX.tmp";
+
 struct temp *
 maketemp(Area *ap, Temp_type type, struct temp **tlist)
 {
@@ -1739,23 +1645,21 @@ maketemp(Area *ap, Temp_type type, struc
 	dir = tmpdir ? tmpdir : MKSH_DEFAULT_TMPDIR;
 	/* add "/shXXXXXX.tmp" plus NUL */
 	len = strlen(dir);
-	checkoktoadd(len, offsetof(struct temp, tffn[0]) + 14);
-	tp = alloc(offsetof(struct temp, tffn[0]) + 14 + len, ap);
+	cp = alloc1(mbccFAMSZ(struct temp, tffn, sizeof(temp_tpl)), len, ap);
 
+	tp = (void *)cp;
 	tp->shf = NULL;
 	tp->pid = procpid;
 	tp->type = type;
 
-	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode)) {
-		tp->tffn[0] = '\0';
-		goto maketemp_out;
-	}
-
-	cp = (void *)tp;
-	cp += offsetof(struct temp, tffn[0]);
+	cp += offsetof(struct temp, tffn);
 	memcpy(cp, dir, len);
 	cp += len;
-	memcpy(cp, "/shXXXXXX.tmp", 14);
+	memstr(cp, temp_tpl);
+
+	if (stat(dir, &sb) || !S_ISDIR(sb.st_mode))
+		goto maketemp_out;
+
 	/* point to the first of six Xes */
 	cp += 3;
 
@@ -1805,6 +1709,7 @@ maketemp(Area *ap, Temp_type type, struc
 static void tgrow(struct table *);
 static int tnamecmp(const void *, const void *);
 
+/* pre-initio() tp->tbls=NULL tp->tshift=INIT_TBLSHIFT-1 */
 static void
 tgrow(struct table *tp)
 {
@@ -1813,7 +1718,8 @@ tgrow(struct table *tp)
 	struct tbl **ntblp, **otblp = tp->tbls;
 
 	if (tp->tshift > 29)
-		internal_errorf("hash table size limit reached");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    "hash table size limit reached");
 
 	/* calculate old size, new shift and new size */
 	osize = (size_t)1 << (tp->tshift++);
@@ -1855,8 +1761,9 @@ tgrow(struct table *tp)
 	afree(otblp, tp->areap);
 }
 
+/* pre-initio() initshift=0 */
 void
-ktinit(Area *ap, struct table *tp, uint8_t initshift)
+ktinit(Area *ap, struct table *tp, kby initshift)
 {
 	tp->areap = ap;
 	tp->tbls = NULL;
@@ -1867,7 +1774,7 @@ ktinit(Area *ap, struct table *tp, uint8
 
 /* table, name (key) to search for, hash(name), rv pointer to tbl ptr */
 struct tbl *
-ktscan(struct table *tp, const char *name, uint32_t h, struct tbl ***ppp)
+ktscan(struct table *tp, const char *name, k32 h, struct tbl ***ppp)
 {
 	size_t j, perturb, mask;
 	struct tbl **pp, *p;
@@ -1892,7 +1799,7 @@ ktscan(struct table *tp, const char *nam
 
 /* table, name (key) to enter, hash(n) */
 struct tbl *
-ktenter(struct table *tp, const char *n, uint32_t h)
+ktenter(struct table *tp, const char *n, k32 h)
 {
 	struct tbl **pp, *p;
 	size_t len;
@@ -1908,9 +1815,8 @@ ktenter(struct table *tp, const char *n,
 	}
 
 	/* create new tbl entry */
-	len = strlen(n);
-	checkoktoadd(len, offsetof(struct tbl, name[0]) + 1);
-	p = alloc(offsetof(struct tbl, name[0]) + ++len, tp->areap);
+	len = strlen(n) + 1U;
+	p = alloc(mbccFAMsz(struct tbl, name, len), tp->areap);
 	p->flag = 0;
 	p->type = 0;
 	p->areap = tp->areap;
@@ -1997,8 +1903,8 @@ DF(const char *fmt, ...)
 	mksh_TIME(tv);
 	timet2mjd(&mjd, tv.tv_sec);
 	shf_fprintf(shl_dbg, "[%02u:%02u:%02u (%u) %u.%06u] ",
-	    (unsigned)mjd.sec / 3600, ((unsigned)mjd.sec / 60) % 60,
-	    (unsigned)mjd.sec % 60, (unsigned)getpid(),
+	    (unsigned)mjd.sec / 3600U, ((unsigned)mjd.sec / 60U) % 60U,
+	    (unsigned)mjd.sec % 60U, (unsigned)getpid(),
 	    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
 	va_start(args, fmt);
 	shf_vfprintf(shl_dbg, fmt, args);
@@ -2010,7 +1916,7 @@ DF(const char *fmt, ...)
 #endif
 
 void
-x_mkraw(int fd, mksh_ttyst *ocb, bool forread)
+x_mkraw(int fd, mksh_ttyst *ocb, Wahr forread)
 {
 	mksh_ttyst cb;
 
@@ -2018,22 +1924,24 @@ x_mkraw(int fd, mksh_ttyst *ocb, bool fo
 		mksh_tcget(fd, ocb);
 	else
 		ocb = &tty_state;
+#ifdef FLUSHO
+	ocb->c_lflag &= ~(FLUSHO);
+#endif
 
 	cb = *ocb;
-	if (forread) {
-		cb.c_iflag &= ~(ISTRIP);
-		cb.c_lflag &= ~(ICANON) | ECHO;
-	} else {
-		cb.c_iflag &= ~(INLCR | ICRNL | ISTRIP);
+	cb.c_iflag &= ~(IGNPAR | PARMRK | INLCR | IGNCR | ICRNL | ISTRIP);
+	cb.c_iflag |= BRKINT;
+	if (forread)
+		cb.c_lflag &= ~(ICANON);
+	else
 		cb.c_lflag &= ~(ISIG | ICANON | ECHO);
-	}
-#if defined(VLNEXT) && defined(_POSIX_VDISABLE)
+#if defined(VLNEXT)
 	/* OSF/1 processes lnext when ~icanon */
-	cb.c_cc[VLNEXT] = _POSIX_VDISABLE;
+	KSH_DOVDIS(cb.c_cc[VLNEXT]);
 #endif
 	/* SunOS 4.1.x and OSF/1 process discard(flush) when ~icanon */
-#if defined(VDISCARD) && defined(_POSIX_VDISABLE)
-	cb.c_cc[VDISCARD] = _POSIX_VDISABLE;
+#if defined(VDISCARD)
+	KSH_DOVDIS(cb.c_cc[VDISCARD]);
 #endif
 	cb.c_cc[VTIME] = 0;
 	cb.c_cc[VMIN] = 1;
@@ -2042,6 +1950,9 @@ x_mkraw(int fd, mksh_ttyst *ocb, bool fo
 }
 
 #ifdef MKSH_ENVDIR
+#if HAVE_POSIX_UTF8_LOCALE
+# error MKSH_ENVDIR has not been adapted to work with POSIX locale!
+#else
 static void
 init_environ(void)
 {
@@ -2053,21 +1964,19 @@ init_environ(void)
 	struct dirent *dent;
 
 	if ((dirp = opendir(MKSH_ENVDIR)) == NULL) {
-		warningf(false, "cannot read environment from %s: %s",
-		    MKSH_ENVDIR, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, MKSH_ENVDIR,
+		    "can't read environment");
 		return;
 	}
 	XinitN(xs, 256, ATEMP);
  read_envfile:
 	errno = 0;
 	if ((dent = readdir(dirp)) != NULL) {
-		if (skip_varname(dent->d_name, true)[0] == '\0') {
+		if (skip_varname(dent->d_name, Ja)[0] == '\0') {
 			strpathx(xp, MKSH_ENVDIR, dent->d_name, 1);
 			if (!(shf = shf_open(xp, O_RDONLY, 0, 0))) {
-				warningf(false,
-				    "cannot read environment %s from %s: %s",
-				    dent->d_name, MKSH_ENVDIR,
-				    cstrerror(errno));
+				kwarnf(KWF_PREFIX | KWF_THREEMSG, MKSH_ENVDIR,
+				    dent->d_name, "can't read environment");
 				goto read_envfile;
 			}
 			afree(xp, ATEMP);
@@ -2080,28 +1989,28 @@ init_environ(void)
 			while ((n = shf_read(xp, Xnleft(xs, xp), shf)) > 0) {
 				xp += n;
 				if (Xnleft(xs, xp) <= 0)
-					XcheckN(xs, xp, Xlength(xs, xp));
+					XcheckN(xs, xp, 128);
 			}
 			if (n < 0) {
-				warningf(false,
-				    "cannot read environment %s from %s: %s",
-				    dent->d_name, MKSH_ENVDIR,
-				    cstrerror(shf_errno(shf)));
+				kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+				    shf_errno(shf), MKSH_ENVDIR,
+				    dent->d_name, "can't read environment");
 			} else {
 				*xp = '\0';
+				rndpush(Xstring(xs, xp), Xlength(xs, xp));
 				xp = Xstring(xs, xp);
-				rndpush(xp);
 				typeset(xp, IMPORT | EXPORT, 0, 0, 0);
 			}
 			shf_close(shf);
 		}
 		goto read_envfile;
 	} else if (errno)
-		warningf(false, "cannot read environment from %s: %s",
-		    MKSH_ENVDIR, cstrerror(errno));
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, MKSH_ENVDIR,
+		    "can't read environment");
 	closedir(dirp);
 	Xfree(xs, xp);
 }
+#endif
 #else
 extern char **environ;
 
@@ -2115,9 +2024,25 @@ init_environ(void)
 
 	wp = (const char **)environ;
 	while (*wp != NULL) {
-		rndpush(*wp);
+		rndpush(*wp, strlen(*wp));
 		typeset(*wp, IMPORT | EXPORT, 0, 0, 0);
+#ifdef MKSH_EARLY_LOCALE_TRACKING
+		if (isch((*wp)[0], 'L') && (
+		    (isch((*wp)[1], 'C') && isch((*wp)[2], '_')) ||
+		    !strcmp(*wp, "LANG"))) {
+			const char **P;
+
+			/* remove LC_* / LANG from own environment */
+			P = wp;
+			while ((*P = *(P + 1)))
+				++P;
+			/* now setlocale with "" will use the default locale */
+			/* matching the user expectation wrt passed-in vars */
+		} else
+			++wp;
+#else
 		++wp;
+#endif
 	}
 }
 #endif
@@ -2127,25 +2052,194 @@ void
 recheck_ctype(void)
 {
 	const char *ccp;
-	uint8_t old_utfmode = UTFMODE;
+#if !HAVE_POSIX_UTF8_LOCALE
+	const char *cdp;
+#endif
 
+	/* determine active LC_CTYPE value */
 	ccp = str_val(global("LC_ALL"));
-	if (ccp == null)
+	if (!*ccp)
 		ccp = str_val(global("LC_CTYPE"));
-	if (ccp == null)
+	if (!*ccp)
 		ccp = str_val(global("LANG"));
-	UTFMODE = isuc(ccp);
-#if HAVE_SETLOCALE_CTYPE
-	ccp = setlocale(LC_CTYPE, ccp);
-#if HAVE_LANGINFO_CODESET
-	if (!isuc(ccp))
-		ccp = nl_langinfo(CODESET);
+#if !HAVE_POSIX_UTF8_LOCALE
+	if (!*ccp)
+		ccp = MKSH_DEFAULT_LOCALE;
 #endif
-	if (isuc(ccp))
-		UTFMODE = 1;
+
+	/* determine codeset used */
+#if HAVE_POSIX_UTF8_LOCALE
+	errno = EINVAL;
+	if (!setlocale(LC_CTYPE, ccp)) {
+		kwarnf(KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG, "setlocale");
+		return;
+	}
+	ccp = nl_langinfo(CODESET);
+#else
+	/* tacked on to a locale name or just a codeset? */
+	if ((cdp = cstrchr(ccp, '.')))
+		ccp = cdp + 1;
 #endif
 
-	if (Flag(FPOSIX) && UTFMODE && !old_utfmode)
-		warningf(true, "early locale tracking enabled UTF-8 mode while in POSIX mode, you are now noncompliant");
+	/* see whether it’s UTF-8 */
+	UTFMODE = 0;
+	if (!isCh(ccp[0], 'U', 'u') ||
+	    !isCh(ccp[1], 'T', 't') ||
+	    !isCh(ccp[2], 'F', 'f'))
+		return;
+	ccp += isch(ccp[3], '-') ? 4 : 3;
+	if (!isch(*ccp, '8'))
+		return;
+	++ccp;
+	/* verify nothing untoward trails the string */
+#if !HAVE_POSIX_UTF8_LOCALE
+	if (cdp) {
+		/* tacked onto a locale name */
+		if (*ccp && !isch(*ccp, '@'))
+			return;
+	} else
+	  /* OSX has a "UTF-8" locale… */
+#endif
+	/* just a codeset so require EOS */
+	  if (*ccp != '\0')
+		return;
+	/* positively identified as UTF-8 */
+	UTFMODE = 1;
+}
+#endif
+
+#if !HAVE_MEMMOVE
+void *
+rpl_memmove(void *dst, const void *src, size_t len)
+{
+	const unsigned char *s = src;
+	unsigned char *d = dst;
+
+	if (len) {
+		if (src < dst) {
+			s += len;
+			d += len;
+			while (len--)
+				*--d = *--s;
+		} else
+			while (len--)
+				*d++ = *s++;
+	}
+	return (dst);
 }
 #endif
+
+const char *
+ksh_getwd(void)
+{
+#if HAVE_GET_CURRENT_DIR_NAME
+	free_gnu_gcdn(getwd_bufp);
+	getwd_bufp = get_current_dir_name();
+	if (getwd_bufp && !mksh_abspath(getwd_bufp)) {
+		free_gnu_gcdn(getwd_bufp);
+		getwd_bufp = NULL;
+		errno = EACCES;
+	}
+#else
+ redo:
+	if (getcwd(getwd_bufp, getwd_bufsz)) {
+		if (mksh_abspath(getwd_bufp))
+			goto done;
+		errno = EACCES;
+		return (NULL);
+	}
+	if (errno == ERANGE) {
+		if (notoktomul(getwd_bufsz, 2U)) {
+			errno = ENAMETOOLONG;
+			return (NULL);
+		}
+		getwd_bufsz <<= 1;
+		getwd_bufp = aresize(getwd_bufp, getwd_bufsz + 1U, APERM);
+		getwd_bufp[getwd_bufsz] = '\0';
+		goto redo;
+	}
+	return (NULL);
+ done:
+#endif
+	return (getwd_bufp);
+}
+
+#ifdef DEBUG
+#if 1 /* enforce, 0 to find out */
+static void
+reclim_trace(void)
+{
+	struct env *ep = e;
+	unsigned int nenv = 0;
+
+ count:
+	if (++nenv == 128U) {
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_PREFIX |
+		    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+		    "\"mksh/Build.sh -g\" recursion limit exceeded");
+	} else if (ep) {
+		ep = ep->oenv;
+		goto count;
+	}
+}
+#elif defined(SIG_ATOMIC_MAX) && (SIG_ATOMIC_MAX >= 0x7FFF)
+#include <syslog.h>
+static void reclim_atexit(void);
+
+static volatile sig_atomic_t reclim_v = 0;
+static kby reclim_warned = 0;
+
+static void
+reclim_trace(void)
+{
+	struct env *ep = e;
+	unsigned int nenv = 0;
+
+	if (!reclim_v)
+		atexit(reclim_atexit);
+ count:
+	if (nenv == SIG_ATOMIC_MAX) {
+		syslog(LOG_WARNING, "reclim_trace: SIG_ATOMIC_MAX reached");
+		reclim_v = SIG_ATOMIC_MAX;
+		return;
+	}
+	if (!++nenv) {
+		--nenv;
+		if (!reclim_warned) {
+			syslog(LOG_WARNING, "reclim_trace: %s reached",
+			    "UINT_MAX");
+			reclim_warned = 1;
+		}
+	} else if (ep) {
+		ep = ep->oenv;
+		goto count;
+	}
+
+	if ((mbiHUGE_U)nenv >= (mbiHUGE_U)(SIG_ATOMIC_MAX)) {
+		if (!reclim_warned) {
+			syslog(LOG_WARNING, "reclim_trace: %s reached",
+			    "SIG_ATOMIC_MAX");
+			reclim_warned = 1;
+		}
+		reclim_v = SIG_ATOMIC_MAX;
+		return;
+	}
+	if ((sig_atomic_t)nenv > reclim_v)
+		reclim_v = (sig_atomic_t)nenv;
+}
+
+static void
+reclim_atexit(void)
+{
+	unsigned int nenv = (unsigned int)reclim_v;
+
+	if (nenv > 32U)
+		syslog(LOG_DEBUG, "max recursion limit: %u", nenv);
+}
+#else /* missing suitable large sig_atomic_t */
+static void
+reclim_trace(void)
+{
+}
+#endif /* missing suitable large sig_atomic_t */
+#endif /* DEBUG */
--- /dev/null
+++ mksh-59c/mbsdcc.h
@@ -0,0 +1,245 @@
+/*-
+ * MirBSD ISO C compiler toolkit (macros for mbsdint.h and others)
+ *
+ * © mirabilos Ⓕ CC0 or The MirOS Licence (MirBSD)
+ */
+
+#ifndef SYSKERN_MBSDCC_H
+#define SYSKERN_MBSDCC_H "$MirOS: src/bin/mksh/mbsdcc.h,v 1.11 2025/02/11 03:56:07 tg Exp $"
+
+/*
+ * Note: this header uses the SIZE_MAX (or similar) definitions
+ * from <basetsd.h> or <limits.h> if present, so either include
+ * these before this header or include "mbsdint.h", which fixes
+ * up the corresponding definition.
+ *
+ * Place the inclusion of this after <sys/cdefs.h> or something
+ * that pulls it, for example <sys/types.h>.
+ *
+ * Furthermore, either include <stdlib.h> for abort(3), or pro‐
+ * vide an mbccABEND macro (preferred).
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <stddef.h>
+#else
+#include <sys/stddef.h>
+#endif
+
+/* mbccABEND should be provided by the user, called by mbsd*.h only */
+#ifndef mbccABEND
+#define mbccABEND(reasonstr) abort()
+#endif
+
+/* monkey-patch known-bad offsetof versions */
+#if (defined(__KLIBC__) || defined(__dietlibc__)) && \
+    ((defined(__GNUC__) && (__GNUC__ > 3)) || defined(__NWCC__))
+#undef offsetof
+#define offsetof(struc,memb)	__builtin_offsetof(struc, memb)
+#endif
+
+/* should be defined by <sys/cdefs.h> already */
+#ifndef __predict_true
+#if defined(__GNUC__) && (__GNUC__ >= 3) /* 2.96, but keep it simple here */
+#define __predict_true(exp)	__builtin_expect(!!(exp), 1)
+#define __predict_false(exp)	__builtin_expect(!!(exp), 0)
+#else
+#define __predict_true(exp)	(!!(exp))
+#define __predict_false(exp)	(!!(exp))
+#endif /* !GCC 3.x */
+#endif /* ndef(__predict_true) */
+
+/* mbsdint.h replaces this with mbiSIZE_MAX */
+#undef mbccSIZE_MAX
+#if defined(SIZE_MAX)
+#define mbccSIZE_MAX		((size_t)(SIZE_MAX)
+#elif defined(SIZE_T_MAX)
+#define mbccSIZE_MAX		((size_t)(SIZE_T_MAX)
+#elif defined(MAXSIZE_T)
+#define mbccSIZE_MAX		((size_t)(MAXSIZE_T)
+#else
+#define mbccSIZE_MAX		((size_t)~(size_t)0)
+#endif
+
+#ifdef __cplusplus
+#define mbcextern		extern "C"
+/* for headers (BSD __BEGIN_DECLS/__END_DECLS) */
+#define mbcextern_beg		extern "C" {
+#define mbcextern_end		}
+#else
+#define mbcextern		extern
+#define mbcextern_beg
+#define mbcextern_end
+#endif
+
+/* compiler warning pragmas, NOP for other compilers */
+#ifdef _MSC_VER
+/* push, suppress space-separated listed warning numbers */
+#define mbmscWd(d)		__pragma(warning(push)) \
+				__pragma(warning(disable: d))
+/* suppress for only the next line */
+#define mbmscWs(d)		__pragma(warning(suppress: d))
+/* pop from mbmscWd */
+#define mbmscWpop		__pragma(warning(pop))
+#else
+#define mbmscWd(d)
+#define mbmscWs(d)
+#define mbmscWpop
+#endif
+
+/* in-expression compile-time check evaluating to 0 */
+#ifdef __cplusplus
+template<bool> struct mbccChkExpr_sa;
+template<> struct mbccChkExpr_sa<true> { typedef int Type; };
+#define mbccChkExpr(test)	(static_cast<mbccChkExpr_sa<!!(0+(test))>::Type>(0))
+#else
+#define mbccChkExpr(test)	mbmscWs(4116) \
+				(sizeof(struct { unsigned int (mbccChkExpr):((0+(test)) ? 1 : -1); }) * 0)
+#endif
+
+/* ensure value x is a constant expression */
+#ifdef __cplusplus
+template<bool,bool> struct mbccCEX_sa;
+template<> struct mbccCEX_sa<true,false> { typedef int Type; };
+template<> struct mbccCEX_sa<false,true> { typedef int Type; };
+#define mbccCEX(x)		(static_cast<mbccCEX_sa<!!(0+(x)), !(0+(x))>::Type>(0) + (x))
+#else
+#define mbccCEX(x)		mbmscWs(4116) \
+				(sizeof(struct { unsigned int (mbccCEX):(((0+(x)) && 1) + 1); }) * 0 + (x))
+#endif
+
+/* flexible array member */
+#if defined(MBSDCC_H_NO_FAM)
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820)
+#elif defined(__cplusplus)
+#ifdef __cpp_flexible_array_members
+#define mbccFAMslot(type,memb)	type memb[]
+#elif defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER)
+#define mbccFAMslot(type,memb)	type memb[0] mbmscWs(4200 4820)
+#else
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820)
+#endif
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L))
+#define mbccFAMslot(type,memb)	type memb[]
+#elif defined(__GNUC__)
+#define mbccFAMslot(type,memb)	type memb[0] mbmscWs(4200 4820)
+#else
+#define mbccFAMslot(type,memb)	type memb[1] mbmscWs(4820) /* SOL */
+#endif
+#define mbccFAMsz_i(t,memb,sz)	/*private*/ (size_t)(offsetof(t, memb) + (size_t)sz)
+/* compile-time constant */
+#define mbccFAMSZ(struc,memb,sz) ((size_t)( \
+	    mbccChkExpr(mbccSIZE_MAX - sizeof(struc) > mbccCEX((size_t)(sz))) + \
+	    (mbccFAMsz_i(struc, memb, (sz)) > sizeof(struc) ? \
+	     mbccFAMsz_i(struc, memb, (sz)) : sizeof(struc))))
+/* run-time */
+#define mbccFAMsz(struc,memb,sz) ((size_t)( \
+	    !(mbccSIZE_MAX - sizeof(struc) > (size_t)(sz)) ? \
+	    (mbccABEND("mbccFAMsz: " mbccS(sz) " too large for " mbccS(struc) "." mbccS(memb)), 0) : \
+	    (mbccFAMsz_i(struc, memb, (sz)) > sizeof(struc) ? \
+	     mbccFAMsz_i(struc, memb, (sz)) : sizeof(struc))))
+/* example:
+ *
+ * struct s {
+ *	int type;
+ *	mbccFAMslot(char, label);	// like char label[…];
+ * };
+ * struct t {
+ *	int count;
+ *	mbccFAMslot(time_t, value);
+ * };
+ * union fixed_s {
+ *	struct s s;
+ *	char storage[mbccFAMSZ(struct s, label, 28)];
+ * };
+ * struct s *sp = malloc(mbccFAMsz(struct s, label, strlen(labelvar) + 1U));
+ * struct t *tp = malloc(mbccFAMsz(struct t, value, sizeof(time_t[cnt])));
+ * tp->count = cnt;
+ * struct s *np = malloc(mbccFAMSZ(struct s, label, sizeof("myname")));
+ * memcpy(np->label, "myname", sizeof("myname"));
+ * static union fixed_s preallocated;
+ * preallocated.s.label[0] = '\0';
+ * somefunc((struct s *)&preallocated);
+ */
+
+/* field sizeof */
+#if defined(__cplusplus)
+/* TODO: add better way on CFrustFrust once it has one */
+#define mbccFSZ(struc,memb)	(sizeof(((struc *)0)->memb))
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L))
+#define mbccFSZ(struc,memb)	(sizeof(((struc){0}).memb))
+#else
+#define mbccFSZ(struc,memb)	(sizeof(((struc *)0)->memb))
+#endif
+
+/* stringification with expansion */
+#define mbccS(x)		#x
+#define mbccS2(x)		mbccS(x)
+
+/* compile-time assertions */
+#undef mbccCTA
+#if defined(__WATCOMC__) && !defined(__WATCOM_CPLUSPLUS__)
+				/* “Comparison result always 0” */
+#define mbccCTA_wb		_Pragma("warning 124 5")
+				/*XXX no pop so set to visible info */
+#define mbccCTA_we		_Pragma("warning 124 4")
+#else
+#define mbccCTA_wb		/* nothing */
+#define mbccCTA_we		/* nothing */
+#endif
+#if defined(__cplusplus)
+#ifdef __cpp_static_assert
+#define mbccCTA(fldn,cond)	static_assert(cond, mbccS(fldn))
+#endif
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 202311L))
+#define mbccCTA(fldn,cond)	static_assert(cond, mbccS(fldn))
+#elif (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 201112L))
+#define mbccCTA(fldn,cond)	_Static_assert(cond, mbccS(fldn))
+#elif defined(__GNUC__) && \
+    ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
+#define mbccCTA(fldn,cond)	__extension__ _Static_assert(cond, mbccS(fldn))
+#endif
+#ifndef mbccCTA
+/* single assertion for macros (with fldn prefixed, cond parenthesised) */
+#define mbccCTA(fldn,cond)	unsigned int fldn:(cond ? 1 : -1)
+/* begin/end assertion block */
+#define mbCTA_BEG(name)		struct ctassert_ ## name { mbccCTA_wb	\
+					int _ctabeg /* plus user semicolon */
+#define mbCTA_END(name)			int _ctaend;			\
+				};					\
+				struct ctassert2 ## name {		\
+					char t[sizeof(struct ctassert_ ## name) > 1U ? 1 : -1]; \
+				mbccCTA_we } /* semicolon provided by user */
+#else
+/* nothing, but syntax-check equally to manual compile-time assert macro */
+#define mbCTA_BEG(name)		struct ctassert_ ## name { mbccCTA_wb	\
+					char t[2];			\
+				} /* semicolon provided by user */
+#define mbCTA_END(name)		struct ctassert2 ## name {		\
+					char t[sizeof(struct ctassert_ ## name) > 1U ? 1 : -1]; \
+				mbccCTA_we } /* semicolon provided by user */
+#endif
+/* single assertion */
+#define mbCTA(name,cond)	mbccCTA(cta_ ## name, (cond))
+
+/* nil pointer constant */
+#if (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
+    (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 202311L))
+#define mbnil			nullptr
+#elif defined(__GNUG__)
+#define mbnil			__null
+#elif defined(__cplusplus)
+#define mbnil			(size_t)0UL	/* wtf, why? */
+#else
+#define mbnil			(void *)0UL
+#endif
+
+/* præfix to avoid -Wunused-result when it really cannot be helped */
+#ifdef _FORTIFY_SOURCE
+/* workaround via https://stackoverflow.com/a/64407070/2171120 */
+#define SHIKATANAI		(void)!
+#else
+#define SHIKATANAI		(void)
+#endif
+
+#endif /* !SYSKERN_MBSDCC_H */
--- /dev/null
+++ mksh-59c/mbsdint.h
@@ -0,0 +1,1245 @@
+/*-
+ * MirBSD sanitisation attempt for C integer madness
+ *
+ * © mirabilos Ⓕ CC0 or The MirOS Licence (MirBSD)
+ */
+
+#ifndef SYSKERN_MBSDINT_H
+#define SYSKERN_MBSDINT_H "$MirOS: src/bin/mksh/mbsdint.h,v 1.61 2024/07/25 02:29:43 tg Exp $"
+
+/*
+ * cpp defines to set:
+ *
+ * -DHAVE_INTCONSTEXPR_RSIZE_MAX=1 if RSIZE_MAX is an integer constexpr
+ * -DHAVE_OFF_T=0 if you do not supply the POSIX off_t typedef
+ *
+ * -DMBSDINT_H_SMALL_SYSTEM=1 (or 2) to shorten some macros, for old systems
+ * or -DMBSDINT_H_SMALL_SYSTEM=3 in very tiny systems, e.g. 16-bit
+ *
+ * -DMBSDINT_H_MBIPTR_IS_SIZET=0 stop assuming mbiPTR is size_t-ranged
+ * -DMBSDINT_H_MBIPTR_IN_LARGE=0 mbiPTR fits mbiHUGE but no longer mbiLARGE
+ * -DMBSDINT_H_WANT_LONG_IN_SIZET=0 don’t ensure long fits in size_t (16-bit)
+ *
+ * -DMBSDINT_H_WANT_PTR_IN_SIZET (breaks some) ensure pointers fit in size_t
+ * -DMBSDINT_H_WANT_SIZET_IN_LONG (breaks LLP64) ensure size_t fits in long
+ * -DMBSDINT_H_WANT_INT32=1 to ensure unsigned int has at least 32 bit width
+ * -DMBSDINT_H_WANT_LRG64=1 to ensure mbiLARGE_U has at least 64 bit width
+ * -DMBSDINT_H_WANT_SAFEC=1 to ensure mbiSAFECOMPLEMENT==1
+ * (these trigger extra compile-time assertion checks)
+ *
+ * This header always includes <limits.h> so please ensure any possible
+ * prerequisites as well as all existing of the following headers…
+ *	<sys/types.h>		// from POSIX
+ *	<basetsd.h>		// on Windows®
+ *	<inttypes.h>		// some pre-C99
+ *	<stdint.h>		// ISO C99
+ *	"mbsdcc.h"		// from this directory, in this order
+ * … are included before this header, for full functionality.
+ */
+
+#if !defined(_KERNEL) && !defined(_STANDALONE)
+#include <limits.h>
+#else
+#include <sys/cdefs.h>
+#include <sys/limits.h>
+#endif
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable:4127 4146 4296)
+#endif
+
+#if !defined(MBSDINT_H_SMALL_SYSTEM) || ((MBSDINT_H_SMALL_SYSTEM) < 1)
+#undef MBSDINT_H_SMALL_SYSTEM	/* in case someone defined it as 0 */
+#define mbiMASK_bitmax		279
+#elif (MBSDINT_H_SMALL_SYSTEM) >= 2
+#define mbiMASK_bitmax		75
+#else
+#define mbiMASK_bitmax		93
+#endif
+
+#if defined(HAVE_INTCONSTEXPR_RSIZE_MAX) && ((HAVE_INTCONSTEXPR_RSIZE_MAX) < 1)
+#undef HAVE_INTCONSTEXPR_RSIZE_MAX
+#endif
+#if defined(MBSDINT_H_WANT_PTR_IN_SIZET) && ((MBSDINT_H_WANT_PTR_IN_SIZET) < 1)
+#undef MBSDINT_H_WANT_PTR_IN_SIZET
+#endif
+#if defined(MBSDINT_H_WANT_SIZET_IN_LONG) && ((MBSDINT_H_WANT_SIZET_IN_LONG) < 1)
+#undef MBSDINT_H_WANT_SIZET_IN_LONG
+#endif
+#if defined(MBSDINT_H_WANT_INT32) && ((MBSDINT_H_WANT_INT32) < 1)
+#undef MBSDINT_H_WANT_INT32
+#endif
+#if defined(MBSDINT_H_WANT_LRG64) && ((MBSDINT_H_WANT_LRG64) < 1)
+#undef MBSDINT_H_WANT_LRG64
+#endif
+#if defined(MBSDINT_H_WANT_SAFEC) && ((MBSDINT_H_WANT_SAFEC) < 1)
+#undef MBSDINT_H_WANT_SAFEC
+#endif
+
+#ifndef HAVE_OFF_T
+#define HAVE_OFF_T 1
+#endif
+#ifndef MBSDINT_H_MBIPTR_IS_SIZET
+#define MBSDINT_H_MBIPTR_IS_SIZET 1
+#endif
+#ifndef MBSDINT_H_MBIPTR_IN_LARGE
+#define MBSDINT_H_MBIPTR_IN_LARGE 1
+#endif
+#ifndef MBSDINT_H_WANT_LONG_IN_SIZET
+#define MBSDINT_H_WANT_LONG_IN_SIZET 1
+#endif
+
+/* expose SIZE_MAX if possible and provided, not guessed */
+#ifndef SIZE_MAX
+#if defined(SIZE_T_MAX)
+#define SIZE_MAX		SIZE_T_MAX
+#elif defined(MAXSIZE_T)
+#define SIZE_MAX		MAXSIZE_T
+#endif
+#endif
+
+/* expose POSIX SSIZE_MAX and ssize_t on Win32 */
+#if defined(SIZE_MAX) && !defined(SSIZE_MAX) && \
+    defined(MINSSIZE_T) && defined(MAXSSIZE_T) && !defined(ssize_t)
+#define SSIZE_MIN		MINSSIZE_T
+#define SSIZE_MAX		MAXSSIZE_T
+#define ssize_t			SSIZE_T
+#endif
+
+/* special compile-time assertions */
+#define mbiCTA_TYPE_MBIT(nm,ty)	mbccCTA(ctatm_ ## nm, \
+	(sizeof(ty) <= (mbiMASK_bitmax / (CHAR_BIT))))
+
+/* kinds of types */
+	/* compile-time and runtime */
+#define mbiTYPE_ISF(type)	(!!(0+(int)(2 * (type)0.5)))
+#define mbiTYPE_ISU(type)	((type)-1 > (type)0)
+/* limits of types */
+#define mbiTYPE_UMAX(type)	((type)~(type)0U)
+#define mbiTYPE_UBITS(type)	mbiMASK_BITS(mbiTYPE_UMAX(type))
+/* calculation by Hallvard B Furuseth (via comp.lang.c), ≤ 2039 bit */
+#define mbiMASK__lh(maxv)	((maxv) / ((maxv) % 255 + 1) / 255 % 255 * 8)
+#define mbiMASK__rh(maxv)	(7 - 86 / ((maxv) % 255 + 12))
+/* mbiMASK_BITS everywhere except #if uses (castless) mbiMASK__BITS */
+#define mbiMASK__BITS(maxv)	(mbiMASK__lh(maxv) + mbiMASK__rh(maxv))
+#define mbiMASK__type(maxv)	(mbiMASK__lh(maxv) + (int)mbiMASK__rh(maxv))
+#define mbiMASK_BITS(maxv)	(0U + (unsigned int)mbiMASK__type(maxv))
+
+/* ensure v is a positive (2ⁿ-1) number (n>0), up to 279 (or less) bits */
+#define mbiMASK_CHK(v)		mbmscWd(4296) \
+				((v) > 0 ? mbi_maskchk31_1((v)) : 0) \
+				mbmscWpop
+#define mbi_maskchks(v,m,o,n)	(v <= m ? o : ((v & m) == m) && n)
+#define mbi_maskchk31s(v,n)	mbi_maskchks(v, 0x7FFFFFFFUL, \
+				    mbi_maskchk16(v), n)
+#define mbi_maskchk15s(v,n)	mbi_maskchks(v, 0x7FFFUL, \
+				    mbi_maskchk8(v), n)
+#if !defined(MBSDINT_H_SMALL_SYSTEM)
+#define mbi_maskchk31_1(v)	mbi_maskchk31s(v, mbi_maskchk31_2(v >> 31))
+#define mbi_maskchk31_2(v)	mbi_maskchk31s(v, mbi_maskchk31_3(v >> 31))
+#define mbi_maskchk31_3(v)	mbi_maskchk31s(v, mbi_maskchk31_4(v >> 31))
+#define mbi_maskchk31_4(v)	mbi_maskchk31s(v, mbi_maskchk31_5(v >> 31))
+#define mbi_maskchk31_5(v)	mbi_maskchk31s(v, mbi_maskchk31_6(v >> 31))
+#define mbi_maskchk31_6(v)	mbi_maskchk31s(v, mbi_maskchk31_7(v >> 31))
+#define mbi_maskchk31_7(v)	mbi_maskchk31s(v, mbi_maskchk31_8(v >> 31))
+#define mbi_maskchk31_8(v)	mbi_maskchk31s(v, mbi_maskchk31_9(v >> 31))
+#elif (MBSDINT_H_SMALL_SYSTEM) >= 2
+#define mbi_maskchk31_1(v)	mbi_maskchk15s(v, mbi_maskchk15_2(v >> 15))
+#define mbi_maskchk15_2(v)	mbi_maskchk15s(v, mbi_maskchk15_3(v >> 15))
+#define mbi_maskchk15_3(v)	mbi_maskchk15s(v, mbi_maskchk15_4(v >> 15))
+#define mbi_maskchk15_4(v)	mbi_maskchk15s(v, mbi_maskchk15_9(v >> 15))
+#define mbi_maskchk15_9(v)	(v <= 0x7FFFUL && mbi_maskchk8(v))
+#else /* (MBSDINT_H_SMALL_SYSTEM) == 1 */
+#define mbi_maskchk31_1(v)	mbi_maskchk31s(v, mbi_maskchk31_8(v >> 31))
+#define mbi_maskchk31_8(v)	mbi_maskchk31s(v, mbi_maskchk31_9(v >> 31))
+#endif
+#define mbi_maskchk31_9(v)	(v <= 0x7FFFFFFFUL && mbi_maskchk16(v))
+#define mbi_maskchk16(v)	mbi_maskchks(v, 0xFFFFU, \
+				    mbi_maskchk8(v), mbi_maskchk8(v >> 16))
+#define mbi_maskchk8(v)		mbi_maskchks(v, 0xFFU, \
+				    mbi_maskchk4(v), mbi_maskchk4(v >> 8))
+#define mbi_maskchk4(v)		mbi_maskchks(v, 0xFU, \
+				    mbi_maskchkF(v), mbi_maskchkF(v >> 4))
+#define mbi_maskchkF(v)		(v == 0xF || v == 7 || v == 3 || v == 1 || !v)
+
+/* limit maximum object size so we can express pointer differences w/o UB */
+#if defined(HAVE_INTCONSTEXPR_RSIZE_MAX)
+/* trust but verify operating environment */
+#define mbiRSZCHK	RSIZE_MAX
+#define mbiSIZE_MAX	((size_t)RSIZE_MAX)
+#elif !defined(SIZE_MAX)
+#ifdef PTRDIFF_MAX
+#define mbiRSZCHK	PTRDIFF_MAX
+#define mbiSIZE_MAX	((size_t)PTRDIFF_MAX)
+#elif defined(MBSDINT_H_SMALL_SYSTEM) && ((MBSDINT_H_SMALL_SYSTEM) >= 3)
+#define mbiSIZE_MAX	mbiTYPE_UMAX(size_t)
+#else
+#define mbiSIZE_MAX	((size_t)(mbiTYPE_UMAX(size_t) >> 1))
+#endif /* !PTRDIFF_MAX !MBSDINT_H_SMALL_SYSTEM>=3 */
+#elif !defined(PTRDIFF_MAX) || \
+    (((SIZE_MAX) == (PTRDIFF_MAX)) && ((SIZE_MAX) > 0x7FFFFFFFUL))
+#if defined(MBSDINT_H_SMALL_SYSTEM) && ((MBSDINT_H_SMALL_SYSTEM) >= 3)
+#define mbiSIZE_MAX	((size_t)SIZE_MAX)
+#else
+#define mbiSIZE_MAX	((size_t)(((size_t)SIZE_MAX) >> 1))
+#endif
+#elif (SIZE_MAX) < (PTRDIFF_MAX)
+#define mbiSIZE_MAX	((size_t)SIZE_MAX)
+#else
+#define mbiRSZCHK	PTRDIFF_MAX
+#define mbiSIZE_MAX	((size_t)PTRDIFF_MAX)
+#endif
+/* size_t must fit %lu/%llu if there is no %zu support yet */
+#if (defined(__STDC_VERSION__) && ((__STDC_VERSION__) >= 199901L)) || \
+    (defined(__cplusplus) && ((__cplusplus) >= 201103L))
+#define mbiSIZE_S	ssize_t
+#define mbiSIZE_U	size_t
+#define mbiSIZE_P(c)	"z" #c
+#elif defined(ULLONG_MAX) && defined(SIZE_MAX) && ((SIZE_MAX) > (ULONG_MAX))
+#define mbiSIZE_S	long long
+#define mbiSIZE_U	unsigned long long
+#define mbiSIZE_P(c)	"ll" #c
+#else
+#define mbiSIZE_S	long
+#define mbiSIZE_U	unsigned long
+#define mbiSIZE_P(c)	"l" #c
+#endif
+#define mbiSIZE_PV(v)	((mbiSIZE_U)(v))
+#ifndef SSIZE_MAX
+#undef mbiSIZE_S
+#endif
+
+/* update mbsdcc.h definition */
+#undef mbccSIZE_MAX
+#define mbccSIZE_MAX	mbiSIZE_MAX
+
+/* largest integer (need not fit a full wide pointer, e.g. on CHERI) */
+#if defined(INTMAX_MIN)
+#define mbiHUGE_S		intmax_t
+#define mbiHUGE_S_MIN		INTMAX_MIN
+#define mbiHUGE_S_MAX		INTMAX_MAX
+#define mbiHUGE_U		uintmax_t
+#define mbiHUGE_U_MAX		UINTMAX_MAX
+#define mbiHUGE_P(c)		PRI ## c ## MAX
+#elif defined(LLONG_MIN)
+#define mbiHUGE_S		long long
+#define mbiHUGE_S_MIN		LLONG_MIN
+#define mbiHUGE_S_MAX		LLONG_MAX
+#define mbiHUGE_U		unsigned long long
+#define mbiHUGE_U_MAX		ULLONG_MAX
+#define mbiHUGE_P(c)		"ll" #c
+#elif defined(_UI64_MAX) && (mbiMASK__BITS(_UI64_MAX) > mbiMASK__BITS(ULONG_MAX))
+#define mbiHUGE_S		signed __int64
+#define mbiHUGE_S_MIN		_I64_MIN
+#define mbiHUGE_S_MAX		_I64_MAX
+#define mbiHUGE_U		unsigned __int64
+#define mbiHUGE_U_MAX		_UI64_MAX
+#define mbiHUGE_UBITS		64
+#define mbiHUGE_P(c)		"I64" #c
+#elif defined(QUAD_MIN)
+#define mbiHUGE_S		quad_t
+#define mbiHUGE_S_MIN		QUAD_MIN
+#define mbiHUGE_S_MAX		QUAD_MAX
+#define mbiHUGE_U		u_quad_t
+#define mbiHUGE_U_MAX		UQUAD_MAX
+#define mbiHUGE_UBITS		64
+#define mbiHUGE_P(c)		"q" #c
+#else /* C89? */
+#define mbiHUGE_S		long
+#define mbiHUGE_S_MIN		LONG_MIN
+#define mbiHUGE_S_MAX		LONG_MAX
+#define mbiHUGE_U		unsigned long
+#define mbiHUGE_U_MAX		ULONG_MAX
+#define mbiHUGE_P(c)		"l" #c
+#endif
+/* larger than int, 64 bit if possible; storage fits off_t, size_t */
+#if (mbiMASK__BITS(ULONG_MAX) >= 64)
+#define mbiLARGE_S		long
+#define mbiLARGE_S_MIN		LONG_MIN
+#define mbiLARGE_S_MAX		LONG_MAX
+#define mbiLARGE_U		unsigned long
+#define mbiLARGE_U_MAX		ULONG_MAX
+#define mbiLARGE_P(c)		"l" #c
+#elif defined(ULLONG_MAX) && (mbiMASK__BITS(ULLONG_MAX) >= 64)
+#define mbiLARGE_S		long long
+#define mbiLARGE_S_MIN		LLONG_MIN
+#define mbiLARGE_S_MAX		LLONG_MAX
+#define mbiLARGE_U		unsigned long long
+#define mbiLARGE_U_MAX		ULLONG_MAX
+#define mbiLARGE_P(c)		"ll" #c
+#elif defined(_UI64_MAX) && (mbiMASK__BITS(_UI64_MAX) >= 64)
+#define mbiLARGE_S		signed __int64
+#define mbiLARGE_S_MIN		_I64_MIN
+#define mbiLARGE_S_MAX		_I64_MAX
+#define mbiLARGE_U		unsigned __int64
+#define mbiLARGE_U_MAX		_UI64_MAX
+#define mbiLARGE_UBITS		64
+#define mbiLARGE_P(c)		"I64" #c
+#elif defined(UQUAD_MAX)
+#define mbiLARGE_S		quad_t
+#define mbiLARGE_S_MIN		QUAD_MIN
+#define mbiLARGE_S_MAX		QUAD_MAX
+#define mbiLARGE_U		u_quad_t
+#define mbiLARGE_U_MAX		UQUAD_MAX
+#define mbiLARGE_UBITS		64
+#define mbiLARGE_P(c)		"q" #c
+#else
+#define mbiLARGE_S		mbiHUGE_S
+#define mbiLARGE_S_MIN		mbiHUGE_S_MIN
+#define mbiLARGE_S_MAX		mbiHUGE_S_MAX
+#define mbiLARGE_U		mbiHUGE_U
+#define mbiLARGE_U_MAX		mbiHUGE_U_MAX
+#define mbiLARGE_P		mbiHUGE_P
+#endif
+/* integer type that can keep the base address of a pointer */
+#ifdef __CHERI__
+#define mbiPTR_U		ptraddr_t
+#define mbiPTR_U_MAX		mbiTYPE_UMAX(mbiPTR_U)
+#elif defined(UINTPTR_MAX)
+#define mbiPTR_U		uintptr_t
+#define mbiPTR_U_MAX		UINTPTR_MAX
+#else
+#define mbiPTR_U		size_t
+#define mbiPTR_U_MAX		mbiTYPE_UMAX(mbiPTR_U)
+#endif
+#if MBSDINT_H_MBIPTR_IS_SIZET || \
+    (!defined(__CHERI__) && !defined(UINTPTR_MAX))
+#define mbiPTR_P		mbiSIZE_P
+#define mbiPTR_PV(v)		((mbiSIZE_U)(v))
+#elif MBSDINT_H_MBIPTR_IN_LARGE
+#define mbiPTR_P		mbiLARGE_P
+#define mbiPTR_PV(v)		((mbiLARGE_U)(v))
+#else
+#define mbiPTR_P		mbiHUGE_P
+#define mbiPTR_PV(v)		((mbiHUGE_U)(v))
+#endif
+
+#undef mbiSAFECOMPLEMENT
+#if ((SCHAR_MIN) == -(SCHAR_MAX))
+#define mbiSAFECOMPLEMENT 0
+#elif ((SCHAR_MIN)+1 == -(SCHAR_MAX))
+#define mbiSAFECOMPLEMENT 1
+#endif
+
+#ifndef MBSDINT_H_SKIP_CTAS
+/* compile-time assertions for mbsdint.h */
+mbCTA_BEG(mbsdint_h);
+ /* compiler (in)sanity, from autoconf */
+#define mbiCTf(x) 'x'
+ mbCTA(xlc6, mbiCTf(a) == 'x');
+#undef mbiCTf
+ mbCTA(osf4, '\x00' == 0);
+ /* C types */
+ mbCTA(basic_char_smask, mbiMASK_CHK(SCHAR_MAX));
+ mbCTA(basic_char_umask, mbiMASK_CHK(UCHAR_MAX));
+ mbCTA(basic_char,
+	sizeof(char) == 1 && (CHAR_BIT) >= 7 && (CHAR_BIT) < 2040 &&
+	(((CHAR_MAX) == (SCHAR_MAX) && (CHAR_MIN) == (SCHAR_MIN)) ||
+	 ((CHAR_MAX) == (UCHAR_MAX) && (CHAR_MIN) == 0)) &&
+	mbiTYPE_UMAX(unsigned char) == (UCHAR_MAX) &&
+	sizeof(signed char) == 1 &&
+	sizeof(unsigned char) == 1 &&
+	mbiTYPE_UBITS(unsigned char) >= 8 && (SCHAR_MIN) < 0 &&
+	((SCHAR_MIN) == -(SCHAR_MAX) || (SCHAR_MIN)+1 == -(SCHAR_MAX)) &&
+	mbiTYPE_UBITS(unsigned char) == (unsigned int)(CHAR_BIT));
+#ifndef mbiSAFECOMPLEMENT
+ mbCTA(basic_char_complement, /* fail */ 0);
+#endif
+ mbiCTA_TYPE_MBIT(short, short);
+ mbiCTA_TYPE_MBIT(ushort, unsigned short);
+ mbiCTA_TYPE_MBIT(int, int);
+ mbiCTA_TYPE_MBIT(uint, unsigned int);
+ mbiCTA_TYPE_MBIT(long, long);
+ mbiCTA_TYPE_MBIT(ulong, unsigned long);
+#ifdef LLONG_MIN
+ mbiCTA_TYPE_MBIT(llong, long long);
+ mbiCTA_TYPE_MBIT(ullong, unsigned long long);
+#endif
+#ifdef INTMAX_MIN
+ mbiCTA_TYPE_MBIT(imax, intmax_t);
+ mbiCTA_TYPE_MBIT(uimax, uintmax_t);
+#endif
+#ifdef _UI64_MAX
+ mbiCTA_TYPE_MBIT(ms_i64, signed __int64);
+ mbiCTA_TYPE_MBIT(ms_ui64, unsigned __int64);
+#endif
+#ifdef QUAD_MIN
+ mbiCTA_TYPE_MBIT(ucb_sq, quad_t);
+ mbiCTA_TYPE_MBIT(ucb_uq, u_quad_t);
+#endif
+ mbiCTA_TYPE_MBIT(shuge, mbiHUGE_S);
+ mbiCTA_TYPE_MBIT(uhuge, mbiHUGE_U);
+ mbiCTA_TYPE_MBIT(slarge, mbiLARGE_S);
+ mbiCTA_TYPE_MBIT(ularge, mbiLARGE_U);
+ mbiCTA_TYPE_MBIT(uptr, mbiPTR_U);
+ mbCTA(basic_short_smask, mbiMASK_CHK(SHRT_MAX));
+ mbCTA(basic_short_umask, mbiMASK_CHK(USHRT_MAX));
+ mbCTA(basic_short,
+	mbiTYPE_UMAX(unsigned short) == (USHRT_MAX) &&
+	mbiTYPE_UBITS(unsigned short) >= 16 && (SHRT_MIN) < 0 &&
+	((SHRT_MIN) == -(SHRT_MAX) || (SHRT_MIN)+1 == -(SHRT_MAX)) &&
+	((SHRT_MIN) == -(SHRT_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(short) >= sizeof(signed char) &&
+	sizeof(unsigned short) >= sizeof(unsigned char) &&
+	mbiMASK_BITS(SHRT_MAX) >= mbiMASK_BITS(SCHAR_MAX) &&
+	mbiMASK_BITS(SHRT_MAX) < mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(USHRT_MAX) >= mbiMASK_BITS(UCHAR_MAX) &&
+	mbiMASK_BITS(USHRT_MAX) < mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(short) == sizeof(unsigned short));
+ mbCTA(basic_int_smask, mbiMASK_CHK(INT_MAX));
+ mbCTA(basic_int_umask, mbiMASK_CHK(UINT_MAX));
+ mbCTA(basic_int,
+	mbiTYPE_UMAX(unsigned int) == (UINT_MAX) &&
+	mbiTYPE_UBITS(unsigned int) >= 16 && (INT_MIN) < 0 &&
+	((INT_MIN) == -(INT_MAX) || (INT_MIN)+1 == -(INT_MAX)) &&
+	((INT_MIN) == -(INT_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(int) >= sizeof(short) &&
+	sizeof(unsigned int) >= sizeof(unsigned short) &&
+	mbiMASK_BITS(INT_MAX) >= mbiMASK_BITS(SHRT_MAX) &&
+	mbiMASK_BITS(INT_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UINT_MAX) >= mbiMASK_BITS(USHRT_MAX) &&
+	mbiMASK_BITS(UINT_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(int) == sizeof(unsigned int));
+ mbCTA(basic_long_smask, mbiMASK_CHK(LONG_MAX));
+ mbCTA(basic_long_umask, mbiMASK_CHK(ULONG_MAX));
+ mbCTA(basic_long,
+	mbiTYPE_UMAX(unsigned long) == (ULONG_MAX) &&
+	mbiTYPE_UBITS(unsigned long) >= 32 && (LONG_MIN) < 0 &&
+	((LONG_MIN) == -(LONG_MAX) || (LONG_MIN)+1 == -(LONG_MAX)) &&
+	((LONG_MIN) == -(LONG_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(long) >= sizeof(int) &&
+	sizeof(unsigned long) >= sizeof(unsigned int) &&
+	mbiMASK_BITS(LONG_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(LONG_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(ULONG_MAX) >= mbiMASK_BITS(UINT_MAX) &&
+	mbiMASK_BITS(ULONG_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(long) == sizeof(unsigned long));
+ /* __int64 is MSC */
+#ifdef _UI64_MAX
+ mbCTA(basic_i64_smask, mbiMASK_CHK(_I64_MAX));
+ mbCTA(basic_i64_umask, mbiMASK_CHK(_UI64_MAX));
+ mbCTA(basic_i64,
+	!mbiTYPE_ISF(unsigned __int64) && !mbiTYPE_ISF(signed __int64) &&
+	mbiTYPE_ISU(unsigned __int64) && !mbiTYPE_ISU(signed __int64) &&
+	mbiTYPE_UMAX(unsigned __int64) == (_UI64_MAX) &&
+	mbiTYPE_UBITS(unsigned __int64) == 64 && (_I64_MIN) < 0 &&
+	((_I64_MIN)+1 == -(_I64_MAX)) &&
+	((_I64_MIN) == -(_I64_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(signed __int64) >= sizeof(long) &&
+	sizeof(unsigned __int64) >= sizeof(unsigned long) &&
+	sizeof(signed __int64) <= sizeof(mbiHUGE_S) &&
+	sizeof(unsigned __int64) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(_I64_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(_I64_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(_UI64_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(_UI64_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(signed __int64) == sizeof(unsigned __int64));
+#endif
+ /* legacy 4.4BSD extension, not cpp-safe, no suffixed constants */
+#ifdef QUAD_MIN
+ mbCTA(basic_quad_smask, mbiMASK_CHK(QUAD_MAX));
+ mbCTA(basic_quad_umask, mbiMASK_CHK(UQUAD_MAX));
+ mbCTA(basic_quad,
+	!mbiTYPE_ISF(u_quad_t) && !mbiTYPE_ISF(quad_t) &&
+	mbiTYPE_ISU(u_quad_t) && !mbiTYPE_ISU(quad_t) &&
+	mbiTYPE_UMAX(u_quad_t) == (UQUAD_MAX) &&
+	mbiTYPE_UBITS(u_quad_t) == 64 && (QUAD_MIN) < 0 &&
+	((QUAD_MIN)+1 == -(QUAD_MAX)) &&
+	((QUAD_MIN) == -(QUAD_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(quad_t) >= sizeof(long) &&
+	sizeof(u_quad_t) >= sizeof(unsigned long) &&
+	sizeof(quad_t) <= sizeof(mbiHUGE_S) &&
+	sizeof(u_quad_t) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(QUAD_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(QUAD_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UQUAD_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(UQUAD_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(quad_t) == sizeof(u_quad_t));
+#endif
+ /* common pre-C99 extension now standardised */
+#ifdef LLONG_MIN
+ mbCTA(basic_llong_smask, mbiMASK_CHK(LLONG_MAX));
+ mbCTA(basic_llong_umask, mbiMASK_CHK(ULLONG_MAX));
+ mbCTA(basic_llong,
+	mbiTYPE_UMAX(unsigned long long) == (ULLONG_MAX) &&
+	mbiTYPE_UBITS(unsigned long long) >= 64 && (LLONG_MIN) < 0 &&
+	((LLONG_MIN) == -(LLONG_MAX) || (LLONG_MIN)+1 == -(LLONG_MAX)) &&
+	((LLONG_MIN) == -(LLONG_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(long long) >= sizeof(long) &&
+	sizeof(unsigned long long) >= sizeof(unsigned long) &&
+	sizeof(long long) <= sizeof(mbiHUGE_S) &&
+	sizeof(unsigned long long) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(LLONG_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(LLONG_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(ULLONG_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(ULLONG_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(long long) == sizeof(unsigned long long));
+#endif
+ /* {,u}intmax_t are C99 */
+#ifdef INTMAX_MIN
+ mbCTA(basic_imax_smask, mbiMASK_CHK(INTMAX_MAX));
+ mbCTA(basic_imax_umask, mbiMASK_CHK(UINTMAX_MAX));
+ mbCTA(basic_imax,
+	!mbiTYPE_ISF(uintmax_t) && !mbiTYPE_ISF(intmax_t) &&
+	mbiTYPE_ISU(uintmax_t) && !mbiTYPE_ISU(intmax_t) &&
+	mbiTYPE_UMAX(uintmax_t) == (UINTMAX_MAX) &&
+	mbiTYPE_UBITS(uintmax_t) >= 32 && (INTMAX_MIN) < 0 &&
+	((INTMAX_MIN) == -(INTMAX_MAX) || (INTMAX_MIN)+1 == -(INTMAX_MAX)) &&
+	((INTMAX_MIN) == -(INTMAX_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(intmax_t) >= sizeof(long) &&
+	sizeof(uintmax_t) >= sizeof(unsigned long) &&
+	sizeof(intmax_t) <= sizeof(mbiHUGE_S) &&
+	sizeof(uintmax_t) <= sizeof(mbiHUGE_U) &&
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(INTMAX_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(intmax_t) == sizeof(uintmax_t));
+#ifdef LLONG_MIN
+ mbCTA(basic_imax_llong,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(LLONG_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(ULLONG_MAX) &&
+	sizeof(intmax_t) >= sizeof(long long) &&
+	sizeof(uintmax_t) >= sizeof(unsigned long long));
+#endif /* INTMAX_MIN && LLONG_MIN */
+#ifdef _I64_MIN
+ mbCTA(basic_imax_i64,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(_I64_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(_UI64_MAX) &&
+	sizeof(intmax_t) >= sizeof(signed __int64) &&
+	sizeof(uintmax_t) >= sizeof(unsigned __int64));
+#endif /* INTMAX_MIN && _I64_MIN */
+#ifdef QUAD_MIN
+ mbCTA(basic_imax_quad,
+	mbiMASK_BITS(INTMAX_MAX) >= mbiMASK_BITS(QUAD_MAX) &&
+	mbiMASK_BITS(UINTMAX_MAX) >= mbiMASK_BITS(UQUAD_MAX) &&
+	sizeof(intmax_t) >= sizeof(quad_t) &&
+	sizeof(uintmax_t) >= sizeof(u_quad_t));
+#endif /* INTMAX_MIN && QUAD_MIN */
+#endif /* INTMAX_MIN */
+ /* mbi{LARGE,HUGE}_{S,U} are defined by us */
+ mbCTA(basic_large_smask, mbiMASK_CHK(mbiLARGE_S_MAX));
+ mbCTA(basic_large_umask, mbiMASK_CHK(mbiLARGE_U_MAX));
+ mbCTA(basic_large,
+	!mbiTYPE_ISF(mbiLARGE_U) && !mbiTYPE_ISF(mbiLARGE_S) &&
+	mbiTYPE_ISU(mbiLARGE_U) && !mbiTYPE_ISU(mbiLARGE_S) &&
+	mbiTYPE_UMAX(mbiLARGE_U) == (mbiLARGE_U_MAX) && (mbiLARGE_S_MIN) < 0 &&
+	((mbiLARGE_S_MIN) == -(mbiLARGE_S_MAX) || (mbiLARGE_S_MIN)+1 == -(mbiLARGE_S_MAX)) &&
+	((mbiLARGE_S_MIN) == -(mbiLARGE_S_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(mbiLARGE_S) >= sizeof(long) &&
+	sizeof(mbiLARGE_U) >= sizeof(unsigned long) &&
+	mbiMASK_BITS(mbiLARGE_S_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(mbiLARGE_S_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	mbiMASK_BITS(mbiLARGE_U_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	mbiMASK_BITS(mbiLARGE_U_MAX) <= mbiMASK_BITS(mbiHUGE_U_MAX) &&
+	sizeof(mbiLARGE_S) == sizeof(mbiLARGE_U));
+ mbCTA(basic_huge_smask, mbiMASK_CHK(mbiHUGE_S_MAX));
+ mbCTA(basic_huge_umask, mbiMASK_CHK(mbiHUGE_U_MAX));
+ mbCTA(basic_huge,
+	!mbiTYPE_ISF(mbiHUGE_U) && !mbiTYPE_ISF(mbiHUGE_S) &&
+	mbiTYPE_ISU(mbiHUGE_U) && !mbiTYPE_ISU(mbiHUGE_S) &&
+	mbiTYPE_UMAX(mbiHUGE_U) == (mbiHUGE_U_MAX) && (mbiHUGE_S_MIN) < 0 &&
+	((mbiHUGE_S_MIN) == -(mbiHUGE_S_MAX) || (mbiHUGE_S_MIN)+1 == -(mbiHUGE_S_MAX)) &&
+	((mbiHUGE_S_MIN) == -(mbiHUGE_S_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)) &&
+	sizeof(mbiHUGE_S) >= sizeof(mbiLARGE_S) &&
+	sizeof(mbiHUGE_U) >= sizeof(mbiLARGE_U) &&
+	mbiMASK_BITS(mbiHUGE_S_MAX) >= mbiMASK_BITS(LONG_MAX) &&
+	mbiMASK_BITS(mbiHUGE_U_MAX) >= mbiMASK_BITS(ULONG_MAX) &&
+	sizeof(mbiHUGE_S) == sizeof(mbiHUGE_U));
+ /* off_t is POSIX, with no _MIN/_MAX constants (WTF‽) */
+#if HAVE_OFF_T
+ mbCTA(basic_offt,
+	sizeof(off_t) >= sizeof(int) &&
+	sizeof(off_t) <= sizeof(mbiLARGE_S) &&
+	!mbiTYPE_ISF(off_t) && !mbiTYPE_ISU(off_t));
+#endif
+ /* ptrdiff_t is C */
+ mbCTA(basic_ptrdifft,
+	sizeof(ptrdiff_t) >= sizeof(int) &&
+	sizeof(ptrdiff_t) <= sizeof(mbiHUGE_S) &&
+	!mbiTYPE_ISF(ptrdiff_t) && !mbiTYPE_ISU(ptrdiff_t));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_ptrdifft_mask, mbiMASK_CHK(PTRDIFF_MAX));
+ mbCTA(basic_ptrdifft_max,
+	mbiMASK_BITS(PTRDIFF_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(PTRDIFF_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	((mbiHUGE_S)(PTRDIFF_MAX) == (mbiHUGE_S)(ptrdiff_t)(PTRDIFF_MAX)));
+#endif
+ /* size_t is C */
+ mbCTA(basic_sizet,
+	sizeof(size_t) >= sizeof(unsigned int) &&
+	sizeof(size_t) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(size_t) && mbiTYPE_ISU(size_t) &&
+	mbiTYPE_UBITS(size_t) >= mbiMASK_BITS(UINT_MAX) &&
+	mbiTYPE_UBITS(size_t) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef SIZE_MAX
+ mbCTA(basic_sizet_mask, mbiMASK_CHK(SIZE_MAX));
+ mbCTA(basic_sizet_max,
+	mbiMASK_BITS(SIZE_MAX) >= mbiMASK_BITS(USHRT_MAX) &&
+	mbiMASK_BITS(SIZE_MAX) <= mbiTYPE_UBITS(size_t) &&
+	((mbiHUGE_U)(SIZE_MAX) == (mbiHUGE_U)(size_t)(SIZE_MAX)));
+#endif
+ /* mbiSIZE_S is only defined if ssize_t is defined */
+ /* but consistently mapped, no extra checks here */
+ mbCTA(basic_sizet_P,
+	sizeof(size_t) <= sizeof(mbiSIZE_U) &&
+	mbiTYPE_UBITS(size_t) <= mbiTYPE_UBITS(mbiSIZE_U));
+ /* note mbiSIZE_MAX is not necessarily a bitmask (0b0*1+) */
+#ifdef mbiRSZCHK
+ mbCTA(smax_range, (0U + (mbiRSZCHK)) <= (0U + (mbiHUGE_U_MAX)));
+ mbCTA(smax_check, ((mbiHUGE_U)(mbiRSZCHK) == (mbiHUGE_U)(size_t)(mbiRSZCHK)));
+#undef mbiRSZCHK
+#endif
+ /* ssize_t is POSIX (or mapped from Win32 SSIZE_T by us) */
+#ifdef SSIZE_MAX
+ mbCTA(basic_ssizet_mask, mbiMASK_CHK(SSIZE_MAX));
+ mbCTA(basic_ssizet,
+	sizeof(ssize_t) == sizeof(size_t) &&
+	!mbiTYPE_ISF(ssize_t) && !mbiTYPE_ISU(ssize_t) &&
+	mbiMASK_BITS(SSIZE_MAX) >= mbiMASK_BITS(INT_MAX) &&
+	mbiMASK_BITS(SSIZE_MAX) <= mbiMASK_BITS(mbiHUGE_S_MAX) &&
+	((mbiHUGE_S)(SSIZE_MAX) == (mbiHUGE_S)(ssize_t)(SSIZE_MAX)) &&
+	mbiMASK_BITS(SSIZE_MAX) < mbiTYPE_UBITS(size_t));
+#ifdef SSIZE_MIN
+ mbCTA(basic_ssizet_min,
+	(SSIZE_MIN) < 0 &&
+	((SSIZE_MIN) == -(SSIZE_MAX) || (SSIZE_MIN)+1 == -(SSIZE_MAX)) &&
+	((SSIZE_MIN) == -(SSIZE_MAX)) == ((SCHAR_MIN) == -(SCHAR_MAX)));
+#endif
+#ifdef SIZE_MAX
+ mbCTA(basic_ssizet_sizet,
+	mbiMASK_BITS(SSIZE_MAX) <= mbiMASK_BITS(SIZE_MAX));
+#endif /* SSIZE_MAX && SIZE_MAX */
+#endif /* SSIZE_MAX */
+ /* uintptr_t is C99 */
+#if defined(UINTPTR_MAX) && !defined(__CHERI__)
+ mbCTA(basic_uintptr_mask, mbiMASK_CHK(UINTPTR_MAX));
+ mbCTA(basic_uintptr,
+	sizeof(uintptr_t) >= sizeof(ptrdiff_t) &&
+	sizeof(uintptr_t) >= sizeof(size_t) &&
+	sizeof(uintptr_t) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(uintptr_t) && mbiTYPE_ISU(uintptr_t) &&
+	mbiMASK_BITS(UINTPTR_MAX) == mbiTYPE_UBITS(uintptr_t) &&
+	((mbiHUGE_U)(UINTPTR_MAX) == (mbiHUGE_U)(uintptr_t)(UINTPTR_MAX)) &&
+	mbiTYPE_UBITS(uintptr_t) >= mbiMASK_BITS(UINT_MAX) &&
+	((mbiHUGE_U)(UINTPTR_MAX) >= (mbiHUGE_U)(mbiSIZE_MAX)) &&
+	mbiTYPE_UBITS(uintptr_t) >= mbiTYPE_UBITS(size_t) &&
+	mbiTYPE_UBITS(uintptr_t) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_uintptr_pdt,
+	mbiMASK_BITS(UINTPTR_MAX) >= mbiMASK_BITS(PTRDIFF_MAX));
+#endif /* UINTPTR_MAX && PTRDIFF_MAX */
+#ifdef SIZE_MAX
+ mbCTA(basic_uintptr_sizet,
+	mbiMASK_BITS(UINTPTR_MAX) >= mbiMASK_BITS(SIZE_MAX));
+#endif /* UINTPTR_MAX && SIZE_MAX */
+#endif /* UINTPTR_MAX */
+ /* mbiPTR_U is defined by us */
+ mbCTA(basic_mbiptr_mask, mbiMASK_CHK(mbiPTR_U_MAX));
+ mbCTA(basic_mbiptr,
+	sizeof(mbiPTR_U) >= sizeof(ptrdiff_t) &&
+	sizeof(mbiPTR_U) >= sizeof(size_t) &&
+	sizeof(mbiPTR_U) <= sizeof(mbiHUGE_U) &&
+	!mbiTYPE_ISF(mbiPTR_U) && mbiTYPE_ISU(mbiPTR_U) &&
+	mbiMASK_BITS(mbiPTR_U_MAX) == mbiTYPE_UBITS(mbiPTR_U) &&
+	((mbiHUGE_U)(mbiPTR_U_MAX) == (mbiHUGE_U)(mbiPTR_U)(mbiPTR_U_MAX)) &&
+	mbiTYPE_UBITS(mbiPTR_U) >= mbiMASK_BITS(UINT_MAX) &&
+	((mbiHUGE_U)(mbiPTR_U_MAX) >= (mbiHUGE_U)(mbiSIZE_MAX)) &&
+	mbiTYPE_UBITS(mbiPTR_U) >= mbiTYPE_UBITS(size_t) &&
+	mbiTYPE_UBITS(mbiPTR_U) <= mbiMASK_BITS(mbiHUGE_U_MAX));
+#ifdef PTRDIFF_MAX
+ mbCTA(basic_mbiptr_pdt,
+	mbiMASK_BITS(mbiPTR_U_MAX) >= mbiMASK_BITS(PTRDIFF_MAX));
+#endif
+#ifdef SIZE_MAX
+ mbCTA(basic_mbiptr_sizet,
+	mbiMASK_BITS(mbiPTR_U_MAX) >= mbiMASK_BITS(SIZE_MAX));
+#endif
+ /* C99 §6.2.6.2(1, 2, 6) permits M ≤ N, but M < N is normally desired */
+ /* here require signed/unsigned types to have same width (M=N-1) */
+ mbCTA(vbits_char, mbiMASK_BITS(UCHAR_MAX) == mbiMASK_BITS(SCHAR_MAX) + 1U);
+ mbCTA(vbits_short, mbiMASK_BITS(USHRT_MAX) == mbiMASK_BITS(SHRT_MAX) + 1U);
+ mbCTA(vbits_int, mbiMASK_BITS(UINT_MAX) == mbiMASK_BITS(INT_MAX) + 1U);
+ mbCTA(vbits_long, mbiMASK_BITS(ULONG_MAX) == mbiMASK_BITS(LONG_MAX) + 1U);
+#ifdef UQUAD_MAX
+ mbCTA(vbits_quad, mbiMASK_BITS(UQUAD_MAX) == mbiMASK_BITS(QUAD_MAX) + 1U);
+#endif
+#ifdef _UI64_MAX
+ mbCTA(vbits_i64, mbiMASK_BITS(_UI64_MAX) == mbiMASK_BITS(_I64_MAX) + 1U);
+#endif
+#ifdef LLONG_MIN
+ mbCTA(vbits_llong, mbiMASK_BITS(ULLONG_MAX) == mbiMASK_BITS(LLONG_MAX) + 1U);
+#endif
+#ifdef INTMAX_MIN
+ mbCTA(vbits_imax, mbiMASK_BITS(UINTMAX_MAX) == mbiMASK_BITS(INTMAX_MAX) + 1U);
+#endif
+ mbCTA(vbits_large, mbiMASK_BITS(mbiLARGE_U_MAX) == mbiMASK_BITS(mbiLARGE_S_MAX) + 1U);
+ mbCTA(vbits_huge, mbiMASK_BITS(mbiHUGE_U_MAX) == mbiMASK_BITS(mbiHUGE_S_MAX) + 1U);
+#ifdef SSIZE_MAX
+ mbCTA(vbits_size, mbiTYPE_UBITS(size_t) == mbiMASK_BITS(SSIZE_MAX) + 1U);
+#endif
+#if !defined(__CHERI__) && defined(UINTPTR_MAX) && defined(PTRDIFF_MAX)
+ mbCTA(vbits_iptr, mbiMASK_BITS(UINTPTR_MAX) == mbiMASK_BITS(PTRDIFF_MAX) + 1U);
+#endif
+ /* do size_t and ulong fit each other? */
+ mbCTA(sizet_minint, sizeof(size_t) >= sizeof(int)); /* for 16-bit systems */
+#if MBSDINT_H_WANT_LONG_IN_SIZET
+ mbCTA(sizet_minlong, sizeof(size_t) >= sizeof(long));
+#endif
+#ifdef MBSDINT_H_WANT_SIZET_IN_LONG
+ /* with MBSDINT_H_WANT_PTR_IN_SIZET breaks LLP64 (e.g. Windows/amd64) */
+ mbCTA(sizet_inulong, sizeof(size_t) <= sizeof(long));
+#endif
+ /* this is as documented above */
+ mbCTA(sizet_inlarge, sizeof(size_t) <= sizeof(mbiLARGE_U));
+#if MBSDINT_H_MBIPTR_IN_LARGE
+ mbCTA(mbiPTRU_inlarge,
+	sizeof(mbiPTR_U) <= sizeof(mbiLARGE_U) &&
+	mbiTYPE_UBITS(mbiPTR_U) <= mbiMASK_BITS(mbiLARGE_U_MAX));
+#endif
+ /* assume ptrdiff_t and (s)size_t will fit each other */
+ mbCTA(sizet_ptrdiff, sizeof(size_t) == sizeof(ptrdiff_t));
+#ifdef SSIZE_MAX
+ mbCTA(sizet_ssize, sizeof(size_t) == sizeof(ssize_t));
+#endif
+ /* also mbiPTR_U, to rule out certain weird machines */
+#if MBSDINT_H_MBIPTR_IS_SIZET
+ /* note mbiMASK_BITS(SIZE_MAX) could be smaller still */
+ mbCTA(sizet_mbiPTRU,
+	sizeof(mbiPTR_U) == sizeof(size_t) &&
+	mbiTYPE_UBITS(mbiPTR_U) == mbiTYPE_UBITS(size_t));
+ /* more loose bonus check */
+#if defined(UINTPTR_MAX) && !defined(__CHERI__)
+ mbCTA(sizet_uintptr, sizeof(size_t) == sizeof(uintptr_t));
+#endif
+#endif
+ /* user-requested extra checks */
+#ifdef MBSDINT_H_WANT_INT32
+ /* guaranteed by POSIX */
+ mbCTA(user_int32, mbiTYPE_UBITS(unsigned int) >= 32);
+#endif
+#ifdef MBSDINT_H_WANT_LRG64
+ /* guaranteed if 64-bit types even exist */
+ mbCTA(user_lrg64, mbiTYPE_UBITS(mbiLARGE_U) >= 64);
+#endif
+#ifdef MBSDINT_H_WANT_SAFEC
+ /* true as of C23 and POSIX unless INT_MIN == -INT_MAX */
+ mbCTA(user_safec, mbiSAFECOMPLEMENT == 1);
+#endif
+#ifdef MBSDINT_H_WANT_PTR_IN_SIZET
+ /* require pointers and size_t to take up the same amount of space */
+ mbCTA(sizet_voidptr, sizeof(size_t) == sizeof(void *));
+ mbCTA(sizet_sintptr, sizeof(size_t) == sizeof(int *));
+ mbCTA(sizet_funcptr, sizeof(size_t) == sizeof(void (*)(void)));
+#endif
+ /* C23 §5.2.4.2.1 */
+#ifdef CHAR_WIDTH
+ mbCTA(char_width, (CHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef SCHAR_WIDTH
+ mbCTA(schar_width, (SCHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef UCHAR_WIDTH
+ mbCTA(uchar_width, (UCHAR_WIDTH) == (CHAR_BIT));
+#endif
+#ifdef USHRT_WIDTH
+ mbCTA(ushrt_width, (USHRT_WIDTH) == mbiMASK_BITS(USHRT_MAX));
+#endif
+#ifdef SHRT_WIDTH
+ mbCTA(shrt_width, (SHRT_WIDTH) == mbiMASK_BITS(SHRT_MAX) + 1);
+#endif
+#ifdef UINT_WIDTH
+ mbCTA(uint_width, (UINT_WIDTH) == mbiMASK_BITS(UINT_MAX));
+#endif
+#ifdef INT_WIDTH
+ mbCTA(int_width, (INT_WIDTH) == mbiMASK_BITS(INT_MAX) + 1);
+#endif
+#ifdef ULONG_WIDTH
+ mbCTA(ulong_width, (ULONG_WIDTH) == mbiMASK_BITS(ULONG_MAX));
+#endif
+#ifdef LONG_WIDTH
+ mbCTA(long_width, (LONG_WIDTH) == mbiMASK_BITS(LONG_MAX) + 1);
+#endif
+#ifdef ULLONG_WIDTH
+ mbCTA(ullong_width, (ULLONG_WIDTH) == mbiMASK_BITS(ULLONG_MAX));
+#endif
+#ifdef LLONG_WIDTH
+ mbCTA(llong_width, (LLONG_WIDTH) == mbiMASK_BITS(LLONG_MAX) + 1);
+#endif
+#ifdef UINTMAX_WIDTH
+ mbCTA(uintmax_width, (UINTMAX_WIDTH) == mbiMASK_BITS(UINTMAX_MAX));
+#endif
+#ifdef INTMAX_WIDTH
+ mbCTA(intmax_width, (INTMAX_WIDTH) == mbiMASK_BITS(INTMAX_MAX) + 1);
+#endif
+#if defined(UINTPTR_WIDTH) && !defined(__CHERI__)
+ mbCTA(uintptr_width, (UINTPTR_WIDTH) == mbiMASK_BITS(UINTPTR_MAX));
+#endif
+#ifdef PTRDIFF_WIDTH
+ mbCTA(ptrdiff_width, (PTRDIFF_WIDTH) == mbiMASK_BITS(PTRDIFF_MAX) + 1);
+#endif
+#ifdef SIZE_WIDTH
+ mbCTA(size_width, (SIZE_WIDTH) == mbiMASK_BITS(SIZE_MAX));
+#endif
+ /* require nōn-cpp (possibly casted) match if extant */
+#ifdef mbiHUGE_UBITS
+ mbCTA(huge_width, mbiHUGE_UBITS == mbiMASK_BITS(mbiHUGE_U_MAX));
+#endif
+#ifdef mbiLARGE_UBITS
+ mbCTA(large_width, mbiLARGE_UBITS == mbiMASK_BITS(mbiLARGE_U_MAX));
+#endif
+mbCTA_END(mbsdint_h);
+#endif /* !MBSDINT_H_SKIP_CTAS */
+
+/* cpp-safe */
+#ifndef mbiHUGE_UBITS
+#define mbiHUGE_UBITS		mbiMASK__BITS(mbiHUGE_U_MAX)
+#endif
+#ifndef mbiLARGE_UBITS
+#define mbiLARGE_UBITS		mbiMASK__BITS(mbiLARGE_U_MAX)
+#endif
+
+/*
+ * various arithmetics, optionally masking
+ *
+ * key:	O = operation, A = arithmetic, M* = masking
+ *	U = unsigned, S = signed, m = magnitude
+ *	VZ = sign (Vorzeichen) 0=positive, 1=negative
+ *	v = value, ut = unsigned type, st = signed type
+ *	w = boolean value, y = yes, n = no
+ *	CA = checked arithmetics, define mbiCfail
+ *	K = k̲alculations for unsigned mantwo’s k̲omplement vars
+ *
+ * masks: HM = half mask (e.g. FM >> 1 or 0x7FFFFFFFUL) == signed _MAX
+ *	  FM = full mask (e.g. ULONG_MAX or 0xFFFFFFFFUL)
+ *	  tM = type-corresponding mask
+ *
+ * Where unsigned values may be either properly unsigned or
+ * manually represented in two’s complement (M=N-1 above),
+ * signed values are the host’s (and conversion will UB for
+ * -type_MAX-1 unless the mbiSAFECOMPLEMENT macro equals 1,
+ * so don’t use that without checking), unsigned magnitude
+ * ranges from 0 to type_MAX+1, and we try pretty hard to
+ * avoid UB and (with one exception, below, casting into
+ * smaller-width signed integers, checked to be safe, but
+ * an implementation-defined signal may be raised, which is
+ * then the caller’s responsibility) IB.
+ *
+ * Every operation needs casting applied, as the type may
+ * have lower integer rank than (signed) int. Additional
+ * masking may be used to guarantee bit widths in the result
+ * even when the executing type is wider. In conversion, if
+ * unsigned and magnitude both exist, magnitude is halfmasked
+ * whereas unsigned is fullmasked with vz acting as neg op.
+ */
+
+/* basic building blocks: arithmetics cast helpers */
+
+#define mbiUI(v)		(0U + (v))
+#define mbiUP(ut,v)		mbiUI((ut)(v))
+#define mbiSP(st,v)		(0 + ((st)(v)))
+
+/* basic building blocks: masking */
+
+#define mbiMM(ut,tM,v)		mbiOU(ut, (v), &, (tM))
+
+/* basic building blocks: operations */
+
+/* 1. unary */
+#define mbiOS1(st,op,v)		((st)(op mbiSP(st, (v))))
+#define mbiOU1(ut,op,v)		((ut)(op mbiUP(ut, (v))))
+#define mbiMO1(ut,tM,op,v)	mbiMM(ut, (tM), mbiOU1(ut, op, (v)))
+
+/* 2. binary or comparison */
+#define mbiOS(st,l,op,r)	((st)(mbiSP(st, (l)) op mbiSP(st, (r))))
+#define mbiOU(ut,l,op,r)	((ut)(mbiUP(ut, (l)) op mbiUP(ut, (r))))
+#define mbiMO(ut,tM,l,op,r)	mbiMM(ut, (tM), mbiOU(ut, (l), op, (r)))
+
+#define mbiOshl(ut,l,r)		((ut)(mbiUP(ut, (l)) << (r)))
+#define mbiOshr(ut,l,r)		((ut)(mbiUP(ut, (l)) >> (r)))
+
+#define mbiCOS(st,l,op,r)	(!!(mbiSP(st, (l)) op mbiSP(st, (r))))
+#define mbiCOU(ut,l,op,r)	(!!(mbiUP(ut, (l)) op mbiUP(ut, (r))))
+
+/* 3. ternary */
+#define mbiOT(t,w,j,n)		((w) ? (t)(j) : (t)(n))
+#define mbiMOT(ut,tM,w,j,n)	mbiMM(ut, (tM), mbiOT(ut, (w), (j), (n)))
+
+/* 4. helpers */
+#define mbiOUneg(ut,v)		mbmscWd(4146) \
+				mbiOU1(ut, -, (v)) \
+				mbmscWpop
+
+/* manual two’s complement in unsigned arithmetics */
+
+/* 1. obtain sign of encoded value */
+#define mbiA_S2VZ(v)		((v) < 0)
+#define mbiA_U2VZ(ut,HM,v)	mbiCOU(ut, (v), >, (HM))
+/* masking */
+#define mbiMA_U2VZ(ut,FM,HM,v)	mbiCOU(ut, mbiMM(ut, (FM), (v)), >, (HM))
+
+/* 2. casting between unsigned(two’s complement) and signed(native) */
+#define mbiA_U2S(ut,st,HM,v)						\
+		mbiOT(st,						\
+		 mbiA_U2VZ(ut, (HM), (v)),				\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOU1(ut, ~, (v))					\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_U2S(ut,st,FM,HM,v)					\
+		mbiOT(st,						\
+		 mbiMA_U2VZ(ut, (FM), (HM), (v)),			\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiMO1(ut, (HM), ~, (v))				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+#define mbiA_S2U(ut,st,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU1(ut,						\
+		  ~,							\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOS(st, (v), +, 1)					\
+		  )							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_S2U(ut,st,FM,v)	mbiMM(ut, (FM), mbiA_S2U(ut, st, (v)))
+
+/* 3. converting from signed(native) or unsigned(manual) to magnitude */
+#define mbiA_S2M(ut,st,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU(ut,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOS(st, (v), +, 1)					\
+		  ),							\
+		  +,							\
+		  1U							\
+		 ),							\
+		 (v)							\
+		)
+#define mbiMA_S2M(ut,st,HM,v)						\
+		mbiOT(ut,						\
+		 mbiA_S2VZ(v),						\
+		 mbiOU(ut,						\
+		  mbiMM(ut, (HM),					\
+		   mbiOS1(st,						\
+		    -,							\
+		    mbiOS(st, (v), +, 1)				\
+		   )							\
+		  ),							\
+		  +,							\
+		  1U							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+#define mbiA_U2M(ut,HM,v)						\
+		mbiOT(ut,						\
+		 mbiA_U2VZ(ut, (HM), (v)),				\
+		 mbiOUneg(ut, (v)),					\
+		 (v)							\
+		)
+#define mbiMA_U2M(ut,FM,HM,v)						\
+		mbiOT(ut,						\
+		 mbiMA_U2VZ(ut, (FM), (HM), (v)),			\
+		 mbiOU(ut,						\
+		  mbiMO1(ut, (HM), ~, (v)),				\
+		  +,							\
+		  1U							\
+		 ),							\
+		 mbiMM(ut, (HM), (v))					\
+		)
+
+/* 4a. reverse: signbit plus magnitude to signed(native) */
+#define mbiA_VZM2S(ut,st,vz,m)						\
+		mbiOT(st,						\
+		 (vz) && ((m) > 0U),					\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiOU(ut, (m), -, 1U)				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 (m)							\
+		)
+#define mbiMA_VZM2S(ut,st,FM,HM,vz,m)					\
+		mbiOT(st,						\
+		 (vz) && (mbiMM(ut, (FM), (m)) > 0U),			\
+		 mbiOS(st,						\
+		  mbiOS1(st,						\
+		   -,							\
+		   mbiMO(ut, (HM), (m), -, 1U)				\
+		  ),							\
+		  -,							\
+		  1							\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+
+/* 4b. same: signbit and magnitude(masked) to unsigned(two’s complement) */
+#define mbiA_VZM2U(ut,HM,vz,m)						\
+		mbiOT(ut,						\
+		 (vz) && ((m) > 0U),					\
+		 mbiOU1(ut,						\
+		  ~,							\
+		  mbiMO(ut, (HM), (m), -, 1U)				\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+#define mbiMA_VZM2U(ut,FM,HM,vz,m)					\
+		mbiOT(ut,						\
+		 (vz) && (mbiMM(ut, (FM), (m)) > 0U),			\
+		 mbiMO1(ut, (FM),					\
+		  ~,							\
+		  mbiMO(ut, (HM), (m), -, 1U)				\
+		 ),							\
+		 mbiMM(ut, (HM), (m))					\
+		)
+
+/* 4c. signbit and unsigned to unsigned(two’s complement), basically NEG */
+#define mbiA_VZU2U(ut,vz,m)						\
+		mbiOT(ut,						\
+		 (vz),							\
+		 mbiOUneg(ut, (m)),					\
+		 (m)							\
+		)
+#define mbiMA_VZU2U(ut,FM,vz,u)	mbiMM(ut, (FM), mbiA_VZU2U(ut, (vz), (u)))
+
+/*
+ * UB-safe overflow/underflow-checking integer arithmetics
+ *
+ * Before using, #define mbiCfail to the action that should be
+ * taken on check (e.g. "goto fail" or "return (0)"); make sure
+ * to #undef mbiCfail before the end of the function body though!
+ */
+
+/* 0. internal helpers */
+#define mbi__totypeof(templval,dstval)	((1 ? 0 : (templval)) + (dstval))
+#define mbi__halftmax(stmax)		mbi__totypeof(stmax, \
+	(mbi__totypeof(stmax, 1) << (mbiMASK_BITS(stmax) / 2U)))
+/* note: must constant-evaluate even for signed ut */
+#define mbi__halftype(ut)		mbiOT(ut, mbiTYPE_ISU(ut), \
+	mbiOshl(ut, 1U, mbiTYPE_UBITS(ut) / 2U), 2)
+#define mbi__uabovehalftype(ut,a,b)	(((ut)a | (ut)b) >= mbi__halftype(ut))
+/* assert: !(b < 0) */
+#define mbi__sabovehalftype(stmax,a,b)	(a < 0 ? 1 : \
+	(mbi__totypeof(stmax, a) | mbi__totypeof(stmax, b)) >= mbi__halftmax(stmax))
+
+/* 1. for unsigned types checking afterwards is OK */
+#define mbiCAUinc(vl)		mbiCAUadd(vl, 1U)
+#define mbiCAUdec(vl)		mbiCAUsub(vl, 1U)
+#define mbiCAUadd(vl,vr)	do {					\
+	(vl) += mbiUI(vr);						\
+	if (__predict_false(mbiUI(vl) < mbiUI(vr)))			\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAUsub(vl,vr)	do {					\
+	if (__predict_false(mbiUI(vl) < mbiUI(vr)))			\
+		mbiCfail;						\
+	(vl) -= mbiUI(vr);						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAUmul(ut,vl,vr)	do {					\
+	if (__predict_false((vr) != 0 &&				\
+	    mbi__uabovehalftype(ut, (vl), (vr)) &&			\
+	    mbiOU(ut, mbiTYPE_UMAX(ut), /, (ut)(vr)) < (ut)(vl)))	\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+
+/* 2. for signed types; lim is the prefix (e.g. SHRT) */
+#define mbiCASinc(lim,vl)	do {					\
+	if (__predict_false((vl) == lim ## _MAX))			\
+		mbiCfail;						\
+	++(vl);								\
+} while (/* CONSTCOND */ 0)
+#define mbiCASdec(lim,vl)	do {					\
+	if (__predict_false((vl) == lim ## _MIN))			\
+		mbiCfail;						\
+	--(vl);								\
+} while (/* CONSTCOND */ 0)
+/* CAP means vr is positive */
+#define mbiCAPadd(lim,vl,vr)	do {					\
+	if (__predict_false((vl) > (lim ## _MAX - (vr))))		\
+		mbiCfail;						\
+	(vl) += (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCAPsub(lim,vl,vr)	do {					\
+	if (__predict_false((vl) < (lim ## _MIN + (vr))))		\
+		mbiCfail;						\
+	(vl) -= (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCAPmul(lim,vl,vr)	do {					\
+	if (__predict_false((vr) != 0 &&				\
+	    mbi__sabovehalftype(lim ## _MAX, (vl), (vr)) && ((vl) < 0 ?	\
+	    (vl) < (lim ## _MIN / (vr)) :				\
+	    (vl) > (lim ## _MAX / (vr)))))				\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+/* CAS for add/sub/mul may have negative vr */
+#define mbiCASadd(lim,vl,vr)	do {					\
+	if (__predict_false((vr) < 0 ?					\
+	    (vl) < (lim ## _MIN - (vr)) :				\
+	    (vl) > (lim ## _MAX - (vr))))				\
+		mbiCfail;						\
+	(vl) += (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCASsub(lim,vl,vr)	do {					\
+	if (__predict_false((vr) < 0 ?					\
+	    (vl) > (lim ## _MAX + (vr)) :				\
+	    (vl) < (lim ## _MIN + (vr))))				\
+		mbiCfail;						\
+	(vl) -= (vr);							\
+} while (/* CONSTCOND */ 0)
+#define mbiCASmul(lim,vl,vr)	do {					\
+	if (((vr) >= 0) ? __predict_false((vr) != 0 &&			\
+	    mbi__sabovehalftype(lim ## _MAX, (vl), (vr)) && ((vl) < 0 ?	\
+	    (vl) < (lim ## _MIN / (vr)) :				\
+	    (vl) > (lim ## _MAX / (vr)))) :				\
+	    /* vr < 0 */ __predict_false((vl) < 0 ?			\
+	    (vl) < (lim ## _MAX / (vr)) : /* vl >= 0, vr < 0 */		\
+	    (vr) != -1 && (vl) > (lim ## _MIN / (vr))))			\
+		mbiCfail;						\
+	(vl) *= (vr);							\
+} while (/* CONSTCOND */ 0)
+
+/* 3. autotype or signed narrowing assign; this is checked IB */
+#define mbiCAAlet(vl,srctype,vr) do {					\
+	(vl) = (vr);							\
+	if (__predict_false((srctype)(vl) != (srctype)(vr)))		\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCASlet(dsttype,vl,srctype,vr) do {				\
+	(vl) = (dsttype)(vr);						\
+	if (__predict_false((srctype)(vl) != (srctype)(vr)))		\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+
+/* 4. safe to use mbiA_U2S / mbiA_VZM2S for the given in-range value */
+#if mbiSAFECOMPLEMENT
+#define mbiCAsafeU2S(lim,ut,v) do {					\
+	/* nothing */ (void)(ut)(v); (void)(lim ## _MAX);		\
+} while (/* CONSTCOND */ 0)
+#define mbiCAsafeVZM2S(lim,ut,vz,m) do {				\
+	/* nothing */ (void)(ut)(m); (void)(lim ## _MAX); (void)(vz);	\
+} while (/* CONSTCOND */ 0)
+#else /* one’s complement or sign-and-magnitude or -type_MAX-1 is a trap */
+#define mbiCAsafeU2S(lim,ut,v) do {					\
+	if (__predict_false((ut)(v) == mbiOU(ut, lim ## _MAX, +, 1)))	\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#define mbiCAsafeVZM2S(lim,ut,vz,m) do {				\
+	if ((vz) &&							\
+	    __predict_false((ut)(m) == mbiOU(ut, lim ## _MAX, +, 1)))	\
+		mbiCfail;						\
+} while (/* CONSTCOND */ 0)
+#endif
+
+/*
+ * calculations on manual two’s k̲omplement signed numbers in unsigned vars
+ *
+ * addition, subtraction and multiplication, bitwise and boolean
+ * operations, as well as equality comparisons can be done on the
+ * unsigned value; other operations follow:
+ */
+
+/* k-signed compare < <= > >= */
+#define mbiK_signbit(ut,HM)	mbiOU(ut, (HM), +, 1)
+#define mbiK_signflip(ut,HM,v)	mbiOU(ut, (v), ^, mbiK_signbit(ut, (HM)))
+#define mbiKcmp(ut,HM,vl,op,vr)	mbiCOU(ut, \
+		mbiK_signflip(ut, (HM), (vl)), \
+		op, \
+		mbiK_signflip(ut, (HM), (vr)))
+#define mbiMKcmp(ut,FM,HM,vl,op,vr) \
+	mbiKcmp(ut, (HM), mbiMM(ut, (FM), (vl)), op, mbiMM(ut, (FM), (vr)))
+
+/* rotate and shift (can also be used on unsigned values) */
+#define mbiKrol(ut,vl,vr)	mbiK_sr(ut, mbiK_rol, (vl), (vr), void)
+#define mbiKror(ut,vl,vr)	mbiK_sr(ut, mbiK_ror, (vl), (vr), void)
+#define mbiKshl(ut,vl,vr)	mbiK_sr(ut, mbiK_shl, (vl), (vr), void)
+/* let vz be sgn(vl): mbi{,M}A_U2VZ(ut,HM,vl) */
+/* mbiA_U2VZ(ut,mbiTYPE_UMAX(ut)>>1,vl) if unsigned and nōn-masking */
+#define mbiKsar(ut,vz,vl,vr)	mbiK_sr(ut, mbiK_sar, (vl), (vr), (vz))
+#define mbiKshr(ut,vl,vr)	mbiK_sr(ut, mbiK_shr, (vl), (vr), 0)
+#define mbiMKrol(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_rol, (vl), (vr), void)
+#define mbiMKror(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_ror, (vl), (vr), void)
+#define mbiMKshl(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_shl, (vl), (vr), void)
+#define mbiMKsar(ut,FM,vz,l,r)	mbiMOT(ut, (FM), (vz), \
+					mbiK_SR(ut, mbiMASK_BITS(FM), \
+					    mbiMK_nr, (l), (r), (FM)), \
+					mbiK_SR(ut, mbiMASK_BITS(FM), \
+					    mbiK_shr, (l), (r), 0))
+#define mbiMKshr(ut,FM,vl,vr)	mbiMK_sr(ut, (FM), mbiK_shr, (vl), (vr), 0)
+/* implementation */
+#define mbiK_sr(ut,n,vl,vr,vz)	mbiK_SR(ut, mbiTYPE_UBITS(ut), n, vl, vr, vz)
+#define mbiMK_sr(ut,FM,n,l,r,z)	mbiMM(ut, (FM), mbiK_SR(ut, mbiMASK_BITS(FM), \
+				    n, mbiMM(ut, (FM), (l)), (r), (z)))
+#define mbiK_SR(ut,b,n,l,r,vz)	mbiK_RS(ut, b, n, l, mbiUI(r) % mbiUI(b), (vz))
+#define mbiK_RS(ut,b,n,v,cl,zx)	mbiOT(ut, cl, n(ut, v, cl, b - (cl), zx), v)
+#define mbiK_shl(ut,ax,cl,CL,z)	mbiOshl(ut, ax, cl)
+#define mbiK_shr(ut,ax,cl,CL,z)	mbiOshr(ut, ax, cl)
+#define mbiK_sar(ut,ax,cl,CL,z)	mbiOT(ut, z, mbiOU1(ut, ~, mbiOshr(ut, \
+				    mbiOU1(ut, ~, ax), cl)), \
+				    mbiOshr(ut, ax, cl))
+#define mbiMK_nr(ut,ax,cl,CL,m)	mbiOU1(ut, ~, mbiOshr(ut, \
+				    mbiMO1(ut, m, ~, ax), cl))
+#define mbiK_rol(ut,ax,cl,CL,z)	\
+	mbiOU(ut, mbiOshl(ut, ax, cl), |, mbiOshr(ut, ax, CL))
+#define mbiK_ror(ut,ax,cl,CL,z)	\
+	mbiOU(ut, mbiOshr(ut, ax, cl), |, mbiOshl(ut, ax, CL))
+
+/* k-signed division and remainder */
+#define mbiKdiv(ut,HM,vl,vr)		mbiA_VZU2U(ut, \
+	mbiA_U2VZ(ut, (HM), (vl)) ^ mbiA_U2VZ(ut, (HM), (vr)), \
+	mbiUI(mbiA_U2M(ut, (HM), (vl))) / mbiUI(mbiA_U2M(ut, (HM), (vr))))
+#define mbiMK_div(ut,FM,HM,vl,vr)	mbiA_VZU2U(ut, \
+	mbiMA_U2VZ(ut, (FM), (HM), (vl)) ^ mbiMA_U2VZ(ut, (FM), (HM), (vr)), \
+	mbiUI(mbiMA_U2M(ut, (FM), (HM), (vl))) / mbiUI(mbiMA_U2M(ut, (FM), (HM), (vr))))
+#define mbiMKdiv(ut,FM,HM,vl,vr)	mbiMM(ut, (FM), \
+	mbiMK_div(ut, (FM), (HM), (vl), (vr)))
+#define mbiK_rem(ut,vl,vr,vdiv)		mbiOU(ut, vl, -, mbiOU(ut, vdiv, *, vr))
+#define mbiKrem(ut,HM,vl,vr)		mbiK_rem(ut, (vl), (vr), \
+					    mbiKdiv(ut, (HM), (vl), (vr)))
+#define mbiMKrem(ut,FM,HM,vl,vr)	mbiMM(ut, (FM), mbiK_rem(ut, (vl), (vr), \
+					    mbiMK_div(ut, (FM), (HM), (vl), (vr))))
+/* statement, assigning to dstdiv and dstrem */
+#define mbiKdivrem(dstdiv,dstrem,ut,HM,vl,vr) do {			\
+	ut mbi__TMP = mbiKdiv(ut, (HM), (vl), (vr));			\
+	(dstdiv) = mbi__TMP;						\
+	(dstrem) = mbiK_rem(ut, (vl), (vr), mbi__TMP);			\
+} while (/* CONSTCOND */ 0)
+#define mbiMKdivrem(dstdiv,dstrem,ut,FM,HM,vl,vr) do {			\
+	ut mbi__TMP = mbiMK_div(ut, (FM), (HM), (vl), (vr));		\
+	(dstdiv) = mbiMM(ut, (FM), mbi__TMP);				\
+	(dstrem) = mbiMM(ut, (FM), mbiK_rem(ut, (vl), (vr), mbi__TMP));	\
+} while (/* CONSTCOND */ 0)
+
+/*
+ * anything else
+ */
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+#endif /* !SYSKERN_MBSDINT_H */
--- mksh-59c.orig/mirhash.h
+++ mksh-59c/mirhash.h
@@ -1,5 +1,5 @@
 /*-
- * Copyright © 2011, 2014, 2015
+ * Copyright © 2011, 2014, 2015, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -17,210 +17,126 @@
  * damage or existence of a defect, except proven that it results out
  * of said person’s immediate fault when using the work as intended.
  *-
- * This file provides BAFH (Better Avalanche for the Jenkins Hash) as
- * inline macro bodies that operate on “register uint32_t” variables,
- * with variants that use their local intermediate registers.
- *
- * Usage note for BAFH with entropy distribution: input up to 4 bytes
- * is best combined into a 32-bit unsigned integer, which is then run
- * through BAFHFinish_reg for mixing and then used as context instead
- * of 0. Longer input should be handled the same: take the first four
- * bytes as IV after mixing then add subsequent bytes the same way.
- * This needs counting input bytes and is endian-dependent, thus not,
- * for speed reasons, specified for the regular stable hash, but very
- * much recommended if the actual output value may differ across runs
- * (so is using a random value instead of 0 for the IV).
+ * This file provides BAFH1-0 (Better Avalanche for the Jenkins Hash)
+ * as macro bodies operating on “register k32” variables (from sh.h),
+ * which must be of u_int (or higher) rank, ≥32 bits width.
  *-
  * Little quote gem:
  *	We are looking into it. Changing the core
  *	hash function in PHP isn't a trivial change
  *	and will take us some time.
- * -- Rasmus Lerdorf
+ *		-- Rasmus Lerdorf
  */
 
-#ifndef SYSKERN_MIRHASH_H
-#define SYSKERN_MIRHASH_H 1
-#define SYSKERN_MIRHASH_BAFH
+#ifndef MKSH_MIRHASH_H
+#define MKSH_MIRHASH_H
 
-#include <sys/types.h>
-
-__RCSID("$MirOS: src/bin/mksh/mirhash.h,v 1.6 2015/11/29 17:05:02 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/mirhash.h,v 1.20 2023/08/22 22:42:33 tg Exp $");
 
 /*-
- * BAFH itself is defined by the following primitives:
+ * BAFH1-0 is defined by the following primitives:
  *
  * • BAFHInit(ctx) initialises the hash context, which consists of a
- *   sole 32-bit unsigned integer (ideally in a register), to 0.
- *   It is possible to use any initial value out of [0; 2³²[ – which
+ *   sole 32-bit unsigned integer (ideally in a register), to 0^H1.
+ *   It is possible to use any initial value out of [0; 2³²[ — which
  *   is, in fact, recommended if using BAFH for entropy distribution
- *   – but for a regular stable hash, the IV 0 is needed.
+ *   — but for a regular stable hash, the IV 0^H1 is needed: iff the
+ *   sum of ctx and val in BAFHUpdateOctet is 0, leading NULs aren’t
+ *   counted, so apply suitable bias to ensure that state is avoided.
  *
  * • BAFHUpdateOctet(ctx,val) compresses the unsigned 8-bit quantity
- *   into the hash context. The algorithm used is Jenkins’ one-at-a-
- *   time, except that an additional constant 1 is added so that, if
- *   the context is (still) zero, adding a NUL byte is not ignored.
- *
- * • BAFHror(eax,cl) evaluates to the unsigned 32-bit integer “eax”,
- *   rotated right by “cl” ∈ [0; 31] (no casting, be careful!) where
- *   “eax” must be uint32_t and “cl” an in-range integer.
+ *   into the hash context using Jenkins’ one-at-a-time algorithm.
  *
  * • BAFHFinish(ctx) avalanches the context around so every sub-byte
  *   depends on all input octets; afterwards, the context variable’s
  *   value is the hash output. BAFH does not use any padding, nor is
  *   the input length added; this is due to the common use case (for
  *   quick entropy distribution and use with a hashtable).
- *   Warning: BAFHFinish uses the MixColumn algorithm of AES – which
+ *   Warning: BAFHFinish uses the MixColumn algorithm of AES — which
  *   is reversible (to avoid introducing funnels and reducing entro‐
  *   py), so blinding may need to be employed for some uses, e.g. in
- *   mksh, after a fork.
- *
- * The BAFHUpdateOctet and BAFHFinish are available in two flavours:
- * suffixed with _reg (assumes the context is in a register) or _mem
- * (which doesn’t).
+ *   mksh, after a fork. For ctx == 0 only, ctx will be 0 afterwards.
  *
- * The following high-level macros (with _reg and _mem variants) are
- * available:
+ * The following high-level macros are available:
  *
  * • BAFHUpdateMem(ctx,buf,len) adds a memory block to a context.
  * • BAFHUpdateStr(ctx,buf) is equivalent to using len=strlen(buf).
- * • BAFHHostMem(ctx,buf,len) calculates the hash of the memory buf‐
- *   fer using the first 4 octets (mixed) for IV, as outlined above;
- *   the result is endian-dependent; “ctx” assumed to be a register.
- * • BAFHHostStr(ctx,buf) does the same for C strings.
+ * • BAFHUpdateVLQ(ctx,ut,ival) encodes as VLQ with negated A bit.
  *
  * All macros may use ctx multiple times in their expansion, but all
- * other arguments are always evaluated at most once except BAFHror.
- *
- * To stay portable, never use the BAFHHost*() macros (these are for
- * host-local entropy shuffling), and encode numbers using ULEB128.
+ * other arguments are always evaluated at most once.
  */
 
 #define BAFHInit(h) do {					\
-	(h) = 0;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateOctet_reg(h,b) do {				\
-	(h) += (uint8_t)(b);					\
-	++(h);							\
-	(h) += (h) << 10;					\
-	(h) ^= (h) >> 6;					\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateOctet_mem(m,b) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateOctet_reg(BAFH_h, (b));			\
-	(m) = BAFH_h;						\
+	(h) = mbiMM(k32, K32_FM, 1U);				\
 } while (/* CONSTCOND */ 0)
 
-#define BAFHror(eax,cl) (((eax) >> (cl)) | ((eax) << (32 - (cl))))
-
-#define BAFHFinish_reg(h) do {					\
-	register uint32_t BAFHFinish_v;				\
-								\
-	BAFHFinish_v = ((h) >> 7) & 0x01010101U;		\
-	BAFHFinish_v += BAFHFinish_v << 1;			\
-	BAFHFinish_v += BAFHFinish_v << 3;			\
-	BAFHFinish_v ^= ((h) << 1) & 0xFEFEFEFEU;		\
-								\
-	BAFHFinish_v ^= BAFHror(BAFHFinish_v, 8);		\
-	BAFHFinish_v ^= ((h) = BAFHror((h), 8));		\
-	BAFHFinish_v ^= ((h) = BAFHror((h), 8));		\
-	(h) = BAFHror((h), 8) ^ BAFHFinish_v;			\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHFinish_mem(m) do {					\
-	register uint32_t BAFHFinish_v, BAFH_h = (m);		\
-								\
-	BAFHFinish_v = (BAFH_h >> 7) & 0x01010101U;		\
-	BAFHFinish_v += BAFHFinish_v << 1;			\
-	BAFHFinish_v += BAFHFinish_v << 3;			\
-	BAFHFinish_v ^= (BAFH_h << 1) & 0xFEFEFEFEU;		\
-								\
-	BAFHFinish_v ^= BAFHror(BAFHFinish_v, 8);		\
-	BAFHFinish_v ^= (BAFH_h = BAFHror(BAFH_h, 8));		\
-	BAFHFinish_v ^= (BAFH_h = BAFHror(BAFH_h, 8));		\
-	(m) = BAFHror(BAFH_h, 8) ^ BAFHFinish_v;		\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateMem_reg(h,p,z) do {				\
-	register const uint8_t *BAFHUpdate_p;			\
-	register size_t BAFHUpdate_z = (z);			\
+#define BAFHUpdateOctet(h,b) do {				\
+	(h) = mbiMO(k32, K32_FM, (h), +, KBI(b));		\
+	(h) = mbiMO(k32, K32_FM, (h), +,			\
+	    mbiMKshl(k32, K32_FM, (h), 10));			\
+	(h) = mbiMO(k32, K32_FM, (h), ^,			\
+	    mbiMKshr(k32, K32_FM, (h), 6));			\
+} while (/* CONSTCOND */ 0)
+
+#define BAFHFinish__impl(h,v,d)					\
+	v = mbiMO(k32, K32_FM,					\
+	    mbiMKshr(k32, K32_FM, h, 7), &, 0x01010101U);	\
+	v = mbiMO(k32, K32_FM, v, +,				\
+	    mbiMKshl(k32, K32_FM, v, 1));			\
+	v = mbiMO(k32, K32_FM, v, +,				\
+	    mbiMKshl(k32, K32_FM, v, 3));			\
+	v = mbiMO(k32, K32_FM, v, ^, mbiMO(k32, K32_FM,		\
+	    mbiMKshl(k32, K32_FM, h, 1), &, 0xFEFEFEFEU));	\
+								\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    mbiMKror(k32, K32_FM, v, 8));			\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    (h = mbiMKror(k32, K32_FM, h, 8)));			\
+	v = mbiMO(k32, K32_FM, v, ^,				\
+	    (h = mbiMKror(k32, K32_FM, h, 8)));			\
+	d = mbiMO(k32, K32_FM, v, ^,				\
+	    mbiMKror(k32, K32_FM, h, 8));
+
+#define BAFHFinish(h) do {					\
+	register k32 BAFHFinish_v;				\
+								\
+	BAFHFinish__impl((h), BAFHFinish_v, (h))		\
+} while (/* CONSTCOND */ 0)
+
+#define BAFHUpdateMem(h,p,z) do {				\
+	register const unsigned char *BAFHUpdate_p;		\
+	register const unsigned char *BAFHUpdate_d;		\
 								\
 	BAFHUpdate_p = (const void *)(p);			\
-	while (BAFHUpdate_z--)					\
-		BAFHUpdateOctet_reg((h), *BAFHUpdate_p++);	\
+	BAFHUpdate_d = BAFHUpdate_p + (z);			\
+	while (BAFHUpdate_p < BAFHUpdate_d)			\
+		BAFHUpdateOctet((h), *BAFHUpdate_p++);		\
 } while (/* CONSTCOND */ 0)
 
-/* meh should have named them _r/m but that’s not valid C */
-#define BAFHUpdateMem_mem(m,p,z) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateMem_reg(BAFH_h, (p), (z));			\
-	(m) = BAFH_h;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHUpdateStr_reg(h,s) do {				\
-	register const uint8_t *BAFHUpdate_s;			\
-	register uint8_t BAFHUpdate_c;				\
+#define BAFHUpdateStr(h,s) do {					\
+	register const unsigned char *BAFHUpdate_s;		\
+	register unsigned char BAFHUpdate_c;			\
 								\
 	BAFHUpdate_s = (const void *)(s);			\
-	while ((BAFHUpdate_c = *BAFHUpdate_s++) != 0)		\
-		BAFHUpdateOctet_reg((h), BAFHUpdate_c);		\
+	while ((BAFHUpdate_c = *BAFHUpdate_s++))		\
+		BAFHUpdateOctet((h), BAFHUpdate_c);		\
 } while (/* CONSTCOND */ 0)
 
-#define BAFHUpdateStr_mem(m,s) do {				\
-	register uint32_t BAFH_h = (m);				\
-								\
-	BAFHUpdateStr_reg(BAFH_h, (s));				\
-	(m) = BAFH_h;						\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHHostMem(h,p,z) do {					\
-	register const uint8_t *BAFHUpdate_p;			\
-	register size_t BAFHUpdate_z = (z);			\
-	size_t BAFHHost_z;					\
-	union {							\
-		uint8_t as_u8[4];				\
-		uint32_t as_u32;				\
-	} BAFHHost_v;						\
-								\
-	BAFHUpdate_p = (const void *)(p);			\
-	BAFHHost_v.as_u32 = 0;					\
-	BAFHHost_z = BAFHUpdate_z < 4 ? BAFHUpdate_z : 4;	\
-	memcpy(BAFHHost_v.as_u8, BAFHUpdate_p, BAFHHost_z);	\
-	BAFHUpdate_p += BAFHHost_z;				\
-	BAFHUpdate_z -= BAFHHost_z;				\
-	(h) = BAFHHost_v.as_u32;				\
-	BAFHFinish_reg(h);					\
-	while (BAFHUpdate_z--)					\
-		BAFHUpdateOctet_reg((h), *BAFHUpdate_p++);	\
-	BAFHFinish_reg(h);					\
-} while (/* CONSTCOND */ 0)
-
-#define BAFHHostStr(h,s) do {					\
-	register const uint8_t *BAFHUpdate_s;			\
-	register uint8_t BAFHUpdate_c;				\
-	union {							\
-		uint8_t as_u8[4];				\
-		uint32_t as_u32;				\
-	} BAFHHost_v;						\
-								\
-	BAFHUpdate_s = (const void *)(s);			\
-	BAFHHost_v.as_u32 = 0;					\
-	if ((BAFHHost_v.as_u8[0] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[1] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[2] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	if ((BAFHHost_v.as_u8[3] = *BAFHUpdate_s) != 0)		\
-		++BAFHUpdate_s;					\
-	(h) = BAFHHost_v.as_u32;				\
-	BAFHFinish_reg(h);					\
-	while ((BAFHUpdate_c = *BAFHUpdate_s++) != 0)		\
-		BAFHUpdateOctet_reg((h), BAFHUpdate_c);		\
-	BAFHFinish_reg(h);					\
+#define BAFHUpdateVLQ(h,t,n) do {				\
+	unsigned char BAFHUpdate_s[(sizeof(t)*(CHAR_BIT)+6)/7];	\
+	register size_t BAFHUpdate_n = sizeof(BAFHUpdate_s);	\
+	t BAFHUpdate_v = (n);					\
+								\
+	do {							\
+		BAFHUpdate_s[--BAFHUpdate_n] =			\
+		    BAFHUpdate_v & 0x7FU;			\
+		BAFHUpdate_v >>= 7;				\
+	} while (BAFHUpdate_v);					\
+	BAFHUpdate_s[sizeof(BAFHUpdate_s) - 1] |= 0x80U;	\
+	while (BAFHUpdate_n < sizeof(BAFHUpdate_s))		\
+		BAFHUpdateOctet((h),				\
+		    BAFHUpdate_s[BAFHUpdate_n++]);		\
 } while (/* CONSTCOND */ 0)
 
 #endif
--- mksh-59c.orig/misc.c
+++ mksh-59c/misc.c
@@ -4,7 +4,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019,
- *		 2020
+ *		 2020, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  * Copyright (c) 2015
  *	Daniel Richard G. <skunk@iSKUNK.ORG>
@@ -26,36 +26,21 @@
  */
 
 #include "sh.h"
-#if !HAVE_GETRUSAGE
-#include <sys/times.h>
-#endif
-#if HAVE_GRP_H
-#include <grp.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/misc.c,v 1.302 2020/08/27 19:52:45 tg Exp $");
-
-#define KSH_CHVT_FLAG
-#ifdef MKSH_SMALL
-#undef KSH_CHVT_FLAG
-#endif
-#ifdef TIOCSCTTY
-#define KSH_CHVT_CODE
-#define KSH_CHVT_FLAG
-#endif
 
-/* type bits for unsigned char */
-unsigned char chtypes[UCHAR_MAX + 1];
+__RCSID("$MirOS: src/bin/mksh/misc.c,v 1.359 2023/09/17 01:54:04 tg Exp $");
 
 static const unsigned char *pat_scan(const unsigned char *,
-    const unsigned char *, bool) MKSH_A_PURE;
+    const unsigned char *, Wahr);
 static int do_gmatch(const unsigned char *, const unsigned char *,
     const unsigned char *, const unsigned char *,
-    const unsigned char *) MKSH_A_PURE;
-static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char)
-    MKSH_A_PURE;
-#ifdef KSH_CHVT_CODE
+    const unsigned char *);
+static const unsigned char *gmatch_cclass(const unsigned char *, unsigned char);
 static void chvt(const Getopt *);
+static unsigned int dollarqU(struct shf *, const unsigned char *);
+#ifndef MKSH_SMALL
+static void dollarq8(struct shf *, const unsigned char *);
+#else
+#define dollarq8 dollarqU
 #endif
 
 /*XXX this should go away */
@@ -65,19 +50,19 @@ static int make_path(const char *, const
 /* we don't need to check for other codes, EPERM won't happen */
 #define DO_SETUID(func,argvec) do {					\
 	if ((func argvec) && errno == EAGAIN)				\
-		errorf("%s failed with EAGAIN, probably due to a"	\
-		    " too low process limit; aborting", #func);		\
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |		\
+		    KWF_TWOMSG, #func, "failed, probably due to a"	\
+		    " too low process limit; aborting");		\
 } while (/* CONSTCOND */ 0)
 #else
 #define DO_SETUID(func,argvec) func argvec
 #endif
 
-
 /* called from XcheckN() to grow buffer */
 char *
 Xcheck_grow(XString *xsp, const char *xp, size_t more)
 {
-	const char *old_beg = xsp->beg;
+	size_t old_ofs = xp - xsp->beg;
 
 	if (more < xsp->len)
 		more = xsp->len;
@@ -85,24 +70,30 @@ Xcheck_grow(XString *xsp, const char *xp
 	checkoktoadd(more, xsp->len + X_EXTRA);
 	xsp->beg = aresize(xsp->beg, (xsp->len += more) + X_EXTRA, xsp->areap);
 	xsp->end = xsp->beg + xsp->len;
-	return (xsp->beg + (xp - old_beg));
+	return (xsp->beg + old_ofs);
 }
 
-
 #define SHFLAGS_DEFNS
-#define FN(sname,cname,flags,ochar)		\
-	static const struct {			\
-		/* character flag (if any) */	\
-		char c;				\
-		/* OF_* */			\
-		unsigned char optflags;		\
-		/* long name of option */	\
-		char name[sizeof(sname)];	\
-	} shoptione_ ## cname = {		\
-		ochar, flags, sname		\
+#define FN(sname,cname,flags,ochar)			\
+	static const struct shoptionS_ ## cname {	\
+		/* character flag (if any) */		\
+		char c;					\
+		/* OF_* */				\
+		unsigned char optflags;			\
+		/* long name of option */		\
+		char name[sizeof(sname)];		\
+	} shoptione_ ## cname = {			\
+		ochar, flags, sname			\
 	};
 #include "sh_flags.gen"
 
+mbCTA_BEG(sh_flags_gen);
+#define FN(sname,cname,flags,ochar) mbccCTA(o_ ## cname, ( \
+	offsetof(struct shoptionS_ ## cname, optflags) == 1 && \
+	offsetof(struct shoptionS_ ## cname, name) == 2));
+#include "sh_flags.gen"
+mbCTA_END(sh_flags_gen);
+
 #define OFC(i) (options[i][-2])
 #define OFF(i) (((const unsigned char *)options[i])[-1])
 #define OFN(i) (options[i])
@@ -142,7 +133,7 @@ struct options_info {
 };
 
 static void options_fmt_entry(char *, size_t, unsigned int, const void *);
-static int printoptions(bool);
+static int printoptions(Wahr);
 static int printoption(size_t);
 
 /* format a single select menu item */
@@ -178,7 +169,7 @@ printoption(size_t i)
 }
 
 static int
-printoptions(bool verbose)
+printoptions(Wahr verbose)
 {
 	size_t i = 0;
 	int rv = 0;
@@ -205,7 +196,7 @@ printoptions(bool verbose)
 		}
 		co.shf = shl_stdout;
 		co.linesep = '\n';
-		co.prefcol = co.do_last = true;
+		co.prefcol = co.do_last = Ja;
 		print_columns(&co, n, options_fmt_entry, &oi,
 		    octs + 4, oi.opt_width + 4);
 	} else {
@@ -242,13 +233,16 @@ getoptions(void)
 
 /* change a Flag(*) value; takes care of special actions */
 void
-change_flag(enum sh_flag f, int what, bool newset)
+change_flag(enum sh_flag f,
+    /* OF_INTERNAL, OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
+    unsigned int what,
+    Wahr newset)
 {
 	unsigned char oldval = Flag(f);
 	unsigned char newval = (newset ? 1 : 0);
 
 	if (f == FXTRACE) {
-		change_xtrace(newval, true);
+		change_xtrace(newval, Ja);
 		return;
 	} else if (f == FPRIVILEGED) {
 		if (!oldval)
@@ -292,10 +286,6 @@ change_flag(enum sh_flag f, int what, bo
 
 		/* +++ privs changed +++ */
 	} else if ((f == FPOSIX || f == FSH) && newval) {
-		/* Turning on -o posix? */
-		if (f == FPOSIX)
-			/* C locale required for compliance */
-			UTFMODE = 0;
 		/* Turning on -o posix or -o sh? */
 		Flag(FBRACEEXPAND) = 0;
 #ifndef MKSH_NO_CMDLINE_EDITING
@@ -316,7 +306,7 @@ change_flag(enum sh_flag f, int what, bo
 
 	if (f == FTALKING) {
 		/* Changing interactive flag? */
-		if ((what == OF_CMDLINE || what == OF_SET) && procpid == kshpid)
+		if (what == OF_CMDLINE && procpid == kshpid)
 			Flag(FTALKING_I) = newval;
 #ifndef MKSH_UNEMPLOYED
 	} else if (f == FMONITOR) {
@@ -327,9 +317,9 @@ change_flag(enum sh_flag f, int what, bo
 }
 
 void
-change_xtrace(unsigned char newval, bool dosnapshot)
+change_xtrace(unsigned char newval, Wahr dosnapshot)
 {
-	static bool in_xtrace;
+	static Wahr in_xtrace;
 
 	if (in_xtrace)
 		return;
@@ -359,11 +349,11 @@ change_xtrace(unsigned char newval, bool
 
  changed_xtrace:
 	if ((Flag(FXTRACE) = newval) == 2) {
-		in_xtrace = true;
+		in_xtrace = Ja;
 		Flag(FXTRACE) = 0;
-		shf_puts(substitute(str_val(global("PS4")), 0), shl_xtrace);
+		shf_putsv(substitute(str_val(global("PS4")), 0), shl_xtrace);
 		Flag(FXTRACE) = 2;
-		in_xtrace = false;
+		in_xtrace = Nee;
 	}
 }
 
@@ -374,8 +364,8 @@ change_xtrace(unsigned char newval, bool
 int
 parse_args(const char **argv,
     /* OF_FIRSTTIME, OF_CMDLINE, or OF_SET */
-    int what,
-    bool *setargsp)
+    unsigned int what,
+    Wahr *setargsp)
 {
 	static const char cmd_opts[] =
 #define SHFLAGS_NOT_SET
@@ -389,19 +379,18 @@ parse_args(const char **argv,
 #include "sh_flags.gen"
 #undef SHFLAGS_NOT_CMD
 	    ;
-	bool set;
-	const char *opts = what == OF_CMDLINE || what == OF_FIRSTTIME ?
-	    cmd_opts : set_opts;
+	Wahr set;
+	const char * const opts = what == OF_SET ? set_opts : cmd_opts;
 	const char *array = NULL;
 	Getopt go;
 	size_t i;
 	int optc, arrayset = 0;
-	bool sortargs = false;
-	bool fcompatseen = false;
+	Wahr sortargs = Nee;
+	Wahr fcompatseen = Nee;
 
 	ksh_getopt_reset(&go, GF_ERROR|GF_PLUSOPT);
 	while ((optc = ksh_getopt(argv, &go, opts)) != -1) {
-		set = tobool(!(go.info & GI_PLUS));
+		set = isWahr(!(go.info & GI_PLUS));
 		switch (optc) {
 		case 'A':
 			if (what == OF_FIRSTTIME)
@@ -418,13 +407,12 @@ parse_args(const char **argv,
 				 * lone -o: print options
 				 *
 				 * Note that on the command line, -o requires
-				 * an option (ie, can't get here if what is
-				 * OF_CMDLINE).
+				 * an option (i.e. can't get here if what is
+				 * not OF_SET).
 				 */
 #if !defined(MKSH_SMALL) || defined(DEBUG)
 				if (!set && !baseline_flags[(int)FNFLAGS]) {
-					bi_errorf(Tf_s_s, "too early",
-					    Tset_po);
+					bi_errorf(Ttooearly, T_set_po);
 					return (-1);
 				}
 #endif
@@ -442,7 +430,7 @@ parse_args(const char **argv,
 				 */
 				Flag(FPOSIX) = 0;
 				Flag(FSH) = 0;
-				fcompatseen = true;
+				fcompatseen = Ja;
 			}
 			if ((i != (size_t)-1) && (set ? 1U : 0U) == Flag(i))
 				/*
@@ -457,8 +445,7 @@ parse_args(const char **argv,
 			else if (!strcmp(go.optarg, To_reset)) {
 #if !defined(MKSH_SMALL) || defined(DEBUG)
 				if (!baseline_flags[(int)FNFLAGS]) {
-					bi_errorf(Tf_ss, "too early",
-					    To_o_reset);
+					bi_errorf(Ttooearly, To_o_reset);
 					return (-1);
 				}
 #endif
@@ -477,18 +464,11 @@ parse_args(const char **argv,
 			}
 			break;
 
-#ifdef KSH_CHVT_FLAG
 		case 'T':
 			if (what != OF_FIRSTTIME)
 				break;
-#ifndef KSH_CHVT_CODE
-			errorf("no TIOCSCTTY ioctl");
-#else
-			change_flag(FTALKING, OF_CMDLINE, true);
 			chvt(&go);
 			break;
-#endif
-#endif
 
 		case '?':
 			return (-1);
@@ -496,9 +476,9 @@ parse_args(const char **argv,
 		default:
 			if (what == OF_FIRSTTIME)
 				break;
-			/* -s: sort positional params (AT&T ksh stupidity) */
-			if (what == OF_SET && optc == 's') {
-				sortargs = true;
+			/* -s: sort positional params (via AT&T ksh) */
+			if (what == OF_SET && isch(optc, 's')) {
+				sortargs = Ja;
 				break;
 			}
 			for (i = 0; i < NELEM(options); i++)
@@ -508,18 +488,22 @@ parse_args(const char **argv,
 					break;
 				}
 			if (i == NELEM(options))
-				internal_errorf("parse_args: '%c'", optc);
+				kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+				    "parse_args: '%c'", optc);
 		}
 	}
-	if (!(go.info & GI_MINUSMINUS) && argv[go.optind] &&
+	/* lone ‘-’ (or ‘+’)? */
+	if (argv[go.optind] &&
 	    ctype(argv[go.optind][0], C_MINUS | C_PLUS) &&
-	    argv[go.optind][1] == '\0') {
-		/* lone - clears -v and -x flags */
-		if (argv[go.optind][0] == '-') {
+	    argv[go.optind][1] == '\0' &&
+	    !(go.info & GI_MINUSMINUS)) {
+		/* POSIX: lone hyphen-minus sh first arg ignored */
+		if (what == OF_SET && isch(argv[go.optind][0], '-')) {
+			/* set; lone dash clears -v and -x flags (obsolete) */
 			Flag(FVERBOSE) = 0;
-			change_xtrace(0, false);
+			change_xtrace(0, Nee);
 		}
-		/* set skips lone - or + option */
+		/* either way, skip it (POSIX only dash but… meh) */
 		go.optind++;
 	}
 	if (setargsp)
@@ -531,7 +515,7 @@ parse_args(const char **argv,
 		const char *ccp = NULL;
 
 		if (array && *array)
-			ccp = skip_varname(array, false);
+			ccp = skip_varname(array, Nee);
 		if (!ccp || !(!ccp[0] || (ccp[0] == '+' && !ccp[1]))) {
 			bi_errorf(Tf_sD_s, array, Tnot_ident);
 			return (-1);
@@ -544,7 +528,7 @@ parse_args(const char **argv,
 		    ascpstrcmp);
 	}
 	if (arrayset)
-		go.optind += set_array(array, tobool(arrayset > 0),
+		go.optind += set_array(array, isWahr(arrayset > 0),
 		    argv + go.optind);
 
 	return (go.optind);
@@ -554,11 +538,41 @@ parse_args(const char **argv,
 int
 getn(const char *s, int *ai)
 {
+	if (!getpn(&s, ai))
+		return (0);
+	if (!*s)
+		return (1);
+	errno = EINVAL;
+	return (0);
+}
+
+int
+getnh(const char *s, mbiHUGE_U *ai)
+{
+	if (!getpnh(&s, ai))
+		return (0);
+	if (!*s)
+		return (1);
+	errno = EINVAL;
+	return (0);
+}
+
+/*
+ * parse a decimal number
+ * on success, returns 1 and *ai contains it and *sp points past it
+ * on overflow, returns 0, *ai is 0, *sp points behind the parsed number
+ * on parse error (not numeric) returns 0, *ai is 0, *sp is not changed
+ */
+int
+getpn(const char **sp, int *ai)
+{
 	char c;
-	mksh_ari_u num;
-	bool neg = false;
+	const char *s;
+	mksh_uari_t num = 0;
+	kby state = 0;
+	Wahr neg = Nee;
 
-	num.u = 0;
+	s = *sp;
 
 	do {
 		c = *s++;
@@ -566,31 +580,103 @@ getn(const char *s, int *ai)
 
 	switch (c) {
 	case '-':
-		neg = true;
+		neg = Ja;
 		/* FALLTHROUGH */
 	case '+':
 		c = *s++;
 		break;
 	}
 
-	do {
-		if (!ctype(c, C_DIGIT))
-			/* not numeric */
-			return (0);
-		if (num.u > 214748364U)
+	while (ctype(c, C_DIGIT)) {
+			  /*XXX this supposed to return int? */
+		if (num > 214748364U) {
 			/* overflow on multiplication */
-			return (0);
-		num.u = num.u * 10U + (unsigned int)ksh_numdig(c);
-		/* now: num.u <= 2147483649U */
-	} while ((c = *s++));
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		if (state < 2) {
+			state = 1;
+			num = num * 10U + (unsigned int)ksh_numdig(c);
+		}
+		/* now: num <= 2147483649U */
+		c = *s++;
+	}
+	--s;
 
-	if (num.u > (neg ? 2147483648U : 2147483647U))
+	if (num > (neg ? 2147483648U : 2147483647U)) {
 		/* overflow for signed 32-bit int */
+		state = 2;
+		errno = EOVERFLOW;
+	}
+
+	if (state)
+		*sp = s;
+	else
+		errno = EINVAL;
+	if (state != 1) {
+		*ai = 0;
 		return (0);
+	}
+	/*XXX this supposed to return int?!?!?!?! */
+	*ai = (neg && num > 0) ?
+	    (mksh_ari_t)(-(mksh_ari_t)((num - 1U) & 0x7FFFFFFF) - 1) :
+	    (mksh_ari_t)num;
+	return (1);
+}
+
+int
+getpnh(const char **sp, mbiHUGE_U *ai)
+{
+	char c;
+	const char *s;
+	mbiHUGE_U num = 0;
+	kby state = 0;
+	Wahr neg = Nee;
+
+	s = *sp;
+
+	do {
+		c = *s++;
+	} while (ctype(c, C_SPACE));
+
+	switch (c) {
+	case '-':
+		neg = Ja;
+		/* FALLTHROUGH */
+	case '+':
+		c = *s++;
+		break;
+	}
 
-	if (neg)
-		num.u = -num.u;
-	*ai = num.i;
+	while (ctype(c, C_DIGIT)) {
+		if (num > (mbiHUGE_U_MAX / 10U)) {
+			/* overflow on multiplication */
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		num *= 10U;
+		if (num > (mbiHUGE_U_MAX - (unsigned int)ksh_numdig(c))) {
+			/* overflow on addition */
+			state = 2;
+			errno = EOVERFLOW;
+		}
+		if (state < 2) {
+			num += (unsigned int)ksh_numdig(c);
+			state = 1;
+		}
+		c = *s++;
+	}
+	--s;
+
+	if (state)
+		*sp = s;
+	else
+		errno = EINVAL;
+	if (state != 1) {
+		*ai = 0;
+		return (0);
+	}
+	*ai = neg ? (mbiHUGE_U)-(mbiHUGE_U)num : num;
 	return (1);
 }
 
@@ -602,7 +688,7 @@ getn(const char *s, int *ai)
 static void *
 simplify_gmatch_pattern(const unsigned char *sp)
 {
-	uint8_t c;
+	kby c;
 	unsigned char *cp, *dp;
 	const unsigned char *ps, *se;
 
@@ -620,12 +706,12 @@ simplify_gmatch_pattern(const unsigned c
 			*dp++ = c;
 			continue;
 		}
-		switch ((c = *sp++)) {
-		case 0x80|'@':
+		switch (ord((c = *sp++))) {
+		case ORD(0x80|'@'):
 		/* simile for @ */
-		case 0x80|' ':
+		case ORD(0x80|' '):
 			/* check whether it has only one clause */
-			ps = pat_scan(sp, se, true);
+			ps = pat_scan(sp, se, Ja);
 			if (!ps || ps[-1] != /*(*/ ')')
 				/* nope */
 				break;
@@ -677,7 +763,7 @@ simplify_gmatch_pattern(const unsigned c
  * pattern character are prefixed with MAGIC by expand.
  */
 int
-gmatchx(const char *s, const char *p, bool isfile)
+gmatchx(const char *s, const char *p, Wahr isfile)
 {
 	const char *se, *pe;
 	char *pnew;
@@ -688,8 +774,8 @@ gmatchx(const char *s, const char *p, bo
 
 	pe = strnul(p);
 	/*
-	 * isfile is false iff no syntax check has been done on
-	 * the pattern. If check fails, just do a strcmp().
+	 * isfile is Nee iff no syntax check has been done on the pattern.
+	 * If check fails just do a strcmp().
 	 */
 	if (!isfile && !has_globbing(p)) {
 		size_t len = pe - p + 1;
@@ -715,8 +801,8 @@ gmatchx(const char *s, const char *p, bo
 }
 
 /**
- * Returns if p is a syntacticly correct globbing pattern, false
- * if it contains no pattern characters or if there is a syntax error.
+ * Returns if p is a syntacticly correct globbing pattern, Nee if it
+ * contains no pattern characters or if there is a syntax error.
  * Syntax errors are:
  *	- [ with no closing ]
  *	- imbalanced $(...) expression
@@ -731,11 +817,11 @@ gmatchx(const char *s, const char *p, bo
  *	return ?
  * - return ?
  */
-bool
+Wahr
 has_globbing(const char *pat)
 {
 	unsigned char c, subc;
-	bool saw_glob = false;
+	Wahr saw_glob = Nee;
 	unsigned int nest = 0;
 	const unsigned char *p = (const unsigned char *)pat;
 	const unsigned char *s;
@@ -746,11 +832,11 @@ has_globbing(const char *pat)
 			continue;
 		/* MAGIC + NUL? abort. */
 		if (!(c = *p++))
-			return (false);
+			return (Nee);
 		/* some specials */
 		if (ord(c) == ORD('*') || ord(c) == ORD('?')) {
 			/* easy glob, accept */
-			saw_glob = true;
+			saw_glob = Ja;
 		} else if (ord(c) == ORD('[')) {
 			/* bracket expression; eat negation and initial ] */
 			if (ISMAGIC(p[0]) && ord(p[1]) == ORD('!'))
@@ -765,12 +851,12 @@ has_globbing(const char *pat)
 					continue;
 				/* MAGIC + NUL cannot happen */
 				if (!(c = *s++))
-					return (false);
+					return (Nee);
 				/* terminating bracket? */
 				if (ord(c) == ORD(']')) {
 					/* accept and continue */
 					p = s;
-					saw_glob = true;
+					saw_glob = Ja;
 					break;
 				}
 				/* sub-bracket expressions */
@@ -801,7 +887,7 @@ has_globbing(const char *pat)
 			}
 		} else if ((c & 0x80) && ctype(c & 0x7F, C_PATMO | C_SPC)) {
 			/* opening pattern */
-			saw_glob = true;
+			saw_glob = Ja;
 			++nest;
 		} else if (ord(c) == ORD(/*(*/ ')')) {
 			/* closing pattern */
@@ -870,7 +956,7 @@ do_gmatch(const unsigned char *s, const
 				return (0);
 			if (UTFMODE) {
 				--s;
-				s += utf_ptradj((const void *)s);
+				s += ez_mbtoc(NULL, (const void *)s);
 			}
 			break;
 
@@ -893,7 +979,7 @@ do_gmatch(const unsigned char *s, const
 		case ORD('+') | 0x80:
 		/* matches zero or more times */
 		case ORD('*') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			/* take care of zero matches */
@@ -901,7 +987,7 @@ do_gmatch(const unsigned char *s, const
 			    do_gmatch(s, se, prest, pe, smin))
 				return (1);
 			for (psub = p; ; psub = pnext) {
-				pnext = pat_scan(psub, pe, true);
+				pnext = pat_scan(psub, pe, Ja);
 				for (srest = s; srest <= se; srest++) {
 					if (do_gmatch(s, srest, psub, pnext - 2, smin) &&
 					    (do_gmatch(srest, se, prest, pe, smin) ||
@@ -920,7 +1006,7 @@ do_gmatch(const unsigned char *s, const
 		case ORD('@') | 0x80:
 		/* simile for @ */
 		case ORD(' ') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			/* Take care of zero matches */
@@ -928,7 +1014,7 @@ do_gmatch(const unsigned char *s, const
 			    do_gmatch(s, se, prest, pe, smin))
 				return (1);
 			for (psub = p; ; psub = pnext) {
-				pnext = pat_scan(psub, pe, true);
+				pnext = pat_scan(psub, pe, Ja);
 				srest = prest == pe ? se : s;
 				for (; srest <= se; srest++) {
 					if (do_gmatch(s, srest, psub, pnext - 2, smin) &&
@@ -942,14 +1028,14 @@ do_gmatch(const unsigned char *s, const
 
 		/* matches none of the patterns */
 		case ORD('!') | 0x80:
-			if (!(prest = pat_scan(p, pe, false)))
+			if (!(prest = pat_scan(p, pe, Nee)))
 				return (0);
 			s--;
 			for (srest = s; srest <= se; srest++) {
 				int matched = 0;
 
 				for (psub = p; ; psub = pnext) {
-					pnext = pat_scan(psub, pe, true);
+					pnext = pat_scan(psub, pe, Ja);
 					if (do_gmatch(s, srest, psub,
 					    pnext - 2, smin)) {
 						matched = 1;
@@ -977,7 +1063,7 @@ do_gmatch(const unsigned char *s, const
 /*XXX this is a prime example for bsearch or a const hashtable */
 static const struct cclass {
 	const char *name;
-	uint32_t value;
+	kui value;
 } cclasses[] = {
 	/* POSIX */
 	{ "alnum",	C_ALNUM	},
@@ -1013,14 +1099,14 @@ gmatch_cclass(const unsigned char *pat,
 {
 	unsigned char c, subc, lc;
 	const unsigned char *p = pat, *s;
-	bool found = false;
-	bool negated = false;
+	Wahr found = Nee;
+	Wahr negated = Nee;
 	char *subp;
 
 	/* check for negation */
 	if (ISMAGIC(p[0]) && ord(p[1]) == ORD('!')) {
 		p += 2;
-		negated = true;
+		negated = Ja;
 	}
 	/* make initial ] non-MAGIC */
 	if (ISMAGIC(p[0]) && ord(p[1]) == ORD(']'))
@@ -1076,7 +1162,7 @@ gmatch_cclass(const unsigned char *pat,
 							/* found, match? */
 							if (ctype(sc,
 							    cls->value))
-								found = true;
+								found = Ja;
 							/* break either way */
 							break;
 						} else
@@ -1100,7 +1186,7 @@ gmatch_cclass(const unsigned char *pat,
 				if ((c &= 0x7F) != ' ') {
 					/* check single match NOW */
 					if (sc == c)
-						found = true;
+						found = Ja;
 					/* next character is (...) */
 				}
 				c = '(' /*)*/;
@@ -1113,7 +1199,7 @@ gmatch_cclass(const unsigned char *pat,
 			/* no, check single match */
 			if (sc == c)
 				/* note: sc is never NUL */
-				found = true;
+				found = Ja;
 			/* do the next "first" character */
 			continue;
 		}
@@ -1163,10 +1249,10 @@ gmatch_cclass(const unsigned char *pat,
 
 					/* match single previous char */
 					if (lc && (sc == lc))
-						found = true;
+						found = Ja;
 					/* match hyphen-minus */
 					if (ord(sc) == ORD('-'))
-						found = true;
+						found = Ja;
 					/* handle cclass common part */
 					goto cclass_common;
 				}
@@ -1194,7 +1280,7 @@ gmatch_cclass(const unsigned char *pat,
 		if (lc != 0 /* && c != 0 */ &&
 		    asciibetical(lc) <= asciibetical(sc) &&
 		    asciibetical(sc) <= asciibetical(c))
-			found = true;
+			found = Ja;
 		/* forced next character? */
 		if (subc) {
 			c = subc;
@@ -1212,7 +1298,7 @@ gmatch_cclass(const unsigned char *pat,
 
 /* Look for next ) or | (if match_sep) in *(foo|bar) pattern */
 static const unsigned char *
-pat_scan(const unsigned char *p, const unsigned char *pe, bool match_sep)
+pat_scan(const unsigned char *p, const unsigned char *pe, Wahr match_sep)
 {
 	int nest = 0;
 
@@ -1231,7 +1317,7 @@ pat_scan(const unsigned char *p, const u
 int
 ascstrcmp(const void *s1, const void *s2)
 {
-	const uint8_t *cp1 = s1, *cp2 = s2;
+	const kby *cp1 = s1, *cp2 = s2;
 
 	while (*cp1 == *cp2) {
 		if (*cp1++ == '\0')
@@ -1252,15 +1338,12 @@ ascpstrcmp(const void *pstr1, const void
 void
 ksh_getopt_reset(Getopt *go, int flags)
 {
+	memset(go, '\0', sizeof(Getopt));
 	go->optind = 1;
 	go->optarg = NULL;
-	go->p = 0;
 	go->flags = flags;
-	go->info = 0;
-	go->buf[1] = '\0';
 }
 
-
 /**
  * getopt() used for shell built-in commands, the getopts command, and
  * command line options.
@@ -1271,7 +1354,7 @@ ksh_getopt_reset(Getopt *go, int flags)
  *
  * Non-standard features:
  *	- ';' is like ':' in options, except the argument is optional
- *	  (if it isn't present, optarg is set to 0).
+ *	  (if it isn't present, optarg is set to NULL).
  *	  Used for 'set -o'.
  *	- ',' is like ':' in options, except the argument always immediately
  *	  follows the option character (optarg is set to the null string if
@@ -1321,12 +1404,11 @@ ksh_getopt(const char **argv, Getopt *go
 			go->buf[0] = c;
 			go->optarg = go->buf;
 		} else {
-			warningf(true, Tf_optfoo,
-			    (go->flags & GF_NONAME) ? "" : argv[0],
-			    (go->flags & GF_NONAME) ? "" : Tcolsp,
-			    c, Tunknown_option);
+			ksh_getopt_opterr(c,
+			    (go->flags & GF_NONAME) ? null : argv[0],
+			    Tunknown_option);
 			if (go->flags & GF_ERROR)
-				bi_errorfz();
+				bi_unwind(1);
 		}
 		return (ORD('?'));
 	}
@@ -1349,12 +1431,11 @@ ksh_getopt(const char **argv, Getopt *go
 				go->optarg = go->buf;
 				return (ORD(':'));
 			}
-			warningf(true, Tf_optfoo,
-			    (go->flags & GF_NONAME) ? "" : argv[0],
-			    (go->flags & GF_NONAME) ? "" : Tcolsp,
-			    c, Treq_arg);
+			ksh_getopt_opterr(c,
+			    (go->flags & GF_NONAME) ? null : argv[0],
+			    Treq_arg);
 			if (go->flags & GF_ERROR)
-				bi_errorfz();
+				bi_unwind(1);
 			return (ORD('?'));
 		}
 		go->p = 0;
@@ -1386,6 +1467,20 @@ ksh_getopt(const char **argv, Getopt *go
 	return (ord(c));
 }
 
+void
+ksh_getopt_opterr(int ch, const char *name, const char *msg)
+{
+	static char buf[3] = { '-', KSH_BEL, '\0' };
+
+	buf[1] = ch;
+	if (name == null || name == kshname)
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, buf, msg);
+	else
+		kwarnf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_THREEMSG | KWF_NOERRNO, name, buf, msg);
+}
+
 /*
  * print variable/alias value using necessary quotes
  * (POSIX says they should be suitable for re-entry...)
@@ -1396,7 +1491,7 @@ print_value_quoted(struct shf *shf, cons
 {
 	unsigned char c;
 	const unsigned char *p = (const unsigned char *)s;
-	bool inquote = true;
+	Wahr inquote = Ja;
 
 	/* first, special-case empty strings (for re-entrancy) */
 	if (!*s) {
@@ -1406,117 +1501,249 @@ print_value_quoted(struct shf *shf, cons
 	}
 
 	/* non-empty; check whether any quotes are needed */
-	while (rtt2asc(c = *p++) >= 32)
-		if (ctype(c, C_QUOTE | C_SPC))
-			inquote = false;
+	if (UTFMODE) {
+		/* C1 always escaped; multibyte makes this tricky */
+		while ((c = *p++) != 0) {
+			if (ctype(c, C_CNTRL)) {
+				dollarqU(shf, (const unsigned char *)s);
+				return;
+			}
+			/* anything out of ASCII present? */
+			if (rtt2asc(c) > 0x7EU) {
+				/* dollar-quote, but be prepared to redo */
+				char *guess;
+				struct shf to;
+
+				shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC, &to);
+				c = dollarqU(&to, (const unsigned char *)s);
+				guess = shf_sclose(&to);
+				/* output guess if it was right */
+				if (c > 1)
+					shf_puts(guess, shf);
+				afree(guess, ATEMP);
+				if (c == 1)
+					goto always_single;
+				if (c == 0)
+ noquoteneeded:
+					shf_puts(s, shf);
+				return;
+			}
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+		}
+		/* assert: c == 0; all chars in [20;7E] ASCII */
+#ifndef MKSH_EBCDIC
+	} else if (Flag(FASIS)) {
+		while ((c = *p++), !ksh_asisctrl(c))
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+#endif
+	} else {
+		while ((c = *p++), !ksh_isctrl(c))
+			if (ctype(c, C_QUOTE | C_SPC))
+				inquote = Nee;
+	}
+	/* state: if c == 0, all chars printable, inquote shortcuts */
+
+	if (c) {
+		/* otherwise, escape control chars */
+		dollarq8(shf, (const unsigned char *)s);
+		return;
+	}
 
+	/* can we shortcut? */
+	if (inquote)
+		goto noquoteneeded;
+	/* no */
+ always_single:
+	/* all chars printable, no control chars, quote nicely */
+	inquote = Nee;
 	p = (const unsigned char *)s;
-	if (c == 0) {
-		if (inquote) {
-			/* nope, use the shortcut */
-			shf_puts(s, shf);
-			return;
+
+	while ((c = *p++) != 0) {
+		if (c == '\'') {
+			if (inquote) {
+				shf_scheck(3, shf);
+				shf_putc('\'', shf);
+				inquote = Nee;
+			}
+			shf_putc('\\', shf);
+		} else if (!inquote) {
+			shf_putc('\'', shf);
+			inquote = Ja;
 		}
+		shf_putc(c, shf);
+	}
+	if (inquote)
+		shf_putc('\'', shf);
+}
 
-		/* otherwise, quote nicely via state machine */
-		while ((c = *p++) != 0) {
-			if (c == '\'') {
+#define dollarq_Uctrl(c)	(!ctype((c), C_PRINT))
+#ifndef MKSH_SMALL
+#define dollarq_isctrlU(c)	dollarq_Uctrl(c)
+#else
+#define dollarq_isctrlU(c)	(UTFMODE ? dollarq_Uctrl(c) : ksh_isctrl8(c))
+#endif
+
+/* escape with $'...' (!MKSH_SMALL: in UTFMODE) */
+static unsigned int
+dollarqU(struct shf *shf, const unsigned char *s)
+{
+	unsigned char c;
+	unsigned int wc;
+	size_t n;
+	unsigned int rv = 0;
+
+	shf_putc('$', shf);
+	shf_putc('\'', shf);
+	while ((c = *s) != 0) {
+		if (
+#ifdef MKSH_SMALL
+		    UTFMODE &&
+#endif
+		    rtt2asc(c) >= 0xC2U && (n = utf_mbtowc(&wc,
+		    (const char *)s)) != (size_t)-1) {
+			/* valid UTF-8 multibyte character > 0x7F */
+			if ((wc ^ 0x80U) < 0x20U) {
+				/* C1 control character */
+				shf_fprintf(shf, "\\u%04X", wc);
+				rv = 2;
+				s += n;
+			} else {
 				/*
-				 * multiple single quotes or any of them
-				 * at the beginning of a string look nicer
-				 * this way than when simply substituting
+				 * print as-is; we assume the tty DTRT for
+				 * interlinear annotations, LTR/RTL mark,
+				 * U+2028, U+2029, U+2066..U+206F, etc.
 				 */
-				if (inquote) {
-					shf_putc('\'', shf);
-					inquote = false;
-				}
-				shf_putc('\\', shf);
-			} else if (!inquote) {
-				shf_putc('\'', shf);
-				inquote = true;
+				shf_wr_sm(s, n, shf);
 			}
-			shf_putc(c, shf);
+			continue;
 		}
-	} else {
-		unsigned int wc;
-		size_t n;
+		++s;
+		/* single octet */
+		rv |= ctype(c, C_QUOTE | C_SPC);
+		switch (c) {
+		/* see unbksl() in this file for comments */
+		case KSH_BEL:
+			c = 'a';
+			if (0)
+				/* FALLTHROUGH */
+		case '\b':
+			  c = 'b';
+			if (0)
+				/* FALLTHROUGH */
+		case '\f':
+			  c = 'f';
+			if (0)
+				/* FALLTHROUGH */
+		case '\n':
+			  c = 'n';
+			if (0)
+				/* FALLTHROUGH */
+		case '\r':
+			  c = 'r';
+			if (0)
+				/* FALLTHROUGH */
+		case '\t':
+			  c = 't';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_VTAB:
+			  c = 'v';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_ESC:
+			/* take E not e because \e is \ in *roff */
+			  c = 'E';
+			rv = 2;
+			/* FALLTHROUGH */
+		case '\\':
+			shf_putc('\\', shf);
 
-		/* use $'...' quote format */
-		shf_putc('$', shf);
-		shf_putc('\'', shf);
-		while ((c = *p) != 0) {
-#ifndef MKSH_EBCDIC
-			if (c >= 0xC2) {
-				n = utf_mbtowc(&wc, (const char *)p);
-				if (n != (size_t)-1) {
-					p += n;
-					shf_fprintf(shf, "\\u%04X", wc);
-					continue;
-				}
-			}
-#endif
-			++p;
-			switch (c) {
-			/* see unbksl() in this file for comments */
-			case KSH_BEL:
-				c = 'a';
-				if (0)
-					/* FALLTHROUGH */
-			case '\b':
-				  c = 'b';
-				if (0)
-					/* FALLTHROUGH */
-			case '\f':
-				  c = 'f';
-				if (0)
-					/* FALLTHROUGH */
-			case '\n':
-				  c = 'n';
-				if (0)
-					/* FALLTHROUGH */
-			case '\r':
-				  c = 'r';
-				if (0)
-					/* FALLTHROUGH */
-			case '\t':
-				  c = 't';
-				if (0)
-					/* FALLTHROUGH */
-			case KSH_VTAB:
-				  c = 'v';
-				if (0)
-					/* FALLTHROUGH */
-			case KSH_ESC:
-				/* take E not e because \e is \ in *roff */
-				  c = 'E';
+			if (0)
 				/* FALLTHROUGH */
-			case '\\':
-				shf_putc('\\', shf);
+		default:
+			  if (dollarq_isctrlU(c)) {
+				rv = 2;
+				/* FALLTHROUGH */
+		case '\'':
+				shf_fprintf(shf, "\\%03o", c);
+				break;
+			}
 
-				if (0)
-					/* FALLTHROUGH */
-			default:
-#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
-				  if (ksh_isctrl(c))
-#else
-				  if (!ctype(c, C_PRINT))
-#endif
-				    {
-					/* FALLTHROUGH */
-			case '\'':
-					shf_fprintf(shf, "\\%03o", c);
-					break;
-				}
+			shf_putc(c, shf);
+			break;
+		}
+	}
+	shf_putc('\'', shf);
+	return (rv);
+}
 
-				shf_putc(c, shf);
+#ifndef MKSH_SMALL
+/* escape with $'...' outside UTFMODE */
+static void
+dollarq8(struct shf *shf, const unsigned char *s)
+{
+	unsigned char c;
+
+	shf_putc('$', shf);
+	shf_putc('\'', shf);
+	while ((c = *s++) != 0) {
+		/* single octet */
+		switch (c) {
+		/* see unbksl() in this file for comments */
+		case KSH_BEL:
+			c = 'a';
+			if (0)
+				/* FALLTHROUGH */
+		case '\b':
+			  c = 'b';
+			if (0)
+				/* FALLTHROUGH */
+		case '\f':
+			  c = 'f';
+			if (0)
+				/* FALLTHROUGH */
+		case '\n':
+			  c = 'n';
+			if (0)
+				/* FALLTHROUGH */
+		case '\r':
+			  c = 'r';
+			if (0)
+				/* FALLTHROUGH */
+		case '\t':
+			  c = 't';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_VTAB:
+			  c = 'v';
+			if (0)
+				/* FALLTHROUGH */
+		case KSH_ESC:
+			/* take E not e because \e is \ in *roff */
+			  c = 'E';
+			/* FALLTHROUGH */
+		case '\\':
+			shf_putc('\\', shf);
+
+			if (0)
+				/* FALLTHROUGH */
+		default:
+			  if (ksh_isctrl8(c)) {
+				/* FALLTHROUGH */
+		case '\'':
+				shf_fprintf(shf, "\\%03o", c);
 				break;
 			}
+
+			shf_putc(c, shf);
+			break;
 		}
-		inquote = true;
 	}
-	if (inquote)
-		shf_putc('\'', shf);
+	shf_putc('\'', shf);
 }
+#endif
 
 /*
  * Print things in columns and rows - func() is called to format
@@ -1535,7 +1762,8 @@ print_columns(struct columnise_opts *opt
 
 	if (max_colz > 2147483646) {
 #ifndef MKSH_SMALL
-		internal_warningf("print_columns called with %s=%zu >= INT_MAX",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "print_columns called with %s=%zu >= INT_MAX",
 		    "max_col", max_colz);
 #endif
 		return;
@@ -1544,7 +1772,8 @@ print_columns(struct columnise_opts *opt
 
 	if (max_oct > 2147483646) {
 #ifndef MKSH_SMALL
-		internal_warningf("print_columns called with %s=%zu >= INT_MAX",
+		kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
+		    "print_columns called with %s=%zu >= INT_MAX",
 		    "max_oct", max_oct);
 #endif
 		return;
@@ -1584,7 +1813,7 @@ print_columns(struct columnise_opts *opt
 	max_col = -max_col;
 	goto prcols_hard;
 	while (r < rows) {
-		shf_putchar(opts->linesep, opts->shf);
+		shf_putc(opts->linesep, opts->shf);
  prcols_hard:
 		for (c = 0; c < cols; c++) {
 			if ((i = c * rows + r) >= n)
@@ -1600,7 +1829,7 @@ print_columns(struct columnise_opts *opt
 	}
  out:
 	if (opts->do_last)
-		shf_putchar(opts->linesep, opts->shf);
+		shf_putc(opts->linesep, opts->shf);
 	afree(str, ATEMP);
 }
 
@@ -1610,6 +1839,7 @@ strip_nuls(char *buf, size_t len)
 {
 	char *cp, *dp, *ep;
 
+	rndpush(buf, len);
 	if (!len || !(dp = memchr(buf, '\0', len)))
 		return;
 
@@ -1635,12 +1865,12 @@ ssize_t
 blocking_read(int fd, char *buf, size_t nbytes)
 {
 	ssize_t ret;
-	bool tried_reset = false;
+	Wahr tried_reset = Nee;
 
 	while ((ret = read(fd, buf, nbytes)) < 0) {
 		if (!tried_reset && errno == EAGAIN) {
 			if (reset_nonblock(fd) > 0) {
-				tried_reset = true;
+				tried_reset = Ja;
 				continue;
 			}
 			errno = EAGAIN;
@@ -1670,30 +1900,6 @@ reset_nonblock(int fd)
 	return (1);
 }
 
-/* getcwd(3) equivalent, allocates from ATEMP but doesn't resize */
-char *
-ksh_get_wd(void)
-{
-#ifdef MKSH__NO_PATH_MAX
-	char *rv, *cp;
-
-	if ((cp = get_current_dir_name())) {
-		strdupx(rv, cp, ATEMP);
-		free_gnu_gcdn(cp);
-	} else
-		rv = NULL;
-#else
-	char *rv;
-
-	if (!getcwd((rv = alloc(PATH_MAX + 1, ATEMP)), PATH_MAX)) {
-		afree(rv, ATEMP);
-		rv = NULL;
-	}
-#endif
-
-	return (rv);
-}
-
 #ifndef ELOOP
 #define ELOOP		E2BIG
 #endif
@@ -1703,17 +1909,9 @@ do_realpath(const char *upath)
 {
 	char *xp, *ip, *tp, *ipath, *ldest = NULL;
 	XString xs;
-	size_t pos, len;
-	int llen;
+	size_t pos, len, ldestlen = 1U;
+	ssize_t llen;
 	struct stat sb;
-#ifdef MKSH__NO_PATH_MAX
-	size_t ldestlen = 0;
-#define pathlen sb.st_size
-#define pathcnd (ldestlen < (pathlen + 1))
-#else
-#define pathlen PATH_MAX
-#define pathcnd (!ldest)
-#endif
 	/* max. recursion depth */
 	int symlinks = 32;
 
@@ -1729,11 +1927,12 @@ do_realpath(const char *upath)
 		strpathx(ipath, ldest, upath + 2, 0);
 #endif
 	} else {
+		const char *tcp;
+
 		/* upath is a relative pathname, prepend cwd */
-		if ((tp = ksh_get_wd()) == NULL || !mksh_abspath(tp))
+		if ((tcp = ksh_getwd()) == NULL)
 			return (NULL);
-		strpathx(ipath, tp, upath, 1);
-		afree(tp, ATEMP);
+		strpathx(ipath, tcp, upath, 1);
 	}
 
 	/* ipath and upath are in memory at the same time -> unchecked */
@@ -1810,21 +2009,24 @@ do_realpath(const char *upath)
 				goto notfound;
 			}
 
-			/* get symlink(7) target */
-			if (pathcnd) {
-#ifdef MKSH__NO_PATH_MAX
-				if (notoktoadd(pathlen, 1)) {
+			/* need to resize link target buffer? */
+			if ((mbiHUGE_U)sb.st_size > (mbiHUGE_U)(ldestlen - 1U)) {
+				/* like notoktoadd() */
+				if ((mbiHUGE_U)sb.st_size >= (mbiHUGE_U)mbiSIZE_MAX) {
 					errno = ENAMETOOLONG;
 					goto notfound;
 				}
-#endif
-				ldest = aresize(ldest, pathlen + 1, ATEMP);
+				ldestlen = (size_t)sb.st_size + 1U;
+				/* assert(ldestlen <= mbiSIZE_MAX) */
+				ldest = aresize(ldest, ldestlen, ATEMP);
 			}
-			llen = readlink(Xstring(xs, xp), ldest, pathlen);
-			if (llen < 0)
+			/* get symlink(7) target */
+			errno = ENAMETOOLONG; /* for overflow case */
+			llen = readlink(Xstring(xs, xp), ldest, ldestlen);
+			if (llen == -1 || (size_t)llen >= ldestlen)
 				/* oops... */
 				goto notfound;
-			ldest[llen] = '\0';
+			ldest[(size_t)llen] = '\0';
 
 			/*
 			 * restart if symlink target is an absolute path,
@@ -1910,15 +2112,12 @@ do_realpath(const char *upath)
 
  notfound:
 	/* save; freeing memory might trash it */
-	llen = errno;
+	symlinks = errno;
 	afree(ldest, ATEMP);
 	afree(ipath, ATEMP);
 	Xfree(xs, xp);
-	errno = llen;
+	errno = symlinks;
 	return (NULL);
-
-#undef pathlen
-#undef pathcnd
 }
 
 /**
@@ -1944,17 +2143,21 @@ make_path(const char *cwd, const char *f
     int *phys_pathp)
 {
 	int rval = 0;
-	bool use_cdpath = true;
+	Wahr use_cdpath = Ja;
 	char *plist;
 	size_t len, plen = 0;
 	char *xp = Xstring(*xsp, xp);
 
-	if (!file)
+	if (!file) {
 		file = null;
+#ifdef DEBUG
+		assert(file[0] == '\0'); /* for Coverity */
+#endif
+	}
 
 	if (mksh_abspath(file)) {
 		*phys_pathp = 0;
-		use_cdpath = false;
+		use_cdpath = Nee;
 	} else {
 		if (file[0] == '.') {
 			char c = file[1];
@@ -1962,12 +2165,12 @@ make_path(const char *cwd, const char *f
 			if (c == '.')
 				c = file[2];
 			if (mksh_cdirsep(c) || c == '\0')
-				use_cdpath = false;
+				use_cdpath = Nee;
 		}
 
 		plist = *cdpathp;
 		if (!plist)
-			use_cdpath = false;
+			use_cdpath = Nee;
 		else if (use_cdpath) {
 			char *pend = plist;
 
@@ -2037,17 +2240,17 @@ simplify_path(char *p)
 {
 	char *dp, *ip, *sp, *tp;
 	size_t len;
-	bool needslash;
+	Wahr needslash;
 #ifdef MKSH_DOSPATH
-	bool needdot = true;
+	Wahr needdot = Ja;
 
 	/* keep drive letter */
 	if (mksh_drvltr(p)) {
 		p += 2;
-		needdot = false;
+		needdot = Nee;
 	}
 #else
-#define needdot true
+#define needdot Ja
 #endif
 
 	switch (*p) {
@@ -2066,10 +2269,10 @@ simplify_path(char *p)
 			++p;
 #endif
 		}
-		needslash = true;
+		needslash = Ja;
 		break;
 	default:
-		needslash = false;
+		needslash = Nee;
 	}
 	dp = ip = sp = p;
 
@@ -2098,7 +2301,7 @@ simplify_path(char *p)
 					goto strip_last_component;
 				else if (dp > sp) {
 					/* relative path, with subpaths */
-					needslash = false;
+					needslash = Nee;
  strip_last_component:
 					/* strip off last pathname component */
 					while (dp > sp)
@@ -2112,7 +2315,7 @@ simplify_path(char *p)
 					/* keep dotdot-slash if not absolute */
 					*dp++ = '.';
 					*dp++ = '.';
-					needslash = true;
+					needslash = Ja;
 					sp = dp;
 				}
 				/* then continue with the next one */
@@ -2128,7 +2331,7 @@ simplify_path(char *p)
 		dp += len;
 
 		/* append slash if we continue */
-		needslash = true;
+		needslash = Ja;
 		/* try next component */
 	}
 	if (dp == p) {
@@ -2145,28 +2348,25 @@ simplify_path(char *p)
 void
 set_current_wd(const char *nwd)
 {
-	char *allocd = NULL;
-
 	if (nwd == NULL) {
-		allocd = ksh_get_wd();
-		nwd = allocd ? allocd : null;
+		nwd = ksh_getwd();
+		if (nwd == NULL)
+			nwd = null;
 	}
 
 	afree(current_wd, APERM);
 	strdupx(current_wd, nwd, APERM);
-
-	afree(allocd, ATEMP);
 }
 
 int
 c_cd(const char **wp)
 {
 	int optc, rv, phys_path;
-	bool physical = tobool(Flag(FPHYSICAL));
+	Wahr physical = isWahr(Flag(FPHYSICAL));
 	/* was a node from cdpath added in? */
 	int cdnode;
 	/* show where we went?, error for $PWD */
-	bool printpath = false, eflag = false;
+	Wahr printpath = Nee, eflag = Nee;
 	struct tbl *pwd_s, *oldpwd_s;
 	XString xs;
 	char *dir, *allocd = NULL, *tryp, *pwd, *cdpath;
@@ -2174,13 +2374,13 @@ c_cd(const char **wp)
 	while ((optc = ksh_getopt(wp, &builtin_opt, "eLP")) != -1)
 		switch (optc) {
 		case 'e':
-			eflag = true;
+			eflag = Ja;
 			break;
 		case 'L':
-			physical = false;
+			physical = Nee;
 			break;
 		case 'P':
-			physical = true;
+			physical = Ja;
 			break;
 		case '?':
 			return (2);
@@ -2209,7 +2409,7 @@ c_cd(const char **wp)
 				bi_errorf(Tno_OLDPWD);
 				return (2);
 			}
-			printpath = true;
+			printpath = Ja;
 		} else {
 			strdupx(allocd, wp[0], ATEMP);
 			dir = allocd;
@@ -2228,25 +2428,23 @@ c_cd(const char **wp)
 		 * substitution fails because the cd fails we could try to
 		 * find another substitution. For now, we don't.
 		 */
-		if ((cp = strstr(current_wd, wp[0])) == NULL) {
+		if ((cp = ucstrstr(current_wd, wp[0])) == NULL) {
 			bi_errorf(Tbadsubst);
 			return (2);
 		}
 		/*-
 		 * ilen = part of current_wd before wp[0]
 		 * elen = part of current_wd after wp[0]
-		 * because current_wd and wp[1] need to be in memory at the
-		 * same time beforehand the addition can stay unchecked
 		 */
 		ilen = cp - current_wd;
 		olen = strlen(wp[0]);
 		nlen = strlen(wp[1]);
 		elen = strlen(current_wd + ilen + olen) + 1;
-		dir = allocd = alloc(ilen + nlen + elen, ATEMP);
+		dir = allocd = alloc1(ilen + elen, nlen, ATEMP);
 		memcpy(dir, current_wd, ilen);
 		memcpy(dir + ilen, wp[1], nlen);
 		memcpy(dir + ilen + nlen, current_wd + ilen + olen, elen);
-		printpath = true;
+		printpath = Ja;
 	} else {
 		bi_errorf(Ttoo_many_args);
 		return (2);
@@ -2263,12 +2461,8 @@ c_cd(const char **wp)
 	}
 #endif
 
-#ifdef MKSH__NO_PATH_MAX
 	/* only a first guess; make_path will enlarge xs if necessary */
-	XinitN(xs, 1024, ATEMP);
-#else
-	XinitN(xs, PATH_MAX, ATEMP);
-#endif
+	XinitN(xs, 384U, ATEMP);
 
 	cdpath = str_val(global("CDPATH"));
 	do {
@@ -2298,14 +2492,14 @@ c_cd(const char **wp)
 	allocd = NULL;
 
 	/* Clear out tracked aliases with relative paths */
-	flushcom(false);
+	flushcom(Nee);
 
 	/*
 	 * Set OLDPWD (note: unsetting OLDPWD does not disable this
 	 * setting in AT&T ksh)
 	 */
 	if (current_wd[0])
-		/* Ignore failure (happens if readonly or integer) */
+		/* Ignore failure (happens if read-only or integer) */
 		setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);
 
 	if (!mksh_abspath(Xstring(xs, xp))) {
@@ -2324,7 +2518,7 @@ c_cd(const char **wp)
 		char *ptmp = pwd;
 
 		set_current_wd(ptmp);
-		/* Ignore failure (happens if readonly or integer) */
+		/* Ignore failure (happens if read-only or integer) */
 		setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
 	} else {
 		set_current_wd(null);
@@ -2341,116 +2535,176 @@ c_cd(const char **wp)
 	return (rv);
 }
 
-
-#ifdef KSH_CHVT_CODE
 extern void chvt_reinit(void);
 
 static void
 chvt(const Getopt *go)
 {
+	char buf[99], ch;
 	const char *dv = go->optarg;
-	char *cp = NULL;
-	int fd;
+	int fd, pfd[2];
+	pid_t cpid;
+	Wahr isdaemon = Nee, dowait = Nee;
+#ifndef MKSH_DISABLE_REVOKE_WARNING
+	int revwarn = 0;
+#if !HAVE_REVOKE
+#define ifrevwarn
+#else
+#define ifrevwarn if (revwarn)
+#endif
+#endif
 
-	switch (*dv) {
-	case '-':
+	switch (ord(*dv)) {
+	case ORD('-'):
+		isdaemon = Ja;
 		dv = "/dev/null";
 		break;
-	case '!':
+	case ORD('!'):
+		dowait = Ja;
 		++dv;
 		/* FALLTHROUGH */
 	default: {
 		struct stat sb;
 
 		if (stat(dv, &sb)) {
-			cp = shf_smprintf("/dev/ttyC%s", dv);
-			dv = cp;
-			if (stat(dv, &sb)) {
-				memmove(cp + 1, cp, /* /dev/tty */ 8);
-				dv = cp + 1;
-				if (stat(dv, &sb)) {
-					errorf(Tf_sD_sD_s, "chvt",
-					    "can't find tty", go->optarg);
-				}
-			}
-		}
-		if (!(sb.st_mode & S_IFCHR))
-			errorf(Tf_sD_sD_s, "chvt", "not a char device", dv);
+			int E = errno;
+
+			memcpy(buf, "/dev/ttyC", 9U);
+			strlcpy(buf + 9U, dv, sizeof(buf) - 9U);
+			if (stat(buf, &sb)) {
+				strlcpy(buf + 8U, dv, sizeof(buf) - 8U);
+				if (stat(buf, &sb))
+					kerrf(KWF_VERRNO | KWF_ERR(1) |
+					    KWF_PREFIX | KWF_TWOMSG, E,
+					    "chvt", dv);
+			}
+			dv = buf;
+		}
+		if (!S_ISCHR(sb.st_mode))
+			kerrf(KWF_VERRNO | KWF_ERR(1) | KWF_PREFIX |
+			    KWF_TWOMSG, (int)(ENOTTY), "chvt", dv);
 #ifndef MKSH_DISABLE_REVOKE_WARNING
-#if HAVE_REVOKE
-		if (revoke(dv))
+#if !HAVE_REVOKE
+#ifdef ENOSYS
+		revwarn = ENOSYS;
+#else
+		revwarn = EINVAL;
 #endif
-			warningf(false, Tf_sD_s_s, "chvt",
-			    "new shell is potentially insecure, can't revoke",
-			    dv);
+#else
+		revwarn = revoke(dv) ? errno : 0;
+#endif
+		ifrevwarn kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+		    revwarn, "chvt", dv,
+		    "can't revoke; new shell is potentially insecure");
 #endif
 	    }
 	}
-	if ((fd = binopen2(dv, O_RDWR)) < 0) {
-		sleep(1);
-		if ((fd = binopen2(dv, O_RDWR)) < 0) {
-			errorf(Tf_sD_s_s, "chvt", Tcant_open, dv);
-		}
-	}
-	if (go->optarg[0] != '!') {
-		switch (fork()) {
-		case -1:
-			errorf(Tf_sD_s_s, "chvt", "fork", "failed");
-		case 0:
-			break;
-		default:
-			exit(0);
+	if (pipe(pfd))
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "pipe");
+	switch ((cpid = fork())) {
+	case -1:
+		close(pfd[0]);
+		close(pfd[1]);
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "fork");
+	case 0:
+		close(pfd[0]);
+		break;
+	default:
+		close(pfd[1]);
+		if (read(pfd[0], &ch, 1) != 1 || !isch(ch, '.'))
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_THREEMSG |
+			    KWF_NOERRNO, "chvt", dv,
+			    "child process initialisation failure");
+		close(pfd[0]);
+		if (dowait) {
+			pid_t corpse;
+			int status;
+
+			while (/* CONSTCOND */ 1) {
+#ifndef MKSH_NOPROSPECTOFWORK
+				corpse = waitpid(cpid, &status, 0);
+#else
+				corpse = wait(&status);
+#endif
+				if (corpse == -1) {
+					status = errno;
+					if (status == ECHILD)
+						break;
+					if (status == EINTR)
+						continue;
+					kerrf(KWF_ERR(1) | KWF_PREFIX |
+					    KWF_TWOMSG, "chvt", "wait");
+				}
+#ifdef MKSH_NOPROSPECTOFWORK
+				/* should not happen but… */
+				if (corpse != cpid)
+					continue;
+#endif
+				if (WIFSIGNALED(status)) {
+					status = WTERMSIG(status);
+					if (status > 0 && status < ksh_NSIG)
+						dv = ksh_sigmess(status);
+					else
+						dv = NULL;
+					if (ksh_sigmessf(dv))
+						dv = "Signalled";
+					kwarnf(KWF_PREFIX | KWF_TWOMSG |
+					    KWF_NOERRNO, "chvt", dv);
+				} else if (WIFEXITED(status)) {
+					status = (WEXITSTATUS(status)) & 255;
+					if (!status)
+						break;
+					kwarnf0(KWF_PREFIX | KWF_NOERRNO,
+					    TchvtDone, status);
+				} else
+					continue;
+			}
 		}
+		exit(0);
 	}
 	if (setsid() == -1)
-		errorf(Tf_sD_s_s, "chvt", "setsid", "failed");
-	if (go->optarg[0] != '-') {
+		kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG, "chvt", "setsid");
+	if ((fd = binopen2(dv, O_RDWR)) < 0) {
+		sleep(1);
+		if ((fd = binopen2(dv, O_RDWR)) < 0)
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_THREEMSG,
+			    "chvt", dv, Topen);
+	}
+	if (!isdaemon) {
+#ifdef TIOCSCTTY
 		if (ioctl(fd, TIOCSCTTY, NULL) == -1)
-			errorf(Tf_sD_s_s, "chvt", "TIOCSCTTY", "failed");
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TIOCSCTTY");
+#endif
+#if HAVE_TERMIOS_H
 		if (tcflush(fd, TCIOFLUSH))
-			errorf(Tf_sD_s_s, "chvt", "TCIOFLUSH", "failed");
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TCIOFLUSH");
+#else
+		if (ioctl(fd, TCFLSH, 2) == -1)
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_TWOMSG,
+			    "chvt", "TCFLSH");
+#endif
 	}
-	ksh_dup2(fd, 0, false);
-	ksh_dup2(fd, 1, false);
-	ksh_dup2(fd, 2, false);
+	ksh_dup2(fd, 0, Nee);
+	ksh_dup2(fd, 1, Nee);
+	ksh_dup2(fd, 2, Nee);
+#ifndef MKSH_DISABLE_REVOKE_WARNING
+	if (!isdaemon) {
+		ifrevwarn kwarnf(KWF_VERRNO | KWF_PREFIX | KWF_THREEMSG,
+		    revwarn, "chvt", dv,
+		    "can't revoke; new shell is potentially insecure");
+	}
+#endif
 	if (fd > 2)
 		close(fd);
-	rndset((unsigned long)chvt_rndsetup(go, sizeof(Getopt)));
+	chvt_rndsetup(go, sizeof(Getopt));
 	chvt_reinit();
+	/* signal parent the all OK */
+	if (write(pfd[1], Tdot, 1) != 1)
+		kwarnf(KWF_PREFIX | KWF_TWOMSG, "chvt", "write");
+	close(pfd[1]);
 }
-#endif
-
-#ifdef DEBUG
-char *
-strchr(char *p, int ch)
-{
-	for (;; ++p) {
-		if (*p == ch)
-			return (p);
-		if (!*p)
-			return (NULL);
-	}
-	/* NOTREACHED */
-}
-
-char *
-strstr(char *b, const char *l)
-{
-	char first, c;
-	size_t n;
-
-	if ((first = *l++) == '\0')
-		return (b);
-	n = strlen(l);
- strstr_look:
-	while ((c = *b++) != first)
-		if (c == '\0')
-			return (NULL);
-	if (strncmp(b, l, n))
-		goto strstr_look;
-	return (b - 1);
-}
-#endif
 
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 char *
@@ -2480,10 +2734,13 @@ strdup_i(const char *src, Area *ap)
 } while (/* CONSTCOND */ 0)
 
 int
-getrusage(int what, struct rusage *ru)
+ksh_getrusage(int what, struct rusage *ru)
 {
 	struct tms tms;
 	clock_t u, s;
+#ifndef CLK_TCK
+	long CLK_TCK;
+#endif
 
 	if (/* ru == NULL || */ times(&tms) == (clock_t)-1)
 		return (-1);
@@ -2501,6 +2758,16 @@ getrusage(int what, struct rusage *ru)
 		errno = EINVAL;
 		return (-1);
 	}
+#ifndef CLK_TCK
+#ifdef ENOSYS
+	errno = ENOSYS;
+#else
+	errno = EINVAL;
+#endif
+	if ((CLK_TCK = sysconf(_SC_CLK_TCK)) == -1L)
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG,
+		    "sysconf(_SC_CLK_TCK)");
+#endif
 	INVTCK(ru->ru_utime, u);
 	INVTCK(ru->ru_stime, s);
 	return (0);
@@ -2516,7 +2783,7 @@ getrusage(int what, struct rusage *ru)
  * escape sequence was found
  */
 int
-unbksl(bool cstyle, int (*fg)(void), void (*fp)(int))
+unbksl(Wahr cstyle, int (*fg)(void), void (*fp)(int))
 {
 	int wc, i, c, fc, n;
 
@@ -2532,7 +2799,7 @@ unbksl(bool cstyle, int (*fg)(void), voi
 		if (!cstyle)
 			goto unknown_escape;
 		c = (*fg)();
-		wc = ksh_toctrl(c);
+		wc = asc2rtt(ord(c) == ORD('?') ? 0x7F : rtt2asc(c) & 0x9F);
 		break;
 	case 'E':
 	case 'e':
@@ -2637,3 +2904,61 @@ unbksl(bool cstyle, int (*fg)(void), voi
 
 	return (wc);
 }
+
+#ifdef DEBUG
+#undef strchr
+/* pre-initio() */
+char *
+ucstrchr(char *s, int c)
+{
+	return (strchr(s, c));
+}
+
+const char *
+cstrchr(const char *s, int c)
+{
+	return (strchr(s, c));
+}
+#endif
+
+#if !HAVE_STRSTR
+char *
+ucstrstr(char *big, const char *little)
+{
+	union mksh_cchack res;
+
+	res.ro = cstrstr(big, little);
+	return (res.rw);
+}
+
+const char *
+cstrstr(const char *big, const char *little)
+{
+	char first, c;
+	size_t n;
+
+	if ((first = *little++) == '\0')
+		return (big);
+	n = strlen(little);
+ strstr_look:
+	while ((c = *big++) != first)
+		if (c == '\0')
+			return (NULL);
+	if (strncmp(big, little, n))
+		goto strstr_look;
+	return (big - 1);
+}
+#elif defined(DEBUG)
+#undef strstr
+char *
+ucstrstr(char *big, const char *little)
+{
+	return (strstr(big, little));
+}
+
+const char *
+cstrstr(const char *big, const char *little)
+{
+	return (strstr(big, little));
+}
+#endif
--- mksh-59c.orig/mksh.1
+++ mksh-59c/mksh.1
@@ -1,9 +1,9 @@
-.\" $MirOS: src/bin/mksh/mksh.1,v 1.494 2020/10/01 22:39:57 tg Exp $
+.\" $MirOS: src/bin/mksh/mksh.1,v 1.543+locale-tracking 2024/02/02 02:33:07 tg Exp $
 .\" $OpenBSD: ksh.1,v 1.160 2015/07/04 13:27:04 feinerer Exp $
 .\"-
 .\" Copyright © 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
 .\"		2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
-.\"		2018, 2019, 2020
+.\"		2018, 2019, 2020, 2021, 2022, 2023, 2024
 .\"	mirabilos <m@mirbsd.org>
 .\"
 .\" Provided that these terms and disclaimer and all copyright notices
@@ -21,7 +21,12 @@
 .\" damage or existence of a defect, except proven that it results out
 .\" of said person’s immediate fault when using the work as intended.
 .\"-
-.\" Try to make GNU groff and AT&T nroff more compatible
+.\" $miros: contrib/samples/portmdoc,v 1.23 2024/01/04 22:52:50 tg Exp $
+.\"-
+.\" Copyright © 2008, 2009, 2010, 2016, 2018, 2020, 2023
+.\"	mirabilos <m@mirbsd.org>
+.\"
+.\" Glue GNU groff (BSD and GNU mdoc both) to AT&T nroff (UCB mdoc).
 .\" * ` generates ‘ in gnroff, so use \`
 .\" * ' generates ’ in gnroff, \' generates ´, so use \*(aq
 .\" * - generates ‐ in gnroff, \- generates −, so .tr it to -
@@ -34,18 +39,36 @@
 .\" Also make sure to use \& *before* a punctuation char that is to not
 .\" be interpreted as punctuation, and especially with two-letter words
 .\" but also (after) a period that does not end a sentence (“e.g.\&”).
-.\" The section after the "doc" macropackage has been loaded contains
-.\" additional code to convene between the UCB mdoc macropackage (and
-.\" its variant as BSD mdoc in groff) and the GNU mdoc macropackage.
+.\"-
+.\"
+.\" Implement .Dd with the Mdocdate RCS keyword
+.\"
+.rn Dd xD
+.de Dd
+.ie \\$1$Mdocdate: \{\
+.	xD \\$2 \\$3, \\$4
+.\}
+.el .xD \\$1 \\$2 \\$3
+..
+.\"
+.\" .Dd must come before most everything, because when called
+.\" with -mandoc it loads -mdoc via .so in .Dd (first macro).
+.\"
+.Dd $Mdocdate: February 2 2024 $
+.\"
+.\" Check which macro package we use, and do other -mdoc setup.
 .\"
 .ie \n(.g \{\
+.	if n .ss \n[.ss] 0
 .	if \*[.T]ascii .tr \-\N'45'
 .	if \*[.T]latin1 .tr \-\N'45'
 .	if \*[.T]utf8 .tr \-\N'45'
-.	ds <= \[<=]
-.	ds >= \[>=]
-.	ds Rq \[rq]
-.	ds Lq \[lq]
+.	if \*[.T]utf8 .tr \(la\*(Lt
+.	if \*[.T]utf8 .tr \(ra\*(Gt
+.	ds <= \(<=
+.	ds >= \(>=
+.	ds Rq \(rq
+.	ds Lq \(lq
 .	ds sL \(aq
 .	ds sR \(aq
 .	if \*[.T]utf8 .ds sL `
@@ -56,56 +79,36 @@
 .	ds TI \(ti
 .	ds ha \(ha
 .	ds en \(en
+.	ie d volume-ds-1 .ds tT gnu
+.	el .ie d doc-volume-ds-1 .ds tT gnp
+.	el .ds tT bsd
 .\}
 .el \{\
 .	ds aq '
 .	ds TI ~
 .	ds ha ^
 .	ds en \(em
+.	ds tT ucb
 .\}
 .ie n \{\
-.	ds EM \ \*(en\ \&
+.	ds EM \ \(em\ \&
 .\}
 .el \{\
-.	ds EM \f(TR\^\(em\^\fP
+.	ds EM \f(TR\|\(em\|\fP
 .\}
 .\"
-.\" Implement .Dd with the Mdocdate RCS keyword
-.\"
-.rn Dd xD
-.de Dd
-.ie \\$1$Mdocdate: \{\
-.	xD \\$2 \\$3, \\$4
-.\}
-.el .xD \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8
-..
-.\"
-.\" .Dd must come before definition of .Mx, because when called
-.\" with -mandoc, it might implement .Mx itself, but we want to
-.\" use our own definition. And .Dd must come *first*, always.
-.\"
-.Dd $Mdocdate: October 1 2020 $
-.\"
-.\" Check which macro package we use, and do other -mdoc setup.
-.\"
-.ie \n(.g \{\
-.	if \*[.T]utf8 .tr \[la]\*(Lt
-.	if \*[.T]utf8 .tr \[ra]\*(Gt
-.	ie d volume-ds-1 .ds tT gnu
-.	el .ie d doc-volume-ds-1 .ds tT gnp
-.	el .ds tT bsd
-.\}
-.el .ds tT ucb
-.\"
+.\" Add UCB mdoc compatibility to GNU mdoc
 .\" Implement .Mx (MirBSD)
 .\"
 .ie "\*(tT"gnu" \{\
+.	ds sP \s0
+.	ds tN \*[Tn-font-size]
 .	eo
 .	de Mx
 .	nr curr-font \n[.f]
 .	nr curr-size \n[.ps]
 .	ds str-Mx \f[\n[curr-font]]\s[\n[curr-size]u]
-.	ds str-Mx1 \*[Tn-font-size]\%MirBSD\*[str-Mx]
+.	ds str-Mx1 \*(tN\%MirBSD\*[str-Mx]
 .	if !\n[arg-limit] \
 .	if \n[.$] \{\
 .	ds macro-name Mx
@@ -114,7 +117,7 @@
 .	if (\n[arg-limit] > \n[arg-ptr]) \{\
 .	nr arg-ptr +1
 .	ie (\n[type\n[arg-ptr]] == 2) \
-.	as str-Mx1 \~\*[arg\n[arg-ptr]]
+.	ds str-Mx1 \*(tN\%MirBSD\~#\*[arg\n[arg-ptr]]\*[str-Mx]
 .	el \
 .	nr arg-ptr -1
 .	\}
@@ -127,17 +130,31 @@
 .	parse-space-vector
 .	print-recursive
 ..
+.	de Aq
+.	if !\n[arg-limit] \
+.	ds macro-name Aq
+.	ie \n[in-authors-section] \{\
+.		ds quote-left \*(Lt
+.		ds quote-right \*(Gt
+.	\}
+.	el \{\
+.		ds quote-left \[la]
+.		ds quote-right \[ra]
+.	\}
+.	enclose-string \$@
+..
 .	ec
-.	ds sP \s0
-.	ds tN \*[Tn-font-size]
 .\}
 .el .ie "\*(tT"gnp" \{\
+.	ds sP \s0
+.	ie t .ds tN \s[(\n[.ps]u-1z)]
+.	el .ds tN
 .	eo
 .	de Mx
 .	nr doc-curr-font \n[.f]
 .	nr doc-curr-size \n[.ps]
 .	ds doc-str-Mx \f[\n[doc-curr-font]]\s[\n[doc-curr-size]u]
-.	ds doc-str-Mx1 \*[doc-Tn-font-size]\%MirBSD\*[doc-str-Mx]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\*[doc-str-Mx]
 .	if !\n[doc-arg-limit] \
 .	if \n[.$] \{\
 .	ds doc-macro-name Mx
@@ -146,7 +163,7 @@
 .	if (\n[doc-arg-limit] > \n[doc-arg-ptr]) \{\
 .	nr doc-arg-ptr +1
 .	ie (\n[doc-type\n[doc-arg-ptr]] == 2) \
-.	as doc-str-Mx1 \~\*[doc-arg\n[doc-arg-ptr]]
+.	ds doc-str-Mx1 \*(tN\%MirBSD\~#\*[doc-arg\n[doc-arg-ptr]]\*[doc-str-Mx]
 .	el \
 .	nr doc-arg-ptr -1
 .	\}
@@ -160,8 +177,6 @@
 .	doc-print-recursive
 ..
 .	ec
-.	ds sP \s0
-.	ds tN \*[doc-Tn-font-size]
 .\}
 .el \{\
 .	de Mx
@@ -169,13 +184,18 @@
 .	nr cZ \\n(.s
 .	ds aa \&\f\\n(cF\s\\n(cZ
 .	if \\n(aC==0 \{\
-.		ie \\n(.$==0 \&MirBSD\\*(aa
+.		ie \\n(.$==0 \&\\*(tNMirBSD\\*(aa
 .		el .aV \\$1 \\$2 \\$3 \\$4 \\$5 \\$6 \\$7 \\$8 \\$9
 .	\}
 .	if \\n(aC>\\n(aP \{\
 .		nr aP \\n(aP+1
 .		ie \\n(C\\n(aP==2 \{\
-.			as b1 \&MirBSD\ #\&\\*(A\\n(aP\\*(aa
+.			nr xX 0
+.			nr xX 1+\\*(A\\n(aP
+.			as b1 \&\\*(tNMirBSD\ \&
+.			if \\n(xX>0 .as b1 #\&
+.			as b1 \&\\*(A\\n(aP\\*(aa
+.			rr xX
 .			ie \\n(aC>\\n(aP \{\
 .				nr aP \\n(aP+1
 .				nR
@@ -183,12 +203,13 @@
 .			el .aZ
 .		\}
 .		el \{\
-.			as b1 \&MirBSD\\*(aa
+.			as b1 \&\\*(tNMirBSD\\*(aa
 .			nR
 .		\}
 .	\}
 ..
 .\}
+.\" </MirCVS://contrib/samples/portmdoc>
 .\"-
 .Dt MKSH 1
 .Os MirBSD
@@ -198,29 +219,39 @@
 .Nd MirBSD Korn shell
 .Sh SYNOPSIS
 .Nm
-.Bk -words
 .Op Fl +abCefhiklmnprUuvXx
-.Oo
-.Fl T Oo Ar \&! Oc Ns Ar tty
-\*(Ba
-.Ar \&\-
+.Op Fl +o Ar option
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
 .Oc
+.Op Ar file Op Ar arg1 ...
+.Nm
+.Op Fl +abCefhiklmnprUuvXx
 .Op Fl +o Ar option
-.Oo
-.Fl c Ar string \*(Ba
-.Fl s \*(Ba
-.Ar file
-.Op Ar argument ...
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
 .Oc
-.Ek
+.Fl c
+.Ar cmd
+.Op Ar arg0 ...
+.Nm
+.Op Fl +abCefhiklmnprUuvXx
+.Op Fl +o Ar option
+.Oo Fl T Oo Ar !\&
+.Oc Ns Ar tty Ns \*(Ba Ns Ar \-\&
+.Oc
+.Fl s
+.Op Ar arg1 ...
 .Nm builtin-name
 .Op Ar argument ...
 .Sh DESCRIPTION
 .Nm
 is a command interpreter intended for both interactive and shell
 script use.
-Its command language is a superset of the
+Its command language is a superset of both
 .Xr sh C
+and
+.Tn POSIX
 shell language and largely compatible to the original Korn shell.
 At times, this manual page may give scripting advice; while it
 sometimes does take portable shell scripting or various standards
@@ -231,15 +262,40 @@ in mind and should be taken as such.
 Please refer to:
 .Pa http://www.mirbsd.org/mksh\-faq.htm#sowhatismksh
 .Ss Invocation
-Most builtins can be called directly, for example if a link points from its
-name to the shell; not all make sense, have been tested or work at all though.
+Most builtins can be called directly, for example if a link or
+.Xr symlink 7
+points to
+.Nm ,
+or if
+.Va argv[0]
+is set correspondingly;
+this does not make sense for, or works properly with, all built-in utilities though.
 .Pp
 The options are as follows:
-.Bl -tag -width XcXstring
-.It Fl c Ar string
+.Bl -tag -width 2n
+.It Fl c
 .Nm
 will execute the command(s) contained in
-.Ar string .
+.Ar cmd ,
+setting
+.Li $0
+to
+.Ar arg0
+.Pq if present ,
+.Li $1
+to the next argument, etc.
+If compiled with
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT
+and in
+.Fl o Ic sh
+mode, a
+.Dq Li \-\-
+argument directly following
+.Ar cmd
+is ignored for compatibility with the legacy
+.Fx
+.Nm sh ;
+this is deprecated and may go away in the future.
 .It Fl i
 Interactive shell.
 A shell that reads commands from standard input is
@@ -270,36 +326,42 @@ option is on by default (see the
 command below).
 .It Fl l
 Login shell.
-If the name or basename the shell is called with (i.e. argv[0])
-starts with
+If the name the shell is called as
+.Pq i.e.\& Va argv[0]
+or its basename begins with a dash
+.Pq hyphen-minus
 .Ql \-
-or if this option is used,
-the shell is assumed to be a login shell; see
+or if this option is given,
+the shell is a
+.Dq login shell ;
+see
 .Sx Startup files
 below.
 .It Fl p
 Privileged shell.
 A shell is
 .Dq privileged
-if the real user ID or group ID does not match the
-effective user ID or group ID (see
+if the real user ID from
 .Xr getuid 2
-and
-.Xr getgid 2 ) .
+or group ID from
+.Xr getgid 2
+does not match the effective user ID or group ID.
 Clearing the privileged option causes the shell to set
-its effective user ID (group ID) to its initial real user ID (group ID).
+its effective user ID and group ID to its initial real user ID
+and group ID, respectively.
 For further implications, see
+.Ic set Fl p
+and
 .Sx Startup files .
-If the shell is privileged and this flag is not explicitly set, the
+If the shell is privileged and this flag is not set explicitly on invocation,
+nor during processing the startup files, the
 .Dq privileged
-option is cleared automatically after processing the startup files.
+flag is cleared automatically afterwards.
 .It Fl r
 Restricted shell.
 A shell is
 .Dq restricted
-if the basename the shell is called with, after
-.Ql \-
-processing, starts with
+if the basename the shell is called with, after dash removal, begins with
 .Ql r
 or if this option is used.
 The following restrictions come into effect after the shell processes any
@@ -309,36 +371,43 @@ files:
 .Pp
 .Bl -bullet -compact
 .It
+Command names cannot be specified with pathnames, either absolute or relative;
+the
+.Fl p
+flag of the
+.Ic command
+built-in utility is not usable.
 The
-.Ic cd
-.Po and Ic chdir Pc
-command is disabled.
-.It
-The
-.Ev SHELL ,
-.Ev ENV
-and
+.Ev ENV ,
 .Ev PATH
+and
+.Ev SHELL
 parameters cannot be changed.
 .It
-Command names can't be specified with absolute or relative paths.
-.It
-The
-.Fl p
-option of the built-in command
-.Ic command
-can't be used.
+The current location is fixed: the
+.Ic cd
+builtin is disabled.
 .It
-Redirections that create files can't be used (i.e.\&
+Redirections that create files, i.e.\&
 .Dq Li \*(Gt ,
 .Dq Li \*(Gt\*(Ba ,
-.Dq Li \*(Gt\*(Gt ,
-.Dq Li \*(Lt\*(Gt ) .
+.Dq Li \*(Gt\*(Gt
+and
+.Dq Li \*(Lt\*(Gt ,
+cannot be used, and the
+.Ev HISTFILE
+parameter cannot be changed.
 .El
 .It Fl s
-The shell reads commands from standard input; all non-option arguments
-are positional parameters.
-.It Fl T Ar name
+.Nm
+will read and execute commands from standard input; all non-option arguments
+are assigned to the positional parameters.
+.It Fl T Ar \-
+Detach from the controlling terminal, return immediately
+.Pq daemonise .
+.It Xo
+.Fl T Oo Ar !\& Oc Ns Ar name
+.Xc
 Spawn
 .Nm
 on the
@@ -346,52 +415,53 @@ on the
 device given.
 The paths
 .Ar name ,
-.Pa /dev/ttyC Ns Ar name
+.Li /dev/ttyC Ns Ar name
 and
-.Pa /dev/tty Ns Ar name
+.Li /dev/tty Ns Ar name
 are attempted in order.
-Unless
-.Ar name
-begins with an exclamation mark
-.Pq Ql \&! ,
-this is done in a subshell and returns immediately.
 If
 .Ar name
-is a dash
-.Pq Ql \&\- ,
-detach from controlling terminal (daemonise) instead.
+is prefixed with an exclamation mark
+.Pq Ql \&! ,
+wait for the spawned shell to return,
+report its exit status or terminating signal visually.
+Exit 0 if spawned.
 .El
 .Pp
-In addition to the above, the options described in the
-.Ic set
-built-in command can also be used on the command line:
-both
-.Op Fl +abCefhkmnuvXx
+In addition to the above, the flags
+.Op Fl +abCefhkmnUuvXx
 and
-.Op Fl +o Ar option
-can be used for single letter or long options, respectively.
+.Op Fl +o Ar option ,
+respectively for single-letter and long options,
+as described for the
+.Ic set
+built-in utility, can be used on the command line.
 .Pp
 If neither the
 .Fl c
 nor the
 .Fl s
-option is specified, the first non-option argument specifies the name
-of a file the shell reads commands from.
-If there are no non-option
-arguments, the shell reads commands from the standard input.
-The name of the shell (i.e. the contents of $0)
-is determined as follows: if the
-.Fl c
-option is used and there is a non-option argument, it is used as the name;
-if commands are being read from a file, the file is used as the name;
-otherwise, the name the shell was called with (i.e. argv[0]) is used.
-.Pp
-The exit status of the shell is 127 if the command file specified on the
-command line could not be opened, or non-zero if a fatal syntax error
-occurred during the execution of a script.
-In the absence of fatal errors,
-the exit status is that of the last command executed, or zero if no
-command is executed.
+options are specified,
+.Nm mksh
+will read and execute commands as if the
+.Fl s
+flag was passed iff the
+.Ar file
+argument is absent or
+.Dq Li \- ;
+otherwise, it sets $0 to
+.Ar file
+and reads commands from it.
+Further arguments
+.Ar arg1 ...
+are assigned to positional parameters.
+.Pp
+The exit status of the shell is 127 if the
+.Ar file
+specified on the command line could not be opened,
+or non-zero if a fatal error occurred during execution of the script.
+Otherwise, the errorlevel is that of the last command executed,
+0 if no command was executed.
 .Ss Startup files
 For the actual location of these files, see
 .Sx FILES .
@@ -900,6 +970,7 @@ The
 section describes the
 .Ic time
 reserved word.
+When not a reserved word, a builtin runs the passed command.
 .It Xo Ic until Ar list ;
 .Ic do Ar list ; Ic done
 .Xc
@@ -1227,27 +1298,31 @@ Parameter substitutions,
 which are described in detail in the next section, take the form
 .Pf $ Ns Ar name
 or
-.Pf ${ Ns Ar ... Ns } ;
-command substitutions take the form
+.Pf ${ Ns Ar name... Ns } ;
+arithmetic substitutions take the form
+.Pf $(( Ns Ar expression Ns )) ;
+and command substitutions take the form
 .Pf $( Ns Ar command Ns \&)
 or (deprecated)
 .Pf \` Ns Ar command Ns \`
 or (executed in the current environment)
 .Pf ${\ \& Ar command Ns \&;}
-and strip trailing newlines;
-and arithmetic substitutions take the form
-.Pf $(( Ns Ar expression Ns )) .
-Parsing the current-environment command substitution requires a space,
+and evaluate to the output of
+.Ar command
+with any trailing newlines stripped.
+The latter form requires a space,
 tab or newline after the opening brace and that the closing brace be
 recognised as a keyword (i.e. is preceded by a newline or semicolon).
-They are also called funsubs (function substitutions) and behave like
-functions in that
+They are also called funsubs (function substitutions) and behave
+similar to functions in that shell options are shared and
 .Ic local
 and
 .Ic return
-work, and in that
+work, though, in contrast to valsubs (see below),
 .Ic exit
-terminates the parent shell; shell options are shared.
+does not terminate the parent shell for compatibility with
+.At
+.Nm ksh93 .
 .Pp
 Another variant of substitution are the valsubs (value substitutions)
 .Pf ${\*(Ba\& Ns Ar command Ns \&;}
@@ -1256,7 +1331,8 @@ share their I/O with the parent; instead
 the, initially empty, expression-local variable
 .Ev REPLY
 is set to within the
-.Ar command Ns s .
+.Ar command Ns s ; Ic exit
+affects the parent like in a function call.
 .Pp
 If a substitution appears outside of double quotes, the results of the
 substitution are generally subject to word or field splitting according to
@@ -1316,7 +1392,7 @@ not
 .Dq Li D
 and
 .Dq Li E .
-This behavior is POSIX compliant, but incompatible with some other shell
+This behaviour is POSIX compliant but incompatible with some other shell
 implementations which do field splitting on the word which contained the
 substitution or use
 .Dv IFS
@@ -1325,15 +1401,17 @@ as a general whitespace delimiter.
 The results of substitution are, unless otherwise specified, also subject to
 brace expansion and file name expansion (see the relevant sections below).
 .Pp
-A command substitution is replaced by the output generated by the specified
-command which is run in a subshell.
+A command substitution of the regular (comsub), deprecated, funsub or valsub
+form is replaced by the output generated by the specified
+.Ar command
+which is run in a subshell except for the funsub and valsub types which run
+in the current execution environment.
 For
-.Pf $( Ns Ar command Ns \&)
+.Pf $( Ns Ar command Ns \&) ,
+.Pf ${\ \& Ar command Ns \&;}
 and
 .Pf ${\*(Ba\& Ns Ar command Ns \&;}
-and
-.Pf ${\ \& Ar command Ns \&;}
-substitutions, normal quoting rules are used when
+forms, normal quoting rules are used when
 .Ar command
 is parsed; however, for the deprecated
 .Pf \` Ns Ar command Ns \`
@@ -1347,16 +1425,18 @@ or
 is stripped (as is
 .Ql \&"
 when the substitution is part of a double-quoted string); a backslash
-.Ql \e
 followed by any other character is unchanged.
 As a special case in command substitutions, a command of the form
 .Pf \*(Lt Ar file
 is interpreted to mean substitute the contents of
-.Ar file .
-Note that
+.Ar file
+so that
 .Ic $(\*(Ltfoo)
-has the same effect as
-.Ic $(cat foo) .
+has the same effect, if
+.Pa foo
+is readable, as
+.Ic $(cat foo)
+but is much more performant.
 .Pp
 Note that some shells do not use a recursive parser for command substitutions,
 leading to failure for certain constructs; to be portable, use as workaround
@@ -1384,25 +1464,20 @@ See
 .Sx Arithmetic expressions
 for a description of an expression.
 .Ss Parameters
-Parameters are shell variables; they can be assigned values and their values
+Parameters are shell variables; they can be assigned values, and their values
 can be accessed using a parameter substitution.
 A parameter name is either one
-of the special single punctuation or digit character parameters described
-below, or a letter followed by zero or more letters or digits
-.Po
-.Ql _
-counts as a letter
-.Pc .
-The latter form can be treated as arrays by appending an array index of the
-form
-.Op Ar expr
-where
+of the special single punctuation character or positional parameters described
+below, or a letter followed by zero or more letters, digits or underscores.
+The latter form can be accessed as array appending an index of the form
+.Li [\& Ns Ar expr Ns Li ]\&
+(in which
 .Ar expr
-is an arithmetic expression.
-Array indices in
-.Nm
-are limited to the range 0 through 4294967295, inclusive.
-That is, they are a 32-bit unsigned integer.
+is an arithmetic expression).
+Array indices range from 0 to 4294967295
+.Pq 2\*(ha32\-1 ,
+inclusive, in
+.Nm .
 .Pp
 Parameter substitutions take the form
 .Pf $ Ns Ar name ,
@@ -1493,11 +1568,8 @@ the environment (see
 of commands run by the shell as
 .Ar name Ns = Ns Ar value
 pairs.
-The order in which parameters appear in the environment of a command is
-unspecified.
 When the shell starts up, it extracts parameters and their values
-from its environment and automatically sets the export attribute for those
-parameters.
+from its environment setting the export attribute for those.
 .Pp
 Modifiers can be applied to the
 .Pf ${ Ns Ar name Ns }
@@ -1749,7 +1821,7 @@ and
 are evaluated as arithmetic expressions.
 .Pp
 .It Pf ${ Ns Ar name Ns @#}
-The hash (using the BAFH algorithm) of the expansion of
+The hash (using the BAFH1-0 algorithm) of the expansion of
 .Ar name .
 This is also used internally for the shell's hashtables.
 .Pp
@@ -1757,6 +1829,15 @@ This is also used internally for the she
 A quoted expression safe for re-entry, whose value is the value of the
 .Ar name
 parameter, is substituted.
+.Pp
+.It Pf ${ Ns Ar name Ns @\*(ha}
+The value of
+.Ar name
+in extended caret notation, with both caret
+.Pq Ql \*(ha\&
+and backslash
+.Pq Ql \e\&
+backslash-escaped to avoid ambiguity.
 .El
 .Pp
 Note that
@@ -1813,8 +1894,9 @@ keyword (i.e. a Korn shell style functio
 .It Ev 1 No .. Ev 9
 The first nine positional parameters that were supplied to the shell, function,
 or script sourced using the
-.Dq Li \&.
-built-in.
+.Dq Li .\&
+.Pq Dq dot
+builtin.
 Further positional parameters may be accessed using
 .Pf ${ Ar number Ns } .
 .It Ev *
@@ -1907,13 +1989,13 @@ command (see below).
 .It Ev FPATH
 Like
 .Ev PATH ,
-but used when an undefined function is executed to locate the file defining the
-function.
-It is also searched when a command can't be found using
-.Ev PATH .
+but used when an undefined function is executed
+(or when a command cannot be found using
+.Ev PATH )
+to locate the function definition file.
 See
 .Sx Functions
-below for more information.
+below.
 .It Ev HISTFILE
 The name of the file used to store command history.
 When assigned to or unset, the file is opened, history is truncated
@@ -2316,17 +2398,26 @@ Ranges of octets can be specified by sep
 matches the letter
 .Ql a
 or any digit).
+Character classes can be specified by wrapping the name of the class between
+.Dq Li \&[:
+and
+.Dq Li \&:]
+(e.g.\&
+.Dq Li \&[[:alpha:][:digit:].]
+matches any ASCII letter or digit and the full stop).
+.Pp
 In order to represent itself, a
 .Ql \-
 must either be quoted or the first or last octet in the octet list.
-Similarly, a
+Similarly, if it is to represent itself instead of the end of the list, a
 .Ql \&]
-must be quoted or the first octet in the list if it is to represent itself
-instead of the end of the list.
-Also, a
+must be quoted or the first octet in the list.
+Also, an
 .Ql \&!
 appearing at the start of the list has special meaning (see below), so to
 represent itself it must be quoted or appear later in the list.
+.Ql \*(ha\&
+at the beginning of the list must be quoted or appear later.
 .It \&[!...]
 Like [...],
 except it matches any octet not inside the brackets.
@@ -2394,6 +2485,114 @@ matches no strings; the pattern
 matches all strings (think about it).
 .El
 .Pp
+The following character classes are supported (note all
+.Tn POSIX
+references assume the
+.Dv C
+locale; EBCDIC systems use the bytes from the codepage
+that map to the named ASCII characters so e.g.\&
+.Dq Li \&[[:upper:]]
+is correct while
+.Dq Li \&[A\-Z]
+will contain probably-unwanted characters on EBCDIC systems):
+.Pp
+.Bl -tag -width sh_quote -offset indent -compact
+.It Ic \*(Lt
+.Pq Tn BSD
+the null string at the beginning of a word
+.It Ic \*(Gt
+.Pq Tn BSD
+the null string at the end of a word
+.It Ic alnum
+.Pq Tn POSIX
+alphanumerical
+.Pq Ic alpha No or Ic digit
+.It Ic alpha
+.Pq Tn POSIX
+alphabetical
+.Pq Ic upper No or Ic lower
+.It Ic ascii
+.Pq Tn GNU Nm bash
+any 7-bit
+.Tn ASCII
+character except
+.Dv NUL
+.It Ic blank
+.Pq Tn POSIX
+space or horizontal\ tab
+.It Ic cntrl
+.Pq Tn POSIX
+ASCII C0 control characters
+.Pq \ex00\*(en\ex1F
+or \ex7F
+.It Ic digit
+.Pq Tn POSIX
+ASCII decimal digits
+.Pq 0\*(en9
+.It Ic graph
+.Pq Tn POSIX
+.Ic alnum No or Ic punct
+.Pq !\*(en\*(TI
+.It Ic lower
+.Pq Tn POSIX
+ASCII lowercase letters
+.Pq a\*(enz
+.It Ic print
+.Pq Tn POSIX
+.No space or Ic graph
+.Pq \ex20\*(en\*(TI
+.It Ic punct
+.Pq Tn POSIX
+punctuation
+.Pq Ic graph No except Ic alnum :
+.Li \&!"#$%&\*(aq()*+,\-./:;\*(Lt=\*(Gt?@[\e\e]\*(ha_\`{\*(Ba}\*(TI
+.It Ic sh_alias
+.Pq Nm mksh
+valid in alias names:
+.Ic alnum
+or
+.Li \&!%+,\-.:@[]_
+.It Ic sh_edq
+.Pq Nm mksh
+quoted by tab completion:
+.Li \&"#$&\*(aq()*:;\*(Lt=\*(Gt?[\e\e\`{\*(Ba}\*(TI
+.It Ic sh_ifs
+.Pq Nm mksh
+IFS whitespace, IFS non-whitespace,
+.Dv NUL
+.Pq via Ev $IFS
+.It Ic sh_ifsws
+.Pq Nm mksh
+IFS WS candidates: space, horizontal\ tab, linefeed
+.It Ic sh_nl
+.Pq Nm mksh
+linefeed or (OS/2 TEXTMODE only) carriage\ return
+.It Ic sh_quote
+.Pq Nm mksh
+characters requiring quoting, minus space:
+.Li \&\ex09\ex0A"#$&\*(aq()*;\*(Lt=\*(Gt?[\e\e]\`{\*(Ba}\*(TI
+.It Ic space
+.Pq Tn POSIX
+horizontal\ tab, line\ feed, vertical\ tab, form\ feed,
+carriage\ return, space
+.Pq \ex09\*(en\ex0D\ex20
+.It Ic upper
+.Pq Tn POSIX
+ASCII uppercase letters
+.Pq A\*(enZ
+.It Ic word
+.Pq Tn GNU Nm bash
+alphanumerical
+.Pq Ic alnum
+or underscore
+.Pq Dq Li \&_
+.It Ic xdigit
+.Pq Tn POSIX
+hexadecimal digits
+.Pq 0\*(en9A\*(enFa\*(enf
+a.k.a. nybbles
+.El
+.Pp
 Note that complicated globbing, especially with alternatives,
 is slow; using separate comparisons may (or may not) be faster.
 .Pp
@@ -2624,7 +2823,9 @@ This also affects implicit conversion to
 .Ic let
 command.
 .Em Never
-use unchecked user input, e.g. from the environment, in an arithmetic context!
+use unchecked user input, e.g. from the environment (although the shell
+tracks import status and refuses to automatically coerce those), in
+arithmetic context!
 .Pp
 Expressions are calculated using signed arithmetic and the
 .Vt mksh_ari_t
@@ -2670,7 +2871,8 @@ Grouping operators:
 .Ed
 .Pp
 Integer constants and expressions are calculated using an exactly 32-bit
-wide, signed or unsigned, type with silent wraparound on integer overflow.
+wide, signed (two's complement) or unsigned, type with silent wraparound
+on integer overflow.
 Integer constants may be specified with arbitrary bases using the notation
 .Ar base Ns # Ns Ar number ,
 where
@@ -2678,7 +2880,7 @@ where
 is a decimal integer specifying the base (up to 36), and
 .Ar number
 is a number in the specified base.
-Additionally, base-16 integers may be specified by prefixing them with
+Additionally, base-16 integers may be specified by prefixing with
 .Dq Li 0x
 .Pq case-insensitive
 in all forms of arithmetic expressions, except as numeric arguments to the
@@ -2687,7 +2889,11 @@ built-in utility.
 Prefixing numbers with a sole digit zero
 .Pq Dq Li 0
 does not cause interpretation as octal (except in POSIX mode,
-as required by the standard), as that's unsafe to do.
+as required by the standard), as that's unsafe.
+Prefixing with
+.Dq Li 10#\&
+forces interpretation as decimal, even with leading zeros.
+An unset or empty parameter evaluates to 0 in integer context.
 .Pp
 As a special
 .Nm mksh
@@ -2705,7 +2911,6 @@ instead of
 .Dq Li 1#x
 is also supported.
 Note that NUL bytes (integral value of zero) cannot be used.
-An unset or empty parameter evaluates to 0 in integer context.
 If
 .Sq Li x
 isn't comprised of exactly one valid character, the behaviour is undefined
@@ -2716,6 +2921,12 @@ must validate the input first.
 See
 .Sx CAVEATS
 for UTF-8 mode handling.
+Base-1 integers don't work well with a number of other shell features,
+such as reentry-safe output; use
+.Ic print Fl A
+or
+.Ic read Fl a
+if possible.
 .Pp
 The operators are evaluated as follows:
 .Bl -tag -width Ds -offset indent
@@ -2999,6 +3210,8 @@ outside the function).
 .It
 Shell options
 .Pq Ic set Fl o
+except
+.Fl p Pq Fl o Ic privileged
 have local scope, i.e. changes inside a function are reset upon its exit.
 .El
 .Pp
@@ -3046,13 +3259,12 @@ commands keeping assignments:
 All other builtins are not special; these are at least:
 .Pp
 .Ic [\& , alias , bg , bind ,
-.Ic builtin , cat , cd , command ,
-.Ic echo , false , fc , fg ,
-.Ic getopts , jobs , kill , let ,
-.Ic print , pwd , read , realpath ,
-.Ic rename , sleep , suspend , test ,
-.Ic true , ulimit , umask , unalias ,
-.Ic wait , whence
+.Ic builtin , cd , command , echo ,
+.Ic false , fc , fg , getopts ,
+.Ic jobs , kill , let , print ,
+.Ic pwd , read , realpath , rename ,
+.Ic suspend , test , true , ulimit ,
+.Ic umask , unalias , wait , whence
 .Pp
 Once the type of command has been determined, any command-line parameter
 assignments are performed and exported for the duration of the command.
@@ -3100,7 +3312,8 @@ or standard input as base64.
 .It Ic Lbafh_add Op Ar string
 .It Ic Lbafh_finish
 .Pq Li dot.mkshrc No functions
-Implement the Better Avalance for the Jenkins Hash.
+Implement the Better Avalance for Jenkins Hash
+.Pq IV=1 .
 This is the same hash
 .Nm
 currently uses internally.
@@ -3114,7 +3327,7 @@ variable for your consumption.
 .It Ic Lstripcom Op Ar
 .Pq Li dot.mkshrc No function
 Same as
-.Ic cat
+.Xr cat 1
 but strips any empty lines and comments (from any
 .Sq #
 character onwards, no escapes)
@@ -3130,8 +3343,7 @@ See
 .Fl +x Oc
 .Op Fl p
 .Op Cm +
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq regular
@@ -3251,14 +3463,28 @@ string, wherein prefix/control/tilde cha
 .Pq but not those mapped to other macros
 will be processed.
 .Pp
-Prefix and control characters may be written using caret notation, i.e.\&
+The entire argument may be written using extended caret notation:
 .No \*(ha Ns Li Z
 represents
-.No Ctrl- Ns Li Z .
-Use a backslash to escape the caret, an equals sign or another backslash.
+.No Ctrl- Ns Li Z ;
+.No \*(ha Ns Li +Z
+represents UTF-8
+.No Meta-Ctrl- Ns Li Z ,
+and both
+.No \*(ha Ns Li !Z
+and
+.No \ex Ns Li 9A
+represent ASCII
+.No Meta-Ctrl- Ns Li Z .
+Otherwise, a backslash escapes the next character,
+removing the special meaning from backslashes, carets and
+.Pq for the Ar string No part
+equals signs.
+.Pf ( Em These
+backslashes obviously must be quoted for the shell.)
 Note that, although only three prefix characters
 .Pq usually Esc, \*(haX and NUL
-are supported, some multi-character sequences can be supported.
+are usable, some multi-character sequences can be supported.
 .Pp
 .It Ic break Op Ar level
 .Pq keeps assignments , special
@@ -3297,26 +3523,6 @@ declaration utility (see
 is a declaration utility.
 .Pp
 .It Xo
-.Ic cat
-.Op Fl u
-.Op Ar
-.Xc
-.Pq defer with flags
-Copy files in command line order to standard output.
-If a
-.Ar file
-is a single dash
-.Pq Dq Li \-
-or absent, read from standard input.
-For direct builtin calls, the
-.Tn POSIX
-.Fl u
-option is supported as a no-op.
-For calls from shell, if any options are given, an external
-.Xr cat 1
-utility is preferred over the builtin.
-.Pp
-.It Xo
 .Ic cd
 .Op Fl L
 .Op Ar dir
@@ -3813,8 +4019,7 @@ Same as
 .It Xo
 .Ic integer
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3893,8 +4098,7 @@ is syntactic sugar for:
 .It Xo
 .Ic local
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3941,8 +4145,7 @@ however, distributors may have added thi
 .It Xo
 .Ic nameref
 .Op flags
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq built-in alias
@@ -3989,14 +4192,16 @@ resulting value is printed.
 Empty
 .Ar argument Ns s
 separate input words.
+No backslash expansion.
 .It Fl c
-The output is printed columnised, line by line, similar to how the
-.Xr rs 1
-utility, tab completion, the
+The output is printed columnised, top to bottom then left to right,
+similar to how tab completion (control character escaping excepted), the
 .Ic kill Fl l
-built-in utility and the
+built-in utility, the
 .Ic select
-statement do.
+statement and the
+.Xr rs 1
+utility do.
 .It Fl e
 Restore backslash expansion after a previous
 .Fl r .
@@ -4213,8 +4418,7 @@ exits with a non-zero status.
 .It Xo
 .Ic readonly
 .Op Fl p
-.Oo Ar parameter
-.Op Ns = Ns Ar value
+.Oo Ar parameter Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .Pq keeps assignments , special, decl-util
@@ -4255,16 +4459,15 @@ resolving to an extant non-directory is
 .Op Fl \-
 .Ar from to
 .Xc
-.Pq defer always
+.Pq defer always , needs Xr rename 2
 Renames the file
 .Ar from
 to
 .Ar to .
-Both must be complete pathnames and on the same device.
+Both pathnames must be on the same device.
 Intended for emergency situations
 .Pq where Pa /bin/mv No becomes unusable ;
-directly calls
-.Xr rename 2 .
+thin syscall wrapper.
 .Pp
 .It Ic return Op Ar status
 .Pq keeps assignments , special
@@ -4294,12 +4497,17 @@ scripts.
 ROT13-encrypts/-decrypts stdin to stdout.
 .Pp
 .It Xo
-.Ic set Op Fl +abCefhiklmnprsUuvXx
+.Ic set Op Fl +abCefhkmnpsUuvXx
 .Op Fl +o Ar option
 .Op Fl +A Ar name
 .Op Fl \-
-.Op Ar arg ...
+.Op Ar argument ...
 .Xc
+.It Xo
+.Ic set Fl \-
+.Op Ar argument ...
+.Xc
+.It Ic set Fl +o
 .Pq keeps assignments , special
 The
 .Ic set
@@ -4319,15 +4527,16 @@ is the long name of an option, or using
 .Fl + Ns Ar letter
 syntax, where
 .Ar letter
-is the option's single letter name (not all options have a single letter name).
-The following table lists short (if extant) and long names
+is the option's single letter name (not all options have both names).
+The following table lists short and long names
+.Pq if extant
 along with a description of what each option does:
 .Bl -tag -width 3n
 .It Fl A Ar name
 Sets the elements of the array parameter
 .Ar name
 to
-.Ar arg ...
+.Ar argument ...
 .Pp
 If
 .Fl A
@@ -4353,15 +4562,16 @@ and also supported by
 is:
 .Ic foo=(a b c); foo+=(d e)
 .It Fl a \*(Ba Fl o Ic allexport
-All new parameters are created with the export attribute.
+Make all variables assigned to while enabled as exported.
 .It Fl b \*(Ba Fl o Ic notify
 Print job notification messages asynchronously instead of just before the
 prompt.
 Only used with job control
 .Pq Fl m .
 .It Fl C \*(Ba Fl o Ic noclobber
-Prevent \*(Gt redirection from overwriting existing files.
-Instead, \*(Gt\*(Ba must be used to force an overwrite.
+Prevent \*(Gt redirection from overwriting existing files;
+.Ql \*(Gt\*(Ba
+must be used to force overwriting instead.
 .Em Note:
 This is not safe to use for creation of temporary files or
 lockfiles due to a TOCTOU in a check allowing one to redirect output to
@@ -4369,6 +4579,9 @@ lockfiles due to a TOCTOU in a check all
 or other device files even in
 .Ic noclobber
 mode.
+.It Fl c
+Commands are read from an argument string.
+Can only be used when the shell is invoked.
 .It Fl e \*(Ba Fl o Ic errexit
 Exit (after executing the
 .Dv ERR
@@ -4418,10 +4631,10 @@ the real UID or GID does not match
 the effective UID (EUID) or GID (EGID), respectively.
 See above for a description of what this means.
 .Pp
-If the shell is privileged, setting this flag after startup files
-have been processed let it go full setuid and/or setgid.
-Clearing this flag makes the shell drop privileges.
-Changing this flag resets the groups vector.
+If the shell is privileged, setting this flag after startup file
+processing let it go full setuid and/or setgid.
+Clearing the flag makes the shell drop privileges.
+Changing this flag resets the supplementary groups vector.
 .It Fl r \*(Ba Fl o Ic restricted
 The shell is a restricted shell.
 This option can only be used when the shell is invoked.
@@ -4445,25 +4658,18 @@ Enable UTF-8 support in the
 and internal string handling functions.
 This flag is disabled by default, but can be enabled by setting it on the
 shell command line; is enabled automatically for interactive shells if
-requested at compile time, your system supports
-.Fn setlocale LC_CTYPE \&""
-and optionally
-.Fn nl_langinfo CODESET ,
-or the
+the POSIX locale uses the UTF-8 codeset or, lacking POSIX locales, the
 .Ev LC_ALL ,
 .Ev LC_CTYPE
 or
 .Ev LANG
-environment variables,
-and at least one of these returns something that matches
-.Dq UTF\-8
-or
-.Dq utf8
-case-insensitively; for direct builtin calls depending on the
-aforementioned environment variables; or for stdin or scripts,
-if the input begins with a UTF-8 Byte Order Mark.
+environment variables either case-insensitively equal
+.Dq Li UTF\-8
+or
+.Dq Li utf8
+or have that as codeset modifier.
 .Pp
-In near future, locale tracking will be implemented, which means that
+This build of the shell implements baroque locale tracking, that is,
 .Ic set Fl +U
 is changed whenever one of the
 .Tn POSIX
@@ -4488,6 +4694,15 @@ during globbing.
 .It Fl x \*(Ba Fl o Ic xtrace
 Print commands when they are executed, preceded by
 .Ev PS4 .
+.It Fl o Ic asis
+When quoting output, if not in EBCDIC mode and
+.Ic utf8\-mode
+is disabled, show C1 control characters
+.Dq as is ,
+that is, do not escape them.
+Use with codepages where the range 0x80..0x9F contains printable
+characters (such as 437, 850, 1252, etc. but not the ISO\ 8859
+series, for example).
 .It Fl o Ic bgnice
 Background jobs are run with lower priority.
 .It Fl o Ic braceexpand
@@ -4517,14 +4732,7 @@ upon entering functions (default).
 Do not kill running jobs with a
 .Dv SIGHUP
 signal when a login shell exits.
-Currently set by default, but this may
-change in the future to be compatible with
-.At
-.Nm ksh ,
-which
-doesn't have this option, but does send the
-.Dv SIGHUP
-signal.
+Currently enabled by default.
 .It Fl o Ic nolog
 No effect.
 In the original Korn shell, this prevented function definitions from
@@ -4574,9 +4782,7 @@ and
 this autodetection feature is compiled in.
 As a side effect, setting this flag turns off the
 .Ic braceexpand
-and
-.Ic utf8\-mode
-flags, which can be turned back on manually, and
+flag, which can be turned back on manually, and
 .Pq unless both are set in the same command
 .Ic sh
 mode.
@@ -4627,7 +4833,7 @@ is always in viraw mode.
 .Pp
 These options can also be used upon invocation of the shell.
 The current set of
-options (with single letter names) can be found in the parameter
+options with single letter names can be found in the parameter
 .Dq Li $\- .
 .Ic set Fl o
 with no option name will list all the options and whether each is on or off;
@@ -4637,18 +4843,29 @@ prints a command to restore the current
 construct, which is an implementation detail; these commands are transient
 .Pq only valid within the current shell session .
 .Pp
-Remaining arguments, if any, are positional parameters and are assigned, in
-order, to the positional parameters (i.e. $1, $2, etc.).
-If options end with
-.Dq Li \-\-
-and there are no remaining arguments, all positional parameters are cleared.
-For unknown historical reasons, a lone
+A lone
 .Dq Li \-
-option is treated specially\*(EMit clears both the
+clears both the
 .Fl v
 and
 .Fl x
-options.
+options (obsolete); it
+.Pq or a lone Dq Li +\&
+terminates option processing and is otherwise ignored.
+.Pp
+.No Remaining Ar argument Ns s ,
+if any, are assigned (in order, unless
+.Fl s
+is given) to
+.Ar name
+.Pq with Fl A
+or the positional parameters
+.Pq i.e.,\& $1, $2, etc .
+.No Use Fl \-
+if the first argument begins with plus or dash.
+If options end with
+.Dq Li \-\-
+and there are no remaining arguments, all positional parameters are cleared.
 If no options or arguments are given, the values of all parameters are printed
 .Pq suitably quoted .
 .Pp
@@ -4672,13 +4889,6 @@ etc.
 .Pq Ar number No defaults to 1
 are renamed to 1, 2, etc.
 .Pp
-.It Ic sleep Ar seconds
-.Pq regular , needs Xr select 2
-Suspends execution for a minimum of the
-.Ar seconds
-(specified as positive decimal value with an optional fractional part).
-Signal delivery may continue execution earlier.
-.Pp
 .It Ic smores Op Ar
 .Pq Li dot.mkshrc No function
 Simple pager:
@@ -4944,15 +5154,16 @@ or
 .Dq Li \-n .
 Use tests like
 .Dq Li if \&[ x\&"$foo\&" = x"bar" \&]
-instead, or the double-bracket operator (see
-.Ic \&[[
-above):
+instead, or the double-bracket construct
+.Pq see Ic \&[[ No above :
 .Dq Li if \&[[ $foo = bar \&]]
 or, to avoid pattern matching,
 .Dq Li if \&[[ $foo = \&"$bar" \&]] ;
 the
 .Ic \&[[ ... \&]]
 construct is not only more secure to use but also often faster.
+Similarly, operators need to be quoted as usual for
+.Nm test No / Nm \&[ .
 .Pp
 .It Xo
 .Ic time
@@ -5096,8 +5307,7 @@ would be interpreted as command.
 .No \*(Ba Fl R Ns Op Ar n
 .No \*(Ba Fl Z Ns Op Ar n Oc
 .Op Fl i Ns Op Ar n
-.Oo Ar name
-.Op Ns = Ns Ar value
+.Oo Ar name Ns Op = Ns Ar value
 .Ar ... Oc
 .Xc
 .It Xo
@@ -5405,6 +5615,12 @@ Limit the size of
 message queues to
 .Ar n
 bytes.
+.It Fl R Ar n
+.Pq Cm Linux
+Limit the CPU time slice a real-time process can use before
+performing a blocking syscall to
+.Ar n
+milliseconds.
 .It Fl r Ar n
 .Pq Cm AIX
 Limit the number of threads per process to
@@ -5806,7 +6022,7 @@ The
 builtin does not interpret backslashes and only supports the exact option
 .Fl n ,
 unless built with
-.Ev \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
 .It
 The substitution operations
 .Sm off
@@ -5845,7 +6061,7 @@ passes through the errorlevel.
 eats a leading
 .Fl \-
 if built with
-.Ev \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
+.Dv \-DMKSH_MIDNIGHTBSD01ASH_COMPAT .
 .El
 .Ss Interactive input line editing
 The shell supports three modes of reading command lines from a
@@ -5907,21 +6123,28 @@ command.
 .Pp
 The following is a list of available editing commands.
 Each description starts with the name of the command,
-suffixed with a colon;
-an
+suffixed with a colon; a
 .Op Ar n
 (if the command can be prefixed with a count); and any keys the command is
 bound to by default, written using caret notation
-e.g. the ASCII Esc character is written as \*(ha[.
-These control sequences are not case sensitive.
+(e.g. the ASCII Esc character is written as
+.Li \*(ha[ )
+or terminal-specific indications.
 A count prefix for a command is entered using the sequence
 .Pf \*(ha[ Ns Ar n ,
 where
 .Ar n
-is a sequence of 1 or more digits.
+is one or more digits.
 Unless otherwise specified, if a count is
 omitted, it defaults to 1.
 .Pp
+Bigwords, as used below, are separated by spaces or tabs;
+words consist of alphanumerics, underscore
+.Pq Ql _
+or dollar sign
+.Pq Ql $
+characters.
+.Pp
 Note that editing command names are used only with the
 .Ic bind
 command.
@@ -5944,8 +6167,13 @@ Emacs key bindings:
 Abort the current command, save it to the history, empty the line buffer and
 set the exit state to interrupted.
 .It auto\-insert: Op Ar n
+.Pq Most ordinary characters are bound to this command.
 Simply causes the character to appear as literal input.
-Most ordinary characters are bound to this.
+.It Xo backward\-bigword:
+.Op Ar n
+.No \*(ha[B
+.Xc
+Moves the cursor backward to the beginning of the bigword.
 .It Xo backward\-char:
 .Op Ar n
 .No \*(haB , \*(haXD , ANSI-CurLeft , PC-CurLeft
@@ -5957,19 +6185,21 @@ characters.
 .Op Ar n
 .No \*(ha[b , ANSI-Ctrl-CurLeft , ANSI-Alt-CurLeft
 .Xc
-Moves the cursor backward to the beginning of the word; words consist of
-alphanumerics, underscore
-.Pq Ql _
-and dollar sign
-.Pq Ql $
-characters.
+Moves the cursor backward to the beginning of the word.
 .It beginning\-of\-history: \*(ha[\*(Lt
 Moves to the beginning of the history.
 .It beginning\-of\-line: \*(haA, ANSI-Home, PC-Home
 Moves the cursor to the beginning of the edited input line.
+.It Xo capitalise\-bigword:
+.Op Ar n
+.No \*(ha[C
+.Xc
+Uppercase the first character in the next
+.Ar n
+bigwords as below.
 .It Xo capitalise\-word:
 .Op Ar n
-.No \*(ha[C , \*(ha[c
+.No \*(ha[c
 .Xc
 Uppercase the first ASCII character in the next
 .Ar n
@@ -6013,6 +6243,20 @@ match as in the
 .Ic complete
 command above.
 Note that \*(haI is usually generated by the Tab (tabulator) key.
+.It Xo delete\-bigword\-backward:
+.Op Ar n
+.No \*(ha[H
+.Xc
+Deletes
+.Ar n
+bigwords before the cursor.
+.It Xo delete\-bigword\-forward:
+.Op Ar n
+.No \*(ha[D
+.Xc
+Deletes characters after the cursor up to the end of
+.Ar n
+bigwords.
 .It Xo delete\-char\-backward:
 .Op Ar n
 .No ERASE Pq \*(haH ,
@@ -6060,9 +6304,16 @@ is not useful until either
 or
 .Ic up\-history
 has been performed.
+.It Xo downcase\-bigword:
+.Op Ar n
+.No \*(ha[L
+.Xc
+Lowercases the next
+.Ar n
+bigwords.
 .It Xo downcase\-word:
 .Op Ar n
-.No \*(ha[L , \*(ha[l
+.No \*(ha[l
 .Xc
 Lowercases the next
 .Ar n
@@ -6113,6 +6364,13 @@ Appends a
 to the current word and replaces the word with the result of performing file
 globbing on the word.
 If no files match the pattern, the bell is rung.
+.It Xo forward\-bigword:
+.Op Ar n
+.No \*(ha[F
+.Xc
+Moves the cursor forward to the end of the
+.Ar n Ns th
+bigword.
 .It Xo forward\-char:
 .Op Ar n
 .No \*(haF , \*(haXC , ANSI-CurRight , PC-CurRight
@@ -6137,8 +6395,11 @@ Goes to history number
 .No KILL Pq \*(haU
 .Xc
 Deletes the entire input line.
-.It kill\-region: \*(haW
+.It kill\-region: \*(ha[\*(haW
 Deletes the input between the cursor and the mark.
+Note: this used to be bound to \*(haW like in Emacs, which is usually taken by
+.Dv WERASE
+though, so it was moved.
 .It Xo kill\-to\-eol:
 .Op Ar n
 .No \*(haK
@@ -6181,15 +6442,18 @@ This does nothing.
 Introduces a 2-character command sequence.
 .It prefix\-2: \*(haX , \*(ha[[ , \*(ha[O
 Introduces a multi-character command sequence.
-.It Xo prev\-hist\-word:
+.It prefix\-3: \*(ha@
+Introduces a PC keyboard scancode.
+.It Xo prev\-hist\-bigword:
 .Op Ar n
 .No \*(ha[. , \*(ha[_
 .Xc
-The last word or, if given, the
-.Ar n Ns th
-word (zero-based) of the previous (on repeated execution, second-last,
-third-last, etc.) command is inserted at the cursor.
-Use of this editing command trashes the mark.
+If no count is given, the last bigword, otherwise the
+.No ( Ar n Ns +1)th
+bigword of the previous line is inserted at the cursor,
+and the mark is set to the beginning of the inserted word.
+When invoked repeatedly, the inserted text is replaced by the corresponding
+bigword from the second-last, third-last, etc. line.
 .It quote: \*(ha\*(ha , \*(haV
 The following character is taken literally rather than as an editing command.
 .It quote\-region: \*(ha[Q
@@ -6219,7 +6483,7 @@ The internal history list is searched
 backwards for commands matching the input.
 An initial
 .Ql \*(ha
-in the search string anchors the search.
+in the search string anchors the search at the beginning of the line.
 The escape key will leave search mode.
 Other commands, including sequences of escape as
 .Ic prefix\-1
@@ -6227,31 +6491,33 @@ followed by a
 .Ic prefix\-1
 or
 .Ic prefix\-2
-key will be executed after leaving search mode.
+key, will be executed after leaving search mode.
 The
 .Ic abort Pq \*(haG
-command will restore the input line before search started.
+command will restore the input line from before search started.
 Successive
 .Ic search\-history
-commands continue searching backward to the next previous occurrence of the
-pattern.
+commands continue searching backward to the following previous occurrence
+of the pattern.
 The history buffer retains only a finite number of lines; the oldest
 are discarded as necessary.
-.It search\-history\-up: ANSI-PgUp, PC-PgUp
-Search backwards through the history buffer for commands whose beginning match
-the portion of the input line before the cursor.
-When used on an empty line, this has the same effect as
-.Ic up\-history .
 .It search\-history\-down: ANSI-PgDn, PC-PgDn
-Search forwards through the history buffer for commands whose beginning match
+Search forwards (this command is only useful after an
+.Ic up\-history ,
+.Ic search\-history\-up
+or
+.Ic search\-history )
+through the history buffer for commands whose beginning matches
 the portion of the input line before the cursor.
 When used on an empty line, this has the same effect as
 .Ic down\-history .
-This is only useful after an
-.Ic up\-history ,
-.Ic search\-history
-or
-.Ic search\-history\-up .
+.It search\-history\-up: ANSI-PgUp, PC-PgUp
+Search backwards through the history buffer for commands whose beginning
+matches the portion of the input line before the cursor.
+When used on an empty line, this has the same effect as
+.Ic up\-history .
+.It set\-arg: \*(ha[0 .. \*(ha[9
+Mapped to begin prefixing a count to a command.
 .It set\-mark\-command: \*(ha[ Ns Aq space
 Set the mark at the cursor position.
 .It transpose\-chars: \*(haT
@@ -6267,9 +6533,16 @@ character to the right.
 Scrolls the history buffer backward
 .Ar n
 lines (earlier).
+.It Xo upcase\-bigword:
+.Op Ar n
+.No \*(ha[U
+.Xc
+Uppercase the next
+.Ar n
+bigwords.
 .It Xo upcase\-word:
 .Op Ar n
-.No \*(ha[U , \*(ha[u
+.No \*(ha[u
 .Xc
 Uppercase the next
 .Ar n
@@ -6279,6 +6552,8 @@ Display the version of
 .Nm mksh .
 The current edit buffer is restored as soon as a key is pressed.
 The restoring keypress is processed, unless it is a space.
+.It vt100\-hack: \*(ha[[1
+Mapped to internally represent some longer key sequences.
 .It yank: \*(haY
 Inserts the most recently killed text string at the current cursor position.
 .It yank\-pop: \*(ha[y
@@ -6289,7 +6564,7 @@ replaces the inserted text string with t
 .Pp
 The tab completion escapes characters the same way as the following code:
 .Bd -literal
-print \-nr \-\- "${x@/[\e"\-\e$\e&\-*:\-?[\e\e\e`\e{\-\e}${IFS\-$\*(aq \et\en\*(aq}]/\e\e$KSH_MATCH}"
+print \-nr \-\- "${x@/[\e"\-\e$\e&\-*:\-?[\e\e\e\`\e{\-\e\*(TI${IFS\-$\*(aq \et\en\*(aq}]/\e\e$KSH_MATCH}"
 .Ed
 .Ss Vi editing mode
 .Em Note:
@@ -7064,8 +7339,10 @@ and wraparound defined, even (defying PO
 .Pp
 .Nm mksh
 currently uses OPTU-16 internally, which is the same as UTF-8 and CESU-8
-with 0000..FFFD being valid codepoints; raw octets are mapped into the
-PUA range EF80..EFFF, which is assigned by CSUR for this purpose.
+with 0000..FFFD being valid codepoints; raw octets map to U+EF80..U+EFFF.
+.Em Future compatibility note :
+mksh R60 will use full 21-bit UTF-8 and map raw octets to
+U\-001BBB80..U\-001BBBFF instead.
 .Sh BUGS
 Suspending (using \*(haZ) pipelines like the one below will only suspend
 the currently running part of the pipeline; in this example,
@@ -7089,9 +7366,9 @@ for the in-memory portion of the history
 .Xr memmove 3 .
 .Pp
 This document attempts to describe
-.Nm mksh\ R59c
+.Nm mksh\ R59-CURRENT
 and up,
-.\" with vendor patches from insert-your-name-here,
+with vendor patches from Debian,
 compiled without any options impacting functionality, such as
 .Dv MKSH_SMALL ,
 when not called as
@@ -7107,13 +7384,7 @@ Please report bugs in
 .Nm
 to the public development mailing list at
 .Aq Mt miros\-mksh@mirbsd.org
-(please note the EU-DSGVO/GDPR notice on
-.Pa http://www.mirbsd.org/rss.htm#lists
-and in the SMTP banner!) or in the
+or, in the
 .Li \&#\&!/bin/mksh
-.Pq or Li \&#ksh
-IRC channel at
-.Pa irc.freenode.net
-.Pq Port 6697 SSL, 6667 unencrypted ,
-or at:
-.Pa https://launchpad.net/mksh
+channel, on IRC; for both, note the information at:
+.Pa http://www.mirbsd.org/mksh\-faq.htm#contact
--- mksh-59c.orig/mksh.faq
+++ mksh-59c/mksh.faq
@@ -1,4 +1,4 @@
-RCSID: $MirOS: src/bin/mksh/mksh.faq,v 1.10 2020/10/01 22:59:12 tg Exp $
+RCSID: $MirOS: src/bin/mksh/mksh.faq,v 1.42+locale-tracking 2024/03/12 21:44:53 tg Exp $
 ToC: spelling
 Title: How do you spell <tt>mksh</tt>? How do you pronounce it?
 
@@ -8,12 +8,15 @@ Title: How do you spell <tt>mksh</tt>? H
  initial lowercase letter</a>; this is important) or “MirBSD Korn Shell”,
  possibly with “the”.</p>
 <p>I usually pronounce it as “<span xml:lang="de-DE-1901">em-ka-es-ha</span>”,
- that is, the letters individually in my native German, or say “MirBSD Korn
- Shell”, although it is manageable, mostly for Slavic speakers, to actually
- say “mksh” as if it were a word ☺</p>
+ that is, the letters individually in my native German, emphasis on the
+ first syllable, or say “MirBSD Korn Shell”, although it is manageable,
+ mostly for Slavic speakers, to actually say “mksh” as if it were a word ☺</p>
 <p>Oh… I’ve run into this one, didn’t I? “MirBSD” is pronounced “<span
  xml:lang="de-DE-1901">Mir-Be-Es-De</span>” germanically, for anglophones
  “Mir-beas’tie” is fine.</p>
+<p>This translates well into other languages, such as <span
+ xml:lang="es">eme-ka-ese-ache</span> in Spanish, although English
+ speakers may still find “Mir-beastie korn shell” more palatable.</p>
 ----
 ToC: sowhatismksh
 Title: I’m a $OS (<i>Android, OS/2, …</i>) user, so what’s mksh?
@@ -59,9 +62,10 @@ Title: How does this relate to ksh or th
  flavours exist (ksh88 and ksh93), the latter having been maintained
  until 2012 (last formal release) and 2014 (last beta snapshot, buggy).
  A ksh86 did exist.</p>
-<p>There’s now <tt>ksh2020</tt>, a project having restarted development
- around November 2017 forking the last <tt>ksh93 v-</tt> (beta) snapshot
- and continuing to develop it, presented at FOSDEM.</p>
+<p>The <tt>ksh2020</tt> project to restart development around November
+ 2017 forking the last <tt>ksh93 v-</tt> (beta) snapshot is now dead,
+ but the <tt>ksh93u+m</tt> project from 2021 onwards is active and more
+ stable.</p>
 <p>AT&amp;T ksh88 is “the (original) Korn Shell”. Other implementations,
  of varying quality (MKS Toolkit’s MKS ksh being named as an example of
  the lower end, MirBSD’s mksh at the upper end). They are all <em>not</em>
@@ -98,8 +102,8 @@ Title: How does this relate to ksh or th
  getting close to, ksh88 compatibility.</p>
 <p>SKsh is an AmigaOS-specific Korn Shell-lookalike by Steve Koren.</p>
 <p>The <a href="@@RELPATH@@ksh-chan.htm">Homepage of the <tt>#ksh</tt>
- channel on Freenode IRC</a> contains more information about the Korn
- Shell in general and its flavours.</p>
+ channel on IRC</a> contains more information about the Korn Shell in
+ general and its flavours.</p>
 ----
 ToC: packaging
 Title: How should I package mksh? (common cases)
@@ -190,6 +194,23 @@ Title: I forbid stat(2) in my SELinux po
 
 Don’t break Unix. Read up on the GIGO principle. Duh.
 ----
+ToC: printf-c
+Title: Which revision of printf.c do I use?
+
+<p>If you have to add printf(1) as an extra, nōn-standard, builtin,
+ use <tt>src/usr.bin/printf/printf.c,v</tt> revision…</p>
+<ul>
+ <li>r1.25 or newer for mksh CVS HEAD (R59d/R60+)</li>
+ <li>r1.22 for mksh R59c</li>
+</ul>
+<p>… and add <tt>USE_PRINTF_BUILTIN=1</tt> to the <tt>Build.sh</tt>
+ environment. Do note that this can no longer be used as “speed hack”
+ because as of R51, if an external printf(1) exists, it is preferred,
+ as the OS’ own implementations will often have extensions, and they
+ usually will have floating point support (which the one embedded in
+ mksh cannot provide). It mostly exists for invocations where no such
+ utility is in <tt>$PATH</tt> but scripts are targetting POSIX.</p>
+----
 ToC: makefile
 Title: Why doesn’t this use a Makefile to build?
 
@@ -238,9 +259,10 @@ so you are probably best off starting wi
 or ksh88 reference such as the first edition (the second one deals
 with ksh93 which differs far more from mksh than ksh88, as ancient
 as it is, does) of the O’Reilly book (⚠ disclaimer: only an example,
-not a recommendation) and going forward by reading scripts (the
-“shellsnippets” repository referenced in the <tt>#ksh</tt> channel
-homepage (see the top of this document) has many examples) and
+not a recommendation) “Learning the Korn Shell” and going forward
+by reading scripts (the “shellsnippets” repository referenced in <a
+href="@@RELPATH@@ksh-chan.htm">the <tt>#ksh</tt> channel homepage</a>
+has many examples) and
 trying to understand them and the mksh specifics from the manpage.
 ----
 ToC: ps1conv
@@ -260,7 +282,7 @@ Title: My prompt is weird!
  (This was agreed upon as suggestion in a discussion between bash, zsh and
  Korn shell developers.) The feature set of different shells vastly differs
  and each shell should use its default PS1 or from its startup files.</li>
-<li><tt>$ENV</tt> <a href="#env">is set and/or <tt>export</tt>ed</a>.</li>
+<li><tt>$ENV</tt> <a href="#env">is set and probably <tt>export</tt>ed</a>.</li>
 <li>Your prompt is just “<tt># </tt>”: you’re entering a root shell, and
  <tt>$PS1</tt> does not contain the ‘#’ character, in which case the shell
  forces this prompt, making extra privileges obvious.</li>
@@ -284,7 +306,7 @@ Title: My prompt is weird!
 ToC: env
 Title: On startup files and <tt>$ENV</tt> across and detecting various shells
 
-Interactive shells look at <tt>~/.mkshrc</tt> (or <tt>/system/etc/mkshrc</tt>
+<p>Interactive shells look at <tt>~/.mkshrc</tt> (or <tt>/system/etc/mkshrc</tt>
 on Android and <tt>/etc/mkshrc</tt> on FreeWRT and OpenWrt) by default. This
 location can, however, be overridden by setting the <tt>ENV</tt> environment
 variable. (FreeBSD is rumoured to set it in their system profile.) It’s better
@@ -295,7 +317,30 @@ or “MIRBSD KSH” for mksh, “PD KSH
 for ksh93); <tt>$NETBSD_SHELL</tt> (NetBSD ash); <tt>POSH_VERSION</tt> (posh, a
 pdksh derivative); <tt>$SH_VERSION</tt> (“PD KSH” as sh), <tt>$YASH_VERSION</tt>
 (yash), <tt>$ZSH_VERSION</tt> (or if <tt>$VERSION</tt> begins with “zsh”); a <a
-href="@@RELPATH@@ksh-chan.htm#which-shell">list of more approaches</a> exists.
+href="@@RELPATH@@ksh-chan.htm#which-shell">list of more approaches</a> exists.</p>
+
+<p>Note that, in some scenarios, it might be very useful to actually set
+ <tt>$ENV</tt>: the regular interactive shell startup file lies in the
+ user’s home directory, relying on being copied from <tt>/etc/skel/</tt>
+ which normally is only done at user creation time. If mksh was installed
+ later, the user often won’t get it at all, and delivering updates is
+ challenging. One way of partially working around this is to ship an
+ <tt>/etc/skel/.mkshrc</tt> that reads <tt>/etc/mkshrc</tt> by default
+ (but the user can change it of course) and ship the <tt>dot.mkshrc</tt>
+ file as <tt>/etc/mkshrc</tt>, but that won’t fully help. This is where
+ <tt>$ENV</tt> comes into play:</p><ul>
+  <li>In <tt>/etc/profile</tt>, set <tt>ENV</tt> to a, say, <tt>shrc</tt>
+   file shipped in <tt>/etc/</tt> and export it.</li>
+  <li>In that new file, which must use only constructs compatible with
+   all shells, usually a subset of POSIX, read the various rc files
+   (<tt>.mkshrc</tt> for mksh, <tt>.kshrc</tt> for AT&amp;T ksh93, etc.)
+   from the user’s home if they exist, from <tt>/etc/skel/</tt> otherwise.</li>
+</ul><p>This may very well be <em>required</em> if the alternative would
+ be <a href="#ps1weird">to <del><tt>export PS1</tt></del>[sic!]</a>. <a
+  href="https://gitlab.alpinelinux.org/alpine/aports/-/issues/12398#note_146574"
+ >alpine Linux</a> encountered this very problem, and the linked post is
+ a (draft) solution using the <tt>$ENV</tt> method and looks at various
+ other shells’ startup file situation as well.</p>
 ----
 ToC: ctrl-x-e
 Title: Multiline command editing
@@ -320,6 +365,40 @@ Title: Multiline command editing
  nōn-zero (e.g. using jupp’s “abendjoe” command) to prevent execution.
  This is <em>really</em> useful to write ad-hōc scripts as well.</p>
 ----
+ToC: escaping
+Title: Some characters don’t display right
+
+<p>First, make sure that either you’re using a UTF-8 terminal and system
+ and the shell’s UTF-8 mode is on (<tt>set -U</tt>) or that you’re using
+ an 8-bit codepage/CCSID and the UTF-8 mode is off (<tt>set +U</tt>). If
+ you’re on an EBCDIC system ensure to pick a codepage that has a bijective
+ mapping to (Extended) ASCII and in which all necessary characters are
+ present, for example 1047. Furthermore ensure the compile-time and runtime
+ codepages match. (Other encoding schemes, e.g. DBCS or ISO-2022-JP, are
+ not supported.) This should already fix most relevant issues.</p>
+<p>If using an 8-bit coding system that (unlike e.g. ISO 8859 or EBCDIC)
+ does not assign control characters to “Extended ASCII” codepoints 0x80‥0x9F,
+ such as codepages 437, 850, 1252, … (usually on OS/2 or DOS-based systems),
+ enable the option <tt>set -o asis</tt> (new in R60); otherwise, they will
+ be escaped to avoid accidentally setting off terminal control sequences.</p>
+<p>Note that escaping of characters is, at runtime, dependent on whether the
+ shell was compiled for EBCDIC and/or <tt>utf8-mode</tt> and/or <tt>asis</tt>
+ are enabled, the latter being ignored if either of the former two are true
+ (in UTF-8 mode, UCS C1 codepoints are always escaped).</p>
+----
+ToC: carets
+Title: What’s with these ^Q, ^!Q and ^+Q (e.g. from tab completion)? \x80 too!
+
+The extended caret notation escapes characters that can be harmful for your
+terminal from being output as active control characters. This is dependent
+on the shell mode (see <a href="#escaping">above</a>. The caret (<tt>^</tt>)
+means Ctrl; <tt>^+</tt> is used to denote UTF-8 C1 control characters, while
+raw 8-bit C1 control characters use <tt>^!</tt>, and invalid UTF-8 sequences
+show up as <tt>\x</tt> in <tt>utf8-mode</tt>. The manpage also documents
+these (search for “caret”). Note that the <tt>bind</tt> utility and explicit
+parameter escaping also quote carets and backslashes with a backslash, while
+mere output (tab completion, input line editing) don’t.
+----
 ToC: ctrl-l-cls
 Title: ^L (Ctrl-L) does not clear the screen
 
@@ -329,9 +408,36 @@ Use ^[^L (Escape+Ctrl-L) or rebind it:<b
 ToC: ctrl-u-pico
 Title: ^U (Ctrl-U) clears the entire line
 
-If it should only delete the line up to the cursor, use:<br />
+If you want it to only delete the line up to the cursor, use:<br />
 <tt>bind -m ^U='^[0^K'</tt>
 ----
+ToC: ctrl-w-bash
+Title: ^W (Ctrl-W) deletes a word, not a bigword
+
+If you want it to delete more, with R59d+ you can use:<br />
+<tt>bind '^W=delete-bigword-backward'</tt>
+----
+ToC: esc-d-whole-word
+Title: I want Esc+d to delete the entire word, not just to the right from the cursor
+
+<p class="boxhead">This is not possible with a simple editing
+ command; however, you can use a macro definition to create a
+ matching effect. First, you need to bind the current definition
+ of Esc+d, i.e. <tt>delete-word-forward</tt>, to something else;
+ Esc+Ctrl-D is currently unused, so we’ll use that. Then you’ll
+ define a macro that inserts two letters and moves one back (to
+ work at the beginning and end of words safely), then run both
+ delete word backward and forward:</p>
+<div class="boxtext">
+ <pre>
+	bind '^[^D=delete-word-forward'
+	bind -m '^[d=aa^B^[^H^[^D'
+</pre>
+</div><p class="boxfoot">If your shell is sufficiently recent to
+ do so and you want to delete by <a href="#ctrl-w-bash">bigwords</a>,
+ you do not need the first redefinition and simply swap the deletion
+ commands:<br /><tt>bind -m '^[d=aa^B^[H^[D'</tt></p>
+----
 ToC: cur-up-zsh
 Title: Cursor Up behaves differently from zsh
 
@@ -341,6 +447,61 @@ Cursor Up goes up one command and PgUp s
 above. You can, of course, rebind:<br />
 <tt>bind '^XA=search-history-up'</tt>
 ----
+ToC: amend-git-branch
+Title: Display the current git branch in the prompt
+
+<p style="font-size:small;">Originally posted as wlog entry and
+ for Plänet Debian and Plänet Commanline on 2012-07-14T22:17:01Z</p>
+<p class="boxhead">Originally <a
+ href="http://web.archive.org/web/20161008060953/http://www.perrier.eu.org/weblog/2012/07/15#cool-prompt">posted
+ by bubulle</a> on Planet Debian, a shell prompt that displays the
+ current git branch, in colour on some terminals, after the current
+ working directory. The following snippet does similar things for
+ <a href="@@RELPATH@@mksh.htm">mksh</a> users, except it doesn’t
+ redefine your prompt but amend it — just throw it at the bottom of
+ your <tt>~/.mkshrc</tt> before that last line beginning with a colon
+ (copy from <a href="https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=alioth/mksh.git;a=blob;f=debian/.mkshrc;hb=HEAD"><tt>/etc/skel/.mkshrc</tt></a>
+ if you haven’t done that yet):</p><div class="boxtext">
+ <pre>
+	function parse_git_branch {
+		git branch 2&gt;/dev/null | sed -n '/^\* \(.*\)/s//(\1)/p'
+	}
+
+	function amend_prompt_with_git {
+		[[ -o utf8-mode ]]; local u=$?
+		set +U
+		local p q='$(parse_git_branch)' r
+
+		if [[ $TERM = @(xterm-color|xterm|screen*) ]]; then
+			if [[ ${PS1:1:1} = $'\r' ]]; then
+				p=${PS1:0:1}
+			else
+				p=$'\001'
+				PS1=$p$'\r'$PS1
+			fi
+			q=$p$'\e[1;33m'$p$q$p$'\e[0m'$p
+		fi
+
+		p=${PS1%%*( )[#$]*( )}
+		if [[ $p != "$PS1" ]]; then
+			# prompt ends with space + #-or-$ + space, we can amend
+			r=${PS1: ${#p}}
+			PS1=$p$q$r
+		fi
+
+		(( u )) || set -U
+	}
+	amend_prompt_with_git
+	unset -f amend_prompt_with_git
+</pre>
+</div><p class="boxfoot">The indirection by use of a function is not
+ strictly necessary but allows the use of locals. I took the liberty
+ of adding an asterisk after “screen” to match the GNU/Linux nonsense
+ of having <tt>TERM=screen.xterm</tt> or somesuch.</p>
+<p>The insertion point is right before the trailing space plus (either
+ dollar or number sign) plus space, i.e. after the cwd from the default
+ prompt. YMMV so you may need to customise that, or ask me to help.</p>
+----
 ToC: current
 Title: Can mksh set the title of the window according to the command running?
 
@@ -380,7 +541,7 @@ Title: What about programmable tab compl
 The shell itself provides static deterministic tab completion.
 However, you can use hooks like reprogramming the Tab key to a
 command line editor macro, and using the <tt>evaluate-region</tt>
-editor command (modulo a bugfix) together with <tt>quote-region</tt> and shell functions to
+editor command together with <tt>quote-region</tt> and shell functions to
 implement a programmable completion engine. Multiple people have
 been considering doing so in our IRC channel; we’ll hyperlink to
 these engines when they are available.
@@ -395,10 +556,22 @@ Title: How POSIX compliant is mksh? Also
  (<tt>set -o posix</tt>) explicitly, which also disables brace expansion upon
  being enabled (use <tt>set -o braceexpand</tt> to reenable if needed).</p>
 <p>For the purpose of POSIX, mksh supports only the <tt>C</tt> locale. mksh’s
- <tt>utf8-mode</tt> (which only supports the BMP (Basic Multilingual Plane) of
- UCS and maps raw octets into the U+EF80‥U+EFFF wide character range; see
- <tt>Arithmetic expressions</tt> in mksh(1) for details) <em>must</em> stay
- disabled in POSIX mode (it is disabled upon enabling POSIX mode in R56+).</p>
+ <tt>utf8-mode</tt> <em>must</em> stay disabled in POSIX mode (it was disabled
+ upon enabling POSIX mode in R56‥R59c but decoupled again with R59d).</p>
+<p>EBCDIC interacts with <tt>utf8-mode</tt> in a special way: UTF-EBCDIC is
+ not used by anyone, we cannot use UCS-2/4 in the shell, so “nega-UTF-8”, a
+ scheme in which UTF-8 calculations are done on the octets converted per the
+ current EBCDIC codepage to “extended ASCII”.</p>
+<p>The shell’s <tt>utf8-mode</tt> <em>before</em> mksh R60 supported only the
+ BMP (Basic Multilingual Plane) of UCS and mapped raw (extended ASCII) octets,
+ i.e. these which are not valid UTF-8 BMP codepoints) into the U+EF80‥U+EFFF
+ range, which is allocated at the CSUR for this purpose. (It otherwise lies in
+ the PUA; however, there is ambiguity if encountering those UTF-8-encoded, so
+ it changed for R60.) The <tt>Arithmetic expressions</tt> and <tt>CAVEATS</tt>
+ sections in mksh(1) contain more details about encoding and mapping.</p>
+<p>As of R60, <tt>utf8-mode</tt> maps “raw octets” to U-001BBB80‥U-001BBBFF,
+ which is outside the UCS and therefore collision-free, using full
+ 21-bit UTF-8 (without explicit CESU-8 compatibility).</p>
 <p class="boxhead">The following POSIX sh-compatible code toggles the
  <tt>utf8-mode</tt> option dependent on the current POSIX locale, for mksh
  to allow using the UTF-8 mode, within the constraints outlined above, in
@@ -406,18 +579,21 @@ Title: How POSIX compliant is mksh? Also
 <div class="boxtext">
  <pre>
 	case ${KSH_VERSION:-} in
-	*MIRBSD KSH*|*LEGACY KSH*)
+	*MIRBSD\ KSH*|*LEGACY\ KSH*)
 		case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
 		*[Uu][Tt][Ff]8*|*[Uu][Tt][Ff]-8*) set -U ;;
 		*) set +U ;;
 		esac ;;
 	esac
- </pre>
-</div><p class="boxfoot">In near future, (UTF-8) locale tracking will
- be implemented, though.</p>
+</pre>
+</div><p class="boxfoot">This only applies to mksh before R60 without
+ locale tracking and is obsolete as of R60’s release, except for backwards
+ compatibility. <strong>This build of mksh already enables it.</strong></p>
 <p>The shell is pretty close to POSIX, when run as <tt>lksh -o posix</tt>
  under the "C" locale it is intended to match. It does not do everything
  like other POSIX-compatible or ‑compliant shells, though.</p>
+<p>Like pretty much all other POSIX-compatible shells, builtins are
+ <em>independent</em> of paths and always recognised in mksh.</p>
 ----
 ToC: function-local-scopes
 Title: What differences in function-local scopes are there?
@@ -447,7 +623,7 @@ Title: What differences in function-loca
 		\\builtin alias unset=unset_compat
 		;;
 	esac
- </pre>
+</pre>
 </div><p class="boxfoot">When a local variable is created (e.g. using
  <tt>local</tt>, <tt>typeset</tt>, <tt>integer</tt> or
  <tt>\\builtin typeset</tt>) it does not, like in other shells, inherit
@@ -462,6 +638,86 @@ Title: I get an error in this regex comp
  … becomes…<br />
  <tt>[[ foo = *@(foo|bar)*baz* ]]</tt></p>
 ----
+ToC: cfor
+Title: How can I do C-style “for” loops?
+
+<p>The <tt>for</tt> loop in shell is always a “foreach” loop,
+ not a C-style “for” loop. However, you <em>can</em> use the
+ <tt>while</tt> loop.</p>
+<p class="boxhead">The following three constructs are equivalent:
+ the first is using the GNU bash‑ and AT&amp;T ksh93 C-style for
+ loop, which the second naïvely transfers into a <tt>while</tt>
+ loop that the third example does natively:</p>
+<div class="boxtext">
+ <pre>
+	#     expr1    expr2    expr3
+	for ((idx = 9; idx &gt; 6; --idx)); do
+		echo $idx
+	done
+
+	idx=9
+	while (( idx &gt; 6 )); do
+		echo $idx
+		(( --idx ))
+	done
+
+	idx=10
+	while (( --idx &gt; 6 )); do
+		echo $idx
+	done
+</pre>
+</div><p class="boxfoot">The latter two also run on bash and ksh93,
+ so it’s better to use that anyway.</p>
+<p>The last (native) example rolls the “expr3” part, which otherwise
+ is run at the end of every body, into the loop condition (“expr2”)
+ accounting for the extra first execution by “undoing” its effect in
+ the “expr1” initialisation, here by pre-incrementing as the “expr3”
+ is a decrement.</p>
+<p class="boxhead">Classic counting loops look like this:</p>
+<div class="boxtext">
+ <pre>
+	i=-1
+	while (( ++i &lt; 6 )); do
+		(( j = i ))
+		while (( ++j &lt; 6 )); do
+			print -r -- $i, $j
+		done
+	done
+</pre>
+</div><p class="boxfoot">Here, the increment is offset by a pre-decrement.</p>
+----
+ToC: local-arrays
+Title: How can I do local arrays?
+
+<p class="boxhead">mksh supports function-local arrays with an “onion
+ model” in which you can basically create (and unset) a local variable
+ in a function, which may of course be array-typed:</p>
+<div class="boxtext">
+ <pre>
+	function foo {
+		a[1]=x		# modifies the outer array
+		echo ${a[*]}
+		local a		# makes a local variable…
+		set -A a	# … of type array…
+		a[0]=yz		# modifies the inner array
+		echo ${a[*]}
+		unset a		# removes the local variable
+		echo ${a[*]}
+		a[2]=!		# modifies the unveiled outer again
+		echo ${a[*]}
+	}
+	set -A a -- 1 2 3 4 5
+	echo ${a[*]}		# shows the outer array before…
+	foo
+	echo ${a[*]}		# …and after the function ran
+</pre>
+</div><p class="boxfoot">This also works with <tt>a=(…)</tt> and
+ in POSIX-style functions <tt>foo() { …; }</tt> (in mksh, although
+ not in AT&amp;T ksh which uses a different scope model) and with
+ appending <tt>a+=(…)</tt> (and <tt>set -A a+ -- …</tt>), and even
+ no-truncation array assignments <tt>set +A a -- …</tt> behave in
+ a consistent manner.</p>
+----
 ToC: trim-vector
 Title: ${@?}: bad substitution
 
@@ -471,12 +727,24 @@ Title: ${@?}: bad substitution
  applied to <tt>$1</tt> only and <tt>${@?}</tt> can be replaced
  with a test whether <tt>$# -eq 0</tt>.</p>
 ----
+ToC: lineno
+Title: error line numbers are… somewhat close
+
+<p>For block constructs (such as <tt>if</tt>) and function calls,
+ the shell currently reports the line number of the call site (the
+ trailing <tt>fi</tt>), not the line with the command where the
+ actual error occurred.</p>
+<p>While unfortunate, the line numbers are currently only updated
+ when reading commands, not tracked through the internal AST. This
+ is not easy to change and therefore will only be fixed as part of
+ introduction of BASH_SOURCE, FUNCNAME, BASH_LINENO, etc.</p>
+----
 ToC: extensions-to-avoid
 Title: Are there any extensions to avoid?
 
-<p>GNU <tt>bash</tt> supports “<tt>&amp;&gt;</tt>” (and “|&amp;”) to redirect
- both stdout and stderr in one go, but this breaks POSIX and Korn Shell syntax;
- use POSIX redirections instead:</p>
+<p>GNU <tt>bash</tt> supports “<tt>&amp;&gt;</tt>” (and “<tt>|&amp;</tt>”)
+ to redirect both stdout and stderr in one go, but this breaks POSIX
+ and Korn Shell syntax; use POSIX redirections instead:</p>
 <table border="1" cellpadding="3">
  <tr><td>GNU bash</td><td>
   <tt>foo |&amp; bar |&amp; baz &amp;&gt;log</tt>
@@ -496,7 +764,7 @@ Title: Something is going wrong with my
 <div class="boxtext">
  <pre>
 	bar | baz | while read foo; do ...; done
- </pre>
+</pre>
 </div><p class="boxfoot">Note that <tt>exit</tt> in the inner loop will
  also only exit the subshell and not the original shell. Likewise, if the
  code is inside a function, <tt>return</tt> in the inner loop will only
@@ -507,7 +775,7 @@ Title: Something is going wrong with my
 	bar | baz |&amp;
 	while read -p foo; do ...; done
 	exec 3&gt;&amp;p; exec 3&gt;&amp;-
- </pre>
+</pre>
 </div><p class="boxfoot">If <tt>read</tt> is run in a way such as
  <tt>while read foo; do ...; done</tt> then leading whitespace will be
  removed (IFS) and backslashes processed. You might want to use
@@ -521,7 +789,7 @@ Title: Something is going wrong with my
 	    while IFS= read -d '' -pr filename; do
 		print -r -- "found &lt;${filename#./}&gt;"
 	done
- </pre>
+</pre>
 </div>
 ----
 ToC: command-alias
@@ -532,6 +800,15 @@ This is because AT&amp;T ksh93 ships a p
 put this into your <tt>~/.mkshrc</tt>
 (note the space before the closing single quote)
 ----
+ToC: builtin-cat
+Title: Didn’t there used to be a cat(1) builtin?
+
+<p>Up to and including mksh R59c, we indeed shipped a built-in cat(1)
+ inside mksh; this was added originally because Android did not have
+ one <em>at all</em> (but they have since imported a BSD cat). While
+ it could speed up some sh scripts correct signal handling is hard to
+ get right, so (with regret) it was removed in 2021. 🙀</p>
+----
 ToC: builtin-rename
 Title: “rename” doesn’t work as expected!
 
@@ -539,6 +816,7 @@ Title: “rename” doesn’t work as ex
  thin wrapper around the rename(2) syscall. It receives two pathnames,
  source and destination where the first is then atomically renamed to
  the latter. It does not move, i.e. fails for different filesystems.</p>
+<p>The builtin may be absent if your OS doesn’t have rename(2), e.g. Xenix.</p>
 <p>The GNU package <tt>util-linux</tt> has a different <tt>rename</tt>
  command. If you wish to invoke an external utility (in favour over a
  builtin), you can use <tt>dot.mkshrc</tt>’s function <tt>enable</tt>
@@ -546,23 +824,39 @@ Title: “rename” doesn’t work as ex
 <pre>alias rename="$(whence -p rename)"</pre>
 ----
 ToC: builtin-sleep
-Title: “sleep” does not accept ‘m’ for minutes!
+Title: Didn’t there used to be a sleep(1) builtin?
 
-<p>mksh contains a <tt>sleep</tt> built-in utility, in order to be
- able to offer sub-second sleep to shell scripts for most platforms.
- (It does not exist if the platform lacks select(2) — which should
- be rare.)</p>
-<p>GNU coreutils contains a sleep implementation accepting suffixed
- numbers. If you wish to invoke an external utility (in favour over a
- builtin), you can use <tt>dot.mkshrc</tt>’s function <tt>enable</tt>
- or put something along the following lines into <tt>~/.mkshrc</tt>:</p>
-<pre>alias sleep="$(whence -p sleep)"</pre>
-<pre>timer() { sleep $(($1*60${2:++$2})); } # timer mins [secs]</pre>
-<pre>timer() {
-	local arg=${1/m/'*60+'}
-	[[ $arg = *+ ]] &amp;&amp; arg+=0
-	sleep $(($arg)
-}</pre>
+<p>Up to and including mksh R59c, we indeed shipped a subsecond-capable
+ select(2)-based built-in sleep(1). This got originally added because
+ too many platforms do not support sub-second sleep, which nowadays is
+ of less concern. It also led to users complaining about lack for system
+ *ahem* GNU extensions, but the cause of its demise is that getting signal
+ handling right, in a portable way and without too many syscalls (there’s
+ a threshold over which fork+exec is cheaper!), isn’t feasible if even at
+ all possible.</p>
+<p>The MirOS Project now ships <a href="@@RELPATH@@subprj.htm#sleep">a
+ portable sleep</a> which similarly is select(2)-based and capable of
+ subsecond sleep but in addition supports all GNU extensions related to
+ specifying the amount of time to sleep. It will work on <em>at least</em>
+ all platforms on which mksh had a builtin before. Please install this
+ if your operating system lacks a good enough sleep(1) utility.</p>
+<p>Note that, if your OS lacks select(2), you’ll lose out either way.
+ In that case, GNU coreutils’ sleep, which is built on older syscalls,
+ may work if the copyleft licence isn’t a showstopper for you.</p>
+----
+ToC: arith-import
+Title: Some integer variables are 0?
+
+<p class="boxhead">To mitigate potential exploits, variables imported
+ from the environment are not trusted in arithmetic context; that is…</p>
+<div class="boxtext">
+ <pre>
+	foo=1+1 mksh -c 'integer foo; print $foo'
+	foo=1+1 mksh -c 'integer foo=$foo; print $foo'
+</pre>
+</div><p class="boxfoot">… will lose the value in the first line,
+ while the second line explicitly “untaints”, to use a Perl term,
+ the content. Purely numeric values will pass, though.</p>
 ----
 ToC: string-concat
 Title: “+=” behaves differently from other shells
@@ -624,7 +918,7 @@ Title: I use “set -eo pipefail” and
 	for x in 1 2; do
 		false &amp;&amp; echo $x
 	done | cat
- </pre>
+</pre>
 </div><p class="boxfoot">This is because, while the <tt>&amp;&amp;</tt>
  ensures that the inner command’s failure is not taken, it sets the entire
  <tt>for</tt>‥<tt>done</tt> loop’s errorlevel, which is passed on by
@@ -635,18 +929,27 @@ Title: I use “set -eo pipefail” and
 ToC: faq
 Title: My question is not answered here!
 
-Do read the mksh(1) manual page. You might also wish to read the <a
- href="@@RELPATH@@ksh-chan.htm">homepage of the <tt>#ksh</tt> IRC channel
-on Freenode</a> which lists several resources for Korn or POSIX-compatible
-shells in general. Or, <a href="#contact">contact</a> us (developer and
-users), for example via IRC.
+Do read the mksh(1) and lksh(1) manual pages and the <a
+ href="@@RELPATH@@mksh.htm">homepage</a> and other pages like the <a
+ href="@@RELPATH@@mksh_oe.htm">operating environment-specific notes
+ for mksh</a> overview page. You might also wish to read the <a
+ href="@@RELPATH@@ksh-chan.htm">homepage of the <tt>#ksh</tt> IRC channel</a>
+which lists several resources for Korn or POSIX-compatible shells in general.
+Or, <a href="#contact">contact</a> us (developer and users).
 ----
 ToC: contact
-Title: How do I contact you (to say thanks)?
+Title: How do I contact you (to say thanks, for bugreports and questions)?
 
-You can say hi in the <tt>#!/bin/mksh</tt> channel on Freenode <a
- href="@@RELPATH@@irc.htm">IRC</a>, although a <a
- href="@@RELPATH@@danke.htm">donation</a> wouldn’t be amiss ☺ The <a
- href="http://www.mail-archive.com/miros-mksh@mirbsd.org/">mailing
-list</a> can also be used.
+<p>You can say hi in the <tt>#!/bin/mksh</tt> channel on <a
+ href="@@RELPATH@@irc.htm">IRC</a> (OFTC, for now).
+<br />The <a href="@@RELPATH@@rss.htm#lists">mailing list</a> can also
+ be used for this. The <a href="#faq">extra resources</a> from the FAQ
+ entry just one above should also be considered ;-)</p>
+<p>If you insist on sending a bugreport, IRC and the mailing list are
+ great places for that; <a href="https://launchpad.net/mksh">Launchpad</a>,
+ an external gratis service provided by a company, can also be used if you
+ like web-based issue trackers better.</p>
+<p>The primary developer can be reached via Fediverse at
+ <tt>@mirabilos@toot.mirbsd.org</tt> (bonus, alpha status) or
+ <tt>@mirabilos@ipv6.camp</tt> (backup account).</p>
 ----
--- mksh-59c.orig/os2.c
+++ mksh-59c/os2.c
@@ -1,7 +1,7 @@
 /*-
  * Copyright (c) 2015, 2017, 2020
  *	KO Myung-Hun <komh@chollian.net>
- * Copyright (c) 2017, 2020
+ * Copyright (c) 2017, 2020, 2022
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -24,15 +24,12 @@
 #define INCL_DOS
 #include <os2.h>
 
-#include "sh.h"
-
 #include <klibc/startup.h>
-#include <errno.h>
-#include <io.h>
-#include <unistd.h>
 #include <process.h>
 
-__RCSID("$MirOS: src/bin/mksh/os2.c,v 1.11 2020/10/01 21:13:45 tg Exp $");
+#include "sh.h"
+
+__RCSID("$MirOS: src/bin/mksh/os2.c,v 1.23 2024/06/27 12:52:14 tg Exp $");
 
 struct a_s_arg {
 	union {
@@ -43,7 +40,7 @@ struct a_s_arg {
 		int i;
 		void *p;
 	} arg;
-	bool isint;
+	Wahr isint;
 };
 
 static void remove_trailing_dots(char *, size_t);
@@ -68,6 +65,7 @@ static void cleanup(void);
 #define KLIBC_ARG_RESPONSE_EXCLUDE	\
 	(__KLIBC_ARG_DQUOTE | __KLIBC_ARG_WILDCARD | __KLIBC_ARG_SHELL)
 
+/* pre-initio() */
 static void
 response(int *argcp, const char ***argvp)
 {
@@ -106,14 +104,15 @@ response(int *argcp, const char ***argvp
 			line = malloc(filesize + /* type */ 1 + /* NUL */ 1);
 			if (!line) {
  exit_out_of_memory:
-				fputs("Out of memory while reading response file\n", stderr);
+				SHIKATANAI write(2,
+				    SC("mksh: out of memory reading response file\n"));
 				exit(255);
 			}
 
 			line[0] = __KLIBC_ARG_NONZERO | __KLIBC_ARG_RESPONSE;
 			l = line + 1;
 			while (fgets(l, (filesize + 1) - (l - (line + 1)), f)) {
-				p = strchr(l, '\n');
+				p = ucstrchr(l, '\n');
 				if (p) {
 					/*
 					 * if a line ends with a backslash,
@@ -148,7 +147,8 @@ response(int *argcp, const char ***argvp
 			free(line);
 
 			if (ferror(f)) {
-				fputs("Cannot read response file\n", stderr);
+				SHIKATANAI write(2,
+				    SC("mksh: can't read response file\n"));
 				exit(255);
 			}
 
@@ -163,6 +163,7 @@ response(int *argcp, const char ***argvp
 	*argvp = new_argv;
 }
 
+/* pre-initio() */
 static void
 init_extlibpath(void)
 {
@@ -182,6 +183,7 @@ init_extlibpath(void)
 	}
 }
 
+/* pre-initio() */
 void
 os2_init(int *argcp, const char ***argvp)
 {
@@ -287,7 +289,7 @@ access(const char *name, int mode)
 #define MAX_X_SUFFIX_LEN	4
 
 static const char *x_suffix_list[] =
-    { "", ".ksh", ".exe", ".sh", ".cmd", ".com", ".bat", NULL };
+    { "", ".exe", ".ksh", ".sh", ".cmd", ".com", ".bat", NULL };
 
 /* call fn() by appending executable extensions */
 static int
@@ -322,7 +324,7 @@ access_ex(int (*fn)(const char *, int),
 
 	arg.fn.i = fn;
 	arg.arg.i = mode;
-	arg.isint = true;
+	arg.isint = Ja;
 	return (access_stat_ex(name, &arg));
 }
 
@@ -335,7 +337,7 @@ stat_ex(int (*fn)(const char *, struct s
 
 	arg.fn.p = fn;
 	arg.arg.p = buffer;
-	arg.isint = false;
+	arg.isint = Nee;
 	return (access_stat_ex(name, &arg));
 }
 
@@ -362,7 +364,7 @@ real_exec_name(const char *name)
 
 	arg.fn.p = &test_exec_exist;
 	arg.arg.p = (void *)(&real_name);
-	arg.isint = false;
+	arg.isint = Nee;
 	return (access_stat_ex(name, &arg) ? name : real_name);
 }
 
@@ -514,9 +516,11 @@ static void
 add_temp(const char *name)
 {
 	struct temp *tp;
+	size_t len;
 
-	tp = alloc(offsetof(struct temp, tffn[0]) + strlen(name) + 1, APERM);
-	memcpy(tp->tffn, name, strlen(name) + 1);
+	len = strlen(name) + 1U;
+	tp = alloc(mbccFAMsz(struct temp, tffn, len), APERM);
+	memcpy(tp->tffn, name, len);
 	tp->next = templist;
 	templist = tp;
 }
@@ -577,8 +581,7 @@ getdrvwd(char **cpp, unsigned int drvltr
 	}
 
 	/* allocate 'X:/' plus sz plus NUL */
-	checkoktoadd((size_t)sz, (size_t)4);
-	cp = aresize(*cpp, (size_t)sz + (size_t)4, ATEMP);
+	cp = aresize1(*cpp, sz, 4, ATEMP);
 	cp[0] = ksh_toupper(drvltr);
 	cp[1] = ':';
 	cp[2] = '/';
--- mksh-59c.orig/rlimits.opt
+++ mksh-59c/rlimits.opt
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2013, 2015, 2019
+ * Copyright (c) 2013, 2015, 2019, 2021
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -21,7 +21,7 @@
  */
 
 @RLIMITS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/rlimits.opt,v 1.5 2020/07/24 20:11:18 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/rlimits.opt,v 1.6 2021/01/10 18:44:06 tg Exp $");
 @RLIMITS_ITEMS
 #define FN(lname,lid,lfac,lopt) (const struct limits *)(&rlimits_ ## lid),
 @@
@@ -94,6 +94,9 @@ FN("threadsperprocess", RLIMIT_THREADS,
 >e|RLIMIT_NICE
 FN("maxnice", RLIMIT_NICE, 1
 
+>R|RLIMIT_RTTIME
+FN("rttime(ms)", RLIMIT_RTTIME, 1
+
 >r|RLIMIT_RTPRIO
 FN("maxrtprio", RLIMIT_RTPRIO, 1
 
--- mksh-59c.orig/sh.h
+++ mksh-59c/sh.h
@@ -11,7 +11,7 @@
 /*-
  * Copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *	       2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *	       2019, 2020
+ *	       2019, 2020, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -30,23 +30,35 @@
  * of said person’s immediate fault when using the work as intended.
  */
 
-#ifdef __dietlibc__
-/* XXX imake style */
-#define _BSD_SOURCE	/* live, BSD, live❣ */
+#define MKSH_SH_H_ID "$MirOS: src/bin/mksh/sh.h,v 1.1032 2024/07/26 18:39:07 tg Exp $"
+
+#ifdef MKSH_USE_AUTOCONF_H
+/* things that “should” have been on the command line */
+#include "autoconf.h"
+#undef MKSH_USE_AUTOCONF_H
 #endif
 
 #if HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 #include <sys/types.h>
-#if HAVE_BOTH_TIME_H
+#if HAVE_BOTH_TIME_H && HAVE_SELECT_TIME_H
 #include <sys/time.h>
 #include <time.h>
-#elif HAVE_SYS_TIME_H
+#elif HAVE_SYS_TIME_H && HAVE_SELECT_TIME_H
 #include <sys/time.h>
 #elif HAVE_TIME_H
 #include <time.h>
 #endif
+#if HAVE_SYS_BSDTYPES_H
+#include <sys/bsdtypes.h>
+#endif
+#if HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#if HAVE_SYS_FILE_H
+#include <sys/file.h>
+#endif
 #include <sys/ioctl.h>
 #if HAVE_SYS_SYSMACROS_H
 #include <sys/sysmacros.h>
@@ -57,14 +69,35 @@
 #if HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
+#if HAVE_SYS_PTEM_H
+/* prerequisite */
+#include <sys/stream.h>
+/* struct winsize */
+#include <sys/ptem.h>
+#endif
+#if defined(HAVE_GETRANDOM) && (HAVE_GETRANDOM)
+#include <sys/random.h>
+#endif
 #if HAVE_SYS_RESOURCE_H
 #include <sys/resource.h>
 #endif
 #include <sys/stat.h>
+#if !HAVE_GETRUSAGE
+#include <sys/times.h>
+#endif
 #include <sys/wait.h>
+#ifdef DEBUG
+#include <assert.h>
+#endif
+#if HAVE_SELECT && HAVE_BSTRING_H
+#include <bstring.h>
+#endif
 #include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#if HAVE_GRP_H
+#include <grp.h>
+#endif
 #if HAVE_IO_H
 #include <io.h>
 #endif
@@ -75,9 +108,18 @@
 #include <libutil.h>
 #endif
 #include <limits.h>
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC) || HAVE_POSIX_UTF8_LOCALE
+#include <locale.h>
+#if HAVE_POSIX_UTF8_LOCALE
+#include <langinfo.h>
+#endif
+#endif
 #if HAVE_PATHS_H
 #include <paths.h>
 #endif
+#ifdef MKSH_POLL_FOR_PAUSE
+#include <poll.h>
+#endif
 #ifndef MKSH_NOPWNAM
 #include <pwd.h>
 #endif
@@ -108,18 +150,31 @@
 #include <ulimit.h>
 #endif
 #include <unistd.h>
-#if HAVE_VALUES_H
-#include <values.h>
-#endif
 #ifdef MIRBSD_BOOTFLOPPY
 #include <wchar.h>
 #endif
 
-/* monkey-patch known-bad offsetof versions to quell a warning */
-#if (defined(__KLIBC__) || defined(__dietlibc__)) && \
-    ((defined(__GNUC__) && (__GNUC__ > 3)) || defined(__NWCC__))
-#undef offsetof
-#define offsetof(s,e)		__builtin_offsetof(s, e)
+#undef MBSDINT_H_SKIP_CTAS
+#ifndef MKSH_DO_MBI_CTAS
+#define MBSDINT_H_SKIP_CTAS
+#endif
+/* formatting routines assume this */
+#define MBSDINT_H_WANT_PTR_IN_SIZET 1
+#define MBSDINT_H_WANT_SIZET_IN_LONG 1
+/* POSIX guarantees a 32-bit int */
+#define MBSDINT_H_WANT_INT32 1
+/* the code cannot cope without yet */
+#define MBSDINT_H_WANT_SAFEC 1
+#include "mbsdcc.h"
+#include "mbsdint.h"
+
+/* monkey-patch nil pointer constant */
+#undef NULL
+#define NULL mbnil
+
+/* conflict with GCC attributes; fixed in later dietlibcs */
+#ifdef __dietlibc__
+#undef __noinline__
 #endif
 
 #undef __attribute__
@@ -138,11 +193,6 @@
 #else
 #define MKSH_A_NORETURN		/* nothing */
 #endif
-#if HAVE_ATTRIBUTE_PURE
-#define MKSH_A_PURE		__attribute__((__pure__))
-#else
-#define MKSH_A_PURE		/* nothing */
-#endif
 #if HAVE_ATTRIBUTE_UNUSED
 #define MKSH_A_UNUSED		__attribute__((__unused__))
 #else
@@ -192,22 +242,60 @@
 #define __SCCSID(x)		__IDSTRING(sccsid,x)
 #endif
 
-#ifdef EXTERN
-__RCSID("$MirOS: src/bin/mksh/sh.h,v 1.904 2020/10/31 03:53:06 tg Exp $");
-#endif
-#define MKSH_VERSION "R59 2020/10/31"
+#define MKSH_VERSION "R59 2024/07/26"
 
-/* arithmetic types: C implementation */
-#if !HAVE_CAN_INTTYPES
-#if !HAVE_CAN_UCBINTS
-typedef signed int int32_t;
-typedef unsigned int uint32_t;
+/* shell types */
+typedef unsigned char kby;		/* byte */
+typedef unsigned int kui;		/* wchar; kby or EOF; ⊇k32; etc. */
+/* MBSDINT_H_WANT_INT32 guaranteed; u_int rank also guaranteed */
+typedef unsigned int k32;		/* 32-bit arithmetic (hashes etc.) */
+/* for use with/without 32-bit masking */
+typedef unsigned long kul;		/* long, arithmetic */
+typedef signed long ksl;		/* signed long, arithmetic */
+#define KUL_FM ULONG_MAX
+#define KUL_HM LONG_MAX
+/* if mbiHUGE is wider than long, then that, else long */
+#if mbiHUGE_UBITS > mbiMASK__BITS(ULONG_MAX)
+#define MKSH_HAVE_HUGE
+typedef mbiHUGE_U kuH;
+typedef mbiHUGE_S ksH;
+#define KUH_FM mbiHUGE_U_MAX
+#define KUH_HM mbiHUGE_S_MAX
+#else
+#undef MKSH_HAVE_HUGE
+typedef kul kuH;
+typedef ksl ksH;
+#define KUH_FM ULONG_MAX
+#define KUH_HM LONG_MAX
+#endif
+
+#define KBY(c)	((kby)(KUI(c) & 0xFFU))	/* byte, truncated if necessary */
+#define KBI(c)	((kui)(KUI(c) & 0xFFU))	/* byte as u_int, truncated */
+#define KUI(u)	((kui)(u))		/* int as u_int, not truncated */
+
+#define K32_HM		0x7FFFFFFFUL
+#define K32_FM		0xFFFFFFFFUL
+
+/*XXX TODO:
+ * arithmetic type need not be long, it can be unsigned int if we can
+ * guarantee that it’s exactly⚠ 32 bit wide; in the !lksh case, never
+ * shall a signed integer be needed; for lksh signed arithmetic, only
+ * I think, the values need to be converted temporarily; !lksh signed
+ * arithmetic is instead done in unsigned; kul → kua (ksl → ksa lksh)
+ */
+#ifdef MKSH_LEGACY_MODE
+#define KUA_HM		LONG_MAX
+#define KUA_FM		ULONG_MAX
 #else
-typedef u_int32_t uint32_t;
-#endif
+#define KUA_HM		K32_HM
+#define KUA_FM		K32_FM
 #endif
 
 /* arithmetic types: shell arithmetics */
+
+/* new arithmetics tbd, using mbiMA_* */
+
+/* older arithmetics, to be replaced later */
 #ifdef MKSH_LEGACY_MODE
 /*
  * POSIX demands these to be the C environment's long type
@@ -220,33 +308,27 @@ typedef unsigned long mksh_uari_t;
  * integer wraparound, even across division and modulo, for
  * any shell code using them, is guaranteed.
  */
+#if HAVE_CAN_INTTYPES
 typedef int32_t mksh_ari_t;
 typedef uint32_t mksh_uari_t;
-#endif
-
-/* boolean type (no <stdbool.h> deliberately) */
-typedef unsigned char mksh_bool;
-#undef bool
-/* false MUST equal the same 0 as written by static storage initialisation */
-#undef false
-#undef true
-/* access macros for boolean type */
-#define bool		mksh_bool
-/* values must have identity mapping between mksh_bool and short */
-#define false		0
-#define true		1
-/* make any-type into bool or short */
-#define tobool(cond)	((cond) ? true : false)
-
-/* char (octet) type: C implementation */
-#if !HAVE_CAN_INT8TYPE
-#if !HAVE_CAN_UCBINT8
-typedef unsigned char uint8_t;
 #else
-typedef u_int8_t uint8_t;
+/* relies on compile-time asserts and CFLAGS to validate that */
+typedef signed int mksh_ari_t;
+typedef unsigned int mksh_uari_t;
+#define INT32_MIN INT_MIN
+#define INT32_MAX INT_MAX
+#define UINT32_MAX UINT_MAX
 #endif
 #endif
 
+/* new arithmetics in preparation */
+
+/* boolean type (no <stdbool.h> deliberately) */
+typedef unsigned char Wahr;
+#define Ja		1U
+#define Nee		0U
+#define isWahr(cond)	((cond) ? Ja : Nee)
+
 /* other standard types */
 
 #if !HAVE_SIG_T
@@ -258,10 +340,6 @@ typedef void (*sig_t)(int);
 typedef MKSH_TYPEDEF_SIG_ATOMIC_T sig_atomic_t;
 #endif
 
-#ifdef MKSH_TYPEDEF_SSIZE_T
-typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
-#endif
-
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 #define MKSH_SHF_NO_INLINE
 #endif
@@ -278,12 +356,8 @@ typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
 #undef PRINT		/* LynxOS defines that somewhere */
 #undef flock		/* SCO UnixWare defines that to flock64 but ENOENT */
 
-
 #ifndef MKSH_INCLUDES_ONLY
 
-/* compile-time assertions */
-#define cta(name,expr)	struct cta_ ## name { char t[(expr) ? 1 : -1]; }
-
 /* EBCDIC fun */
 
 /* see the large comment in shf.c for an EBCDIC primer */
@@ -295,16 +369,12 @@ typedef MKSH_TYPEDEF_SSIZE_T ssize_t;
 # if __CHARSET_LIB && defined(MKSH_EBCDIC)
 #  error "Please compile without -E argument to Build.sh for ASCII!"
 # endif
-# if __CHARSET_LIB && !defined(_ENHANCED_ASCII_EXT)
-   /* go all-out on ASCII */
-#  define _ENHANCED_ASCII_EXT 0xFFFFFFFF
-# endif
 #endif
 
 /* extra types */
 
-/* getrusage does not exist on OS/2 kLIBC */
-#if !HAVE_GETRUSAGE && !defined(__OS2__)
+/* getrusage does not exist on OS/2 kLIBC and is stubbed on SerenityOS */
+#if !HAVE_GETRUSAGE
 #undef rusage
 #undef RUSAGE_SELF
 #undef RUSAGE_CHILDREN
@@ -316,6 +386,10 @@ struct rusage {
 	struct timeval ru_utime;
 	struct timeval ru_stime;
 };
+
+extern int ksh_getrusage(int, struct rusage *);
+#else
+#define ksh_getrusage getrusage
 #endif
 
 /* extra macros */
@@ -348,24 +422,25 @@ struct rusage {
 		}							\
 	} while (/* CONSTCOND */ 0)
 #endif
-
-#ifdef MKSH__NO_PATH_MAX
-#undef PATH_MAX
-#else
-#ifndef PATH_MAX
-#ifdef MAXPATHLEN
-#define PATH_MAX	MAXPATHLEN
-#else
-#define PATH_MAX	1024
-#endif
+#ifndef timercmp
+#define timercmp(tvp,uvp,cmp) (((tvp)->tv_sec == (uvp)->tv_sec) ?	\
+	    ((tvp)->tv_usec cmp (uvp)->tv_usec) :			\
+	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
 #endif
+
+/* if this breaks, see sh.h,v 1.954 commit message and diff */
+#ifndef _POSIX_VDISABLE
+/* Linux klibc lacks this definition */
+#define _POSIX_VDISABLE 0xFFU /* unsigned (for cc_t) default (BSD) value */
 #endif
-#ifndef SIZE_MAX
-#ifdef SIZE_T_MAX
-#define SIZE_MAX	SIZE_T_MAX
-#else
-#define SIZE_MAX	((size_t)-1)
+#define KSH_ISVDIS(x,d)	((x) == _POSIX_VDISABLE ? (d) : KBI(x))
+#define KSH_DOVDIS(x)	(x) = _POSIX_VDISABLE
+
+#ifndef S_ISFIFO
+#define S_ISFIFO(m)	((m & 0170000) == 0010000)
 #endif
+#ifndef S_ISCHR
+#define S_ISCHR(m)	((m & 0170000) == 0020000)
 #endif
 #ifndef S_ISLNK
 #define S_ISLNK(m)	((m & 0170000) == 0120000)
@@ -380,7 +455,6 @@ struct rusage {
 #define DEFFILEMODE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
 #endif
 
-
 /* determine ksh_NSIG: first, use the traditional definitions */
 #undef ksh_NSIG
 #if defined(NSIG)
@@ -427,6 +501,32 @@ struct rusage {
 
 #define ksh_sigmask(sig) (((sig) < 1 || (sig) > 127) ? 255 : 128 + (sig))
 
+#if HAVE_SIGACTION
+typedef struct sigaction ksh_sigsaved;
+#define ksh_sighandler(saved) (saved.sa_handler)
+void ksh_sigrestore(int, ksh_sigsaved *);
+#else
+typedef sig_t ksh_sigsaved;
+#define ksh_sighandler(saved) (saved)
+#define ksh_sigrestore(s,svp) ksh_sigset((s), *(svp), NULL)
+#endif
+
+#if HAVE_SIGDESCR_NP
+#define ksh_sigmess(nr) sigdescr_np(nr)
+#elif HAVE_SYS_SIGLIST
+#if !HAVE_SYS_SIGLIST_DECL
+extern const char * const sys_siglist[];
+#endif
+#define ksh_sigmess(nr) sys_siglist[nr]
+#elif HAVE_STRSIGNAL
+#define ksh_sigmess(nr) strsignal(nr)
+#else
+#define ksh_sigmess(nr) NULL
+#endif
+#define ksh_sigmessf(mess) (!(mess) || !*(mess))
+
+/* contract: masks the signal, may restart, not oneshot */
+void ksh_sigset(int, sig_t, ksh_sigsaved *);
 
 /* OS-dependent additions (functions, variables, by OS) */
 
@@ -467,23 +567,23 @@ extern int flock(int, int);
 #define mksh_TIME(tv) gettimeofday(&(tv), NULL)
 #endif
 
-#if !HAVE_GETRUSAGE
-extern int getrusage(int, struct rusage *);
-#endif
-
 #if !HAVE_MEMMOVE
-/* we assume either memmove or bcopy exist, at the moment */
-#define memmove(dst,src,len)	bcopy((src), (dst), (len))
+#undef memmove
+#define memmove rpl_memmove
+void *rpl_memmove(void *, const void *, size_t);
 #endif
 
 #if !HAVE_REVOKE_DECL
 extern int revoke(const char *);
 #endif
 
+#ifndef EOVERFLOW
+#define EOVERFLOW		ERANGE
+#endif
+
 #if defined(DEBUG) || !HAVE_STRERROR
 #undef strerror
 #define strerror		/* poisoned */ dontuse_strerror
-#define cstrerror		/* replaced */ cstrerror
 extern const char *cstrerror(int);
 #else
 #define cstrerror(errnum)	((const char *)strerror(errnum))
@@ -553,7 +653,6 @@ extern int __cdecl setegid(gid_t);
 #define KSH_VTAB	11
 #endif
 
-
 /* some useful #defines */
 #ifdef EXTERN
 # define E_INIT(i) = i
@@ -565,6 +664,11 @@ extern int __cdecl setegid(gid_t);
 
 /* define bit in flag */
 #define BIT(i)		(1U << (i))
+/* check bit(s) */
+#define HAS(v,f)	(((v) & (f)) == (f))
+#define IS(v,f,t)	(((v) & (f)) == (t))
+/* array sizing */
+#undef NELEM
 #define NELEM(a)	(sizeof(a) / sizeof((a)[0]))
 
 /*
@@ -588,6 +692,11 @@ EXTERN const char *safe_prompt; /* safe
 #else
 #define KSH_VERSIONNAME_ISLEGACY	"MIRBSD"
 #endif
+#ifdef DEBUG
+#define KSH_VERSIONNAME_DEBUG		" +DEBUG_dont_ship_to_users"
+#else
+#define KSH_VERSIONNAME_DEBUG		""
+#endif
 #ifdef MKSH_WITH_TEXTMODE
 #define KSH_VERSIONNAME_TEXTMODE	" +TEXTMODE"
 #else
@@ -602,7 +711,8 @@ EXTERN const char *safe_prompt; /* safe
 #define KSH_VERSIONNAME_VENDOR_EXT	""
 #endif
 EXTERN const char initvsn[] E_INIT("KSH_VERSION=@(#)" KSH_VERSIONNAME_ISLEGACY \
-    " KSH " MKSH_VERSION KSH_VERSIONNAME_EBCDIC KSH_VERSIONNAME_TEXTMODE \
+    " KSH " MKSH_VERSION KSH_VERSIONNAME_DEBUG \
+    KSH_VERSIONNAME_EBCDIC KSH_VERSIONNAME_TEXTMODE \
     KSH_VERSIONNAME_VENDOR_EXT);
 #define KSH_VERSION	(initvsn + /* "KSH_VERSION=@(#)" */ 16)
 
@@ -621,44 +731,26 @@ union mksh_ccphack {
 	const char **ro;
 };
 
-/*
- * Evil hack since casting uint to sint is implementation-defined
- */
-typedef union {
-	mksh_ari_t i;
-	mksh_uari_t u;
-} mksh_ari_u;
-
 /* for const debugging */
-#if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
-    !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
+#if defined(DEBUG)
 char *ucstrchr(char *, int);
-char *ucstrstr(char *, const char *);
+const char *cstrchr(const char *, int);
 #undef strchr
-#define strchr ucstrchr
-#define strstr ucstrstr
-#define cstrchr(s,c) ({			\
-	union mksh_cchack in, out;	\
-					\
-	in.ro = (s);			\
-	out.rw = ucstrchr(in.rw, (c));	\
-	(out.ro);			\
-})
-#define cstrstr(b,l) ({			\
-	union mksh_cchack in, out;	\
-					\
-	in.ro = (b);			\
-	out.rw = ucstrstr(in.rw, (l));	\
-	(out.ro);			\
-})
-#define vstrchr(s,c)	(cstrchr((s), (c)) != NULL)
-#define vstrstr(b,l)	(cstrstr((b), (l)) != NULL)
-#else /* !DEBUG, !gcc */
+#define strchr		poisoned_strchr
+#else
+#define ucstrchr(s,c)	strchr((s), (c))
 #define cstrchr(s,c)	((const char *)strchr((s), (c)))
+#endif
+#define vstrchr(s,c)	(cstrchr((s), (c)) != NULL)
+#if defined(DEBUG) || !HAVE_STRSTR
+char *ucstrstr(char *, const char *);
+const char *cstrstr(const char *, const char *);
+#define strstr		poisoned_strstr
+#else
+#define ucstrstr(s,c)	strstr((s), (c))
 #define cstrstr(s,c)	((const char *)strstr((s), (c)))
-#define vstrchr(s,c)	(strchr((s), (c)) != NULL)
-#define vstrstr(b,l)	(strstr((b), (l)) != NULL)
 #endif
+#define vstrstr(b,l)	(cstrstr((b), (l)) != NULL)
 
 #if defined(DEBUG) || defined(__COVERITY__)
 #ifndef DEBUG_LEAKS
@@ -666,8 +758,8 @@ char *ucstrstr(char *, const char *);
 #endif
 #endif
 
-#if (!defined(MKSH_BUILDMAKEFILE4BSD) && !defined(MKSH_BUILDSH)) || (MKSH_BUILD_R != 593)
-#error Must run Build.sh to compile this.
+#if (!defined(MKSH_BUILDMEAT)) || (MKSH_BUILD_R != 599)
+#error Use the documented way to build this.
 extern void thiswillneverbedefinedIhope(void);
 int
 im_sorry_dave(void)
@@ -680,9 +772,9 @@ im_sorry_dave(void)
 /* use this ipv strchr(s, 0) but no side effects in s! */
 #define strnul(s)	((s) + strlen((const void *)s))
 
-#define utf_ptradjx(src,dst) do {					\
-	(dst) = (src) + utf_ptradj(src);				\
-} while (/* CONSTCOND */ 0)
+/* inspired by jupp, where they are in lowercase though */
+#define SC(s)		(s), (sizeof(s) / sizeof(s[0]) - 1U)
+#define SZ(s)		(s), strlen(s)
 
 #if defined(MKSH_SMALL) && !defined(MKSH_SMALL_BUT_FAST)
 #define strdupx(d,s,ap) do {						\
@@ -698,7 +790,7 @@ im_sorry_dave(void)
 	char *strdup_dst = NULL;					\
 									\
 	if (strdup_src != NULL) {					\
-		size_t strdup_len = strlen(strdup_src) + 1;		\
+		size_t strdup_len = strlen(strdup_src) + 1U;		\
 		strdup_dst = alloc(strdup_len, (ap));			\
 		memcpy(strdup_dst, strdup_src, strdup_len);		\
 	}								\
@@ -710,19 +802,32 @@ im_sorry_dave(void)
 									\
 	if (strdup_src != NULL) {					\
 		size_t strndup_len = (n);				\
-		strdup_dst = alloc(strndup_len + 1, (ap));		\
+		strdup_dst = alloc(strndup_len + 1U, (ap));		\
 		memcpy(strdup_dst, strdup_src, strndup_len);		\
 		strdup_dst[strndup_len] = '\0';				\
 	}								\
 	(d) = strdup_dst;						\
 } while (/* CONSTCOND */ 0)
 #endif
+#define strnbdupx(d,s,n,ap,b) do {					\
+	const char *strdup_src = (const void *)(s);			\
+	char *strdup_dst = NULL;					\
+									\
+	if (strdup_src != NULL) {					\
+		size_t strndup_len = (n);				\
+		strdup_dst = strndup_len < sizeof(b) ? (b) :		\
+		    alloc(strndup_len + 1U, (ap));			\
+		memcpy(strdup_dst, strdup_src, strndup_len);		\
+		strdup_dst[strndup_len] = '\0';				\
+	}								\
+	(d) = strdup_dst;						\
+} while (/* CONSTCOND */ 0)
 #define strdup2x(d,s1,s2) do {						\
 	const char *strdup_src = (const void *)(s1);			\
 	const char *strdup_app = (const void *)(s2);			\
 	size_t strndup_len = strlen(strdup_src);			\
-	size_t strndup_ln2 = strlen(strdup_app) + 1;			\
-	char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP);	\
+	size_t strndup_ln2 = strlen(strdup_app) + 1U;			\
+	char *strdup_dst = alloc1(strndup_len, strndup_ln2, ATEMP);	\
 									\
 	memcpy(strdup_dst, strdup_src, strndup_len);			\
 	memcpy(strdup_dst + strndup_len, strdup_app, strndup_ln2);	\
@@ -731,19 +836,20 @@ im_sorry_dave(void)
 #define strpathx(d,s1,s2,cond) do {					\
 	const char *strdup_src = (const void *)(s1);			\
 	const char *strdup_app = (const void *)(s2);			\
-	size_t strndup_len = strlen(strdup_src) + 1;			\
+	size_t strndup_len = strlen(strdup_src) + 1U;			\
 	size_t strndup_ln2 = ((cond) || *strdup_app) ?			\
-	    strlen(strdup_app) + 1 : 0;					\
-	char *strdup_dst = alloc(strndup_len + strndup_ln2, ATEMP);	\
+	    strlen(strdup_app) + 1U : 0;				\
+	char *strdup_dst = alloc1(strndup_len, strndup_ln2, ATEMP);	\
 									\
 	memcpy(strdup_dst, strdup_src, strndup_len);			\
 	if (strndup_ln2) {						\
-		strdup_dst[strndup_len - 1] = '/';			\
+		strdup_dst[strndup_len - 1U] = '/';			\
 		memcpy(strdup_dst + strndup_len, strdup_app,		\
 		    strndup_ln2);					\
 	}								\
 	(d) = strdup_dst;						\
 } while (/* CONSTCOND */ 0)
+#define memstr(d,s) memcpy((d), (s), sizeof(s))
 
 #ifdef MKSH_SMALL
 #ifndef MKSH_NOPWNAM
@@ -762,14 +868,38 @@ im_sorry_dave(void)
 #define MKSH_UNEMPLOYED		1
 #endif
 
-#define NUFILE		32	/* Number of user-accessible files */
-#define FDBASE		10	/* First file usable by Shell */
+/* savedfd data type */
+typedef kby ksh_fdsave;
+/* savedfd “index is closed” mask */
+#define FDICLMASK	((ksh_fdsave)0x80U)
+/* savedfd “fd number” mask */
+#define FDNUMMASK	((ksh_fdsave)0x7FU)
+/* savedfd fd numbers are ≥ FDBASE */
+/* savedfd “not saved” number: 0 */
+/* savedfd “saved is closed” or savefd error indicator number */
+#define FDCLOSED	((ksh_fdsave)0x01U)
+/* savefd() to savedfd mapper */
+#define FDSAVE(i,sfd)	do {					\
+	int FDSAVEsavedfd = (sfd);				\
+	e->savedfd[i] = FDSAVEsavedfd < FDBASE ? FDCLOSED :	\
+	    /* ≤ FDMAXNUM checked in savefd() already */	\
+	    (ksh_fdsave)(FDSAVEsavedfd & FDNUMMASK);		\
+} while (/* CONSTCOND */ 0)
+/* savedfd to restfd mapper */
+#define FDSVNUM(ep,i)	((kui)((ep)->savedfd[i] & FDNUMMASK))
+#define SAVEDFD(ep,i)	(FDSVNUM(ep, i) == (kui)FDCLOSED ? \
+			    -1 : (int)FDSVNUM(ep, i))
+/* first fd number usable by the shell for its own purposes */
+#define FDBASE		10
+/* … and last one */
+#define FDMAXNUM	127 /* 0x7FU, cf. FDNUMMASK */
+/* number of user-accessible file descriptors */
+#define NUFILE		10
 
 /*
  * simple grouping allocator
  */
 
-
 /* 0. OS API: where to get memory from and how to free it (grouped) */
 
 /* malloc(3)/realloc(3) -> free(3) for use by the memory allocator */
@@ -787,12 +917,11 @@ im_sorry_dave(void)
 #define free_ossetmode(p)	free(p)
 #endif
 
-#ifdef MKSH__NO_PATH_MAX
+#if HAVE_GET_CURRENT_DIR_NAME
 /* GNU libc: get_current_dir_name(3) -> free(3) */
 #define free_gnu_gcdn(p)	free(p)
 #endif
 
-
 /* 1. internal structure */
 struct lalloc_common {
 	struct lalloc_common *next;
@@ -818,7 +947,6 @@ struct lalloc_item {
 /* 3. group structure */
 typedef struct lalloc_common Area;
 
-
 EXTERN Area aperm;		/* permanent object space */
 #define APERM	&aperm
 #define ATEMP	&e->area
@@ -839,6 +967,8 @@ enum sh_flag {
  * parsing & execution environment
  *
  * note that kshlongjmp MUST NOT be passed 0 as second argument!
+ *
+ * kshsetjmp() is to *not* save (and kshlongjmp() to not restore) signals!
  */
 #ifdef MKSH_NO_SIGSETJMP
 #define kshjmp_buf	jmp_buf
@@ -861,13 +991,13 @@ extern struct env {
 	Area area;		/* temporary allocation area */
 	struct env *oenv;	/* link to previous environment */
 	struct block *loc;	/* local variables and functions */
-	short *savefd;		/* original redirected fds */
+	ksh_fdsave *savedfd;	/* original fds for redirected fds */
 	struct temp *temps;	/* temp files */
 	/* saved parser recursion state */
 	struct yyrecursive_state *yyrecursive_statep;
 	kshjmp_buf jbuf;	/* long jump back to env creator */
-	uint8_t type;		/* environment type - see below */
-	uint8_t flags;		/* EF_* */
+	kby type;		/* environment type - see below */
+	kby flags;		/* EF_* */
 } *e;
 
 /* struct env.type values */
@@ -897,7 +1027,7 @@ extern struct env {
 /* note that i MUST NOT be zero */
 #define LRETURN	1	/* return statement */
 #define LEXIT	2	/* exit statement */
-#define LERROR	3	/* errorf() called */
+#define LERROR	3	/* kerrf() called */
 #define LERREXT 4	/* set -e caused */
 #define LINTR	5	/* ^C noticed */
 #define LBREAK	6	/* break statement */
@@ -912,14 +1042,14 @@ EXTERN int exstat;		/* exit status */
 EXTERN int subst_exstat;	/* exit status of last $(..)/`..` */
 EXTERN struct tbl *vp_pipest;	/* global PIPESTATUS array */
 EXTERN short trap_exstat;	/* exit status before running a trap */
-EXTERN uint8_t trap_nested;	/* running nested traps */
-EXTERN uint8_t shell_flags[FNFLAGS];
-EXTERN uint8_t baseline_flags[FNFLAGS
+EXTERN kby trap_nested;		/* running nested traps */
+EXTERN kby shell_flags[FNFLAGS];
+EXTERN kby baseline_flags[FNFLAGS
 #if !defined(MKSH_SMALL) || defined(DEBUG)
     + 1
 #endif
     ];
-EXTERN bool as_builtin;		/* direct builtin call */
+EXTERN Wahr as_builtin;		/* direct builtin call */
 EXTERN const char *kshname;	/* $0 */
 EXTERN struct {
 	uid_t kshuid_v;		/* real UID of shell at startup */
@@ -939,17 +1069,16 @@ EXTERN struct {
 #define kshegid		rndsetupstate.kshegid_v
 #define kshppid		rndsetupstate.kshppid_v
 
-
 /* option processing */
-#define OF_CMDLINE	0x01	/* command line */
-#define OF_SET		0x02	/* set builtin */
-#define OF_SPECIAL	0x04	/* a special variable changing */
-#define OF_INTERNAL	0x08	/* set internally by shell */
-#define OF_FIRSTTIME	0x10	/* as early as possible, once */
-#define OF_ANY		(OF_CMDLINE | OF_SET | OF_SPECIAL | OF_INTERNAL)
+#define OF_CMDLINE	0x01U	/* command line */
+#define OF_SET		0x02U	/* set builtin */
+#define OF_INTERNAL	0x04U	/* set internally by shell */
+#define OF_FIRSTTIME	0x08U	/* as early as possible, once */
+#define OF_ANY		(OF_CMDLINE | OF_SET | OF_INTERNAL)
 
 /* null value for variable; comparison pointer for unset */
-EXTERN char null[] E_INIT("");
+#define null (&null_string[2])
+extern char null_string[4];	/* backing, initialised */
 
 /* string pooling: do we rely on the compiler? */
 #ifndef HAVE_STRING_POOLING
@@ -970,12 +1099,11 @@ EXTERN char null[] E_INIT("");
 #endif
 
 #ifndef HAVE_STRING_POOLING /* helpers for pooled strings */
-EXTERN const char T4spaces[] E_INIT("    ");
+#define Tnl (Tf_s_s_sN + 8)
 #define T1space (Treal_sp2 + 5)
-#define Tcolsp (Tf_sD_ + 2)
 #define TC_IFSWS (TinitIFS + 4)
 EXTERN const char TinitIFS[] E_INIT("IFS= \t\n");
-EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} $_");
+EXTERN const char TFCEDIT_dollaru[] E_INIT("${FCEDIT:-/bin/ed} \"$_\"");
 #define Tspdollaru (TFCEDIT_dollaru + 18)
 EXTERN const char Tsgdot[] E_INIT("*=.");
 EXTERN const char Taugo[] E_INIT("augo");
@@ -985,46 +1113,43 @@ EXTERN const char Tbracket[] E_INIT("[")
 EXTERN const char Tbadnum[] E_INIT("bad number");
 #define Tbadsubst (Tfg_badsubst + 10)
 EXTERN const char Tbg[] E_INIT("bg");
-EXTERN const char Tbad_bsize[] E_INIT("bad shf/buf/bsize");
-#define Tbsize (Tbad_bsize + 12)
-EXTERN const char Tbad_sig_ss[] E_INIT("%s: bad signal '%s'");
-#define Tbad_sig_s (Tbad_sig_ss + 4)
+EXTERN const char Tbad_buf[] E_INIT("%s: buf %zX len %zd");
+EXTERN const char Tbad_flags[] E_INIT("%s: flags 0x%08X");
+EXTERN const char Tbad_sig[] E_INIT("bad signal");
 EXTERN const char Tsgbreak[] E_INIT("*=break");
 #define Tbreak (Tsgbreak + 2)
 EXTERN const char T__builtin[] E_INIT("-\\builtin");
 #define T_builtin (T__builtin + 1)
 #define Tbuiltin (T__builtin + 2)
-EXTERN const char Toomem[] E_INIT("can't allocate %zu data bytes");
 EXTERN const char Tcant_cd[] E_INIT("restricted shell - can't cd");
-EXTERN const char Tcant_find[] E_INIT("can't find");
-EXTERN const char Tcant_open[] E_INIT("can't open");
-#define Tbytes (Toomem + 24)
-EXTERN const char Tbcat[] E_INIT("!cat");
-#define Tcat (Tbcat + 1)
+EXTERN const char Tcant_filesub[] E_INIT("can't open $(<...) file");
 #define Tcd (Tcant_cd + 25)
+EXTERN const char Tcloexec_failed[] E_INIT("failed to %s close-on-exec flag for fd#%d");
 #define T_command (T_funny_command + 9)
 #define Tcommand (T_funny_command + 10)
 EXTERN const char Tsgcontinue[] E_INIT("*=continue");
 #define Tcontinue (Tsgcontinue + 2)
 EXTERN const char Tcreate[] E_INIT("create");
+EXTERN const char TchvtDone[] E_INIT("chvt: Done (%d)");
+#define TDone (TchvtDone + 6)
 EXTERN const char TELIF_unexpected[] E_INIT("TELIF unexpected");
 EXTERN const char TEXECSHELL[] E_INIT("EXECSHELL");
 EXTERN const char TENV[] E_INIT("ENV");
 EXTERN const char Tdsgexport[] E_INIT("^*=export");
 #define Texport (Tdsgexport + 3)
-#ifdef __OS2__
-EXTERN const char Textproc[] E_INIT("extproc");
-#endif
 EXTERN const char Tfalse[] E_INIT("false");
 EXTERN const char Tfg[] E_INIT("fg");
 EXTERN const char Tfg_badsubst[] E_INIT("fileglob: bad substitution");
-#define Tfile (Tfile_fd + 20)
-EXTERN const char Tfile_fd[] E_INIT("function definition file");
+#define Tfile (Tcant_filesub + 19)
+EXTERN const char Tyankfirst[] E_INIT("\nyank something first");
+#define Tfirst (Tyankfirst + 16)
 EXTERN const char TFPATH[] E_INIT("FPATH");
 EXTERN const char T_function[] E_INIT(" function");
 #define Tfunction (T_function + 1)
 EXTERN const char T_funny_command[] E_INIT("funny $()-command");
 EXTERN const char Tgetopts[] E_INIT("getopts");
+#define Tgetrusage (Ttime_getrusage + 6)
+EXTERN const char Ttime_getrusage[] E_INIT("time: getrusage");
 #define Thistory (Tnot_in_history + 7)
 EXTERN const char Tintovfl[] E_INIT("integer overflow %zu %c %zu prevented");
 EXTERN const char Tinvname[] E_INIT("%s: invalid %s name");
@@ -1032,25 +1157,29 @@ EXTERN const char Tjobs[] E_INIT("jobs")
 EXTERN const char Tjob_not_started[] E_INIT("job not started");
 EXTERN const char Tmksh[] E_INIT("mksh");
 #define Tname (Tinvname + 15)
+EXTERN const char Tnil[] E_INIT("(null)");
 EXTERN const char Tno_args[] E_INIT("missing argument");
 EXTERN const char Tno_OLDPWD[] E_INIT("no OLDPWD");
-EXTERN const char Tnot_ident[] E_INIT("is not an identifier");
+EXTERN const char Tnot_ident[] E_INIT("not an identifier");
 EXTERN const char Tnot_in_history[] E_INIT("not in history");
-EXTERN const char Tnot_found_s[] E_INIT("%s not found");
-#define Tnot_found (Tnot_found_s + 3)
+#define Tnot_found (Tinacc_not_found + 16)
+#define Tsp_not_found (Tinacc_not_found + 15)
+EXTERN const char Tinacc_not_found[] E_INIT("inaccessible or not found");
 #define Tnot_started (Tjob_not_started + 4)
 #define TOLDPWD (Tno_OLDPWD + 3)
-#define Topen (Tcant_open + 6)
+EXTERN const char Topen[] E_INIT("open");
+EXTERN const char Ttooearly[] E_INIT("too early%s");
 EXTERN const char To_o_reset[] E_INIT(" -o .reset");
 #define To_reset (To_o_reset + 4)
 #define TPATH (TFPATH + 1)
-#define Tpo (Tset_po + 4)
+#define Tpo (T_set_po + 5)
 #define Tpv (TpVv + 1)
 EXTERN const char TpVv[] E_INIT("Vpv");
 #define TPWD (Tno_OLDPWD + 6)
 #define Tread (Tshf_read + 4)
 EXTERN const char Tdsgreadonly[] E_INIT("^*=readonly");
 #define Treadonly (Tdsgreadonly + 3)
+EXTERN const char Tread_only[] E_INIT("read-only");
 EXTERN const char Tredirection_dup[] E_INIT("can't finish (dup) redirection");
 #define Tredirection (Tredirection_dup + 19)
 #define Treal_sp1 (Treal_sp2 + 1)
@@ -1058,12 +1187,13 @@ EXTERN const char Treal_sp2[] E_INIT(" r
 EXTERN const char TREPLY[] E_INIT("REPLY");
 EXTERN const char Treq_arg[] E_INIT("requires an argument");
 EXTERN const char Tselect[] E_INIT("select");
-#define Tset (Tf_parm + 18)
-EXTERN const char Tset_po[] E_INIT("set +o");
+#define Tset (Tf_parm + 14)
+#define Tset_po (T_set_po + 1)
+EXTERN const char T_set_po[] E_INIT(" set +o");
 EXTERN const char Tsghset[] E_INIT("*=#set");
 #define Tsh (Tmksh + 2)
 #define TSHELL (TEXECSHELL + 4)
-#define Tshell (Ttoo_many_files + 23)
+EXTERN const char Tshell[] E_INIT("shell");
 EXTERN const char Tshf_read[] E_INIT("shf_read");
 EXTERN const char Tshf_write[] E_INIT("shf_write");
 EXTERN const char Tgsource[] E_INIT("=source");
@@ -1073,10 +1203,8 @@ EXTERN const char Tj_suspend[] E_INIT("j
 EXTERN const char Tsynerr[] E_INIT("syntax error");
 EXTERN const char Ttime[] E_INIT("time");
 EXTERN const char Ttoo_many_args[] E_INIT("too many arguments");
-EXTERN const char Ttoo_many_files[] E_INIT("too many open files in shell");
+EXTERN const char Ttoo_many_files[] E_INIT("too many open files (%d -> %d)");
 EXTERN const char Ttrue[] E_INIT("true");
-EXTERN const char Ttty_fd_dupof[] E_INIT("dup of tty fd");
-#define Ttty_fd (Ttty_fd_dupof + 7)
 EXTERN const char Tdgtypeset[] E_INIT("^=typeset");
 #define Ttypeset (Tdgtypeset + 2)
 #define Tugo (Taugo + 1)
@@ -1088,61 +1216,48 @@ EXTERN const char Tunwind[] E_INIT("unwi
 #define Tuser_sp1 (Tuser_sp2 + 1)
 EXTERN const char Tuser_sp2[] E_INIT(" user ");
 #define Twrite (Tshf_write + 4)
+#define Thex32 (Tbad_flags + 12)
 EXTERN const char Tf__S[] E_INIT(" %S");
 #define Tf__d (Tunexpected_type + 22)
-#define Tf_ss (Tf__ss + 1)
-EXTERN const char Tf__ss[] E_INIT(" %s%s");
 #define Tf__sN (Tf_s_s_sN + 5)
+EXTERN const char Tf_s_T[] E_INIT("%s %T");
 #define Tf_T (Tf_s_T + 3)
 EXTERN const char Tf_dN[] E_INIT("%d\n");
 EXTERN const char Tf_s_[] E_INIT("%s ");
-EXTERN const char Tf_s_T[] E_INIT("%s %T");
 EXTERN const char Tf_s_s_sN[] E_INIT("%s %s %s\n");
-#define Tf_s_s (Tf_sD_s_s + 4)
 #define Tf__s_s (Tf_sD_s_s + 3)
-#define Tf_s_sD_s (Tf_cant_ss_s + 6)
-EXTERN const char Tf_optfoo[] E_INIT("%s%s-%c: %s");
-EXTERN const char Tf_sD_[] E_INIT("%s: ");
-EXTERN const char Tf_szs[] E_INIT("%s: %zd %s");
-EXTERN const char Tf_parm[] E_INIT("%s: parameter not set");
-EXTERN const char Tf_coproc[] E_INIT("-p: %s");
+EXTERN const char Tf_s_sD_s[] E_INIT("%s %s: %s");
+EXTERN const char Tf_parm[] E_INIT("parameter not set");
 EXTERN const char Tf_cant_s[] E_INIT("%s: can't %s");
-EXTERN const char Tf_cant_ss_s[] E_INIT("can't %s %s: %s");
 EXTERN const char Tf_heredoc[] E_INIT("here document '%s' unclosed");
-#if HAVE_MKNOD
-EXTERN const char Tf_nonnum[] E_INIT("non-numeric %s %s '%s'");
-#endif
 EXTERN const char Tf_S_[] E_INIT("%S ");
 #define Tf_S (Tf__S + 1)
-#define Tf_lu (Tf_toolarge + 17)
-EXTERN const char Tf_toolarge[] E_INIT("%s %s too large: %lu");
-EXTERN const char Tf_ldfailed[] E_INIT("%s %s(%d, %ld) failed: %s");
-EXTERN const char Tf_sD_s_sD_s[] E_INIT("%s: %s %s: %s");
+EXTERN const char Tf_sSQlu[] E_INIT("%s[%lu]");
+#define Tf_SQlu (Tf_sSQlu + 2)
+#define Tf_lu (Tf_toolarge + 14)
+EXTERN const char Tf_toolarge[] E_INIT("%s too large: %lu");
+EXTERN const char Tf_ldfailed[] E_INIT("%s tcsetpgrp(%d, %ld)");
 EXTERN const char Tf_toomany[] E_INIT("too many %ss");
 EXTERN const char Tf_sd[] E_INIT("%s %d");
-#define Tf_s (Tf_temp + 28)
+#define Tf_s (Tf_temp + 24)
 EXTERN const char Tft_end[] E_INIT("%;");
-EXTERN const char Tft_R[] E_INIT("%R");
-#define Tf_d (Tunexpected_type + 23)
+#define Tft_R (Tft_s_R + 3)
+EXTERN const char Tft_s_R[] E_INIT("%s %R");
+#define Tf_d (Tcloexec_failed + 39)
 EXTERN const char Tf_sD_s_qs[] E_INIT("%s: %s '%s'");
-EXTERN const char Tf_ro[] E_INIT("read-only: %s");
-EXTERN const char Tf_flags[] E_INIT("%s: flags 0x%X");
-EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s: %s");
-EXTERN const char Tf_ssfaileds[] E_INIT("%s: %s failed: %s");
-EXTERN const char Tf_sD_sD_s[] E_INIT("%s: %s: %s");
+EXTERN const char Tf_temp[] E_INIT("can't %s temporary file %s");
+EXTERN const char Tf_ssfailed[] E_INIT("%s: %s failed");
 EXTERN const char Tf__c_[] E_INIT("-%c ");
 EXTERN const char Tf_sD_s_s[] E_INIT("%s: %s %s");
 #define Tf_sN (Tf_s_s_sN + 6)
-#define Tf_sD_s (Tf_temp + 24)
-EXTERN const char T_devtty[] E_INIT("/dev/tty");
+#define Tf_sD_s (Tf_s_sD_s + 3)
 #else /* helpers for string pooling */
-#define T4spaces "    "
+#define Tnl "\n"
 #define T1space " "
-#define Tcolsp ": "
 #define TC_IFSWS " \t\n"
 #define TinitIFS "IFS= \t\n"
-#define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} $_"
-#define Tspdollaru " $_"
+#define TFCEDIT_dollaru "${FCEDIT:-/bin/ed} \"$_\""
+#define Tspdollaru " \"$_\""
 #define Tsgdot "*=."
 #define Taugo "augo"
 #define Tbracket "["
@@ -1151,46 +1266,43 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tbadnum "bad number"
 #define Tbadsubst "bad substitution"
 #define Tbg "bg"
-#define Tbad_bsize "bad shf/buf/bsize"
-#define Tbsize "bsize"
-#define Tbad_sig_ss "%s: bad signal '%s'"
-#define Tbad_sig_s "bad signal '%s'"
+#define Tbad_buf "%s: buf %zX len %zd"
+#define Tbad_flags "%s: flags 0x%08X"
+#define Tbad_sig "bad signal"
 #define Tsgbreak "*=break"
 #define Tbreak "break"
 #define T__builtin "-\\builtin"
 #define T_builtin "\\builtin"
 #define Tbuiltin "builtin"
-#define Toomem "can't allocate %zu data bytes"
 #define Tcant_cd "restricted shell - can't cd"
-#define Tcant_find "can't find"
-#define Tcant_open "can't open"
-#define Tbytes "bytes"
-#define Tbcat "!cat"
-#define Tcat "cat"
+#define Tcant_filesub "can't open $(<...) file"
 #define Tcd "cd"
+#define Tcloexec_failed "failed to %s close-on-exec flag for fd#%d"
 #define T_command "-command"
 #define Tcommand "command"
 #define Tsgcontinue "*=continue"
 #define Tcontinue "continue"
 #define Tcreate "create"
+#define TchvtDone "chvt: Done (%d)"
+#define TDone "Done (%d)"
 #define TELIF_unexpected "TELIF unexpected"
 #define TEXECSHELL "EXECSHELL"
 #define TENV "ENV"
 #define Tdsgexport "^*=export"
 #define Texport "export"
-#ifdef __OS2__
-#define Textproc "extproc"
-#endif
 #define Tfalse "false"
 #define Tfg "fg"
 #define Tfg_badsubst "fileglob: bad substitution"
 #define Tfile "file"
-#define Tfile_fd "function definition file"
+#define Tyankfirst "\nyank something first"
+#define Tfirst "first"
 #define TFPATH "FPATH"
 #define T_function " function"
 #define Tfunction "function"
 #define T_funny_command "funny $()-command"
 #define Tgetopts "getopts"
+#define Tgetrusage "getrusage"
+#define Ttime_getrusage "time: getrusage"
 #define Thistory "history"
 #define Tintovfl "integer overflow %zu %c %zu prevented"
 #define Tinvname "%s: invalid %s name"
@@ -1198,15 +1310,18 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tjob_not_started "job not started"
 #define Tmksh "mksh"
 #define Tname "name"
+#define Tnil "(null)"
 #define Tno_args "missing argument"
 #define Tno_OLDPWD "no OLDPWD"
-#define Tnot_ident "is not an identifier"
+#define Tnot_ident "not an identifier"
 #define Tnot_in_history "not in history"
-#define Tnot_found_s "%s not found"
 #define Tnot_found "not found"
+#define Tsp_not_found " not found"
+#define Tinacc_not_found "inaccessible or not found"
 #define Tnot_started "not started"
 #define TOLDPWD "OLDPWD"
 #define Topen "open"
+#define Ttooearly "too early%s"
 #define To_o_reset " -o .reset"
 #define To_reset ".reset"
 #define TPATH "PATH"
@@ -1217,6 +1332,7 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tread "read"
 #define Tdsgreadonly "^*=readonly"
 #define Treadonly "readonly"
+#define Tread_only "read-only"
 #define Tredirection_dup "can't finish (dup) redirection"
 #define Tredirection "redirection"
 #define Treal_sp1 "real "
@@ -1226,6 +1342,7 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tselect "select"
 #define Tset "set"
 #define Tset_po "set +o"
+#define T_set_po " set +o"
 #define Tsghset "*=#set"
 #define Tsh "sh"
 #define TSHELL "SHELL"
@@ -1239,10 +1356,8 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tsynerr "syntax error"
 #define Ttime "time"
 #define Ttoo_many_args "too many arguments"
-#define Ttoo_many_files "too many open files in shell"
+#define Ttoo_many_files "too many open files (%d -> %d)"
 #define Ttrue "true"
-#define Ttty_fd_dupof "dup of tty fd"
-#define Ttty_fd "tty fd"
 #define Tdgtypeset "^=typeset"
 #define Ttypeset "typeset"
 #define Tugo "ugo"
@@ -1254,56 +1369,48 @@ EXTERN const char T_devtty[] E_INIT("/de
 #define Tuser_sp1 "user "
 #define Tuser_sp2 " user "
 #define Twrite "write"
+#define Thex32 "%08X"
 #define Tf__S " %S"
 #define Tf__d " %d"
-#define Tf_ss "%s%s"
-#define Tf__ss " %s%s"
 #define Tf__sN " %s\n"
+#define Tf_s_T "%s %T"
 #define Tf_T "%T"
 #define Tf_dN "%d\n"
 #define Tf_s_ "%s "
-#define Tf_s_T "%s %T"
 #define Tf_s_s_sN "%s %s %s\n"
-#define Tf_s_s "%s %s"
 #define Tf__s_s " %s %s"
 #define Tf_s_sD_s "%s %s: %s"
-#define Tf_optfoo "%s%s-%c: %s"
-#define Tf_sD_ "%s: "
-#define Tf_szs "%s: %zd %s"
-#define Tf_parm "%s: parameter not set"
-#define Tf_coproc "-p: %s"
+#define Tf_parm "parameter not set"
 #define Tf_cant_s "%s: can't %s"
-#define Tf_cant_ss_s "can't %s %s: %s"
 #define Tf_heredoc "here document '%s' unclosed"
-#if HAVE_MKNOD
-#define Tf_nonnum "non-numeric %s %s '%s'"
-#endif
 #define Tf_S_ "%S "
 #define Tf_S "%S"
+#define Tf_sSQlu "%s[%lu]"
+#define Tf_SQlu "[%lu]"
 #define Tf_lu "%lu"
-#define Tf_toolarge "%s %s too large: %lu"
-#define Tf_ldfailed "%s %s(%d, %ld) failed: %s"
-#define Tf_sD_s_sD_s "%s: %s %s: %s"
+#define Tf_toolarge "%s too large: %lu"
+#define Tf_ldfailed "%s tcsetpgrp(%d, %ld)"
 #define Tf_toomany "too many %ss"
 #define Tf_sd "%s %d"
 #define Tf_s "%s"
 #define Tft_end "%;"
 #define Tft_R "%R"
+#define Tft_s_R "%s %R"
 #define Tf_d "%d"
 #define Tf_sD_s_qs "%s: %s '%s'"
-#define Tf_ro "read-only: %s"
-#define Tf_flags "%s: flags 0x%X"
-#define Tf_temp "can't %s temporary file %s: %s"
-#define Tf_ssfaileds "%s: %s failed: %s"
-#define Tf_sD_sD_s "%s: %s: %s"
+#define Tf_temp "can't %s temporary file %s"
+#define Tf_ssfailed "%s: %s failed"
 #define Tf__c_ "-%c "
 #define Tf_sD_s_s "%s: %s %s"
 #define Tf_sN "%s\n"
 #define Tf_sD_s "%s: %s"
-#define T_devtty "/dev/tty"
 #endif /* end of string pooling */
 
-typedef uint8_t Temp_type;
+#ifdef __OS2__
+EXTERN const char Textproc[] E_INIT("extproc");
+#endif
+
+typedef kby Temp_type;
 /* expanded heredoc */
 #define TT_HEREDOC_EXP	0
 /* temporary file used for history editing (fc -e) */
@@ -1318,8 +1425,8 @@ struct temp {
 	/* pid of process parsed here-doc */
 	pid_t pid;
 	Temp_type type;
-	/* actually longer: name (variable length) */
-	char tffn[3];
+	/* name */
+	mbccFAMslot(char, tffn);
 };
 
 /*
@@ -1332,7 +1439,8 @@ struct temp {
 #ifdef DF
 #define shl_dbg		(&shf_iob[3])	/* for DF() */
 #endif
-EXTERN bool shl_stdout_ok;
+EXTERN Wahr initio_done;		/* shl_*out:Ja/1, shl_dbg:2 */
+EXTERN Wahr shl_stdout_ok;
 
 /*
  * trap handlers
@@ -1382,7 +1490,7 @@ extern Trap sigtraps[ksh_NSIG + 1];
 #ifdef SIGWINCH
 EXTERN volatile sig_atomic_t got_winch E_INIT(1);
 #else
-#define got_winch	true
+#define got_winch	Ja
 #endif
 
 /*
@@ -1398,7 +1506,7 @@ EXTERN unsigned int ksh_tmout;
 EXTERN enum tmout_enum ksh_tmout_state;
 
 /* For "You have stopped jobs" message */
-EXTERN bool really_exit;
+EXTERN Wahr really_exit;
 
 /*
  * fast character classes
@@ -1415,9 +1523,9 @@ EXTERN bool really_exit;
 #define CiOCTAL	BIT(5)	/* 0‥7				*/
 #define CiQCL	BIT(6)	/* &();|			*/
 #define CiALIAS	BIT(7)	/* !,.@				*/
-#define CiQCX	BIT(8)	/* *[\\				*/
+#define CiQCX	BIT(8)	/* *[\\~			*/
 #define CiVAR1	BIT(9)	/* !*@				*/
-#define CiQCM	BIT(10)	/* /^~				*/
+#define CiQCM	BIT(10)	/* /^				*/
 #define CiDIGIT	BIT(11)	/* 89				*/
 #define CiQC	BIT(12)	/* "'				*/
 #define CiSPX	BIT(13)	/* \x0B\x0C			*/
@@ -1442,9 +1550,9 @@ EXTERN bool really_exit;
 /* out of space, but one for *@ would make sense, possibly others */
 
 /* compile-time initialised, ASCII only */
-extern const uint32_t tpl_ctypes[128];
+extern const kui tpl_ctypes[128];
 /* run-time, contains C_IFS as well, full 2⁸ octet range */
-EXTERN uint32_t ksh_ctypes[256];
+EXTERN kui ksh_ctypes[256];
 /* first octet of $IFS, for concatenating "$*" */
 EXTERN char ifs0;
 
@@ -1461,20 +1569,20 @@ EXTERN char ifs0;
 /* A‥Z_a‥z		alphabetical plus underscore (identifier lead) */
 #define C_ALPHX	(CiLOWER | CiUNDER | CiUPPER)
 /* \x01‥\x7F		7-bit ASCII except NUL */
-#define C_ASCII (CiALIAS | CiANGLE | CiBRACK | CiCNTRL | CiCOLON | CiCR | CiCURLY | CiDIGIT | CiEQUAL | CiGRAVE | CiHASH | CiLOWER | CiMINUS | CiNL | CiOCTAL | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSP | CiSPX | CiSS | CiTAB | CiUNDER | CiUPPER)
+#define C_ASCII	(C_GRAPH | CiCNTRL | CiCR | CiNL | CiSP | CiSPX | CiTAB)
 /* \x09\x20		tab and space */
 #define C_BLANK	(CiSP | CiTAB)
-/* \x09\x20"'		separator for completion */
-#define C_CFS	(CiQC | CiSP | CiTAB)
 /* \x00‥\x1F\x7F	POSIX control characters */
 #define C_CNTRL	(CiCNTRL | CiCR | CiNL | CiNUL | CiSPX | CiTAB)
 /* 0‥9			decimal digits */
 #define C_DIGIT	(CiDIGIT | CiOCTAL)
 /* &();`|			editor x_locate_word() command */
 #define C_EDCMD	(CiGRAVE | CiQCL)
+/* $*?[\\`~			escape for globbing */
+#define C_EDGLB	(CiGRAVE | CiQCX | CiQUEST | CiSS)
 /* \x09\x0A\x20"&'():;<=>`|	editor non-word characters */
 #define C_EDNWC	(CiANGLE | CiCOLON | CiEQUAL | CiGRAVE | CiNL | CiQC | CiQCL | CiSP | CiTAB)
-/* "#$&'()*:;<=>?[\\`{|}	editor quotes for tab completion */
+/* "#$&'()*:;<=>?[\\`{|}~	editor quotes for tab completion */
 #define C_EDQ	(CiANGLE | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiQC | CiQCL | CiQCX | CiQUEST | CiSS)
 /* !‥~			POSIX graphical (alphanumerical plus punctuation) */
 #define C_GRAPH	(C_PUNCT | CiDIGIT | CiLOWER | CiOCTAL | CiUPPER)
@@ -1482,7 +1590,7 @@ EXTERN char ifs0;
 #define C_HEXLT	CiHEXLT
 /* \x00 + $IFS		IFS whitespace, IFS non-whitespace, NUL */
 #define C_IFS	(CiIFS | CiNUL)
-/* \x09\x0A\x20		IFS whitespace */
+/* \x09\x0A\x20		IFS whitespace candidates */
 #define C_IFSWS	(CiNL | CiSP | CiTAB)
 /* \x09\x0A\x20&();<>|	(for the lexer) */
 #define C_LEX1	(CiANGLE | CiNL | CiQCL | CiSP | CiTAB)
@@ -1498,8 +1606,8 @@ EXTERN char ifs0;
 #define C_PRINT	(C_GRAPH | CiSP)
 /* !"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~	POSIX punctuation */
 #define C_PUNCT	(CiALIAS | CiANGLE | CiBRACK | CiCOLON | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiMINUS | CiPERCT | CiPLUS | CiQC | CiQCL | CiQCM | CiQCX | CiQUEST | CiSS | CiUNDER)
-/* \x09\x0A"#$&'()*;<=>?[\\]`|	characters requiring quoting, minus space */
-#define C_QUOTE	(CiANGLE | CiBRACK | CiEQUAL | CiGRAVE | CiHASH | CiNL | CiQC | CiQCL | CiQCX | CiQUEST | CiSS | CiTAB)
+/* \x09\x0A"#$&'()*;<=>?[\\]`{|}~	characters requiring quoting, minus space */
+#define C_QUOTE	(CiANGLE | CiBRACK | CiCURLY | CiEQUAL | CiGRAVE | CiHASH | CiNL | CiQC | CiQCL | CiQCX | CiQUEST | CiSS | CiTAB)
 /* 0‥9A‥Fa‥f		hexadecimal digit */
 #define C_SEDEC	(CiDIGIT | CiHEXLT | CiOCTAL)
 /* \x09‥\x0D\x20	POSIX space class */
@@ -1524,9 +1632,9 @@ EXTERN char ifs0;
 #define C_LF	CiNL		/* \x0A	ASCII line feed */
 #define C_MINUS	CiMINUS		/* -	hyphen-minus */
 #ifdef MKSH_WITH_TEXTMODE
-#define C_NL	(CiNL | CiCR)	/* 	CR or LF under OS/2 TEXTMODE */
+#define C_NL	(CiNL | CiCR)	/*	CR or LF under OS/2 TEXTMODE */
 #else
-#define C_NL	CiNL		/* 	LF only like under Unix */
+#define C_NL	CiNL		/*	LF only like under Unix */
 #endif
 #define C_NUL	CiNUL		/* \x00	ASCII NUL */
 #define C_PLUS	CiPLUS		/* +	plus sign */
@@ -1539,22 +1647,21 @@ EXTERN char ifs0;
 /* identity transform of octet */
 #if defined(DEBUG) && defined(__GNUC__) && !defined(__ICC) && \
     !defined(__INTEL_COMPILER) && !defined(__SUNPRO_C)
-extern unsigned int eek_ord;
-#define ORD(c)	((size_t)(c) > 0xFF ? eek_ord : \
-		    ((unsigned int)(unsigned char)(c)))
-#define ord(c)	__builtin_choose_expr(				\
-    __builtin_types_compatible_p(__typeof__(c), char) ||	\
-    __builtin_types_compatible_p(__typeof__(c), unsigned char),	\
-    ((unsigned int)(unsigned char)(c)), ({			\
-	size_t ord_c = (c);					\
-								\
-	if (ord_c > (size_t)0xFFU)				\
-		internal_errorf("%s:%d:ord(%zX)",		\
-		    __FILE__, __LINE__, ord_c);			\
-	((unsigned int)(unsigned char)(ord_c));			\
+extern kui eek_ord;
+#define ORD(c)	((size_t)(c) > 0xFF ? eek_ord : KBI(c))
+#define ord(c)	__builtin_choose_expr(					\
+    __builtin_types_compatible_p(__typeof__(c), char) ||		\
+    __builtin_types_compatible_p(__typeof__(c), unsigned char),		\
+    KBI(c), ({								\
+	size_t ord_c = (c);						\
+									\
+	if (ord_c > (size_t)0xFFU)					\
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,	\
+		    "%s:%d:ord(%zX)", __FILE__, __LINE__, ord_c);	\
+	(KBI(ord_c));							\
 }))
 #else
-#define ord(c)	((unsigned int)(unsigned char)(c))
+#define ord(c)	KBI(c)
 #define ORD(c)	ord(c) /* may evaluate arguments twice */
 #endif
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
@@ -1563,30 +1670,38 @@ EXTERN unsigned char ebcdic_rtt_toascii[
 EXTERN unsigned char ebcdic_rtt_fromascii[256];
 extern void ebcdic_init(void);
 /* one-way to-ascii-or-high conversion, for POSIX locale ordering */
-#define asciibetical(c)	((unsigned int)ebcdic_map[(unsigned char)(c)])
+#define asciibetical(c)	KUI(ebcdic_map[ord(c)])
 /* two-way round-trip conversion, for general use */
-#define rtt2asc(c)	ebcdic_rtt_toascii[(unsigned char)(c)]
-#define asc2rtt(c)	ebcdic_rtt_fromascii[(unsigned char)(c)]
+#define rtt2asc(c)	ebcdic_rtt_toascii[KBY(c)]
+#define asc2rtt(c)	ebcdic_rtt_fromascii[KBY(c)]
 /* case-independent char comparison */
-#define ksh_eq(c,u,l)	(ord(c) == ord(u) || ord(c) == ord(l))
+#define isCh(c,u,l)	(ord(c) == ord(u) || ord(c) == ord(l))
 #else
-#define asciibetical(c)	ord(c)
-#define rtt2asc(c)	((unsigned char)(c))
-#define asc2rtt(c)	((unsigned char)(c))
-#define ksh_eq(c,u,l)	((ord(c) | 0x20) == ord(l))
+/* POSIX locale ordering */
+#define asciibetical(c)	KUI(ord(c)) /* ranging to USHRT_MAX */
+/* if inspecting numerical values (mapping on EBCDIC) */
+#define rtt2asc(c)	KBY(c)
+#define asc2rtt(c)	KBY(c)
+/* case-independent char comparison */
+#define isCh(c,u,l)	((ord(c) | 0x20U) == ord(l))
 #endif
+/* vs case-sensitive char comparison */
+#define isch(c,t)	(ord(c) == ORD(t))
 /* control character foo */
 #ifdef MKSH_EBCDIC
-#define ksh_isctrl(c)	(ord(c) < 0x40 || ord(c) == 0xFF)
+#define ksh_isctrl(c)	(ord(c) < 0x40U || ord(c) == 0xFFU)
+#define ksh_isctrl8(c)	ksh_isctrl(c)
 #else
-#define ksh_isctrl(c)	((ord(c) & 0x7F) < 0x20 || ord(c) == 0x7F)
+#define ksh_isctrl(c)	((ord(c) & 0x7FU) < 0x20U || ord(c) == 0x7FU)
+#define ksh_asisctrl(c)	(ord(c) < 0x20U || ord(c) == 0x7FU)
+#define ksh_isctrl8(c)	(Flag(FASIS) ? ksh_asisctrl(c) : ksh_isctrl(c))
 #endif
 /* new fast character classes */
-#define ctype(c,t)	tobool(ksh_ctypes[ord(c)] & (t))
+#define ctype(c,t)	isWahr(ksh_ctypes[ord(c)] & (t))
 #define cinttype(c,t)	((c) >= 0 && (c) <= 0xFF ? \
-			tobool(ksh_ctypes[(unsigned char)(c)] & (t)) : false)
+			isWahr(ksh_ctypes[KBY(c)] & (t)) : Nee)
 /* helper functions */
-#define ksh_isdash(s)	tobool(ord((s)[0]) == '-' && ord((s)[1]) == '\0')
+#define ksh_isdash(s)	isWahr(ord((s)[0]) == '-' && ord((s)[1]) == '\0')
 /* invariant distance even in EBCDIC */
 #define ksh_tolower(c)	(ctype(c, C_UPPER) ? (c) - 'A' + 'a' : (c))
 #define ksh_toupper(c)	(ctype(c, C_LOWER) ? (c) - 'a' + 'A' : (c))
@@ -1594,8 +1709,6 @@ extern void ebcdic_init(void);
 #define ksh_numdig(c)	(ord(c) - ORD('0'))
 #define ksh_numuc(c)	(rtt2asc(c) - rtt2asc('A'))
 #define ksh_numlc(c)	(rtt2asc(c) - rtt2asc('a'))
-#define ksh_toctrl(c)	asc2rtt(ord(c) == ORD('?') ? 0x7F : rtt2asc(c) & 0x9F)
-#define ksh_unctrl(c)	asc2rtt(rtt2asc(c) ^ 0x40U)
 
 #ifdef MKSH_SMALL
 #define SMALLP(x)	/* nothing */
@@ -1606,7 +1719,7 @@ extern void ebcdic_init(void);
 /* Argument parsing for built-in commands and getopts command */
 
 /* Values for Getopt.flags */
-#define GF_ERROR	BIT(0)	/* call errorf() if there is an error */
+#define GF_ERROR	BIT(0)	/* KWF_BIERR if there is an error */
 #define GF_PLUSOPT	BIT(1)	/* allow +c as an option */
 #define GF_NONAME	BIT(2)	/* don't print argv[0] in errors */
 
@@ -1634,8 +1747,8 @@ EXTERN Getopt user_opt;		/* parsing stat
 
 /* This for co-processes */
 
-/* something that won't (realisticly) wrap */
-typedef int Coproc_id;
+/* something that won't (realistically) wrap */
+typedef unsigned int Coproc_id;
 
 struct coproc {
 	void *job;	/* 0 or job of co-process using input pipe */
@@ -1655,7 +1768,7 @@ EXTERN sigset_t		sm_default, sm_sigchld;
 /* name of called builtin function (used by error functions) */
 EXTERN const char *builtin_argv0;
 /* is called builtin a POSIX special builtin? (error functions only) */
-EXTERN bool builtin_spec;
+EXTERN Wahr builtin_spec;
 
 /* current working directory */
 EXTERN char	*current_wd;
@@ -1670,7 +1783,6 @@ EXTERN char	*current_wd;
 EXTERN mksh_ari_t x_cols E_INIT(80);
 EXTERN mksh_ari_t x_lins E_INIT(24);
 
-
 /* Determine the location of the system (common) profile */
 
 #ifndef MKSH_DEFAULT_PROFILEDIR
@@ -1680,7 +1792,6 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 #define MKSH_SYSTEM_PROFILE	MKSH_DEFAULT_PROFILEDIR "/profile"
 #define MKSH_SUID_PROFILE	MKSH_DEFAULT_PROFILEDIR "/suid_profile"
 
-
 /* Used by v_evaluate() and setstr() to control action when error occurs */
 #define KSH_UNWIND_ERROR	0	/* unwind the stack (kshlongjmp) */
 #define KSH_RETURN_ERROR	1	/* return 1/0 for success/failure */
@@ -1697,8 +1808,23 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 				    (shf)->rnleft--, (int)ord(*(shf)->rp++) : \
 				    shf_getchar(shf))
 #define shf_putc_i(c,shf)	((shf)->wnleft == 0 ? \
-				    shf_putchar((uint8_t)(c), (shf)) : \
+				    shf_putchar((kby)(c), (shf)) : \
 				    ((shf)->wnleft--, *(shf)->wp++ = (c)))
+/*
+ * small strings (e.g. one multibyte character) only, atomically
+ * no side effects in arguments please; does s+=n; may do n=0
+ */
+#define shf_wr_sm(s,n,shf)	do {				\
+	if ((shf)->wnleft < (ssize_t)(n)) {			\
+		shf_scheck_grow((n), (shf));			\
+		shf_write((const void *)(s), (n), (shf));	\
+		(s) += (n);					\
+	} else {						\
+		(shf)->wnleft -= n;				\
+		while ((n)--)					\
+			*(shf)->wp++ = *(s)++;			\
+	}							\
+} while (/* CONSTCOND */ 0)
 #define shf_eof(shf)		((shf)->flags & SHF_EOF)
 #define shf_error(shf)		((shf)->flags & SHF_ERROR)
 #define shf_errno(shf)		((shf)->errnosv)
@@ -1725,7 +1851,6 @@ EXTERN mksh_ari_t x_lins E_INIT(24);
 #define SHF_READING	0x2000		/* currently reading: rnleft,rp valid */
 #define SHF_WRITING	0x4000		/* currently writing: wnleft,wp valid */
 
-
 struct shf {
 	Area *areap;		/* area shf/buf were allocated in */
 	unsigned char *rp;	/* read: current position in buffer */
@@ -1747,7 +1872,7 @@ struct table {
 	Area *areap;		/* area to allocate entries */
 	struct tbl **tbls;	/* hashed table items */
 	size_t nfree;		/* free table entries */
-	uint8_t tshift;		/* table size (2^tshift) */
+	kby tshift;		/* table size (2^tshift) */
 };
 
 /* table item */
@@ -1767,28 +1892,32 @@ struct tbl {
 		const char *fpath;	/* temporary path to undef function */
 	} u;
 	union {
+		k32 hval;		/* hash(name) */
+		k32 index;		/* index for an array */
+	} ua;
+	union {
 		int field;		/* field with for -L/-R/-Z */
 		int errnov;		/* CEXEC/CTALIAS */
 	} u2;
-	union {
-		uint32_t hval;		/* hash(name) */
-		uint32_t index;		/* index for an array */
-	} ua;
 	/*
 	 * command type (see below), base (if INTEGER),
 	 * offset from val.s of value (if EXPORT)
 	 */
 	int type;
 	/* flags (see below) */
-	uint32_t flag;
+	kui flag;
 
-	/* actually longer: name (variable length) */
-	char name[4];
+	mbccFAMslot(char, name);
+};
+
+union tbl_static {
+	struct tbl tbl;
+	char storage[mbccFAMSZ(struct tbl, name, 4)];
 };
 
 EXTERN struct tbl *vtemp;
 /* set by isglobal(), global() and local() */
-EXTERN bool last_lookup_was_array;
+EXTERN Wahr last_lookup_was_array;
 
 /* common flag bits */
 #define ALLOC		BIT(0)	/* val.s has been allocated */
@@ -1929,7 +2058,7 @@ EXTERN char *path;		/* copy of either PA
 EXTERN const char *def_path;	/* path to use if PATH not set */
 EXTERN char *tmpdir;		/* TMPDIR value */
 EXTERN const char *prompt;
-EXTERN uint8_t cur_prompt;	/* PS1 or PS2 */
+EXTERN kby cur_prompt;		/* PS1 or PS2 */
 EXTERN int current_lineno;	/* LINENO value */
 
 /*
@@ -2012,7 +2141,7 @@ struct ioword {
 	char *delim;		/* delimiter for <<, <<- */
 	char *heredoc;		/* content of heredoc */
 	unsigned short ioflag;	/* action (below) */
-	short unit;		/* unit (fd) affected */
+	signed char unit;	/* unit (fd) affected */
 };
 
 /* ioword.flag - type of redirection */
@@ -2032,6 +2161,7 @@ struct ioword {
 #define IOBASH		BIT(10)	/* &> etc. */
 #define IOHERESTR	BIT(11)	/* <<< (here string) */
 #define IONDELIM	BIT(12)	/* null delimiter (<<) */
+#define IOSYNIONEXT	BIT(13)	/* already fully configured */
 
 /* execute/exchild flags */
 #define XEXEC	BIT(0)		/* execute without forking */
@@ -2102,10 +2232,10 @@ typedef struct XString {
 #define Xput(xs,xp,c)	(*xp++ = (c))
 
 /* check if there are at least n bytes left */
-#define XcheckN(xs,xp,n) do {					\
-	ssize_t more = ((xp) + (n)) - (xs).end;			\
-	if (more > 0)						\
-		(xp) = Xcheck_grow(&(xs), (xp), (size_t)more);	\
+#define XcheckN(xs,xp,n) do {						\
+	ssize_t XcheckNi = (size_t)((xp) - (xs).beg) + (n) - (xs).len;	\
+	if (XcheckNi > 0)						\
+		(xp) = Xcheck_grow(&(xs), (xp), (size_t)XcheckNi);	\
 } while (/* CONSTCOND */ 0)
 
 /* check for overflow, expand string */
@@ -2166,8 +2296,8 @@ typedef struct {
 struct columnise_opts {
 	struct shf *shf;
 	char linesep;
-	bool do_last;
-	bool prefcol;
+	Wahr do_last;
+	Wahr prefcol;
 };
 
 /*
@@ -2276,7 +2406,7 @@ typedef union {
 #define KEYWORD		BIT(3)	/* recognise keywords */
 #define LETEXPR		BIT(4)	/* get expression inside (( )) */
 #define CMDASN		BIT(5)	/* parse x[1 & 2] as one word, for typeset */
-#define HEREDOC 	BIT(6)	/* parsing a here document body */
+#define HEREDOC		BIT(6)	/* parsing a here document body */
 #define ESACONLY	BIT(7)	/* only accept esac keyword */
 #define CMDWORD		BIT(8)	/* parsing simple command (alias related) */
 #define HEREDELIM	BIT(9)	/* parsing <<,<<- delimiter */
@@ -2378,22 +2508,26 @@ EXTERN struct timeval j_usrtime, j_systi
 #define notok2mul(max,val,c)	(((val) != 0) && ((c) != 0) && \
 				    (((max) / (c)) < (val)))
 #define notok2add(max,val,c)	((val) > ((max) - (c)))
-#define notoktomul(val,cnst)	notok2mul(SIZE_MAX, (val), (cnst))
-#define notoktoadd(val,cnst)	notok2add(SIZE_MAX, (val), (cnst))
+#define notoktomul(val,cnst)	notok2mul(mbiSIZE_MAX, (val), (cnst))
+#define notoktoadd(val,cnst)	notok2add(mbiSIZE_MAX, (val), (cnst))
 #define checkoktoadd(val,cnst) do {					\
 	if (notoktoadd((val), (cnst)))					\
-		internal_errorf(Tintovfl, (size_t)(val),		\
-		    '+', (size_t)(cnst));				\
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,	\
+		    Tintovfl, (size_t)(val), '+', (size_t)(cnst));	\
 } while (/* CONSTCOND */ 0)
-
+#undef mbccABEND
+#define mbccABEND(reason)	kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | \
+				    KWF_ONEMSG | KWF_NOERRNO, (reason))
 
 /* lalloc.c */
 void ainit(Area *);
 void afreeall(Area *);
 /* these cannot fail and can take NULL (not for ap) */
 #define alloc(n,ap)		aresize(NULL, (n), (ap))
+#define alloc1(m,n,ap)		aresize1(NULL, (m), (n), (ap))
 #define alloc2(m,n,ap)		aresize2(NULL, (m), (n), (ap))
 void *aresize(void *, size_t, Area *);
+void *aresize1(void *, size_t, size_t, Area *);
 void *aresize2(void *, size_t, size_t, Area *);
 void afree(void *, Area *);	/* can take NULL */
 #define aresizeif(z,p,n,ap)	(((p) == NULL) || ((z) < (n)) || \
@@ -2401,7 +2535,7 @@ void afree(void *, Area *);	/* can take
 				    aresize((p), (n), (ap)) : (p))
 /* edit.c */
 #ifndef MKSH_NO_CMDLINE_EDITING
-int x_bind(const char * SMALLP(bool));
+int x_bind(const char * SMALLP(Wahr));
 int x_bind_check(void);
 int x_bind_list(void);
 int x_bind_showall(void);
@@ -2409,9 +2543,9 @@ void x_init(void);
 #ifdef DEBUG_LEAKS
 void x_done(void);
 #endif
-int x_read(char *);
+char *x_read(char *);
 #endif
-void x_mkraw(int, mksh_ttyst *, bool);
+void x_mkraw(int, mksh_ttyst *, Wahr);
 void x_initterm(const char *);
 /* eval.c */
 char *substitute(const char *, int);
@@ -2420,36 +2554,45 @@ char *evalstr(const char *cp, int);
 char *evalonestr(const char *cp, int);
 char *debunk(char *, const char *, size_t);
 void expand(const char *, XPtrV *, int);
-int glob_str(char *, XPtrV *, bool);
+int glob_str(char *, XPtrV *, Wahr);
 char *do_tilde(char *);
 /* exec.c */
 int execute(struct op * volatile, volatile int, volatile int * volatile);
 int c_builtin(const char **);
 struct tbl *get_builtin(const char *);
-struct tbl *findfunc(const char *, uint32_t, bool);
+struct tbl *findfunc(const char *, k32, Wahr);
 int define(const char *, struct op *);
 const char *builtin(const char *, int (*)(const char **));
 struct tbl *findcom(const char *, int);
-void flushcom(bool);
+void flushcom(Wahr);
 int search_access(const char *, int);
 const char *search_path(const char *, const char *, int, int *);
 void pr_menu(const char * const *);
 void pr_list(struct columnise_opts *, char * const *);
 int herein(struct ioword *, char **);
+const char **cpyargv(int *, const char **, Area *);
 /* expr.c */
-int evaluate(const char *, mksh_ari_t *, int, bool);
-int v_evaluate(struct tbl *, const char *, volatile int, bool);
+int evaluate(const char *, mksh_ari_t *, int, Wahr);
+int v_evaluate(struct tbl *, const char *, volatile int, Wahr);
 /* UTF-8 stuff */
+char *ez_bs(char *, char *);
 size_t utf_mbtowc(unsigned int *, const char *);
 size_t utf_wctomb(char *, unsigned int);
+#define OPTUISRAW(wc) IS(wc, 0xFFFFFF80U, 0x0000EF80U)
+#define OPTUMKRAW(ch) (ord(ch) | 0x0000EF00U)
+#if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
+size_t ez_mbtowc(unsigned int *, const char *);
+#else
+#define ez_mbtowc ez_mbtoc
+#endif
+size_t ez_mbtoc(unsigned int *, const char *);
+size_t ez_ctomb(char *, unsigned int);
 int utf_widthadj(const char *, const char **);
-size_t utf_mbswidth(const char *) MKSH_A_PURE;
-const char *utf_skipcols(const char *, int, int *);
-size_t utf_ptradj(const char *) MKSH_A_PURE;
+size_t utf_mbswidth(const char *);
 #ifdef MIRBSD_BOOTFLOPPY
 #define utf_wcwidth(i) wcwidth((wchar_t)(i))
 #else
-int utf_wcwidth(unsigned int) MKSH_A_PURE;
+int utf_wcwidth(unsigned int);
 #endif
 int ksh_access(const char *, int);
 struct tbl *tempvar(const char *);
@@ -2463,7 +2606,7 @@ int c_printf(const char **);
 int c_whence(const char **);
 int c_command(const char **);
 int c_typeset(const char **);
-bool valid_alias_name(const char *);
+Wahr valid_alias_name(const char *);
 int c_alias(const char **);
 int c_unalias(const char **);
 int c_let(const char **);
@@ -2499,17 +2642,15 @@ int c_mknod(const char **);
 #endif
 int c_realpath(const char **);
 int c_rename(const char **);
-int c_cat(const char **);
-int c_sleep(const char **);
 /* histrap.c */
 void init_histvec(void);
 void hist_init(Source *);
 #if HAVE_PERSISTENT_HISTORY
 void hist_finish(void);
 #endif
-void histsave(int *, const char *, int, bool);
+void histsave(int *, const char *, int, Wahr);
 #if !defined(MKSH_SMALL) && HAVE_PERSISTENT_HISTORY
-bool histsync(void);
+Wahr histsync(void);
 #endif
 int c_fc(const char **);
 void sethistsize(mksh_ari_t);
@@ -2517,24 +2658,24 @@ void sethistsize(mksh_ari_t);
 void sethistfile(const char *);
 #endif
 #if !defined(MKSH_NO_CMDLINE_EDITING) && !MKSH_S_NOVI
-char **histpos(void) MKSH_A_PURE;
+char **histpos(void);
 int histnum(int);
 #endif
-int findhist(int, const char *, bool, bool) MKSH_A_PURE;
-char **hist_get_newest(bool);
+int findhist(int, const char *, Wahr, Wahr);
+char **hist_get_newest(Wahr);
 void inittraps(void);
 void alarm_init(void);
-Trap *gettrap(const char *, bool, bool);
+Trap *gettrap(const char *, Wahr, Wahr);
 void trapsig(int);
 void intrcheck(void);
 int fatal_trap_check(void);
 int trap_pending(void);
 void runtraps(int intr);
-void runtrap(Trap *, bool);
+void runtrap(Trap *, Wahr);
 void cleartraps(void);
 void restoresigs(void);
 void settrap(Trap *, const char *);
-bool block_pipe(void);
+Wahr block_pipe(void);
 void restore_pipe(void);
 int setsig(Trap *, sig_t, int);
 void setexecsig(Trap *, int);
@@ -2565,15 +2706,12 @@ pid_t j_async(void);
 int j_stopped_running(void);
 /* lex.c */
 int yylex(int);
-void yyskiputf8bom(void);
-void yyerror(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
 Source *pushs(int, Area *);
 void set_prompt(int, Source *);
 int pprompt(const char *, int);
 /* main.c */
-int include(const char *, int, const char **, bool);
+kby kshname_islogin(const char **);
+int include(const char *, const char **, Wahr);
 int command(const char *, int);
 int shell(Source * volatile, volatile int);
 /* argument MUST NOT be 0 */
@@ -2582,27 +2720,10 @@ void newenv(int);
 void quitenv(struct shf *);
 void cleanup_parents_env(void);
 void cleanup_proc_env(void);
-void errorf(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void errorfx(int, const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 2, 3);
-void warningf(bool, const char *, ...)
-    MKSH_A_FORMAT(__printf__, 2, 3);
+/* old {{{ */
 void bi_errorf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
-void maybe_errorf(int *, int, const char *, ...)
-    MKSH_A_FORMAT(__printf__, 3, 4);
-#define errorfz()	errorf(NULL)
-#define errorfxz(rc)	errorfx((rc), NULL)
-#define bi_errorfz()	bi_errorf(NULL)
-void internal_errorf(const char *, ...)
-    MKSH_A_NORETURN
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void internal_warningf(const char *, ...)
-    MKSH_A_FORMAT(__printf__, 1, 2);
-void error_prefix(bool);
+/* old }}} */
 void shellf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 void shprintf(const char *, ...)
@@ -2610,8 +2731,8 @@ void shprintf(const char *, ...)
 int can_seek(int);
 void initio(void);
 void recheck_ctype(void);
-int ksh_dup2(int, int, bool);
-short savefd(int);
+int ksh_dup2(int, int, Wahr);
+int savefd(int);
 void restfd(int, int);
 void openpipe(int *);
 void closepipe(int *);
@@ -2623,11 +2744,11 @@ void coproc_write_close(int);
 int coproc_getfd(int, const char **);
 void coproc_cleanup(int);
 struct temp *maketemp(Area *, Temp_type, struct temp **);
-void ktinit(Area *, struct table *, uint8_t);
-struct tbl *ktscan(struct table *, const char *, uint32_t, struct tbl ***);
+void ktinit(Area *, struct table *, kby);
+struct tbl *ktscan(struct table *, const char *, k32, struct tbl ***);
 /* table, name (key) to search for, hash(n) */
 #define ktsearch(tp,s,h) ktscan((tp), (s), (h), NULL)
-struct tbl *ktenter(struct table *, const char *, uint32_t);
+struct tbl *ktenter(struct table *, const char *, k32);
 #define ktdelete(p)	do { p->flag = 0; } while (/* CONSTCOND */ 0)
 void ktwalk(struct tstate *, struct table *);
 struct tbl *ktnext(struct tstate *);
@@ -2636,17 +2757,22 @@ struct tbl **ktsort(struct table *);
 void DF(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 #endif
+const char *ksh_getwd(void);
 /* misc.c */
-size_t option(const char *) MKSH_A_PURE;
+size_t option(const char *);
 char *getoptions(void);
-void change_flag(enum sh_flag, int, bool);
-void change_xtrace(unsigned char, bool);
-int parse_args(const char **, int, bool *);
+void change_flag(enum sh_flag, unsigned int, Wahr);
+void change_xtrace(unsigned char, Wahr);
+int parse_args(const char **, unsigned int, Wahr *);
 int getn(const char *, int *);
-int gmatchx(const char *, const char *, bool);
-bool has_globbing(const char *) MKSH_A_PURE;
-int ascstrcmp(const void *, const void *) MKSH_A_PURE;
-int ascpstrcmp(const void *, const void *) MKSH_A_PURE;
+int getpn(const char **, int *);
+int getnh(const char *, mbiHUGE_U *);
+int getpnh(const char **, mbiHUGE_U *);
+int gmatchx(const char *, const char *, Wahr);
+Wahr has_globbing(const char *);
+int ascstrcmp(const void *, const void *);
+int ascpstrcmp(const void *, const void *);
+void ksh_getopt_opterr(int, const char *, const char *);
 void ksh_getopt_reset(Getopt *, int);
 int ksh_getopt(const char **, Getopt *, const char *);
 void print_value_quoted(struct shf *, const char *);
@@ -2659,7 +2785,6 @@ void strip_nuls(char *, size_t)
 ssize_t blocking_read(int, char *, size_t)
     MKSH_A_BOUNDED(__buffer__, 2, 3);
 int reset_nonblock(int);
-char *ksh_get_wd(void);
 char *do_realpath(const char *);
 void simplify_path(char *);
 void set_current_wd(const char *);
@@ -2668,7 +2793,7 @@ int c_cd(const char **);
 char *strdup_i(const char *, Area *);
 char *strndup_i(const char *, size_t, Area *);
 #endif
-int unbksl(bool, int (*)(void), void (*)(int));
+int unbksl(Wahr, int (*)(void), void (*)(int));
 #ifdef __OS2__
 /* os2.c */
 void os2_init(int *, const char ***);
@@ -2682,6 +2807,10 @@ struct shf *shf_open(const char *, int,
 struct shf *shf_fdopen(int, int, struct shf *);
 struct shf *shf_reopen(int, int, struct shf *);
 struct shf *shf_sopen(char *, ssize_t, int, struct shf *);
+struct shf *shf_sreopen(char *, ssize_t, Area *, struct shf *);
+int shf_scheck_grow(ssize_t, struct shf *);
+#define shf_scheck(n,shf)	(((shf)->wnleft < (ssize_t)(n)) ? \
+				    shf_scheck_grow((n), (shf)) : 0)
 int shf_close(struct shf *);
 int shf_fdclose(struct shf *);
 char *shf_sclose(struct shf *);
@@ -2698,7 +2827,12 @@ int shf_putc(int, struct shf *);
 #define shf_putc shf_putc_i
 #endif
 int shf_putchar(int, struct shf *);
-ssize_t shf_puts(const char *, struct shf *);
+#ifdef MKSH_SHF_NO_INLINE
+#define shf_puts shf_putsv
+#else
+#define shf_puts(s,shf) ((s) ? shf_write((s), strlen(s), (shf)) : (ssize_t)-1)
+#endif
+ssize_t shf_putsv(const char *, struct shf *);
 ssize_t shf_write(const char *, ssize_t, struct shf *);
 ssize_t shf_fprintf(struct shf *, const char *, ...)
     MKSH_A_FORMAT(__printf__, 2, 3);
@@ -2708,14 +2842,115 @@ ssize_t shf_snprintf(char *, ssize_t, co
 char *shf_smprintf(const char *, ...)
     MKSH_A_FORMAT(__printf__, 1, 2);
 ssize_t shf_vfprintf(struct shf *, const char *, va_list)
-    MKSH_A_FORMAT(__printf__, 2, 0);
+#ifdef MKSH_SHF_VFPRINTF_NO_GCC_FORMAT_ATTRIBUTE
+#define shf_vfprintf poisoned_shf_vfprintf
+#else
+    MKSH_A_FORMAT(__printf__, 2, 0)
+#endif
+    ;
 void set_ifs(const char *);
+/* flags for numfmt below */
+#define FL_SGN		0x0000	/* signed decimal */
+#define FL_DEC		0x0001	/* unsigned decimal */
+#define FL_OCT		0x0002	/* unsigned octal */
+#define FL_HEX		0x0003	/* unsigned sedecimal */
+#define FM_TYPE		0x0003	/* mask: decimal/octal/hex */
+#define FL_UCASE	0x0004	/* use upper-case digits beyond 9 */
+#define FL_UPPER	0x000C	/* use upper-case digits beyond 9 and 'X' */
+#define FL_PLUS		0x0010	/* FL_SGN force sign output */
+#define FL_BLANK	0x0020	/* FL_SGN output space unless sign present */
+#define FL_HASH		0x0040	/* FL_OCT force 0; FL_HEX force 0x/0X */
+/* internal flags to numfmt / shf_vfprintf */
+#define FL_NEG		0x0080	/* negative number, negated */
+#define FL_SHORT	0x0100	/* ‘h’ seen */
+#define FL_LONG		0x0200	/* ‘l’ seen */
+#define FL_SIZET	0x0400	/* ‘z’ seen */
+#ifdef MKSH_HAVE_HUGE
+#define FL_HUGE		0x0800	/* ‘j’ seen */
+#endif
+#define FM_SIZES	0x0F00	/* mask: short/long/sizet/huge */
+#define FL_RIGHT	0x1000	/* ‘-’ seen: right-pad, left-align */
+#define FL_ZERO		0x2000	/* ‘0’ seen: pad with leading zeros */
+#define FL_DOT		0x4000	/* ‘.’ seen: printf(3) precision specified */
+#define FL_NUMBER	0x8000	/* %[douxefg] a number was formatted */
+/*
+ * %#o produces the longest output: '0' + w/3 + NUL
+ * %#x produces '0x' + w/4 + NUL which is at least as long (w=8, w>9)
+ * %+d produces sign + w/log₂(10) + NUL which takes less than octal obviously
+ */
+#define NUMBUFSZ (1U + (mbiTYPE_UBITS(kuH) + 2U) / 3U + /* NUL */ 1U)
+#define NUMBUFLEN(base,result) ((base) + NUMBUFSZ - (result) - 1U)
+char *kulfmt(kul number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+char *kslfmt(ksl number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+#ifdef MKSH_HAVE_HUGE
+char *kuHfmt(kuH number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+char *ksHfmt(ksH number, kui flags, char *numbuf)
+    MKSH_A_BOUNDED(__minbytes__, 3, NUMBUFSZ);
+#else
+#define kuHfmt kulfmt
+#define ksHfmt kslfmt
+#endif
 /* syn.c */
 void initkeywords(void);
-struct op *compile(Source *, bool, bool);
-bool parse_usec(const char *, struct timeval *);
+struct op *compile(Source *, Wahr);
+Wahr parse_usec(const char *, struct timeval *);
 char *yyrecursive(int);
-void yyrecursive_pop(bool);
+void yyrecursive_pop(Wahr);
+void yyerror(const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 1, 2);
+/* shell error reporting */
+void bi_unwind(int);
+Wahr error_prefix(Wahr);
+#define KWF_BIERR	(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | \
+			    KWF_BUILTIN | KWF_BIUNWIND)
+#define KWF_ERR(n)	((((unsigned int)(n)) & KWF_EXSTAT) | KWF_ERROR)
+#define KWF_EXSTAT	0x0000FFU	/* (mask) errorlevel to use */
+#define KWF_VERRNO	0x000100U	/* int vararg: use ipv errno */
+#define KWF_INTERNAL	0x000200U	/* internal {error,warning} */
+#define KWF_WARNING	0x000000U	/* (default) warning */
+#define KWF_ERROR	0x000400U	/* error + consequences */
+#define KWF_PREFIX	0x000800U	/* run error_prefix() */
+#define KWF_FILELINE	0x001000U	/* error_prefix arg:=Ja */
+#define KWF_BUILTIN	0x002000U	/* possibly show builtin_argv0 */
+#define KWF_MSGMASK	0x00C000U	/* (mask) message to display */
+#define KWF_MSGFMT	0x000000U	/* (default) printf-style variadic */
+#define KWF_ONEMSG	0x004000U	/* only one string to show */
+#define KWF_TWOMSG	0x008000U	/* two strings to show with colon */
+#define KWF_THREEMSG	0x00C000U	/* three strings to colonise */
+#define KWF_NOERRNO	0x010000U	/* omit showing strerror */
+#define KWF_BIUNWIND	0x020000U	/* let kwarnf* tailcall bi_unwind(0) */
+void kwarnf(unsigned int, ...);
+#ifndef MKSH_SMALL
+void kwarnf0(unsigned int, const char *, ...)
+    MKSH_A_FORMAT(__printf__, 2, 3);
+void kwarnf1(unsigned int, int, const char *, ...)
+    MKSH_A_FORMAT(__printf__, 3, 4);
+#else
+#define kwarnf0 kwarnf	/* with KWF_MSGFMT and !KWF_VERRNO */
+#define kwarnf1 kwarnf	/* with KWF_MSGFMT and KWF_VERRNO */
+#endif
+void kerrf(unsigned int, ...)
+    MKSH_A_NORETURN;
+#ifndef MKSH_SMALL
+void kerrf0(unsigned int, const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 2, 3);
+void kerrf1(unsigned int, int, const char *, ...)
+    MKSH_A_NORETURN
+    MKSH_A_FORMAT(__printf__, 3, 4);
+#else
+#define kerrf0 kerrf	/* with KWF_MSGFMT and !KWF_VERRNO */
+#define kerrf1 kerrf	/* with KWF_MSGFMT and KWF_VERRNO */
+#endif
+void merrF(int *, unsigned int, ...);
+#define merrf(rv,va) do {	\
+	merrF va;		\
+	return (rv);		\
+} while (/* CONSTCOND */ 0)
 /* tree.c */
 void fptreef(struct shf *, int, const char *, ...);
 char *snptreef(char *, ssize_t, const char *, ...);
@@ -2725,43 +2960,51 @@ const char *wdscan(const char *, int);
 #define WDS_TPUTS	BIT(0)		/* tputS (dumpwdvar) mode */
 char *wdstrip(const char *, int);
 void tfree(struct op *, Area *);
-void dumpchar(struct shf *, unsigned char);
+#ifdef DEBUG
 void dumptree(struct shf *, struct op *);
 void dumpwdvar(struct shf *, const char *);
-void dumpioact(struct shf *shf, struct op *t);
-void vistree(char *, size_t, struct op *)
-    MKSH_A_BOUNDED(__string__, 1, 2);
-void fpFUNCTf(struct shf *, int, bool, const char *, struct op *);
+void dumpioact(struct shf *, struct op *);
+void dumphex(struct shf *, const void *, size_t)
+    MKSH_A_BOUNDED(__string__, 2, 3);
+#endif
+void uprntc(unsigned char, struct shf *);
+#ifndef MKSH_NO_CMDLINE_EDITING
+void uescmbT(unsigned char *, const char **)
+    MKSH_A_BOUNDED(__minbytes__, 1, 5);
+int uwidthmbT(char *, char **);
+#endif
+const char *uprntmbs(const char *, Wahr, struct shf *);
+void fpFUNCTf(struct shf *, int, Wahr, const char *, struct op *);
 /* var.c */
 void newblock(void);
 void popblock(void);
 void initvar(void);
-struct block *varsearch(struct block *, struct tbl **, const char *, uint32_t);
+struct block *varsearch(struct block *, struct tbl **, const char *, k32);
 struct tbl *global(const char *);
-struct tbl *isglobal(const char *, bool);
-struct tbl *local(const char *, bool);
+struct tbl *isglobal(const char *, Wahr);
+struct tbl *local(const char *, Wahr);
 char *str_val(struct tbl *);
 int setstr(struct tbl *, const char *, int);
-struct tbl *setint_v(struct tbl *, struct tbl *, bool);
+struct tbl *setint_v(struct tbl *, struct tbl *, Wahr);
 void setint(struct tbl *, mksh_ari_t);
 void setint_n(struct tbl *, mksh_ari_t, int);
-struct tbl *typeset(const char *, uint32_t, uint32_t, int, int);
+struct tbl *typeset(const char *, kui, kui, int, int);
 void unset(struct tbl *, int);
-const char *skip_varname(const char *, bool) MKSH_A_PURE;
-const char *skip_wdvarname(const char *, bool) MKSH_A_PURE;
-int is_wdvarname(const char *, bool) MKSH_A_PURE;
-int is_wdvarassign(const char *) MKSH_A_PURE;
-struct tbl *arraysearch(struct tbl *, uint32_t);
+const char *skip_varname(const char *, Wahr);
+const char *skip_wdvarname(const char *, Wahr);
+int is_wdvarname(const char *, Wahr);
+int is_wdvarassign(const char *, Wahr);
+struct tbl *arraysearch(struct tbl *, k32);
 char **makenv(void);
 void change_winsz(void);
-size_t array_ref_len(const char *) MKSH_A_PURE;
-char *arrayname(const char *);
-mksh_uari_t set_array(const char *, bool, const char **);
-uint32_t hash(const void *) MKSH_A_PURE;
-uint32_t chvt_rndsetup(const void *, size_t) MKSH_A_PURE;
-mksh_ari_t rndget(void);
+size_t array_ref_len(const char *);
+struct tbl *arraybase(const char *);
+mksh_uari_t set_array(const char *, Wahr, const char **);
+k32 hash(const void *);
+void chvt_rndsetup(const void *, size_t);
+k32 rndget(void);
 void rndset(unsigned long);
-void rndpush(const void *);
+void rndpush(const void *, size_t);
 void record_match(const char *);
 
 enum Test_op {
@@ -2805,8 +3048,10 @@ extern const struct t_op u_ops[];
 extern const struct t_op b_ops[];
 /* ensure order with funcs.c */
 #define Tda (u_ops[0].op_text)
+#define Tdc (u_ops[2].op_text)
 #define Tdn (u_ops[12].op_text)
 #define Tdo (u_ops[14].op_text)
+#define Tdp (u_ops[15].op_text)
 #define Tdr (u_ops[16].op_text)
 #define Tdu (u_ops[20].op_text)	/* "-u" */
 #define Tdx (u_ops[23].op_text)
@@ -2823,29 +3068,29 @@ typedef struct test_env {
 	} pos;
 	const char **wp_end;		/* used by ptest_* */
 	Test_op (*isa)(struct test_env *, Test_meta);
-	const char *(*getopnd) (struct test_env *, Test_op, bool);
-	int (*eval)(struct test_env *, Test_op, const char *, const char *, bool);
+	const char *(*getopnd) (struct test_env *, Test_op, Wahr);
+	int (*eval)(struct test_env *, Test_op, const char *, const char *, Wahr);
 	void (*error)(struct test_env *, int, const char *);
 	int flags;			/* TEF_* */
 } Test_env;
 
 extern const char * const dbtest_tokens[];
 
-Test_op	test_isop(Test_meta, const char *) MKSH_A_PURE;
-int test_eval(Test_env *, Test_op, const char *, const char *, bool);
+Test_op	test_isop(Test_meta, const char *);
+int test_eval(Test_env *, Test_op, const char *, const char *, Wahr);
 int test_parse(Test_env *);
 
 /* tty_fd is not opened O_BINARY, it's thus never read/written */
 EXTERN int tty_fd E_INIT(-1);	/* dup'd tty file descriptor */
-EXTERN bool tty_devtty;		/* true if tty_fd is from /dev/tty */
+EXTERN Wahr tty_devtty;		/* if tty_fd is from /dev/tty */
 EXTERN mksh_ttyst tty_state;	/* saved tty state */
-EXTERN bool tty_hasstate;	/* true if tty_state is valid */
+EXTERN Wahr tty_hasstate;	/* if tty_state is valid */
 
 extern int tty_init_fd(void);	/* initialise tty_fd, tty_devtty */
 
 #ifdef __OS2__
 #define binopen2(path,flags)		__extension__({			\
-	int binopen2_fd = open((path), (flags) | O_BINARY);		\
+	int binopen2_fd = open((path), (flags) | O_BINARY, 0);		\
 	if (binopen2_fd >= 0)						\
 		setmode(binopen2_fd, O_BINARY);				\
 	(binopen2_fd);							\
@@ -2857,7 +3102,7 @@ extern int tty_init_fd(void);	/* initial
 	(binopen3_fd);							\
 })
 #else
-#define binopen2(path,flags)		open((path), (flags) | O_BINARY)
+#define binopen2(path,flags)		open((path), (flags) | O_BINARY, 0)
 #define binopen3(path,flags,mode)	open((path), (flags) | O_BINARY, (mode))
 #endif
 
@@ -2888,7 +3133,7 @@ int getdrvwd(char **, unsigned int);
 #else
 #define mksh_abspath(s)			(ord((s)[0]) == ORD('/'))
 #define mksh_cdirsep(c)			(ord(c) == ORD('/'))
-#define mksh_sdirsep(s)			strchr((s), '/')
+#define mksh_sdirsep(s)			ucstrchr((s), '/')
 #define mksh_vdirsep(s)			vstrchr((s), '/')
 #endif
 
--- mksh-59c.orig/sh_flags.opt
+++ mksh-59c/sh_flags.opt
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2013, 2014, 2015, 2017
+ * Copyright (c) 2013, 2014, 2015, 2017, 2021
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -19,7 +19,7 @@
  */
 
 @SHFLAGS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/sh_flags.opt,v 1.9 2020/05/16 22:38:25 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/sh_flags.opt,v 1.10 2021/05/30 04:17:56 tg Exp $");
 @SHFLAGS_ENUMS
 #define FN(sname,cname,flags,ochar)	cname,
 #define F0(sname,cname,flags,ochar)	cname = 0,
@@ -43,6 +43,10 @@ __RCSID("$MirOS: src/bin/mksh/sh_flags.o
 >a|
 F0("allexport", FEXPORT, OF_ANY
 
+/* ./.	when quoting, show C1 control characters as-is; +U only */
+>|
+FN("asis", FASIS, OF_ANY
+
 /* ./.	bgnice */
 >| HAVE_NICE
 FN("bgnice", FBGNICE, OF_ANY
--- mksh-59c.orig/shf.c
+++ mksh-59c/shf.c
@@ -2,7 +2,8 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2011,
- *		 2012, 2013, 2015, 2016, 2017, 2018, 2019
+ *		 2012, 2013, 2015, 2016, 2017, 2018, 2019, 2021,
+ *		 2022, 2023
  *	mirabilos <m@mirbsd.org>
  * Copyright (c) 2015
  *	Daniel Richard G. <skunk@iSKUNK.ORG>
@@ -27,7 +28,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/shf.c,v 1.102 2020/06/22 17:11:03 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/shf.c,v 1.134 2023/03/19 23:31:29 tg Exp $");
 
 /* flags to shf_emptybuf() */
 #define EB_READSW	0x01	/* about to switch to reading */
@@ -57,7 +58,7 @@ shf_open(const char *name, int oflags, i
 	int fd, eno;
 
 	/* Done before open so if alloca fails, fd won't be lost. */
-	shf = alloc(sizeof(struct shf) + bsize, ATEMP);
+	shf = alloc1(sizeof(struct shf), bsize, ATEMP);
 	shf->areap = ATEMP;
 	shf->buf = (unsigned char *)&shf[1];
 	shf->bsize = bsize;
@@ -92,6 +93,7 @@ shf_open(const char *name, int oflags, i
 }
 
 /* helper function for shf_fdopen and shf_reopen */
+/* pre-initio() *sflagsp=SHF_WR */
 static void
 shf_open_hlp(int fd, int *sflagsp, const char *where)
 {
@@ -121,16 +123,18 @@ shf_open_hlp(int fd, int *sflagsp, const
 	}
 
 	if (!(sflags & (SHF_RD | SHF_WR)))
-		internal_errorf(Tf_sD_s, where, "missing read/write");
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, where, sflags);
 }
 
 /* Set up the shf structure for a file descriptor. Doesn't fail. */
+/* pre-initio() sflags=SHF_WR */
 struct shf *
 shf_fdopen(int fd, int sflags, struct shf *shf)
 {
 	ssize_t bsize =
 	    /* at most 512 */
-	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
+	    (sflags & SHF_UNBUF) ? ((sflags & SHF_RD) ? 1 : 0) : SHF_BSIZE;
 
 	shf_open_hlp(fd, &sflags, "shf_fdopen");
 	if (shf) {
@@ -140,8 +144,11 @@ shf_fdopen(int fd, int sflags, struct sh
 		} else
 			shf->buf = NULL;
 	} else {
-		shf = alloc(sizeof(struct shf) + bsize, ATEMP);
-		shf->buf = (unsigned char *)&shf[1];
+		unsigned char *cp;
+
+		cp = alloc1(sizeof(struct shf), bsize, ATEMP);
+		shf = (void *)cp;
+		shf->buf = cp + sizeof(struct shf);
 		sflags |= SHF_ALLOCS;
 	}
 	shf->areap = ATEMP;
@@ -154,8 +161,8 @@ shf_fdopen(int fd, int sflags, struct sh
 	shf->flags = sflags;
 	shf->errnosv = 0;
 	shf->bsize = bsize;
-	if (sflags & SHF_CLEXEC)
-		fcntl(fd, F_SETFD, FD_CLOEXEC);
+	if ((sflags & SHF_CLEXEC) && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed, "set", fd);
 	return (shf);
 }
 
@@ -168,8 +175,9 @@ shf_reopen(int fd, int sflags, struct sh
 	    sflags & SHF_UNBUF ? (sflags & SHF_RD ? 1 : 0) : SHF_BSIZE;
 
 	shf_open_hlp(fd, &sflags, "shf_reopen");
-	if (!shf || !shf->buf || shf->bsize < bsize)
-		internal_errorf(Tf_sD_s, "shf_reopen", Tbad_bsize);
+	if (!shf->buf || shf->bsize < bsize)
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, "shf_reopen", (size_t)shf->buf, shf->bsize);
 
 	/* assumes shf->buf and shf->bsize already set up */
 	shf->fd = fd;
@@ -180,8 +188,8 @@ shf_reopen(int fd, int sflags, struct sh
 	shf->wbsize = sflags & SHF_UNBUF ? 0 : bsize;
 	shf->flags = (shf->flags & (SHF_ALLOCS | SHF_ALLOCB)) | sflags;
 	shf->errnosv = 0;
-	if (sflags & SHF_CLEXEC)
-		fcntl(fd, F_SETFD, FD_CLOEXEC);
+	if ((sflags & SHF_CLEXEC) && fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
+		kwarnf0(KWF_INTERNAL | KWF_WARNING, Tcloexec_failed, "set", fd);
 	return (shf);
 }
 
@@ -197,10 +205,9 @@ shf_reopen(int fd, int sflags, struct sh
 struct shf *
 shf_sopen(char *buf, ssize_t bsize, int sflags, struct shf *shf)
 {
-	/* can't have a read+write string */
-	if (!(!(sflags & SHF_RD) ^ !(sflags & SHF_WR)))
-		internal_errorf(Tf_flags, "shf_sopen",
-		    (unsigned int)sflags);
+	if (!((sflags & SHF_RD) ^ (sflags & SHF_WR)))
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_sopen", sflags);
 
 	if (!shf) {
 		shf = alloc(sizeof(struct shf), ATEMP);
@@ -226,6 +233,44 @@ shf_sopen(char *buf, ssize_t bsize, int
 	return (shf);
 }
 
+/* Open a string for dynamic writing, using already-allocated buffer */
+struct shf *
+shf_sreopen(char *buf, ssize_t bsize, Area *ap, struct shf *oshf)
+{
+	struct shf *shf;
+
+	shf = shf_sopen(buf, bsize, SHF_WR | SHF_DYNAMIC, oshf);
+	shf->areap = ap;
+	shf->flags |= SHF_ALLOCB;
+	return (shf);
+}
+
+/* Check whether the string can grow to take n bytes, close it up otherwise */
+int
+shf_scheck_grow(ssize_t n, struct shf *shf)
+{
+	if (!(shf->flags & SHF_WR))
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_scheck", shf->flags);
+
+	/* if n < 0 we lose in the macro already */
+
+	/* nōn-string can always grow flushing */
+	if (!(shf->flags & SHF_STRING))
+		return (0);
+
+	while (shf->wnleft < n)
+		if (shf_emptybuf(shf, EB_GROW) == -1)
+			break;
+
+	if (shf->wnleft < n) {
+		/* block subsequent writes as we truncate here */
+		shf->wnleft = 0;
+		return (1);
+	}
+	return (0);
+}
+
 /* Flush and close file descriptor, free the shf structure */
 int
 shf_close(struct shf *shf)
@@ -275,10 +320,8 @@ shf_sclose(struct shf *shf)
 	unsigned char *s = shf->buf;
 
 	/* NUL terminate */
-	if (shf->flags & SHF_WR) {
-		shf->wnleft++;
-		shf_putc('\0', shf);
-	}
+	if (shf->flags & SHF_WR)
+		*shf->wp = '\0';
 	if (shf->flags & SHF_ALLOCS)
 		afree(shf, shf->areap);
 	return ((char *)s);
@@ -296,7 +339,8 @@ shf_flush(struct shf *shf)
 	if (shf->flags & SHF_STRING)
 		rv = (shf->flags & SHF_WR) ? -1 : 0;
 	else if (shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_flush", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_flush", "no fd");
 	else if (shf->flags & SHF_ERROR) {
 		errno = shf->errnosv;
 		rv = -1;
@@ -328,7 +372,8 @@ shf_emptybuf(struct shf *shf, int flags)
 	int ret = 0;
 
 	if (!(shf->flags & SHF_STRING) && shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_emptybuf", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_emptybuf", "no fd");
 
 	if (shf->flags & SHF_ERROR) {
 		errno = shf->errnosv;
@@ -343,7 +388,7 @@ shf_emptybuf(struct shf *shf, int flags)
 		shf->flags &= ~SHF_READING;
 	}
 	if (shf->flags & SHF_STRING) {
-		unsigned char *nbuf;
+		size_t rp, wp;
 
 		/*
 		 * Note that we assume SHF_ALLOCS is not set if
@@ -354,13 +399,14 @@ shf_emptybuf(struct shf *shf, int flags)
 		    !(shf->flags & SHF_ALLOCB))
 			return (-1);
 		/* allocate more space for buffer */
-		nbuf = aresize2(shf->buf, 2, shf->wbsize, shf->areap);
-		shf->rp = nbuf + (shf->rp - shf->buf);
-		shf->wp = nbuf + (shf->wp - shf->buf);
+		rp = shf->rp - shf->buf;
+		wp = shf->wp - shf->buf;
+		shf->buf = aresize2(shf->buf, 2, shf->wbsize, shf->areap);
+		shf->rp = shf->buf + rp;
+		shf->wp = shf->buf + wp;
 		shf->rbsize += shf->wbsize;
 		shf->wnleft += shf->wbsize;
 		shf->wbsize <<= 1;
-		shf->buf = nbuf;
 	} else {
 		if (shf->flags & SHF_WRITING) {
 			ssize_t n, ntowrite = shf->wp - shf->buf;
@@ -383,6 +429,8 @@ shf_emptybuf(struct shf *shf, int flags)
 						memmove(shf->buf, buf,
 						    ntowrite);
 						shf->wp = shf->buf + ntowrite;
+						/* restore errno for caller */
+						errno = shf->errnosv;
 					}
 					return (-1);
 				}
@@ -414,7 +462,8 @@ shf_fillbuf(struct shf *shf)
 		return (0);
 
 	if (shf->fd < 0)
-		internal_errorf(Tf_sD_s, "shf_fillbuf", "no fd");
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+		    "shf_fillbuf", "no fd");
 
 	if (shf->flags & (SHF_EOF | SHF_ERROR)) {
 		if (shf->flags & SHF_ERROR)
@@ -457,11 +506,12 @@ shf_read(char *buf, ssize_t bsize, struc
 	ssize_t ncopy, orig_bsize = bsize;
 
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, Tshf_read,
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, Tshf_read, shf->flags);
 
 	if (bsize <= 0)
-		internal_errorf(Tf_szs, Tshf_read, bsize, Tbsize);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, Tshf_read, (size_t)buf, bsize);
 
 	while (bsize > 0) {
 		if (shf->rnleft == 0 &&
@@ -495,8 +545,8 @@ shf_getse(char *buf, ssize_t bsize, stru
 	char *orig_buf = buf;
 
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_getse",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_getse", shf->flags);
 
 	if (bsize <= 0)
 		return (NULL);
@@ -517,7 +567,7 @@ shf_getse(char *buf, ssize_t bsize, stru
 		ncopy = end ? end - shf->rp + 1 : shf->rnleft;
 		if (ncopy > bsize)
 			ncopy = bsize;
-		memcpy(buf, (char *) shf->rp, ncopy);
+		memcpy(buf, shf->rp, ncopy);
 		shf->rp += ncopy;
 		shf->rnleft -= ncopy;
 		buf += ncopy;
@@ -549,8 +599,8 @@ int
 shf_getchar(struct shf *shf)
 {
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_getchar",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_getchar", shf->flags);
 
 	if (shf->rnleft == 0 && (shf_fillbuf(shf) == -1 || shf->rnleft == 0))
 		return (-1);
@@ -566,8 +616,8 @@ int
 shf_ungetc(int c, struct shf *shf)
 {
 	if (!(shf->flags & SHF_RD))
-		internal_errorf(Tf_flags, "shf_ungetc",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_ungetc", shf->flags);
 
 	if ((shf->flags & SHF_ERROR) || c == -1 ||
 	    (shf->rp == shf->buf && shf->rnleft))
@@ -604,8 +654,8 @@ int
 shf_putchar(int c, struct shf *shf)
 {
 	if (!(shf->flags & SHF_WR))
-		internal_errorf(Tf_flags, "shf_putchar",
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, "shf_putchar", shf->flags);
 
 	if (c == -1)
 		return (-1);
@@ -615,7 +665,8 @@ shf_putchar(int c, struct shf *shf)
 		ssize_t n;
 
 		if (shf->fd < 0)
-			internal_errorf(Tf_sD_s, "shf_putchar", "no fd");
+			kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_TWOMSG | KWF_NOERRNO,
+			    "shf_putchar", "no fd");
 		if (shf->flags & SHF_ERROR) {
 			errno = shf->errnosv;
 			return (-1);
@@ -641,11 +692,11 @@ shf_putchar(int c, struct shf *shf)
 }
 
 /*
- * Write a string. Returns the length of the string if successful, -1
- * if the string could not be written.
+ * Write a string. Returns the length of the string if successful,
+ * less if truncated, and -1 if the string could not be written.
  */
 ssize_t
-shf_puts(const char *s, struct shf *shf)
+shf_putsv(const char *s, struct shf *shf)
 {
 	if (!s)
 		return (-1);
@@ -653,18 +704,22 @@ shf_puts(const char *s, struct shf *shf)
 	return (shf_write(s, strlen(s), shf));
 }
 
-/* Write a buffer. Returns nbytes if successful, -1 if there is an error. */
+/*
+ * Write a buffer. Returns nbytes if successful, less if truncated
+ * (outputting to string only), and -1 if there is an error.
+ */
 ssize_t
 shf_write(const char *buf, ssize_t nbytes, struct shf *shf)
 {
 	ssize_t n, ncopy, orig_nbytes = nbytes;
 
 	if (!(shf->flags & SHF_WR))
-		internal_errorf(Tf_flags, Tshf_write,
-		    (unsigned int)shf->flags);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_flags, Tshf_write, shf->flags);
 
 	if (nbytes < 0)
-		internal_errorf(Tf_szs, Tshf_write, nbytes, Tbytes);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, Tshf_write, (size_t)buf, nbytes);
 
 	/* don't buffer if buffer is empty and we're writing a large amount */
 	if ((ncopy = shf->wnleft) &&
@@ -681,8 +736,13 @@ shf_write(const char *buf, ssize_t nbyte
 		if (shf->flags & SHF_STRING) {
 			/* resize buffer until there's enough space left */
 			while (nbytes > shf->wnleft)
-				if (shf_emptybuf(shf, EB_GROW) == -1)
-					return (-1);
+				if (shf_emptybuf(shf, EB_GROW) == -1) {
+					/* truncate if possible */
+					if (shf->wnleft == 0)
+						return (-1);
+					nbytes = shf->wnleft;
+					break;
+				}
 			/* then write everything into the buffer */
 		} else {
 			/* flush deals with sticky errors */
@@ -747,8 +807,8 @@ shf_snprintf(char *buf, ssize_t bsize, c
 	ssize_t n;
 
 	if (!buf || bsize <= 0)
-		internal_errorf("shf_snprintf: buf %zX, bsize %zd",
-		    (size_t)buf, bsize);
+		kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
+		    Tbad_buf, "shf_snprintf", (size_t)buf, bsize);
 
 	shf_sopen(buf, bsize, SHF_WR, &shf);
 	va_start(args, fmt);
@@ -773,31 +833,156 @@ shf_smprintf(const char *fmt, ...)
 	return (shf_sclose(&shf));
 }
 
-#define	FL_HASH		0x001	/* '#' seen */
-#define FL_PLUS		0x002	/* '+' seen */
-#define FL_RIGHT	0x004	/* '-' seen */
-#define FL_BLANK	0x008	/* ' ' seen */
-#define FL_SHORT	0x010	/* 'h' seen */
-#define FL_LONG		0x020	/* 'l' seen */
-#define FL_ZERO		0x040	/* '0' seen */
-#define FL_DOT		0x080	/* '.' seen */
-#define FL_UPPER	0x100	/* format character was uppercase */
-#define FL_NUMBER	0x200	/* a number was formatted %[douxefg] */
-#define FL_SIZET	0x400	/* 'z' seen */
-#define FM_SIZES	0x430	/* h/l/z mask */
+/* pre-initio() */
+char *
+kslfmt(ksl number, kui flags, char *numbuf)
+{
+	/* easy for positive number */
+	if (number >= 0)
+		return (kulfmt((kul)number, flags, numbuf));
+	/* negative signed quantity */
+	if (!IS(flags, FM_TYPE, FL_SGN)) {
+		/* uh-oh, output a signed quantity unsignedly */
+		return (kulfmt(mbiA_S2U(kul, ksl, number), flags, numbuf));
+	}
+	return (kulfmt(mbiA_S2M(kul, ksl, number), flags | FL_NEG, numbuf));
+}
+
+/* pre-initio() */
+char *
+kulfmt(kul number, kui flags, char *numbuf)
+{
+	char *cp;
+
+	cp = numbuf + NUMBUFSZ;
+	*--cp = '\0';
+	switch (flags & FM_TYPE) {
+	case FL_OCT:
+		do {
+			*--cp = digits_lc[number & 07UL];
+			number >>= 3;
+		} while (number);
+
+		if (HAS(flags, FL_HASH) && ord(*cp) != ORD('0'))
+			*--cp = '0';
+		break;
+	case FL_HEX: {
+		const char *digits;
+
+		digits = HAS(flags, FL_UCASE) ? digits_uc : digits_lc;
+		do {
+			*--cp = digits[number & 0xFUL];
+			number >>= 4;
+		} while (number);
+
+		if (HAS(flags, FL_HASH)) {
+			*--cp = IS(flags, FL_UPPER, FL_UPPER) ? 'X' : 'x';
+			*--cp = '0';
+		}
+		break;
+	    }
+	default:
+		do {
+			*--cp = digits_lc[number % 10UL];
+			number /= 10UL;
+		} while (number);
+
+		if (IS(flags, FM_TYPE, FL_SGN)) {
+			if (HAS(flags, FL_NEG))
+				*--cp = '-';
+			else if (HAS(flags, FL_PLUS))
+				*--cp = '+';
+			else if (HAS(flags, FL_BLANK))
+				*--cp = ' ';
+		}
+		break;
+	}
+
+	return (cp);
+}
+
+#ifdef MKSH_HAVE_HUGE
+/* pre-initio() */
+char *
+ksHfmt(ksH number, kui flags, char *numbuf)
+{
+	/* easy for positive number */
+	if (number >= 0)
+		return (kuHfmt((kuH)number, flags, numbuf));
+	/* negative signed quantity */
+	if (!IS(flags, FM_TYPE, FL_SGN)) {
+		/* uh-oh, output a signed quantity unsignedly */
+		return (kuHfmt(mbiA_S2U(kuH, ksH, number), flags, numbuf));
+	}
+	return (kuHfmt(mbiA_S2M(kuH, ksH, number), flags | FL_NEG, numbuf));
+}
+
+/* pre-initio() */
+char *
+kuHfmt(kuH number, kui flags, char *numbuf)
+{
+	char *cp;
+
+	cp = numbuf + NUMBUFSZ;
+	*--cp = '\0';
+	switch (flags & FM_TYPE) {
+	case FL_OCT:
+		do {
+			*--cp = digits_lc[number & 07UL];
+			number >>= 3;
+		} while (number);
+
+		if (HAS(flags, FL_HASH) && ord(*cp) != ORD('0'))
+			*--cp = '0';
+		break;
+	case FL_HEX: {
+		const char *digits;
+
+		digits = HAS(flags, FL_UCASE) ? digits_uc : digits_lc;
+		do {
+			*--cp = digits[number & 0xFUL];
+			number >>= 4;
+		} while (number);
+
+		if (HAS(flags, FL_HASH)) {
+			*--cp = IS(flags, FL_UPPER, FL_UPPER) ? 'X' : 'x';
+			*--cp = '0';
+		}
+		break;
+	    }
+	default:
+		do {
+			*--cp = digits_lc[number % 10UL];
+			number /= 10UL;
+		} while (number);
+
+		if (IS(flags, FM_TYPE, FL_SGN)) {
+			if (HAS(flags, FL_NEG))
+				*--cp = '-';
+			else if (HAS(flags, FL_PLUS))
+				*--cp = '+';
+			else if (HAS(flags, FL_BLANK))
+				*--cp = ' ';
+		}
+		break;
+	}
+
+	return (cp);
+}
+#endif
 
 ssize_t
 shf_vfprintf(struct shf *shf, const char *fmt, va_list args)
 {
+	char numbuf[NUMBUFSZ];
 	const char *s;
-	char c, *cp;
+	char c;
 	int tmp = 0, flags;
 	size_t field, precision, len;
-	unsigned long lnum;
-	/* %#o produces the longest output */
-	char numbuf[(8 * sizeof(long) + 2) / 3 + 1 + /* NUL */ 1];
 	/* this stuff for dealing with the buffer */
 	ssize_t nwritten = 0;
+	/* for width determination */
+	const char *lp, *np;
 
 #define VA(type) va_arg(args, type)
 
@@ -862,14 +1047,23 @@ shf_vfprintf(struct shf *shf, const char
 					field = (unsigned int)tmp;
 				continue;
 
-			case 'l':
+			case 'h':
 				flags &= ~FM_SIZES;
+				flags |= FL_SHORT;
+				continue;
+
+			case 'j':
+				flags &= ~FM_SIZES;
+#ifdef MKSH_HAVE_HUGE
+				flags |= FL_HUGE;
+#else
 				flags |= FL_LONG;
+#endif
 				continue;
 
-			case 'h':
+			case 'l':
 				flags &= ~FM_SIZES;
-				flags |= FL_SHORT;
+				flags |= FL_LONG;
 				continue;
 
 			case 'z':
@@ -878,17 +1072,8 @@ shf_vfprintf(struct shf *shf, const char
 				continue;
 			}
 			if (ctype(c, C_DIGIT)) {
-				bool overflowed = false;
-
-				tmp = ksh_numdig(c);
-				while (ctype((c = *fmt++), C_DIGIT))
-					if (notok2mul(2147483647, tmp, 10))
-						overflowed = true;
-					else
-						tmp = tmp * 10 + ksh_numdig(c);
 				--fmt;
-				if (overflowed)
-					tmp = 0;
+				getpn((const char **)&fmt, &tmp);
 				if (flags & FL_DOT)
 					precision = (unsigned int)tmp;
 				else
@@ -910,83 +1095,39 @@ shf_vfprintf(struct shf *shf, const char
 		switch (c) {
 		case 'd':
 		case 'i':
-			if (flags & FL_SIZET)
-				lnum = (long)VA(ssize_t);
-			else if (flags & FL_LONG)
-				lnum = VA(long);
-			else if (flags & FL_SHORT)
-				lnum = (long)(short)VA(int);
+#ifdef MKSH_HAVE_HUGE
+			if (HAS(flags, FL_HUGE))
+				s = ksHfmt(VA(ksH), flags | FL_SGN, numbuf);
 			else
-				lnum = (long)VA(int);
+#endif
+			  s = kslfmt(HAS(flags, FL_SIZET) ? (ksl)VA(ssize_t) :
+			    HAS(flags, FL_LONG) ? (ksl)VA(long) :
+			    HAS(flags, FL_SHORT) ? (ksl)(short)VA(int) :
+			    (ksl)VA(int), flags | FL_SGN, numbuf);
 			goto integral;
 
 		case 'o':
+			flags |= FL_OCT;
+			if (0)
+				/* FALLTHROUGH */
 		case 'u':
+			  flags |= FL_DEC;
+			if (0)
+				/* FALLTHROUGH */
 		case 'x':
-			if (flags & FL_SIZET)
-				lnum = VA(size_t);
-			else if (flags & FL_LONG)
-				lnum = VA(unsigned long);
-			else if (flags & FL_SHORT)
-				lnum = (unsigned long)(unsigned short)VA(int);
+			  flags |= FL_HEX;
+#ifdef MKSH_HAVE_HUGE
+			if (HAS(flags, FL_HUGE))
+				s = kuHfmt(VA(kuH), flags, numbuf);
 			else
-				lnum = (unsigned long)VA(unsigned int);
-
+#endif
+			  s = kulfmt(HAS(flags, FL_SIZET) ? (kul)VA(size_t) :
+			    HAS(flags, FL_LONG) ? (kul)VA(unsigned long) :
+			    HAS(flags, FL_SHORT) ? (kul)(unsigned short)VA(int) :
+			    (kul)VA(unsigned int), flags, numbuf);
  integral:
 			flags |= FL_NUMBER;
-			cp = numbuf + sizeof(numbuf);
-			*--cp = '\0';
-
-			switch (c) {
-			case 'd':
-			case 'i':
-				if (0 > (long)lnum) {
-					lnum = -(long)lnum;
-					tmp = 1;
-				} else
-					tmp = 0;
-				/* FALLTHROUGH */
-			case 'u':
-				do {
-					*--cp = digits_lc[lnum % 10];
-					lnum /= 10;
-				} while (lnum);
-
-				if (c != 'u') {
-					if (tmp)
-						*--cp = '-';
-					else if (flags & FL_PLUS)
-						*--cp = '+';
-					else if (flags & FL_BLANK)
-						*--cp = ' ';
-				}
-				break;
-
-			case 'o':
-				do {
-					*--cp = digits_lc[lnum & 0x7];
-					lnum >>= 3;
-				} while (lnum);
-
-				if ((flags & FL_HASH) && *cp != '0')
-					*--cp = '0';
-				break;
-
-			case 'x': {
-				const char *digits = (flags & FL_UPPER) ?
-				    digits_uc : digits_lc;
-				do {
-					*--cp = digits[lnum & 0xF];
-					lnum >>= 4;
-				} while (lnum);
-
-				if (flags & FL_HASH) {
-					*--cp = (flags & FL_UPPER) ? 'X' : 'x';
-					*--cp = '0';
-				}
-			    }
-			}
-			len = numbuf + sizeof(numbuf) - 1 - (s = cp);
+			len = NUMBUFLEN(numbuf, s);
 			if (flags & FL_DOT) {
 				if (precision > len) {
 					field = precision;
@@ -999,7 +1140,7 @@ shf_vfprintf(struct shf *shf, const char
 
 		case 's':
 			if ((s = VA(const char *)) == NULL)
-				s = "(null)";
+				s = Tnil;
 			else if (flags & FL_HASH) {
 				print_value_quoted(shf, s);
 				continue;
@@ -1027,11 +1168,30 @@ shf_vfprintf(struct shf *shf, const char
 		 */
 		if (!(flags & FL_DOT) || len < precision)
 			precision = len;
+		/* determine whether we can indeed write precision columns */
+		len = 0;
+		lp = s;
+		while (*lp) {
+			int w = utf_widthadj(lp, &np);
+
+			if ((len + w) > precision)
+				break;
+			lp = np;
+			len += w;
+		}
+		/* trailing combining characters */
+		if (UTFMODE)
+			while (*lp && utf_widthadj(lp, &np) == 0)
+				lp = np;
+		/* how much we can actually output */
+		precision = len;
+
+		/* output leading padding */
 		if (field > precision) {
 			field -= precision;
 			if (!(flags & FL_RIGHT)) {
 				/* skip past sign or 0x when padding with 0 */
-				if ((flags & FL_ZERO) && (flags & FL_NUMBER)) {
+				if ((flags & (FL_ZERO | FL_NUMBER)) == (FL_ZERO | FL_NUMBER)) {
 					if (ctype(*s, C_SPC | C_PLUS | C_MINUS)) {
 						shf_putc(*s, shf);
 						s++;
@@ -1042,7 +1202,7 @@ shf_vfprintf(struct shf *shf, const char
 						s++;
 						nwritten++;
 						if (--precision &&
-						    ksh_eq(*s, 'X', 'x')) {
+						    isCh(*s, 'X', 'x')) {
 							shf_putc(*s, shf);
 							s++;
 							precision--;
@@ -1061,11 +1221,11 @@ shf_vfprintf(struct shf *shf, const char
 		} else
 			field = 0;
 
-		nwritten += precision;
-		precision = utf_skipcols(s, precision, &tmp) - s;
-		while (precision--)
-			shf_putc(*s++, shf);
+		/* output string */
+		nwritten += (lp - s);
+		shf_write(s, lp - s, shf);
 
+		/* output trailing padding */
 		nwritten += field;
 		while (field--)
 			shf_putc(c, shf);
@@ -1088,34 +1248,38 @@ shf_putc(int c, struct shf *shf)
 }
 #endif
 
-#ifdef DEBUG
-const char *
-cstrerror(int errnum)
-{
-#undef strerror
-	return (strerror(errnum));
-#define strerror dontuse_strerror /* poisoned */
-}
-#elif !HAVE_STRERROR
+#if !HAVE_STRERROR
 
-#if HAVE_SYS_ERRLIST
+#if HAVE_STRERRORDESC_NP
+/* assume prototype, _GNU_SOURCE may be needed */
+#elif HAVE_SYS_ERRLIST
 #if !HAVE_SYS_ERRLIST_DECL
 extern const int sys_nerr;
 extern const char * const sys_errlist[];
 #endif
 #endif
 
+/* pre-initio() */
 const char *
 cstrerror(int errnum)
 {
-	/* "Unknown error: " + sign + rough estimate + NUL */
-	static char errbuf[15 + 1 + (8 * sizeof(int) + 2) / 3 + 1];
+#define unkerrstr "Unknown error: "
+#define unkerrlen (sizeof(unkerrstr) - 1U)
+	static char errbuf[unkerrlen + NUMBUFSZ];
+#if HAVE_STRERRORDESC_NP
+	const char *ccp;
+#endif
+	char *cp;
 
-#if HAVE_SYS_ERRLIST
+#if HAVE_STRERRORDESC_NP
+	if ((ccp = strerrordesc_np(errnum)))
+		return (ccp);
+#elif HAVE_SYS_ERRLIST
 	if (errnum > 0 && errnum < sys_nerr && sys_errlist[errnum])
 		return (sys_errlist[errnum]);
 #endif
 
+	/* do not add ERANGE, might be EOVERFLOW */
 	switch (errnum) {
 	case 0:
 		return ("Undefined error: 0");
@@ -1127,10 +1291,8 @@ cstrerror(int errnum)
 	case ESRCH:
 		return ("No such process");
 #endif
-#ifdef E2BIG
 	case E2BIG:
 		return ("Argument list too long");
-#endif
 	case ENOEXEC:
 		return ("Exec format error");
 	case EBADF:
@@ -1145,24 +1307,36 @@ cstrerror(int errnum)
 		return ("File exists");
 	case ENOTDIR:
 		return ("Not a directory");
-#ifdef EINVAL
 	case EINVAL:
 		return ("Invalid argument");
-#endif
 #ifdef ELOOP
 	case ELOOP:
 		return ("Too many levels of symbolic links");
 #endif
+	case EOVERFLOW:
+		return ("Value too large");
 	default:
-		shf_snprintf(errbuf, sizeof(errbuf),
-		    "Unknown error: %d", errnum);
-		return (errbuf);
+		cp = kslfmt(errnum, FL_SGN, errbuf + unkerrlen);
+		cp -= unkerrlen;
+		memcpy(cp, unkerrstr, unkerrlen);
+		return (cp);
 	}
+#undef unkerrlen
+#undef unkerrstr
+}
+#elif defined(DEBUG)
+/* pre-initio() */
+const char *
+cstrerror(int errnum)
+{
+#undef strerror
+	return (strerror(errnum));
+#define strerror dontuse_strerror /* poisoned */
 }
 #endif
 
 /* fast character classes */
-const uint32_t tpl_ctypes[128] = {
+const kui tpl_ctypes[128] = {
 	/* 0x00 */
 	CiNUL,		CiCNTRL,	CiCNTRL,	CiCNTRL,
 	CiCNTRL,	CiCNTRL,	CiCNTRL,	CiCNTRL,
@@ -1206,11 +1380,16 @@ const uint32_t tpl_ctypes[128] = {
 	CiLOWER,	CiLOWER,	CiLOWER,	CiLOWER,
 	CiLOWER,	CiLOWER,	CiLOWER,	CiLOWER,
 	CiLOWER,	CiLOWER,	CiLOWER,	CiCURLY,
-	CiQCL,		CiCURLY,	CiQCM,		CiCNTRL
+	CiQCL,		CiCURLY,	CiQCX,		CiCNTRL
 };
 
-void
-set_ifs(const char *s)
+#ifdef MKSH__DEBUG_CCLASSES
+static int debug_ccls(void);
+#endif
+
+/* pre-initio() */
+static void
+set_ccls(void)
 {
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
 	int i = 256;
@@ -1224,13 +1403,28 @@ set_ifs(const char *s)
 	memset((char *)ksh_ctypes + sizeof(tpl_ctypes), '\0',
 	    sizeof(ksh_ctypes) - sizeof(tpl_ctypes));
 #endif
+}
+
+/* pre-initio() */
+void
+set_ifs(const char *s)
+{
+	set_ccls();
 	ifs0 = *s;
 	while (*s)
 		ksh_ctypes[ord(*s++)] |= CiIFS;
+#ifdef MKSH__DEBUG_CCLASSES
+	if (debug_ccls())
+		exit(254);
+#endif
 }
 
 #if defined(MKSH_EBCDIC) || defined(MKSH_FAUX_EBCDIC)
-#include <locale.h>
+#if !HAVE_SETLOCALE_LCALL && !defined(MKSH_FAUX_EBCDIC)
+# error EBCDIC support requires use of the system locale
+#endif
+
+static void ebcdic_initerr(const char *, size_t, int, int, int) MKSH_A_NORETURN;
 
 /*
  * Many headaches with EBCDIC:
@@ -1239,8 +1433,8 @@ set_ifs(const char *s)
  *    contain all (most?) of the characters in ASCII, and these
  *    usually tend to agree on the code points assigned to the ASCII
  *    subset. If you need a representative example, look at EBCDIC 1047,
- *    which is first among equals in the IBM MVS development
- *    environment: https://en.wikipedia.org/wiki/EBCDIC_1047
+ *    which is first among equals in the IBM MVS development environment:
+ * https://web.archive.org/web/20200810035140/https://en.wikipedia.org/wiki/EBCDIC_1047
  *    Unfortunately, the square brackets are not consistently mapped,
  *    and for certain reasons, we need an unambiguous bijective
  *    mapping between EBCDIC and "extended ASCII".
@@ -1262,24 +1456,32 @@ set_ifs(const char *s)
  *    mainframe systems, using the -qascii option to the XL C compiler.
  *    We can determine the build mode by looking at __CHARSET_LIB:
  *    0 == EBCDIC, 1 == ASCII
+ *
+ * UTF-8 is not used, nor is UTF-EBCDIC really. We solve this problem
+ * by treating it as "nega-UTF-8": on EBCDIC systems, the output is
+ * converted to the "extended ASCII" codepage from the current EBCDIC
+ * codepage always so we convert UTF-8 backwards so the conversion
+ * will result in valid UTF-8. This may introduce fun on the EBCDIC
+ * side, but as it's not really used anyway we decided to take the risk.
  */
 
+/* pre-initio() */
 void
 ebcdic_init(void)
 {
 	int i = 256;
 	unsigned char t;
-	bool mapcache[256];
+	Wahr mapcache[256];
 
 	while (i--)
 		ebcdic_rtt_toascii[i] = i;
 	memset(ebcdic_rtt_fromascii, 0xFF, sizeof(ebcdic_rtt_fromascii));
 	setlocale(LC_ALL, "");
 #ifdef MKSH_EBCDIC
-	if (__etoa_l(ebcdic_rtt_toascii, 256) != 256) {
-		write(2, "mksh: could not map EBCDIC to ASCII\n", 36);
-		exit(255);
-	}
+	errno = ENOTDIR;
+	if ((i = __etoa_l(ebcdic_rtt_toascii, 256)) != 256)
+		ebcdic_initerr(SC("mksh: could not map EBCDIC to ASCII"),
+		    -1, i, errno);
 #endif
 
 	memset(mapcache, 0, sizeof(mapcache));
@@ -1287,15 +1489,14 @@ ebcdic_init(void)
 	while (i--) {
 		t = ebcdic_rtt_toascii[i];
 		/* ensure unique round-trip capable mapping */
-		if (mapcache[t]) {
-			write(2, "mksh: duplicate EBCDIC to ASCII mapping\n", 40);
-			exit(255);
-		}
+		if (mapcache[t])
+			ebcdic_initerr(SC("mksh: duplicate EBCDIC to ASCII mapping"),
+			    -2, i, ebcdic_rtt_fromascii[t]);
 		/*
 		 * since there are 256 input octets, this also ensures
 		 * the other mapping direction is completely filled
 		 */
-		mapcache[t] = true;
+		mapcache[t] = Ja;
 		/* fill the complete round-trip map */
 		ebcdic_rtt_fromascii[t] = i;
 		/*
@@ -1314,9 +1515,663 @@ ebcdic_init(void)
 		else
 			ebcdic_map[i] = (unsigned short)(0x100U | ord(i));
 	}
-	if (ebcdic_rtt_toascii[0] || ebcdic_rtt_fromascii[0] || ebcdic_map[0]) {
-		write(2, "mksh: NUL not at position 0\n", 28);
+	if (ebcdic_rtt_toascii[0] || ebcdic_rtt_fromascii[0] || ebcdic_map[0])
+		ebcdic_initerr(SC("mksh: NUL not at position 0"),
+		    ebcdic_rtt_toascii[0], ebcdic_rtt_fromascii[0],
+		    ebcdic_map[0]);
+	/* ensure control characters, i.e. 0x00‥0x3F and 0xFF, map sanely */
+	for (i = 0x00; i < 0x20; ++i)
+		if (!ksh_isctrl(asc2rtt(i)))
+			goto ebcdic_ctrlmis;
+	for (i = 0x7F; i < 0xA0; ++i)
+		if (!ksh_isctrl(asc2rtt(i))) {
+ ebcdic_ctrlmis:
+			ebcdic_initerr(SC("mksh: control character mismapping"),
+			    -2, i, asc2rtt(i));
+		}
+	/* validate character literals used in the code */
+#define litcheck(c,v) \
+	if (rtt2asc(c) != v) \
+		ebcdic_initerr(SC("mksh: compiler vs. runtime codepage mismatch"), \
+		    -3, c, rtt2asc(c))
+	litcheck('\n', 0x0AU);
+	litcheck('\r', 0x0DU);
+	litcheck(' ', 0x20U);
+	litcheck('!', 0x21U);
+	litcheck('"', 0x22U);
+	litcheck('#', 0x23U);
+	litcheck('$', 0x24U);
+	litcheck('%', 0x25U);
+	litcheck('&', 0x26U);
+	litcheck('\'', 0x27U);
+	litcheck('(', 0x28U);
+	litcheck(')', 0x29U);
+	litcheck('*', 0x2AU);
+	litcheck('+', 0x2BU);
+	litcheck(',', 0x2CU);
+	litcheck('-', 0x2DU);
+	litcheck('.', 0x2EU);
+	litcheck('/', 0x2FU);
+	litcheck('0', 0x30U);
+	litcheck(':', 0x3AU);
+	litcheck(';', 0x3BU);
+	litcheck('<', 0x3CU);
+	litcheck('=', 0x3DU);
+	litcheck('>', 0x3EU);
+	litcheck('?', 0x3FU);
+	litcheck('@', 0x40U);
+	litcheck('A', 0x41U);
+	litcheck('B', 0x42U);
+	litcheck('C', 0x43U);
+	litcheck('D', 0x44U);
+	litcheck('E', 0x45U);
+	litcheck('F', 0x46U);
+	litcheck('G', 0x47U);
+	litcheck('H', 0x48U);
+	litcheck('I', 0x49U);
+	litcheck('N', 0x4EU);
+	litcheck('O', 0x4FU);
+	litcheck('P', 0x50U);
+	litcheck('Q', 0x51U);
+	litcheck('R', 0x52U);
+	litcheck('S', 0x53U);
+	litcheck('T', 0x54U);
+	litcheck('U', 0x55U);
+	litcheck('W', 0x57U);
+	litcheck('X', 0x58U);
+	litcheck('Y', 0x59U);
+	litcheck('[', 0x5BU);
+	litcheck('\\', 0x5CU);
+	litcheck(']', 0x5DU);
+	litcheck('^', 0x5EU);
+	litcheck('_', 0x5FU);
+	litcheck('`', 0x60U);
+	litcheck('a', 0x61U);
+	litcheck('b', 0x62U);
+	litcheck('c', 0x63U);
+	litcheck('d', 0x64U);
+	litcheck('e', 0x65U);
+	litcheck('f', 0x66U);
+	litcheck('g', 0x67U);
+	litcheck('h', 0x68U);
+	litcheck('i', 0x69U);
+	litcheck('j', 0x6AU);
+	litcheck('k', 0x6BU);
+	litcheck('l', 0x6CU);
+	litcheck('n', 0x6EU);
+	litcheck('p', 0x70U);
+	litcheck('r', 0x72U);
+	litcheck('s', 0x73U);
+	litcheck('t', 0x74U);
+	litcheck('u', 0x75U);
+	litcheck('v', 0x76U);
+	litcheck('w', 0x77U);
+	litcheck('x', 0x78U);
+	litcheck('y', 0x79U);
+	litcheck('{', 0x7BU);
+	litcheck('|', 0x7CU);
+	litcheck('}', 0x7DU);
+	litcheck('~', 0x7EU);
+#undef litcheck
+	/* validate sh.h control character literals */
+#define ctlcheck(n,c,v) \
+	if (rtt2asc(c) != v) \
+		ebcdic_initerr(SC("mksh: control character mismapping"), \
+		    -3, n, rtt2asc(c))
+	ctlcheck('@', CTRL_AT, 0x00U);
+	ctlcheck('A', CTRL_A, 0x01U);
+	ctlcheck('B', CTRL_B, 0x02U);
+	ctlcheck('C', CTRL_C, 0x03U);
+	ctlcheck('D', CTRL_D, 0x04U);
+	ctlcheck('E', CTRL_E, 0x05U);
+	ctlcheck('F', CTRL_F, 0x06U);
+	ctlcheck('G', CTRL_G, 0x07U);
+	ctlcheck('H', CTRL_H, 0x08U);
+	ctlcheck('I', CTRL_I, 0x09U);
+	ctlcheck('J', CTRL_J, 0x0AU);
+	ctlcheck('K', CTRL_K, 0x0BU);
+	ctlcheck('L', CTRL_L, 0x0CU);
+	ctlcheck('M', CTRL_M, 0x0DU);
+	ctlcheck('N', CTRL_N, 0x0EU);
+	ctlcheck('O', CTRL_O, 0x0FU);
+	ctlcheck('P', CTRL_P, 0x10U);
+	ctlcheck('Q', CTRL_Q, 0x11U);
+	ctlcheck('R', CTRL_R, 0x12U);
+	ctlcheck('S', CTRL_S, 0x13U);
+	ctlcheck('T', CTRL_T, 0x14U);
+	ctlcheck('U', CTRL_U, 0x15U);
+	ctlcheck('V', CTRL_V, 0x16U);
+	ctlcheck('W', CTRL_W, 0x17U);
+	ctlcheck('X', CTRL_X, 0x18U);
+	ctlcheck('Y', CTRL_Y, 0x19U);
+	ctlcheck('Z', CTRL_Z, 0x1AU);
+	ctlcheck('[', CTRL_BO, 0x1BU);
+	ctlcheck('\\', CTRL_BK, 0x1CU);
+	ctlcheck(']', CTRL_BC, 0x1DU);
+	ctlcheck('^', CTRL_CA, 0x1EU);
+	ctlcheck('_', CTRL_US, 0x1FU);
+	ctlcheck('?', CTRL_QM, 0x7FU);
+#undef ctlcheck
+}
+
+/* pre-initio() */
+static void
+ebcdic_initerr(const char *s, size_t n, int a, int b, int c)
+{
+	char buf[NUMBUFSZ + 3];
+	char *cp;
+	const char *ccp;
+
+	SHIKATANAI write(2, s, n);
+	/*
+	 * a>=0: a,b,c=hex
+	 * a=-1: b=sgn c=errno
+	 * a=-2: b=hex c=hex
+	 * a=-3: b=chr c=hex
+	 */
+	if (a == -1) {
+		ccp = cstrerror(c);
+		cp = kslfmt(b, FL_SGN, buf + 1U);
+		*--cp = '<';
+		buf[NUMBUFSZ] = '>';
+		buf[NUMBUFSZ + 1U] = ccp ? '<' : '(';
+		SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 2U);
+		if (ccp) {
+			SHIKATANAI write(2, SZ(ccp));
+			SHIKATANAI write(2, SC(">\n"));
+		} else
+			SHIKATANAI write(2, SC("unknown error)\n"));
 		exit(255);
 	}
+	if (a == -3) {
+		buf[0] = '<';
+		buf[1] = b;
+		buf[2] = '>';
+		SHIKATANAI write(2, buf, 3);
+	} else {
+		if (a != -2) {
+			cp = kslfmt(a, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+			*--cp = '<';
+			buf[NUMBUFSZ] = '>';
+			SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 1U);
+		}
+		cp = kslfmt(b, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+		*--cp = '<';
+		buf[NUMBUFSZ] = '>';
+		SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 1U);
+	}
+	cp = kslfmt(c, FL_HEX | FL_UCASE | FL_HASH, buf + 1);
+	*--cp = '<';
+	buf[NUMBUFSZ] = '>';
+	buf[NUMBUFSZ + 1U] = '\n';
+	SHIKATANAI write(2, cp, NUMBUFLEN(buf + 1U, cp) + 2U);
+	exit(255);
+}
+#endif
+
+#ifdef MKSH__DEBUG_CCLASSES
+/*
+ * This is developer debugging code. It makes no attempt
+ * at being performant, not redundant, have acceptable
+ * style, or anything really.
+ */
+
+/* pre-initio() */
+static unsigned int
+v(unsigned int c)
+{
+	if (ord(c) == ORD('\\')) {
+		printf("\\\\");
+		return (2);
+	} else if (c < 0x21U || c > 0x7EU) {
+		printf("\\x%02X", c);
+		return (4);
+	} else {
+		putchar(c);
+		return (1);
+	}
+}
+
+#define tabto(len,to) do {		\
+	while (len < to) {		\
+		putchar('\t');		\
+		len = (len | 7) + 1;	\
+	}				\
+} while (/* CONSTCOND */ 0)
+
+static char vert[40][40];
+
+static struct ciname {
+	const char *name;
+	kui val;
+	kui bit;
+} ci[32], *cibit[32];
+
+/* pre-initio() */
+static int
+cicomp(const void *a_, const void *b_)
+{
+	const struct ciname *a = a_;
+	const struct ciname *b = b_;
+	return (strcmp(a->name, b->name));
+}
+
+/* pre-initio() */
+static int
+debug_ccls(void)
+{
+	unsigned int i, j, k, x, y, z;
+
+	printf("\t0               1               2               3               4               5               6               7            ->7\n");
+	printf("\t0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF\n");
+#define D(x) do { \
+	printf("%s\t", #x); \
+	for (i = 0; i <= 0x7F; ++i) \
+		putchar(tpl_ctypes[i] & x ? '#' : '-'); \
+	putchar('\n'); \
+} while (/* CONSTCOND */ 0)
+#define DCi() do {	\
+	D(CiIFS);	\
+	D(CiCNTRL);	\
+	D(CiUPPER);	\
+	D(CiLOWER);	\
+	D(CiHEXLT);	\
+	D(CiOCTAL);	\
+	D(CiQCL);	\
+	D(CiALIAS);	\
+	D(CiQCX);	\
+	D(CiVAR1);	\
+	D(CiQCM);	\
+	D(CiDIGIT);	\
+	D(CiQC);	\
+	D(CiSPX);	\
+	D(CiCURLY);	\
+	D(CiANGLE);	\
+	D(CiNUL);	\
+	D(CiTAB);	\
+	D(CiNL);	\
+	D(CiCR);	\
+	D(CiSP);	\
+	D(CiHASH);	\
+	D(CiSS);	\
+	D(CiPERCT);	\
+	D(CiPLUS);	\
+	D(CiMINUS);	\
+	D(CiCOLON);	\
+	D(CiEQUAL);	\
+	D(CiQUEST);	\
+	D(CiBRACK);	\
+	D(CiUNDER);	\
+	D(CiGRAVE);	\
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	putchar('\n');
+
+	printf("\t  i i i i i   i       i     i i               i   i i i i i i i\n");
+	printf("\tC C U L H O   A   i   D     C A           i   P i M C E Q B U G\n");
+	printf("\ti N P O E C i L i V i I   i U N i i       H   E P I O Q U R N R\n");
+	printf("\tI T P W X T Q I Q A Q G i S R G N T i i i A i R L N L U E A D A\n");
+	printf("\tF R E E L A C A C R C I Q P L L U A N C S S S C U U O A S C E V\n");
+	printf("\tS L R R T L L S X 1 M T C X Y E L B L R P H S T S S N L T K R E\n");
+	j = 0;
+#define D(x,i1,i2,i3) do { \
+	printf("%s\t", #x); \
+	for (i = 0; i <= 31; ++i) { \
+		printf(x & BIT(i) ? "**" : "- "); \
+		vert[i][j] = (x & BIT(i) ? '#' : '-'); \
+	} \
+	printf("\t%08X\n", x); \
+	++j; \
+} while (/* CONSTCOND */ 0)
+#define DC_() do {	\
+	D(C_ALIAS, 2, 24, "valid characters in alias names"); \
+	D(C_ALNUM, 1, 24, "alphanumerical"); \
+	D(C_ALNUX, 1, 24, "alphanumerical plus underscore (“word character”)"); \
+	D(C_ALPHA, 1, 24, "alphabetical (upper plus lower)"); \
+	D(C_ALPHX, 1, 24, "alphabetical plus underscore (identifier lead)"); \
+	D(C_ASCII, 1, 24, "7-bit ASCII except NUL"); \
+	D(C_BLANK, 0, 24, "tab and space"); \
+	D(C_CNTRL, 1, 24, "POSIX control characters"); \
+	D(C_DIGIT, 1, 24, "decimal digits"); \
+	D(C_EDCMD, 0, 32, "editor x_locate_word() command"); \
+	D(C_EDGLB, 0, 32, "escape for globbing"); \
+	D(C_EDNWC, 0, 32, "editor non-word characters"); \
+	D(C_EDQ, 0, 32, "editor quotes for tab completion"); \
+	D(C_GRAPH, 1, 24, "POSIX graphical (alphanumerical plus punctuation)"); \
+	D(C_HEXLT, 1, 24, "hex letter"); \
+	D(C_IFS, 0, 24, "IFS whitespace, IFS non-whitespace, NUL"); \
+	D(C_IFSWS, 0, 24, "IFS whitespace candidates"); \
+	D(C_LEX1, 0, 24, "(for the lexer)"); \
+	D(C_LOWER, 1, 24, "lowercase letters"); \
+	D(C_MFS, 3, 24, "separator for motion"); \
+	D(C_OCTAL, 1, 24, "octal digit"); \
+	D(C_PATMO, 0, 24, "pattern magical operator, except space"); \
+	D(C_PRINT, 1, 24, "POSIX printable characters (graph plus space)"); \
+	D(C_PUNCT, 0, 40, "POSIX punctuation"); \
+	D(C_QUOTE, 0, 40, "characters requiring quoting, minus space"); \
+	D(C_SEDEC, 1, 24, "hexadecimal digit"); \
+	D(C_SPACE, 1, 24, "POSIX space class"); \
+	D(C_SUB1, 0, 24, "substitution operations with word"); \
+	D(C_SUB2, 0, 24, "substitution operations with pattern"); \
+	D(C_UPPER, 1, 24, "uppercase letters"); \
+	D(C_VAR1, 0, 24, "substitution parameters, other than positional"); \
+} while (/* CONSTCOND */ 0)
+	DC_();
+#undef D
+	putchar('\n');
+
+	for (i = 0; i <= 31; ++i)
+		vert[i][j] = 0;
+	j = 0;
+#define D(x) do { \
+	printf("%s\t%s\n", #x, vert[j++]); \
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	putchar('\n');
+
+#define D(x) do {					\
+	y = 0;						\
+	while (BIT(y) != x)				\
+		if (y++ == 31) {			\
+			printf("E: %s=%X\n", #x, x);	\
+			exit(255);			\
+		}					\
+	ci[y].name = #x;				\
+	ci[y].val = x;				\
+	ci[y].bit = y;					\
+} while (/* CONSTCOND */ 0)
+	DCi();
+#undef D
+	qsort(ci, NELEM(ci), sizeof(struct ciname), &cicomp);
+	for (i = 0; i < NELEM(ci); ++i) {
+		cibit[ci[i].bit] = &ci[i];
+		printf("BIT(%d)\t%08X  %s\n", ci[i].bit, ci[i].val, ci[i].name);
+	}
+	putchar('\n');
+
+#define D(x) do { \
+	if (x != CiIFS && (ksh_ctypes[i] & x)) { \
+		if (z) { \
+			printf(" | "); \
+			z += 3; \
+		} \
+		printf("%s", #x); \
+		z += strlen(#x); \
+	} \
+} while (/* CONSTCOND */ 0)
+	printf("// shf.c begin {{{\n/* fast character classes */\n");
+	printf("const kui tpl_ctypes[128] = {\n");
+	x = 0, y = 0; /* fsck GCC */
+	for (i = 0; i <= 0x7F; ++i) {
+		if (!(i & 0x0F)) {
+			printf("\t/* 0x%02X */\n", i);
+			x = 1; /* did newline */
+		}
+		if (x) {
+			printf("\t");
+			x = 0;
+			y = 16;
+		}
+		z = 0;
+		DCi();
+		if (i != 0x7F) {
+			putchar(',');
+			++z;
+		}
+		if (((i & 0x03) == 0x03) || ((i & 0x59) == 0x41)) {
+			putchar('\n');
+			x = 1;
+		} else {
+			if ((i & 0x58) == 0x40)
+				y = 24;
+			tabto(z, y);
+			if (z > 16) {
+				y = 8;
+				tabto(z, 24);
+			}
+		}
+	}
+#undef D
+	printf("};\n// shf.c end }}}\n\n");
+
+#define putrangef(len,cond,count) do {			\
+	for (count = 0; count <= 0xFF; ++count)		\
+		if (ksh_ctypes[count] & cond)		\
+			len += v(count);		\
+} while (/* CONSTCOND */ 0)
+#define putranget(len,cond,count,hold,flag) do {	\
+	flag = 0;					\
+	count = -1;					\
+	while (1) {					\
+		++count;				\
+		if (!flag) {				\
+			if (count > 0xFF)		\
+				break;			\
+			if (ksh_ctypes[count] & cond) {	\
+				hold = count;		\
+				flag = 1;		\
+			}				\
+		} else if (count > 0xFF ||		\
+		    !(ksh_ctypes[count] & cond)) {	\
+			flag = count - 1;		\
+			len += v(hold);			\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			if (count > 0xFF)		\
+				break;			\
+			flag = 0;			\
+		}					\
+	}						\
+} while (/* CONSTCOND */ 0)
+#define putrangea(len,cond,count,hold,flag) do {	\
+	flag = 0;					\
+	count = -1;					\
+	while (1) {					\
+		++count;				\
+		if (!flag) {				\
+			if (count > 0xFF)		\
+				break;			\
+			if (ksh_ctypes[count] & cond) {	\
+				len += v(count);	\
+				hold = count;		\
+				flag = count == '0' ||	\
+				    count == 'A' ||	\
+				    count == 'a';	\
+			}				\
+		} else if (count > 0xFF ||		\
+		    !(ksh_ctypes[count] & cond)) {	\
+			flag = count - 1;		\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			if (count > 0xFF)		\
+				break;			\
+			flag = 0;			\
+		} else if ((count - 1) == '9' ||	\
+		    (count - 1) == 'Z' ||		\
+		    (count - 1) == 'z') {		\
+			flag = count - 1;		\
+			if (flag == hold + 1) {		\
+				len += v(flag);		\
+			} else if (flag > hold) {	\
+				printf("‥");		\
+				len += 1 + v(flag);	\
+			}				\
+			len += v(count);		\
+			flag = 0;			\
+		}					\
+	}						\
+} while (/* CONSTCOND */ 0)
+
+#define DD(n,x,ign) do {				\
+	y = 0;						\
+	while (BIT(y) != x)				\
+		if (y++ == 31) {			\
+			printf("E: %s=%X\n", n, x);	\
+			exit(255);			\
+		}					\
+	printf("#define %s\tBIT(%d)", n, y);		\
+	if (x != ign) {					\
+		printf("\t/* ");			\
+		y = 3;					\
+		switch (x) {				\
+		case CiCNTRL:				\
+		case CiUPPER: case CiLOWER:		\
+		case CiHEXLT: case CiOCTAL:		\
+			putranget(y, x, i, j, k);	\
+			break;				\
+		default:				\
+			putrangef(y, x, i);		\
+		}					\
+		tabto(y, 32);				\
+		printf("*/");				\
+	}						\
+	putchar('\n');					\
+} while (/* CONSTCOND */ 0)
+	DD("??IFS", CiIFS, CiCNTRL);
+
+	printf("// sh.h begin {{{\n/*\n * fast character classes\n */\n\n");
+	printf("/* internal types, do not reference */\n\n");
+
+#define D(x) DD(#x, x, CiIFS)
+	printf("/* initially empty — filled at runtime from $IFS */\n");
+	DCi();
+#undef DD
+#undef D
+	printf("/* out of space, but one for *@ would make sense, possibly others */\n\n");
+
+	printf("/* compile-time initialised, ASCII only */\n"
+		"extern const kui tpl_ctypes[128];\n"
+		"/* run-time, contains C_IFS as well, full 2⁸ octet range */\n"
+		"EXTERN kui ksh_ctypes[256];\n"
+		"/* first octet of $IFS, for concatenating \"$*\" */\n"
+		"EXTERN char ifs0;\n"
+		"\n");
+
+#define expcond(cond,len,cnt,flg,fnd,cnd) do {		\
+	flg = 1;					\
+	for (cnt = 0; cnt < NELEM(ci); ++cnt)		\
+		if (cond == ci[cnt].val) {		\
+			len += printf("%s",		\
+			    ci[cnt].name);		\
+			flg = 0;			\
+			break;				\
+		}					\
+	if (flg) {					\
+		cnd = cond;				\
+		fnd = 0;				\
+		if (cnd != C_GRAPH &&			\
+		    (cnd & C_GRAPH) == C_GRAPH) {	\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    "C_GRAPH");			\
+			fnd = 1;			\
+			cnd &= ~C_GRAPH;		\
+		}					\
+		if (cnd != C_PUNCT &&			\
+		    (cnd & C_PUNCT) == C_PUNCT) {	\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    "C_PUNCT");			\
+			fnd = 1;			\
+			cnd &= ~C_PUNCT;		\
+		}					\
+		for (cnt = 0; cnt < NELEM(ci); ++cnt)	\
+		   if (cnd & ci[cnt].val) {		\
+			len += printf("%s%s",		\
+			    fnd ? " | " : "(",		\
+			    ci[cnt].name);		\
+			fnd = 1;			\
+		}					\
+		if (!fnd) {				\
+			printf("<ERR>\n");		\
+			exit(255);			\
+		}					\
+		putchar(')');				\
+		++len;					\
+	}						\
+} while (/* CONSTCOND */ 0)
+
+	set_ccls(); /* drop CiIFS from ksh_ctypes */
+#define D(cond,rng,tabstop,lbl) do {			\
+	printf("/* ");					\
+	y = 3;						\
+	switch (rng) {					\
+	case 0:						\
+		putrangef(y, cond, i);			\
+		break;					\
+	case 1:						\
+		putranget(y, cond, i, j, k);		\
+		break;					\
+	case 2:						\
+		putrangea(y, cond, i, j, k);		\
+		break;					\
+	case 3:						\
+		for (i = 0; i <= 0x7F; ++i) {		\
+			if (!!(ksh_ctypes[i] & cond) ^	\
+			    !!(ksh_ctypes[i] & (	\
+			    C_ALNUX | CiSS)))		\
+				continue;		\
+			printf("<ERR(%02X)>\n", i);	\
+			exit(255);			\
+		}					\
+		y += printf("not alnux or dollar");	\
+		break;					\
+	}						\
+	if (cond & CiIFS)				\
+		y += printf(" + $IFS");			\
+	tabto(y, tabstop);				\
+	printf("%s */\n#define %s\t", lbl, #cond);	\
+	expcond(cond, y, i, z, j, k);			\
+	putchar('\n');					\
+} while (/* CONSTCOND */ 0)
+	printf("/* external types */\n\n");
+	DC_();
+#undef D
+
+#define D(x,lbl) do {			\
+	y = printf("#define %s", #x);	\
+	tabto(y, 16);			\
+	expcond(x, y, i, z, j, k);	\
+	tabto(y, 32);			\
+	y += printf("/* ");		\
+	putrangef(y, x, i);		\
+	tabto(y, 40);			\
+	printf("%s */\n", lbl);		\
+} while (/* CONSTCOND */ 0)
+	printf("\n/* individual chars you might like */\n");
+	D(C_ANGLE, "angle brackets");
+	D(C_COLON, "colon");
+	D(C_CR, "ASCII carriage return");
+	D(C_DOLAR, "dollar sign");
+	D(C_EQUAL, "equals sign");
+	D(C_GRAVE, "accent gravis");
+	D(C_HASH, "hash sign");
+	D(C_LF, "ASCII line feed");
+	D(C_MINUS, "hyphen-minus");
+	printf("#ifdef MKSH_WITH_TEXTMODE\n"
+		"#define C_NL\t(CiNL | CiCR)\t/*\tCR or LF under OS/2 TEXTMODE */\n"
+		"#else\n"
+		"#define C_NL\tCiNL\t\t/*\tLF only like under Unix */\n"
+		"#endif\n");
+	D(C_NUL, "ASCII NUL");
+	D(C_PLUS, "plus sign");
+	D(C_QC, "quote characters");
+	D(C_QUEST, "question mark");
+	D(C_SPC, "ASCII space");
+	D(C_TAB, "ASCII horizontal tabulator");
+	D(C_UNDER, "underscore");
+
+	printf("// sh.h end }}}\n");
+	return (ksh_ctypes[0] == CiNUL);
 }
 #endif
--- mksh-59c.orig/syn.c
+++ mksh-59c/syn.c
@@ -3,7 +3,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2018, 2020
+ *		 2018, 2020, 2021, 2023, 2024
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -22,9 +22,11 @@
  * of said person's immediate fault when using the work as intended.
  */
 
+/* to avoid -Wmissing-format-attribute on vwarnf(), which is no candidate */
+#define MKSH_SHF_VFPRINTF_NO_GCC_FORMAT_ATTRIBUTE
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/syn.c,v 1.129 2020/10/31 01:21:58 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/syn.c,v 1.153 2024/07/26 18:39:09 tg Exp $");
 
 struct nesting_state {
 	int start_token;	/* token than began nesting (eg, FOR) */
@@ -37,46 +39,54 @@ struct yyrecursive_state {
 	struct ioword **old_herep;
 	int old_symbol;
 	unsigned int old_nesting_type;
-	bool old_reject;
+	Wahr old_reject;
 };
 
-static void yyparse(bool);
+static void yyparse(Wahr);
 static struct op *pipeline(int, int);
 static struct op *andor(int);
-static struct op *c_list(int, bool);
+static struct op *c_list(int, Wahr);
 static struct ioword *synio(int);
-static struct op *nested(int, int, int, int);
+static struct op *nested(int, unsigned int, unsigned int, int);
 static struct op *get_command(int, int);
 static struct op *dogroup(int);
 static struct op *thenpart(int);
 static struct op *elsepart(int);
 static struct op *caselist(int);
 static struct op *casepart(int, int);
-static struct op *function_body(char *, int, bool);
+static struct op *function_body(char *, int, Wahr);
 static char **wordlist(int);
 static struct op *block(int, struct op *, struct op *);
 static struct op *newtp(int);
 static void syntaxerr(const char *) MKSH_A_NORETURN;
 static void nesting_push(struct nesting_state *, int);
 static void nesting_pop(struct nesting_state *);
-static int inalias(struct source *) MKSH_A_PURE;
+static int inalias(struct source *);
 static Test_op dbtestp_isa(Test_env *, Test_meta);
-static const char *dbtestp_getopnd(Test_env *, Test_op, bool);
+static const char *dbtestp_getopnd(Test_env *, Test_op, Wahr);
 static int dbtestp_eval(Test_env *, Test_op, const char *,
-    const char *, bool);
+    const char *, Wahr);
 static void dbtestp_error(Test_env *, int, const char *) MKSH_A_NORETURN;
 
+static void vwarnf(unsigned int, int, const char *, va_list);
+#ifndef MKSH_SMALL
+static void vwarnf0(unsigned int, int, const char *, va_list)
+    MKSH_A_FORMAT(__printf__, 3, 0);
+#else
+#define vwarnf0 vwarnf
+#endif
+
 static struct op *outtree;		/* yyparse output */
 static struct nesting_state nesting;	/* \n changed to ; */
 
-static bool reject;			/* token(cf) gets symbol again */
+static Wahr reject;			/* token(cf) gets symbol again */
 static int symbol;			/* yylex value */
 
-#define REJECT		(reject = true)
-#define ACCEPT		(reject = false)
-#define token(cf)	((reject) ? (ACCEPT, symbol) : (symbol = yylex(cf)))
-#define tpeek(cf)	((reject) ? (symbol) : (REJECT, symbol = yylex(cf)))
-#define musthave(c,cf)	do { 					\
+#define REJECT		(reject = Ja)
+#define ACCEPT		(reject = Nee)
+#define token(cf)	((reject ? 0 : (symbol = yylex(cf))), ACCEPT, symbol)
+#define tpeek(cf)	((reject ? 0 : (symbol = yylex(cf))), REJECT, symbol)
+#define musthave(c,cf)	do {					\
 	if ((unsigned int)token(cf) != (unsigned int)(c))	\
 		syntaxerr(NULL);				\
 } while (/* CONSTCOND */ 0)
@@ -85,7 +95,7 @@ static const char Tcbrace[] = "}";
 static const char Tesac[] = "esac";
 
 static void
-yyparse(bool doalias)
+yyparse(Wahr doalias)
 {
 	int c;
 
@@ -138,11 +148,11 @@ andor(int sALIAS)
 }
 
 static struct op *
-c_list(int sALIAS, bool multi)
+c_list(int sALIAS, Wahr multi)
 {
 	struct op *t = NULL, *p, *tl = NULL;
 	int c;
-	bool have_sep;
+	Wahr have_sep;
 
 	while (/* CONSTCOND */ 1) {
 		p = andor(sALIAS);
@@ -151,7 +161,7 @@ c_list(int sALIAS, bool multi)
 		 * we don't worry about what flags to pass token()
 		 */
 		c = token(0);
-		have_sep = true;
+		have_sep = Ja;
 		if (c == '\n' && (multi || inalias(source))) {
 			if (!p)
 				/* ignore blank lines */
@@ -161,7 +171,7 @@ c_list(int sALIAS, bool multi)
 		else if (c == '&' || c == COPROC)
 			p = block(c == '&' ? TASYNC : TCOPROC, p, NULL);
 		else if (c != ';')
-			have_sep = false;
+			have_sep = Nee;
 		if (!t)
 			t = p;
 		else if (!tl)
@@ -181,19 +191,16 @@ static struct ioword *
 synio(int cf)
 {
 	struct ioword *iop;
-	static struct ioword *nextiop;
-	bool ishere;
-
-	if (nextiop != NULL) {
-		iop = nextiop;
-		nextiop = NULL;
-		return (iop);
-	}
+	Wahr ishere;
 
 	if (tpeek(cf) != REDIR)
 		return (NULL);
 	ACCEPT;
 	iop = yylval.iop;
+	if (iop->ioflag & IOSYNIONEXT) {
+		iop->ioflag &= ~IOSYNIONEXT;
+		return (iop);
+	}
 	ishere = (iop->ioflag & IOTYPE) == IOHERE;
 	if (iop->ioflag & IOHERESTR) {
 		musthave(LWORD, 0);
@@ -216,31 +223,31 @@ synio(int cf)
 		iop->ioname = yylval.cp;
 
 	if (iop->ioflag & IOBASH) {
-		char *cp;
-
-		nextiop = alloc(sizeof(*iop), ATEMP);
-		nextiop->ioname = cp = alloc(3, ATEMP);
-		*cp++ = CHAR;
-		*cp++ = digits_lc[iop->unit % 10];
-		*cp = EOS;
-
 		iop->ioflag &= ~IOBASH;
-		nextiop->unit = 2;
-		nextiop->ioflag = IODUP;
-		nextiop->delim = NULL;
-		nextiop->heredoc = NULL;
+
+		yylval.iop = alloc(sizeof(struct ioword), ATEMP);
+		yylval.iop->ioname = alloc(3U, ATEMP);
+		yylval.iop->ioname[0] = CHAR;
+		yylval.iop->ioname[1] = digits_lc[iop->unit];
+		yylval.iop->ioname[2] = EOS;
+		yylval.iop->delim = NULL;
+		yylval.iop->heredoc = NULL;
+		yylval.iop->ioflag = IODUP | IOSYNIONEXT;
+		yylval.iop->unit = 2;
+		REJECT;
+		symbol = REDIR;
 	}
 	return (iop);
 }
 
 static struct op *
-nested(int type, int smark, int emark, int sALIAS)
+nested(int type, unsigned int smark, unsigned int emark, int sALIAS)
 {
 	struct op *t;
 	struct nesting_state old_nesting;
 
-	nesting_push(&old_nesting, smark);
-	t = c_list(sALIAS, true);
+	nesting_push(&old_nesting, (int)smark);
+	t = c_list(sALIAS, Ja);
 	musthave(emark, KEYWORD|sALIAS);
 	nesting_pop(&old_nesting);
 	return (block(type, t, NULL));
@@ -271,8 +278,8 @@ get_command(int cf, int sALIAS)
 	struct ioword *iop;
 	XPtrV args, vars;
 	struct nesting_state old_nesting;
-	bool check_decl_utility;
-	static struct ioword *iops[NUFILE + 1];
+	Wahr check_decl_utility;
+	struct ioword *iops[NUFILE + 1];
 
 	XPinit(args, 16);
 	XPinit(vars, 16);
@@ -297,7 +304,7 @@ get_command(int cf, int sALIAS)
  get_command_loop:
 		if (XPsize(args) == 0) {
  get_command_start:
-			check_decl_utility = true;
+			check_decl_utility = Ja;
 			cf = sALIAS | CMDASN;
 		} else if (t->u.evalflags)
 			cf = CMDWORD | CMDASN;
@@ -317,16 +324,16 @@ get_command(int cf, int sALIAS)
 			ACCEPT;
 			if (check_decl_utility) {
 				struct tbl *tt = get_builtin(ident);
-				uint32_t flag;
+				kui flag;
 
 				flag = tt ? tt->flag : 0;
 				if (flag & DECL_UTIL)
 					t->u.evalflags = DOVACHECK;
 				if (!(flag & DECL_FWDR))
-					check_decl_utility = false;
+					check_decl_utility = Nee;
 			}
 			if ((XPsize(args) == 0 || Flag(FKEYWORD)) &&
-			    is_wdvarassign(yylval.cp))
+			    is_wdvarassign(yylval.cp, Nee))
 				XPput(vars, yylval.cp);
 			else
 				XPput(args, yylval.cp);
@@ -334,7 +341,7 @@ get_command(int cf, int sALIAS)
 
 		case ORD('(' /*)*/):
 			if (XPsize(args) == 0 && XPsize(vars) == 1 &&
-			    is_wdvarassign(yylval.cp)) {
+			    is_wdvarassign(yylval.cp, Ja)) {
 				char *tcp;
 
 				/* wdarrassign: foo=(bar) */
@@ -376,8 +383,7 @@ get_command(int cf, int sALIAS)
 				syntaxerr(NULL);
 			ACCEPT;
 			musthave(/*(*/ ')', 0);
-			t = function_body(XPptrv(args)[0],
-			    sALIAS, false);
+			t = function_body(XPptrv(args)[0], sALIAS, Nee);
 			break;
 		}
 		break;
@@ -438,7 +444,7 @@ get_command(int cf, int sALIAS)
 	case SELECT:
 		t = newtp((c == FOR) ? TFOR : TSELECT);
 		musthave(LWORD, CMDASN);
-		if (!is_wdvarname(yylval.cp, true))
+		if (!is_wdvarname(yylval.cp, Ja))
 			yyerror("%s: bad identifier",
 			    c == FOR ? "for" : Tselect);
 		strdupx(t->str, ident, ATEMP);
@@ -452,8 +458,14 @@ get_command(int cf, int sALIAS)
 	case UNTIL:
 		nesting_push(&old_nesting, c);
 		t = newtp((c == WHILE) ? TWHILE : TUNTIL);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
+		if (!t->left)
+			syntaxerr(NULL);
 		t->right = dogroup(sALIAS);
+#ifndef MKSH_SMALL
+		if (!t->right)
+			syntaxerr(NULL);
+#endif
 		nesting_pop(&old_nesting);
 		break;
 
@@ -469,7 +481,7 @@ get_command(int cf, int sALIAS)
 	case IF:
 		nesting_push(&old_nesting, c);
 		t = newtp(TIF);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
 		t->right = thenpart(sALIAS);
 		musthave(FI, KEYWORD|sALIAS);
 		nesting_pop(&old_nesting);
@@ -497,7 +509,7 @@ get_command(int cf, int sALIAS)
 
 	case FUNCTION:
 		musthave(LWORD, 0);
-		t = function_body(yylval.cp, sALIAS, true);
+		t = function_body(yylval.cp, sALIAS, Ja);
 		break;
 	}
 
@@ -553,7 +565,7 @@ dogroup(int sALIAS)
 		c = ORD('}');
 	else
 		syntaxerr(NULL);
-	list = c_list(sALIAS, true);
+	list = c_list(sALIAS, Ja);
 	musthave(c, KEYWORD|sALIAS);
 	return (list);
 }
@@ -565,7 +577,7 @@ thenpart(int sALIAS)
 
 	musthave(THEN, KEYWORD|sALIAS);
 	t = newtp(0);
-	t->left = c_list(sALIAS, true);
+	t->left = c_list(sALIAS, Ja);
 	if (t->left == NULL)
 		syntaxerr(NULL);
 	t->right = elsepart(sALIAS);
@@ -579,13 +591,13 @@ elsepart(int sALIAS)
 
 	switch (token(KEYWORD|sALIAS|CMDASN)) {
 	case ELSE:
-		if ((t = c_list(sALIAS, true)) == NULL)
+		if ((t = c_list(sALIAS, Ja)) == NULL)
 			syntaxerr(NULL);
 		return (t);
 
 	case ELIF:
 		t = newtp(TELIF);
-		t->left = c_list(sALIAS, true);
+		t->left = c_list(sALIAS, Ja);
 		t->right = thenpart(sALIAS);
 		return (t);
 
@@ -655,7 +667,7 @@ casepart(int endtok, int sALIAS)
 	t->vars = (char **)XPclose(ptns);
 	musthave(ORD(')'), 0);
 
-	t->left = c_list(sALIAS, true);
+	t->left = c_list(sALIAS, Ja);
 
 	/* initialise to default for ;; or omitted */
 	t->u.charflag = ORD(';');
@@ -681,7 +693,7 @@ casepart(int endtok, int sALIAS)
 static struct op *
 function_body(char *name, int sALIAS,
     /* function foo { ... } vs foo() { .. } */
-    bool ksh_func)
+    Wahr ksh_func)
 {
 	char *sname, *p;
 	struct op *t;
@@ -693,9 +705,10 @@ function_body(char *name, int sALIAS,
 	 * have allowed more; the following were never allowed:
 	 *	NUL TAB NL SP " $ & ' ( ) ; < = > \ ` |
 	 * C_QUOTE|C_SPC covers all but adds # * ? [ ]
+	 * CiQCM, as desired, adds / but also ^ (as collateral)
 	 */
 	for (p = sname; *p; p++)
-		if (ctype(*p, C_QUOTE | C_SPC))
+		if (ctype(*p, C_QUOTE | C_SPC | CiQCM))
 			yyerror(Tinvname, sname, Tfunction);
 
 	/*
@@ -710,7 +723,7 @@ function_body(char *name, int sALIAS,
 			ACCEPT;
 			musthave(ORD(/*(*/ ')'), 0);
 			/* degrade to POSIX function */
-			ksh_func = false;
+			ksh_func = Nee;
 		}
 		musthave(ORD('{' /*}*/), CONTIN|KEYWORD|sALIAS);
 		REJECT;
@@ -718,7 +731,7 @@ function_body(char *name, int sALIAS,
 
 	t = newtp(TFUNCT);
 	t->str = sname;
-	t->u.ksh_func = tobool(ksh_func);
+	t->u.ksh_func = isWahr(ksh_func);
 	t->lineno = source->line;
 
 	if ((t->left = get_command(CONTIN, sALIAS)) == NULL) {
@@ -788,37 +801,37 @@ static const struct tokeninfo {
 	short reserved;
 } tokentab[] = {
 	/* Reserved words */
-	{ "if",		IF,	true },
-	{ "then",	THEN,	true },
-	{ "else",	ELSE,	true },
-	{ "elif",	ELIF,	true },
-	{ "fi",		FI,	true },
-	{ "case",	CASE,	true },
-	{ Tesac,	ESAC,	true },
-	{ "for",	FOR,	true },
-	{ Tselect,	SELECT,	true },
-	{ "while",	WHILE,	true },
-	{ "until",	UNTIL,	true },
-	{ "do",		DO,	true },
-	{ "done",	DONE,	true },
-	{ "in",		IN,	true },
-	{ Tfunction,	FUNCTION, true },
-	{ Ttime,	TIME,	true },
-	{ "{",		ORD('{'), true },
-	{ Tcbrace,	ORD('}'), true },
-	{ "!",		BANG,	true },
-	{ "[[",		DBRACKET, true },
+	{ "if",		IF,		Ja },
+	{ "then",	THEN,		Ja },
+	{ "else",	ELSE,		Ja },
+	{ "elif",	ELIF,		Ja },
+	{ "fi",		FI,		Ja },
+	{ "case",	CASE,		Ja },
+	{ Tesac,	ESAC,		Ja },
+	{ "for",	FOR,		Ja },
+	{ Tselect,	SELECT,		Ja },
+	{ "while",	WHILE,		Ja },
+	{ "until",	UNTIL,		Ja },
+	{ "do",		DO,		Ja },
+	{ "done",	DONE,		Ja },
+	{ "in",		IN,		Ja },
+	{ Tfunction,	FUNCTION,	Ja },
+	{ Ttime,	TIME,		Ja },
+	{ "{",		ORD('{'),	Ja },
+	{ Tcbrace,	ORD('}'),	Ja },
+	{ "!",		BANG,		Ja },
+	{ "[[",		DBRACKET,	Ja },
 	/* Lexical tokens (0[EOF], LWORD and REDIR handled specially) */
-	{ "&&",		LOGAND,	false },
-	{ "||",		LOGOR,	false },
-	{ ";;",		BREAK,	false },
-	{ ";|",		BRKEV,	false },
-	{ ";&",		BRKFT,	false },
-	{ "((",		MDPAREN, false },
-	{ "|&",		COPROC,	false },
+	{ "&&",		LOGAND,		Nee },
+	{ "||",		LOGOR,		Nee },
+	{ ";;",		BREAK,		Nee },
+	{ ";|",		BRKEV,		Nee },
+	{ ";&",		BRKFT,		Nee },
+	{ "((",		MDPAREN,	Nee },
+	{ "|&",		COPROC,		Nee },
 	/* and some special cases... */
-	{ "newline",	ORD('\n'), false },
-	{ NULL,		0,	false }
+	{ "newline",	ORD('\n'),	Nee },
+	{ NULL,		0,		Nee }
 };
 
 void
@@ -924,14 +937,12 @@ newtp(int type)
 }
 
 struct op *
-compile(Source *s, bool skiputf8bom, bool doalias)
+compile(Source *s, Wahr doalias)
 {
 	nesting.start_token = 0;
 	nesting.start_line = 0;
 	herep = heres;
 	source = s;
-	if (skiputf8bom)
-		yyskiputf8bom();
 	yyparse(doalias);
 	return (outtree);
 }
@@ -948,7 +959,6 @@ inalias(struct source *s)
 	return (0);
 }
 
-
 /*
  * Order important - indexed by Test_meta values
  * Note that ||, &&, ( and ) can't appear in as unquoted strings
@@ -977,7 +987,7 @@ static Test_op
 dbtestp_isa(Test_env *te, Test_meta meta)
 {
 	int c = tpeek(CMDASN | (meta == TM_BINOP ? 0 : CONTIN));
-	bool uqword;
+	Wahr uqword;
 	char *save = NULL;
 	Test_op ret = TO_NONOP;
 
@@ -1020,7 +1030,7 @@ dbtestp_isa(Test_env *te, Test_meta meta
 
 static const char *
 dbtestp_getopnd(Test_env *te, Test_op op MKSH_A_UNUSED,
-    bool do_eval MKSH_A_UNUSED)
+    Wahr do_eval MKSH_A_UNUSED)
 {
 	int c = tpeek(CMDASN);
 
@@ -1036,7 +1046,7 @@ dbtestp_getopnd(Test_env *te, Test_op op
 static int
 dbtestp_eval(Test_env *te MKSH_A_UNUSED, Test_op op MKSH_A_UNUSED,
     const char *opnd1 MKSH_A_UNUSED, const char *opnd2 MKSH_A_UNUSED,
-    bool do_eval MKSH_A_UNUSED)
+    Wahr do_eval MKSH_A_UNUSED)
 {
 	return (1);
 }
@@ -1057,41 +1067,49 @@ dbtestp_error(Test_env *te, int offset,
 }
 
 #if HAVE_SELECT
-
-#ifndef EOVERFLOW
-#ifdef ERANGE
-#define EOVERFLOW	ERANGE
-#else
-#define EOVERFLOW	EINVAL
-#endif
-#endif
-
-bool
+Wahr
 parse_usec(const char *s, struct timeval *tv)
 {
-	struct timeval tt;
 	int i;
 
 	tv->tv_sec = 0;
 	/* parse integral part */
-	while (ctype(*s, C_DIGIT)) {
-		tt.tv_sec = tv->tv_sec * 10 + ksh_numdig(*s++);
-		/*XXX this overflow check maybe UB */
-		if (tt.tv_sec / 10 != tv->tv_sec) {
-			errno = EOVERFLOW;
-			return (true);
+#define mbiCfail do { errno = EOVERFLOW; return (Ja); } while (/* CONSTCOND */ 0)
+	if (mbiTYPE_ISF(time_t)) {
+		time_t tt = 0;
+
+		while (ctype(*s, C_DIGIT))
+			tt = tt * 10 + ksh_numdig(*s++);
+		mbiCAAlet(tv->tv_sec, time_t, tt);
+	} else if (mbiTYPE_ISU(time_t)) {
+		time_t tt = 0;
+
+		while (ctype(*s, C_DIGIT)) {
+			mbiCAUmul(time_t, tt, 10);
+			mbiCAUadd(tt, ksh_numdig(*s));
+			++s;
 		}
-		tv->tv_sec = tt.tv_sec;
+		mbiCAAlet(tv->tv_sec, time_t, tt);
+	} else {
+		mbiHUGE_S tt = 0;
+
+		while (ctype(*s, C_DIGIT)) {
+			mbiCAPmul(mbiHUGE_S, tt, 10);
+			mbiCAPadd(mbiHUGE_S, tt, ksh_numdig(*s));
+			++s;
+		}
+		mbiCASlet(time_t, tv->tv_sec, mbiHUGE_S, tt);
 	}
+#undef mbiCfail
 
 	tv->tv_usec = 0;
 	if (!*s)
 		/* no decimal fraction */
-		return (false);
+		return (Nee);
 	else if (*s++ != '.') {
 		/* junk after integral part */
 		errno = EINVAL;
-		return (true);
+		return (Ja);
 	}
 
 	/* parse decimal fraction */
@@ -1107,11 +1125,11 @@ parse_usec(const char *s, struct timeval
 		++s;
 	if (*s) {
 		errno = EINVAL;
-		return (true);
+		return (Ja);
 	}
 
 	/* end of input string reached, no errors */
-	return (false);
+	return (Nee);
 }
 #endif
 
@@ -1152,7 +1170,7 @@ yyrecursive(int subtype)
 	e->yyrecursive_statep = ys;
 	/* we use TPAREN as a helper container here */
 	t = nested(TPAREN, stok, etok, ALIAS);
-	yyrecursive_pop(false);
+	yyrecursive_pop(Nee);
 
 	/* t->left because nested(TPAREN, ...) hides our goodies there */
 	cp = snptreef(NULL, 0, Tf_T, t->left);
@@ -1162,7 +1180,7 @@ yyrecursive(int subtype)
 }
 
 void
-yyrecursive_pop(bool popall)
+yyrecursive_pop(Wahr popall)
 {
 	struct yyrecursive_state *ys;
 
@@ -1182,3 +1200,284 @@ yyrecursive_pop(bool popall)
 	if (popall)
 		goto popnext;
 }
+
+void
+yyerror(const char *fmt, ...)
+{
+	va_list ap;
+
+	/* pop aliases and re-reads */
+	while (source->type == SALIAS || source->type == SREREAD)
+		source = source->next;
+	/* zap pending input */
+	source->str = null;
+
+	va_start(ap, fmt);
+	vwarnf0(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE | KWF_NOERRNO,
+	    0, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+
+/* used by error reporting functions to print "ksh: .kshrc[25]: " */
+Wahr
+error_prefix(Wahr fileline)
+{
+	Wahr kshname_shown = Nee;
+
+	/* Avoid foo: foo[2]: ... */
+	if (!fileline || !source || !source->file ||
+	    strcmp(source->file, kshname) != 0) {
+		kshname_shown = Ja;
+		shf_puts(kshname + (isch(*kshname, '-') ? 1 : 0), shl_out);
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+	}
+	if (fileline && source && source->file != NULL) {
+		shf_fprintf(shl_out, "%s[%d]: ", source->file, source->errline ?
+		    source->errline : source->line);
+		source->errline = 0;
+	}
+	return (kshname_shown);
+}
+
+/* error reporting functions */
+
+static void
+vwarnf(unsigned int flags, int verrno, const char *fmt, va_list ap)
+{
+	int rept = 0;
+	Wahr show_builtin_argv0 = Nee;
+
+	if (HAS(flags, KWF_ERROR)) {
+		if (HAS(flags, KWF_INTERNAL))
+			shf_write(SC("internal error: "), shl_out);
+		else
+			shf_write(SC("E: "), shl_out);
+		/* additional things to do on error */
+		exstat = flags & KWF_EXSTAT;
+		if (HAS(flags, KWF_INTERNAL) && trap_exstat != -1)
+			trap_exstat = exstat;
+		/* debugging: note that stdout not valid */
+		shl_stdout_ok = Nee;
+	} else {
+		if (HAS(flags, KWF_INTERNAL))
+			shf_write(SC("internal warning: "), shl_out);
+		else
+			shf_write(SC("W: "), shl_out);
+	}
+	if (HAS(flags, KWF_BUILTIN) &&
+	    /* not set when main() calls parse_args() */
+	    builtin_argv0 && builtin_argv0 != kshname)
+		show_builtin_argv0 = Ja;
+	if (HAS(flags, KWF_PREFIX) && error_prefix(HAS(flags, KWF_FILELINE)) &&
+	    show_builtin_argv0) {
+		const char *kshbasename;
+
+		kshname_islogin(&kshbasename);
+		show_builtin_argv0 = strcmp(builtin_argv0, kshbasename) != 0;
+	}
+	if (show_builtin_argv0) {
+		shf_puts(builtin_argv0, shl_out);
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+	}
+	switch (flags & KWF_MSGMASK) {
+	default:
+#undef shf_vfprintf
+		shf_vfprintf(shl_out, fmt, ap);
+#define shf_vfprintf poisoned_shf_vfprintf
+		break;
+	case KWF_THREEMSG:
+		rept = 2;
+		if (0)
+			/* FALLTHROUGH */
+	case KWF_TWOMSG:
+		  rept = 1;
+		/* FALLTHROUGH */
+	case KWF_ONEMSG:
+		while (/* CONSTCOND */ 1) {
+			shf_puts(fmt ? fmt : Tnil, shl_out);
+			if (!rept--)
+				break;
+			shf_putc_i(':', shl_out);
+			shf_putc_i(' ', shl_out);
+			fmt = va_arg(ap, const char *);
+		}
+		break;
+	}
+	if (!HAS(flags, KWF_NOERRNO)) {
+		/* compare shf.c */
+#if !HAVE_STRERROR
+		shf_putc_i(':', shl_out);
+		shf_putc_i(' ', shl_out);
+		shf_putsv(cstrerror(verrno), shl_out);
+#else
+		/* may be nil */
+		shf_fprintf(shl_out, ": %s", cstrerror(verrno));
+#endif
+	}
+	shf_putc_i('\n', shl_out);
+	shf_flush(shl_out);
+}
+
+#ifndef MKSH_SMALL
+static void
+vwarnf0(unsigned int flags, int verrno, const char *fmt, va_list ap)
+{
+	vwarnf(flags, verrno, fmt, ap);
+}
+#endif
+
+void
+kwarnf(unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+
+#ifndef MKSH_SMALL
+void
+kwarnf0(unsigned int flags, const char *fmt, ...)
+{
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+
+void
+kwarnf1(unsigned int flags, int verrno, const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	if (HAS(flags, KWF_BIUNWIND))
+		bi_unwind(0);
+}
+#endif
+
+/* presented by lack of portable variadic macros in early C */
+
+void
+kerrf(unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+
+#ifndef MKSH_SMALL
+void
+kerrf0(unsigned int flags, const char *fmt, ...)
+{
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+
+#if 0 /* not used */
+void
+kerrf1(unsigned int flags, int verrno, const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(flags, verrno, fmt, ap);
+	va_end(ap);
+	unwind(LERROR);
+}
+#endif
+#endif
+
+/* maybe error, maybe builtin error; use merrf() macro */
+void
+merrF(int *ep, unsigned int flags, ...)
+{
+	const char *fmt;
+	va_list ap;
+	int verrno;
+
+	verrno = errno;
+
+	if (ep)
+		flags |= KWF_BUILTIN;
+
+	va_start(ap, flags);
+	if (HAS(flags, KWF_VERRNO))
+		verrno = va_arg(ap, int);
+	fmt = va_arg(ap, const char *);
+	vwarnf(flags, verrno, fmt, ap);
+	va_end(ap);
+
+	if (ep) {
+		*ep = exstat;
+		bi_unwind(0);
+	} else
+		unwind(LERROR);
+}
+
+/* transform warning into bi_errorf */
+void
+bi_unwind(int rc)
+{
+	if (rc)
+		exstat = rc;
+	/* debugging: note that stdout not valid */
+	shl_stdout_ok = Nee;
+
+	/* POSIX special builtins cause non-interactive shells to exit */
+	if (builtin_spec) {
+		builtin_argv0 = NULL;
+		/* may not want to use LERROR here */
+		unwind(LERROR);
+	}
+}
+
+/*XXX old */
+void
+bi_errorf(const char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vwarnf0(/*XXX*/ KWF_BIERR | KWF_NOERRNO, /*XXX*/ 0, fmt, ap);
+	va_end(ap);
+	bi_unwind(0);
+}
--- mksh-59c.orig/tree.c
+++ mksh-59c/tree.c
@@ -2,7 +2,7 @@
 
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
- *		 2011, 2012, 2013, 2015, 2016, 2017
+ *		 2011, 2012, 2013, 2015, 2016, 2017, 2021
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -23,7 +23,7 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/tree.c,v 1.100 2020/10/31 04:28:54 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/tree.c,v 1.114 2024/07/26 18:34:58 tg Exp $");
 
 #define INDENT	8
 
@@ -35,18 +35,22 @@ static struct ioword **iocopy(struct iow
 static void iofree(struct ioword **, Area *);
 
 /* "foo& ; bar" and "foo |& ; bar" are invalid */
-static bool prevent_semicolon;
+static Wahr prevent_semicolon;
 
 /* here document diversion */
 static unsigned short ptree_nest;
-static bool ptree_hashere;
+static Wahr ptree_hashere;
 static struct shf ptree_heredoc;
 #define ptree_outhere(shf) do {					\
 	if (ptree_hashere) {					\
-		shf_puts(shf_sclose(&ptree_heredoc), (shf));	\
+		char *ptree_thehere;				\
+								\
+		ptree_thehere = shf_sclose(&ptree_heredoc);	\
+		shf_puts(ptree_thehere, (shf));			\
 		shf_putc('\n', (shf));				\
-		ptree_hashere = false;				\
-		/*prevent_semicolon = true;*/			\
+		afree(ptree_thehere, ATEMP);			\
+		ptree_hashere = Nee;				\
+		/*prevent_semicolon = Ja;*/			\
 	}							\
 } while (/* CONSTCOND */ 0)
 
@@ -69,7 +73,7 @@ ptree(struct op *t, int indent, struct s
 		return;
 	switch (t->type) {
 	case TCOM:
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		/* special-case 'var=<<EOF' (cf. exec.c:execute) */
 		if (t->args &&
 		    /* we have zero arguments, i.e. no program to run */
@@ -82,7 +86,7 @@ ptree(struct op *t, int indent, struct s
 		    /* of type "here document" (or "here string") */
 		    (t->ioact[0]->ioflag & IOTYPE) == IOHERE &&
 		    /* the variable assignment begins with a valid varname */
-		    (ccp = skip_wdvarname(t->vars[0], true)) != t->vars[0] &&
+		    (ccp = skip_wdvarname(t->vars[0], Ja)) != t->vars[0] &&
 		    /* and has no right-hand side (i.e. "varname=") */
 		    ccp[0] == CHAR && ((ccp[1] == '=' && ccp[2] == EOS) ||
 		    /* or "varname+=" */ (ccp[1] == '+' && ccp[2] == CHAR &&
@@ -140,7 +144,7 @@ ptree(struct op *t, int indent, struct s
 		break;
 	case TBANG:
 		shf_puts("! ", shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		t = t->right;
 		goto Chain;
 	case TDBRACKET:
@@ -180,7 +184,8 @@ ptree(struct op *t, int indent, struct s
 		fptreef(shf, indent, "%Nesac ");
 		break;
 	case TELIF:
-		internal_errorf(TELIF_unexpected);
+		kerrf(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_ONEMSG | KWF_NOERRNO,
+		    TELIF_unexpected);
 		/* FALLTHROUGH */
 	case TIF:
 		i = 2;
@@ -223,21 +228,21 @@ ptree(struct op *t, int indent, struct s
 		break;
 	case TCOPROC:
 		fptreef(shf, indent, "%T|& ", t->left);
-		prevent_semicolon = true;
+		prevent_semicolon = Ja;
 		break;
 	case TASYNC:
 		fptreef(shf, indent, "%T& ", t->left);
-		prevent_semicolon = true;
+		prevent_semicolon = Ja;
 		break;
 	case TFUNCT:
-		fpFUNCTf(shf, indent, tobool(t->u.ksh_func), t->str, t->left);
+		fpFUNCTf(shf, indent, isWahr(t->u.ksh_func), t->str, t->left);
 		break;
 	case TTIME:
 		fptreef(shf, indent, Tf_s_T, Ttime, t->left);
 		break;
 	default:
 		shf_puts("<botch>", shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
 		break;
 	}
 	if ((ioact = t->ioact) != NULL)
@@ -276,12 +281,12 @@ pioact(struct shf *shf, struct ioword *i
 			if (!ptree_hashere) {
 				shf_sopen(NULL, 0, SHF_WR | SHF_DYNAMIC,
 				    &ptree_heredoc);
-				ptree_hashere = true;
+				ptree_hashere = Ja;
 			}
 			shf_putc('\n', &ptree_heredoc);
 			shf_puts(iop->heredoc, &ptree_heredoc);
 			/* iop->delim is set before iop->heredoc */
-			shf_puts(evalstr(iop->delim, 0), &ptree_heredoc);
+			shf_putsv(evalstr(iop->delim, 0), &ptree_heredoc);
 		}
  ioheredelim:
 		/* delim is NULL during syntax error printing */
@@ -300,7 +305,8 @@ pioact(struct shf *shf, struct ioword *i
 		shf_puts("<>", shf);
 		break;
 	case IODUP:
-		shf_puts(flag & IORDUP ? "<&" : ">&", shf);
+		shf_putc(flag & IORDUP ? '<' : '>', shf);
+		shf_putc('&', shf);
 		break;
 	}
 	/* name is NULL for IOHERE or when printing syntax errors */
@@ -311,7 +317,7 @@ pioact(struct shf *shf, struct ioword *i
 			wdvarput(shf, iop->ioname, 0, WDS_TPUTS);
 	}
 	shf_putc(' ', shf);
-	prevent_semicolon = false;
+	prevent_semicolon = Nee;
 }
 
 /* variant of fputs for ptreef and wdstrip */
@@ -416,7 +422,8 @@ wdvarput(struct shf *shf, const char *wp
 			}
 			return (wp);
 		case OPAT:
-			shf_putchar(*wp++, shf);
+			c = *wp++;
+			shf_putc(c, shf);
 			shf_putc('(', shf);
 			break;
 		case SPAT:
@@ -468,18 +475,14 @@ vfptreef(struct shf *shf, int indent, co
 	int c;
 
 	if (!ptree_nest++)
-		ptree_hashere = false;
+		ptree_hashere = Nee;
 
 	while ((c = ord(*fmt++))) {
 		if (c == '%') {
 			switch ((c = ord(*fmt++))) {
-			case ORD('c'):
-				/* character (octet, probably) */
-				shf_putchar(va_arg(va, int), shf);
-				break;
 			case ORD('s'):
 				/* string */
-				shf_puts(va_arg(va, char *), shf);
+				shf_putsv(va_arg(va, char *), shf);
 				break;
 			case ORD('S'):
 				/* word */
@@ -523,13 +526,17 @@ vfptreef(struct shf *shf, int indent, co
 				/* I/O redirection */
 				pioact(shf, va_arg(va, struct ioword *));
 				break;
+			case ORD('c'):
+				/* character (octet, probably) */
+				c = va_arg(va, int);
+				/* FALLTHROUGH */
 			default:
 				shf_putc(c, shf);
 				break;
 			}
 		} else
 			shf_putc(c, shf);
-		prevent_semicolon = false;
+		prevent_semicolon = Nee;
  dont_trash_prevent_semicolon:
 		;
 	}
@@ -663,9 +670,9 @@ wdscan(const char *wp, int c)
 				nest--;
 			break;
 		default:
-			internal_warningf(
+			kwarnf0(KWF_INTERNAL | KWF_WARNING | KWF_NOERRNO,
 			    "wdscan: unknown char 0x%X (carrying on)",
-			    (unsigned char)wp[-1]);
+			    KBI(wp[-1]));
 		}
 }
 
@@ -769,7 +776,7 @@ iofree(struct ioword **iow, Area *ap)
 }
 
 void
-fpFUNCTf(struct shf *shf, int i, bool isksh, const char *k, struct op *v)
+fpFUNCTf(struct shf *shf, int i, Wahr isksh, const char *k, struct op *v)
 {
 	if (isksh)
 		fptreef(shf, i, "%s %s %T", Tfunction, k, v);
@@ -779,64 +786,300 @@ fpFUNCTf(struct shf *shf, int i, bool is
 		fptreef(shf, i, "%s() %T", k, v);
 }
 
-
-/* for jobs.c */
 void
-vistree(char *dst, size_t sz, struct op *t)
+uprntc(unsigned char c, struct shf *shf)
+{
+	unsigned char a;
+
+	if (ctype(c, C_PRINT)) {
+ doprnt:
+		shf_putc(c, shf);
+		return;
+	}
+
+	if (!UTFMODE) {
+		if (!ksh_isctrl8(c))
+			goto doprnt;
+		if ((a = rtt2asc(c)) >= 0x80U) {
+			shf_scheck(3, shf);
+			shf_putc('^', shf);
+			shf_putc('!', shf);
+			a &= 0x7FU;
+			goto unctrl;
+		}
+	} else if ((a = rtt2asc(c)) >= 0x80U) {
+		shf_scheck(4, shf);
+		shf_putc('\\', shf);
+		shf_putc('x', shf);
+		shf_putc(digits_uc[(a >> 4) & 0x0F], shf);
+		shf_putc(digits_uc[a & 0x0F], shf);
+		return;
+	}
+	shf_scheck(2, shf);
+	shf_putc('^', shf);
+ unctrl:
+	shf_putc(asc2rtt(a ^ 0x40U), shf);
+}
+
+#ifndef MKSH_NO_CMDLINE_EDITING
+/*
+ * For now, these are only used by the edit code, which requires
+ * a difference: tab is output as three spaces, not as control
+ * character in caret notation. If these will ever be used else‐
+ * where split them up.
+ */
+/*size_t*/ void
+uescmbT(unsigned char *dst, const char **cpp)
+{
+	unsigned char c;
+	unsigned int wc;
+	size_t n, dstsz = 0;
+	const char *cp = *cpp;
+
+	c = *cp++;
+	/* test cheap first (easiest) */
+	if (ctype(c, C_PRINT)) {
+ prntb:
+		dst[dstsz++] = c;
+		goto out;
+	}
+	/* differently from uprntc, note tab as three spaces */
+	if (ord(c) == CTRL_I) {
+		dst[dstsz++] = ' ';
+		dst[dstsz++] = ' ';
+		dst[dstsz++] = ' ';
+		goto out;
+	}
+
+	/* more specialised tests depend on shell state */
+	if (UTFMODE) {
+		/* wc = rtt2asc(c) except UTF-8 is decoded */
+		if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+			/* failed: invalid UTF-8 */
+			wc = rtt2asc(c);
+			dst[dstsz++] = '\\';
+			dst[dstsz++] = 'x';
+			dst[dstsz++] = digits_uc[(wc >> 4) & 0x0F];
+			dst[dstsz++] = digits_uc[wc & 0x0F];
+			goto out;
+		}
+		/*
+		 * printable as-is? U+0020‥U+007E already handled
+		 * above as they are C_PRINT, U+00A0 or higher are
+		 * not escaped either, anything in between is special
+		 */
+		if (wc >= 0xA0U) {
+			dst[dstsz++] = c;
+			switch (n) {
+#ifdef notyet
+			case 4:
+				dst[dstsz++] = *cp++;
+				/* FALLTHROUGH */
+#endif
+			case 3:
+				dst[dstsz++] = *cp++;
+				/* FALLTHROUGH */
+			default:
+				dst[dstsz++] = *cp++;
+				break;
+			}
+			goto out;
+		}
+		/* and encoded with either 1 or 2 octets */
+
+		/* C1 control character, UTF-8 encoded */
+		if (wc >= 0x80U) {
+			/* n == 2 so we miss one out */
+			++cp;
+
+			c = '+';
+			goto prntC1;
+		}
+		/* nope, must be C0 or DEL */
+		/* n == 1 so cp needs no adjustment */
+		goto prntC0;
+	}
+
+	/* not UTFMODE allows more but the test is more expensive */
+	if (!ksh_isctrl8(c))
+		goto prntb;
+	/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+	wc = rtt2asc(c);
+	/* C1 control character octet? */
+	if (wc >= 0x80U) {
+		c = '!';
+ prntC1:
+		dst[dstsz++] = '^';
+		dst[dstsz++] = c;
+		wc &= 0x7FU;
+	} else {
+		/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+		dst[dstsz++] = '^';
+	}
+	dst[dstsz++] = asc2rtt(wc ^ 0x40U);
+
+ out:
+	*cpp = cp;
+	dst[dstsz] = '\0';
+#ifdef usedoutsideofedit
+	return (dstsz);
+#endif
+}
+
+int
+uwidthmbT(char *cp, char **dcp)
 {
-	unsigned int c;
-	char *cp, *buf;
+	unsigned char c;
+	unsigned int wc;
+	int w;
 	size_t n;
 
-	buf = alloc(sz + 16, ATEMP);
-	snptreef(buf, sz + 16, Tf_T, t);
-	cp = buf;
- vist_loop:
-	if (UTFMODE && (n = utf_mbtowc(&c, cp)) != (size_t)-1) {
-		if (c == 0 || n >= sz)
-			/* NUL or not enough free space */
-			goto vist_out;
-		/* copy multibyte char */
-		sz -= n;
-		while (n--)
-			*dst++ = *cp++;
-		goto vist_loop;
-	}
-	if (--sz == 0 || (c = ord(*cp++)) == 0)
-		/* NUL or not enough free space */
-		goto vist_out;
-	if (ksh_isctrl(c)) {
-		/* C0 or C1 control character or DEL */
-		if (--sz == 0)
-			/* not enough free space for two chars */
-			goto vist_out;
-		*dst++ = '^';
-		c = ksh_unctrl(c);
-	} else if (UTFMODE && rtt2asc(c) > 0x7F) {
-		/* better not try to display broken multibyte chars */
-		/* also go easy on the UCS: no U+FFFD here */
-		c = ORD('?');
-	}
-	*dst++ = c;
-	goto vist_loop;
-
- vist_out:
-	*dst = '\0';
-	afree(buf, ATEMP);
+	c = *cp++;
+	/* test cheap first (easiest) */
+	if (ctype(c, C_PRINT)) {
+ prntb:
+		w = 1;
+		goto out;
+	}
+	/* differently from uprntc, note tab as three spaces */
+	if (ord(c) == CTRL_I) {
+		w = 3;
+		goto out;
+	}
+
+	/* more specialised tests depend on shell state */
+	if (UTFMODE) {
+		/* wc = rtt2asc(c) except UTF-8 is decoded */
+		if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+			/* \x## */
+			w = 4;
+			goto out;
+		}
+		cp += n - 1;
+		/*
+		 * printable as-is? U+0020‥U+007E already handled
+		 * above as they are C_PRINT, U+00A0 or higher are
+		 * not escaped either, anything in between is special
+		 */
+		if (wc >= 0xA0U) {
+			w = utf_wcwidth(wc);
+			goto out;
+		}
+		/* and encoded with either 1 or 2 octets */
+
+		/* C1 control character, UTF-8 encoded */
+		if (wc >= 0x80U)
+			goto prntC1;
+		/* nope, must be C0 or DEL */
+		goto prntC0;
+	}
+
+	/* not UTFMODE allows more but the test is more expensive */
+	if (!ksh_isctrl8(c))
+		goto prntb;
+	/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+	wc = rtt2asc(c);
+	/* C1 control character octet? */
+	if (wc >= 0x80U) {
+ prntC1:
+		w = 3;
+	} else {
+		/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+		w = 2;
+	}
+
+ out:
+	if (dcp)
+		*dcp = cp;
+	return (w);
 }
+#endif
 
-#ifdef DEBUG
-void
-dumpchar(struct shf *shf, unsigned char c)
+const char *
+uprntmbs(const char *cp, Wahr esc_caret, struct shf *shf)
 {
-	if (ksh_isctrl(c)) {
-		/* C0 or C1 control character or DEL */
-		shf_putc('^', shf);
-		c = ksh_unctrl(c);
+	unsigned char c;
+	unsigned int wc;
+	size_t n;
+
+	while ((c = *cp++) != 0) {
+		/* test cheap first (easiest) */
+		if (ctype(c, C_PRINT)) {
+			if (esc_caret && (c == ORD('\\') || c == ORD('^'))) {
+				shf_scheck(2, shf);
+				shf_putc('\\', shf);
+			}
+ prntb:
+			shf_putc(c, shf);
+			continue;
+		}
+
+		/* more specialised tests depend on shell state */
+		if (UTFMODE) {
+			/* wc = rtt2asc(c) except UTF-8 is decoded */
+			if ((n = utf_mbtowc(&wc, cp - 1)) == (size_t)-1) {
+				/* failed: invalid UTF-8 */
+				wc = rtt2asc(c);
+				shf_scheck(4, shf);
+				shf_putc('\\', shf);
+				shf_putc('x', shf);
+				shf_putc(digits_uc[(wc >> 4) & 0x0F], shf);
+				shf_putc(digits_uc[wc & 0x0F], shf);
+				continue;
+			}
+			/*
+			 * printable as-is? U+0020‥U+007E already handled
+			 * above as they are C_PRINT, U+00A0 or higher are
+			 * not escaped either, anything in between is special
+			 */
+			if (wc >= 0xA0U) {
+				--cp;
+				shf_wr_sm(cp, n, shf);
+				continue;
+			}
+			/* and encoded with either 1 or 2 octets */
+
+			/* C1 control character, UTF-8 encoded */
+			if (wc >= 0x80U) {
+				/* n == 2 so we miss one out */
+				++cp;
+
+				c = '+';
+				goto prntC1;
+			}
+			/* nope, must be C0 or DEL */
+			/* n == 1 so cp needs no adjustment */
+			goto prntC0;
+		}
+
+		/* not UTFMODE allows more but the test is more expensive */
+		if (!ksh_isctrl8(c))
+			goto prntb;
+		/* UTF-8 is not decoded, we just transfer an octet to ASCII */
+		wc = rtt2asc(c);
+		/* C1 control character octet? */
+		if (wc >= 0x80U) {
+			c = '!';
+ prntC1:
+			shf_scheck(3, shf);
+			shf_putc('^', shf);
+			shf_putc(c, shf);
+			wc &= 0x7FU;
+		} else {
+			/* nope, so C0 or DEL, anything else went to prntb */
+ prntC0:
+			shf_scheck(2, shf);
+			shf_putc('^', shf);
+		}
+		shf_putc(asc2rtt(wc ^ 0x40U), shf);
 	}
-	shf_putc(c, shf);
+	/* point to the trailing NUL for continuation */
+	return ((const void *)(cp - 1));
 }
 
+#ifdef DEBUG
 /* see: wdvarput */
 static const char *
 dumpwdvar_i(struct shf *shf, const char *wp, int quotelevel)
@@ -844,7 +1087,7 @@ dumpwdvar_i(struct shf *shf, const char
 	int c;
 
 	while (/* CONSTCOND */ 1) {
-		switch(*wp++) {
+		switch (*wp++) {
 		case EOS:
 			shf_puts("EOS", shf);
 			return (--wp);
@@ -858,7 +1101,7 @@ dumpwdvar_i(struct shf *shf, const char
 				/* FALLTHROUGH */
 		case CHAR:
 			  shf_puts("CHAR=", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			break;
 		case QCHAR:
 			shf_puts("QCHAR<", shf);
@@ -866,7 +1109,7 @@ dumpwdvar_i(struct shf *shf, const char
 			if (quotelevel == 0 || c == ORD('"') ||
 			    c == ORD('\\') || ctype(c, C_DOLAR | C_GRAVE))
 				shf_putc('\\', shf);
-			dumpchar(shf, c);
+			uprntc(c, shf);
 			goto closeandout;
 		case COMASUB:
 			shf_puts("COMASUB<", shf);
@@ -874,8 +1117,7 @@ dumpwdvar_i(struct shf *shf, const char
 		case COMSUB:
 			shf_puts("COMSUB<", shf);
  dumpsub:
-			while ((c = *wp++) != 0)
-				dumpchar(shf, c);
+			wp = uprntmbs(wp, Nee, shf) + 1;
  closeandout:
 			shf_putc('>', shf);
 			break;
@@ -903,21 +1145,20 @@ dumpwdvar_i(struct shf *shf, const char
 			break;
 		case OSUBST:
 			shf_puts("OSUBST(", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			shf_puts(")[", shf);
-			while ((c = *wp++) != 0)
-				dumpchar(shf, c);
+			wp = uprntmbs(wp, Nee, shf) + 1;
 			shf_putc('|', shf);
 			wp = dumpwdvar_i(shf, wp, 0);
 			break;
 		case CSUBST:
 			shf_puts("]CSUBST(", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			shf_putc(')', shf);
 			return (wp);
 		case OPAT:
 			shf_puts("OPAT=", shf);
-			dumpchar(shf, *wp++);
+			uprntc(*wp++, shf);
 			break;
 		case SPAT:
 			shf_puts("SPAT", shf);
@@ -926,7 +1167,7 @@ dumpwdvar_i(struct shf *shf, const char
 			shf_puts("CPAT", shf);
 			break;
 		default:
-			shf_fprintf(shf, "INVAL<%u>", (uint8_t)wp[-1]);
+			shf_fprintf(shf, "INVAL<%u>", (kby)wp[-1]);
 			break;
 		}
 		shf_putc(' ', shf);
@@ -1010,7 +1251,7 @@ dumptree(struct shf *shf, struct op *t)
 	++nesting;
 	shf_puts("{tree:" /*}*/, shf);
 	if (t == NULL) {
-		name = "(null)";
+		name = Tnil;
 		goto out;
 	}
 	dumpioact(shf, t);
@@ -1059,7 +1300,7 @@ dumptree(struct shf *shf, struct op *t)
 		shf_putc('\n', shf);
 		dumptree(shf, t->left);
 /* middumprightandout: (unused) */
-		shf_fprintf(shf, "/%s:", name);
+		shf_fprintf(shf, " /%s:", name);
  dumprightandout:
 		t = t->right;
 		goto dumpandout;
@@ -1179,4 +1420,47 @@ dumptree(struct shf *shf, struct op *t)
 	shf_fprintf(shf, /*{*/ " /%s}\n", name);
 	--nesting;
 }
+
+void
+dumphex(struct shf *shf, const void *buf, size_t len)
+{
+	const kby *s = buf;
+	size_t i = 0;
+
+	if (!len--) {
+		shf_puts("00000000  <\n", shf);
+		goto out;
+	}
+
+ loop:
+	if ((i & 0xFU) == 0x0U)
+		shf_fprintf(shf, "%08zX  ", i);
+	else if ((i & 0xFU) == 0x8U)
+		shf_puts("- ", shf);
+	shf_fprintf(shf, "%02X%c", ord(s[i]), i == len ? '<' : ' ');
+	if (i < len && (i & 0xFU) != 0xFU) {
+		++i;
+		goto loop;
+	}
+	while ((i & 0xFU) != 0xFU) {
+		++i;
+		if ((i & 0xFU) == 0x8U)
+			shf_puts("  ", shf);
+		shf_puts("   ", shf);
+	}
+	shf_puts(" |", shf);
+	i &= (size_t)~(size_t)0xFU;
+ visloop:
+	if (i <= len) {
+		shf_putc(ctype(s[i], C_PRINT) ? ord(s[i]) : '.', shf);
+		++i;
+		if ((i & 0xFU) != 0x0U)
+			goto visloop;
+	}
+	shf_puts("|\n", shf);
+	if (i <= len)
+		goto loop;
+ out:
+	shf_flush(shf);
+}
 #endif
--- mksh-59c.orig/ulimit.c
+++ mksh-59c/ulimit.c
@@ -3,7 +3,7 @@
 /*-
  * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
  *		 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
- *		 2019, 2020
+ *		 2019, 2020, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -24,68 +24,76 @@
 
 #include "sh.h"
 
-__RCSID("$MirOS: src/bin/mksh/ulimit.c,v 1.3 2020/07/24 21:08:26 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/ulimit.c,v 1.17 2023/12/13 14:52:18 tg Exp $");
 
 #define SOFT	0x1
 #define HARD	0x2
 
 #if HAVE_RLIMIT
 
-#if !HAVE_RLIM_T
-typedef unsigned long rlim_t;
-#endif
-
 /* Magic to divine the 'm' and 'v' limits */
 
+#undef MKHL_AS
+#undef MKHL_VMEM
+#undef MKHL_RSS
+
 #ifdef RLIMIT_AS
-#if !defined(RLIMIT_VMEM) || (RLIMIT_VMEM == RLIMIT_AS) || \
-    !defined(RLIMIT_RSS) || (RLIMIT_VMEM == RLIMIT_RSS)
-#define ULIMIT_V_IS_AS
-#elif defined(RLIMIT_VMEM)
-#if !defined(RLIMIT_RSS) || (RLIMIT_RSS == RLIMIT_AS)
-#define ULIMIT_V_IS_AS
-#else
-#define ULIMIT_V_IS_VMEM
-#endif
+#define MKHL_AS
 #endif
+
+#ifdef RLIMIT_VMEM
+#define MKHL_VMEM
 #endif
 
 #ifdef RLIMIT_RSS
-#ifdef ULIMIT_V_IS_VMEM
-#define ULIMIT_M_IS_RSS
-#elif defined(RLIMIT_VMEM) && (RLIMIT_VMEM == RLIMIT_RSS)
-#define ULIMIT_M_IS_VMEM
-#else
-#define ULIMIT_M_IS_RSS
-#endif
-#if defined(ULIMIT_M_IS_RSS) && defined(RLIMIT_AS) && \
-    !defined(__APPLE__) && (RLIMIT_RSS == RLIMIT_AS)
-/* On Mac OSX keep -m as -v alias for pkgsrc and other software expecting it */
-#undef ULIMIT_M_IS_RSS
+#define MKHL_RSS
 #endif
+
+#if defined(MKHL_AS) && defined(MKHL_VMEM) && (RLIMIT_AS == RLIMIT_VMEM)
+#undef MKHL_VMEM
 #endif
 
-#if !defined(RLIMIT_AS) && !defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_VMEM)
-#define ULIMIT_V_IS_VMEM
+#if defined(MKHL_AS) && defined(MKHL_RSS) && (RLIMIT_AS == RLIMIT_RSS)
+#undef MKHL_RSS
 #endif
 
-#if !defined(ULIMIT_V_IS_VMEM) && defined(RLIMIT_VMEM) && \
-    (!defined(RLIMIT_RSS) || (defined(RLIMIT_AS) && (RLIMIT_RSS == RLIMIT_AS)))
-#define ULIMIT_M_IS_VMEM
+#if defined(MKHL_VMEM) && defined(MKHL_RSS) && (RLIMIT_VMEM == RLIMIT_RSS)
+#undef MKHL_VMEM
 #endif
 
-#if defined(ULIMIT_M_IS_VMEM) && defined(RLIMIT_AS) && \
-    (RLIMIT_VMEM == RLIMIT_AS)
+#undef ULIMIT_V_IS_AS
+#undef ULIMIT_V_IS_VMEM
+#undef ULIMIT_M_IS_RSS
 #undef ULIMIT_M_IS_VMEM
-#endif
 
-#if defined(ULIMIT_M_IS_RSS) && defined(ULIMIT_M_IS_VMEM)
-# error nonsensical m ulimit
+#ifdef MKHL_AS
+#define ULIMIT_V_IS_AS
+#if defined(MKHL_RSS)
+#define ULIMIT_M_IS_RSS
+#elif defined(MKHL_VMEM)
+#define ULIMIT_M_IS_VMEM
+#endif
+#else /* !MKHL_AS */
+#ifdef MKHL_VMEM
+#define ULIMIT_V_IS_VMEM
+#endif
+#ifdef MKHL_RSS
+#define ULIMIT_M_IS_RSS
 #endif
+#endif /* !MKHL_AS */
 
-#if defined(ULIMIT_V_IS_VMEM) && defined(ULIMIT_V_IS_AS)
-# error nonsensical v ulimit
+/* pkgsrc® at least on Mac OSX expects -m as -v alias */
+#if !defined(ULIMIT_M_IS_RSS) && !defined(ULIMIT_M_IS_VMEM)
+#if defined(RLIMIT_VMEM)
+#define ULIMIT_M_IS_VMEM
+#elif defined(RLIMIT_RSS)
+#define ULIMIT_M_IS_RSS
 #endif
+#endif
+
+#undef MKHL_AS
+#undef MKHL_VMEM
+#undef MKHL_RSS
 
 #define LIMITS_GEN	"rlimits.gen"
 
@@ -110,9 +118,9 @@ typedef unsigned long rlim_t;
 #endif
 
 #if defined(KSH_UL_SFIL)
-#define KSH_UL_WFIL	true
+#define KSH_UL_WFIL	Ja
 #else
-#define KSH_UL_WFIL	false
+#define KSH_UL_WFIL	Nee
 #define KSH_UL_SFIL	0
 #endif
 
@@ -147,7 +155,7 @@ struct limits {
 	/* write command */
 	int wesource;
 	/* writable? */
-	bool writable;
+	Wahr writable;
 #endif
 	/* getopts char */
 	char optchar;
@@ -171,7 +179,7 @@ struct limits {
 	static const struct {				\
 		int rcmd;				\
 		int wcmd;				\
-		bool writable;				\
+		Wahr writable;				\
 		char optchar;				\
 		char name[sizeof(lname)];		\
 	} rlimits_ ## lg = {				\
@@ -183,6 +191,12 @@ struct limits {
 static void print_ulimit(const struct limits *, int);
 static int set_ulimit(const struct limits *, const char *, int);
 
+/*
+ * UGH! Strictly speaking this is UB in C. Need to figure out whether
+ * it is worth the botherance to fix this (union) or to test for C99+
+ * flexible array member using it when present, maybe keeping this if
+ * not… :~
+ */
 static const struct limits * const rlimits[] = {
 #define RLIMITS_ITEMS
 #include LIMITS_GEN
@@ -202,7 +216,7 @@ c_ulimit(const char **wp)
 	size_t i = 0;
 	int how = SOFT | HARD, optc;
 	char what = 'f';
-	bool all = false;
+	Wahr all = Nee;
 
 	while ((optc = ksh_getopt(wp, &builtin_opt, rlimits_opts)) != -1)
 		switch (optc) {
@@ -213,15 +227,33 @@ c_ulimit(const char **wp)
 			how = SOFT;
 			break;
 		case ORD('a'):
-			all = true;
+			all = Ja;
 			break;
 		case ORD('?'):
-			bi_errorf("usage: ulimit [-%s] [value]", rlimits_opts);
+ unknown_opt:
+			kwarnf0(KWF_BIERR | KWF_NOERRNO,
+			    "usage: ulimit [-%s] [value]", rlimits_opts);
 			return (1);
 		default:
 			what = optc;
 		}
 
+	if (all) {
+		if (wp[builtin_opt.optind]) {
+ unexpected_args:
+			kwarnf(KWF_BIERR | KWF_ONEMSG | KWF_NOERRNO,
+			    Ttoo_many_args);
+			return (1);
+		}
+		while (i < NELEM(rlimits)) {
+			shprintf("-%c: %-20s  ", rlimits[i]->optchar,
+			    rlimits[i]->name);
+			print_ulimit(rlimits[i], how);
+			++i;
+		}
+		return (0);
+	}
+
 	while (i < NELEM(rlimits)) {
 		if (rlimits[i]->optchar == what)
 			goto found;
@@ -230,30 +262,38 @@ c_ulimit(const char **wp)
 #ifndef RLIMIT_CORE
 	if (what == ORD('c'))
 		/* silently accept */
-		return 0;
+		return (0);
 #endif
-	internal_warningf("ulimit: %c", what);
-	return (1);
+	ksh_getopt_opterr(what, wp[0], Tunknown_option);
+	goto unknown_opt;
+
  found:
 	if (wp[builtin_opt.optind]) {
-		if (all || wp[builtin_opt.optind + 1]) {
-			bi_errorf(Ttoo_many_args);
-			return (1);
-		}
+		if (wp[builtin_opt.optind + 1])
+			goto unexpected_args;
 		return (set_ulimit(rlimits[i], wp[builtin_opt.optind], how));
 	}
-	if (!all)
-		print_ulimit(rlimits[i], how);
-	else for (i = 0; i < NELEM(rlimits); ++i) {
-		shprintf("-%c: %-20s  ", rlimits[i]->optchar, rlimits[i]->name);
-		print_ulimit(rlimits[i], how);
-	}
+	print_ulimit(rlimits[i], how);
 	return (0);
 }
 
 #if HAVE_RLIMIT
-#define RL_T rlim_t
-#define RL_U (rlim_t)RLIM_INFINITY
+#ifndef MKSH_RLIM_T
+#define MKSH_RLIM_T rlim_t
+#else
+/* because add_cppflags does not handle spaces */
+#define RLT_SI signed int
+#define RLT_UI unsigned int
+#define RLT_SL signed long
+#define RLT_UL unsigned long
+#define RLT_SQ signed long long
+#define RLT_UQ unsigned long long
+#endif
+#define RL_T MKSH_RLIM_T
+#define RL_U (MKSH_RLIM_T)RLIM_INFINITY
+mbCTA_BEG(ulimit_c);
+ mbCTA(rlinf_fits, (RLIM_INFINITY) == (RL_U));
+mbCTA_END(ulimit_c);
 #else
 #define RL_T long
 #define RL_U LONG_MAX
@@ -263,16 +303,22 @@ static int
 set_ulimit(const struct limits *l, const char *v, int how MKSH_A_UNUSED)
 {
 	RL_T val = (RL_T)0;
+	mbiHUGE_U hval;
 #if HAVE_RLIMIT
 	struct rlimit limit;
 #endif
 
-	if (strcmp(v, "unlimited") == 0)
+	if (strcmp(v, "unlimited") == 0) {
 		val = RL_U;
-	else {
+		goto got_val;
+	}
+	if (!getnh(v, &hval)) {
 		mksh_uari_t rval;
 
-		if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, false))
+		if (errno != EINVAL)
+			goto inv_val;
+
+		if (!evaluate(v, (mksh_ari_t *)&rval, KSH_RETURN_ERROR, Nee))
 			return (1);
 		/*
 		 * Avoid problems caused by typos that evaluate misses due
@@ -281,21 +327,43 @@ set_ulimit(const struct limits *l, const
 		 * evaluate() to control if unset params are 0 or an error.
 		 */
 		if (!rval && !ctype(v[0], C_DIGIT)) {
-			bi_errorf("invalid %s limit: %s", l->name, v);
+			errno = EINVAL;
+ inv_val:
+			kwarnf0(KWF_BIERR, "invalid %s limit: %s", l->name, v);
 			return (1);
 		}
+		hval = rval;
+	}
+	errno = EOVERFLOW;
+#define mbiCfail goto inv_val
 #if HAVE_RLIMIT
-		val = (rlim_t)((rlim_t)rval * l->factor);
-#else
-		val = (RL_T)rval;
+	mbiCAUmul(mbiHUGE_U, hval, l->factor);
 #endif
+	if (mbiTYPE_ISU(RL_T))
+		mbiCASlet(RL_T, val, mbiHUGE_U, hval);
+	else {
+		/* huh, rlim_t is supposed to be unsigned! */
+		mbiHUGE_S hsval;
+
+		mbiCAsafeU2S(mbiHUGE_S, mbiHUGE_U, hval);
+		hsval = mbiA_U2S(mbiHUGE_U, mbiHUGE_S, mbiHUGE_S_MAX, hval);
+		mbiCASlet(RL_T, val, mbiHUGE_S, hsval);
 	}
+#undef mbiCfail
+	/* do not numerically apprehend magic values */
+	if (
+#if HAVE_RLIMIT && (defined(RLIM_SAVED_CUR) || defined(RLIM_SAVED_MAX))
+	    val == RLIM_SAVED_CUR || val == RLIM_SAVED_MAX ||
+#endif
+	    val == RL_U)
+		goto inv_val;
+ got_val:
 
 #if HAVE_RLIMIT
 	if (getrlimit(l->resource, &limit) < 0) {
 #ifndef MKSH_SMALL
-		bi_errorf("limit %s could not be read, contact the mksh developers: %s",
-		    l->name, cstrerror(errno));
+		kwarnf(KWF_BIERR | KWF_TWOMSG, l->name,
+		    "limit could not be read, contact the mksh developers");
 #endif
 		/* some can't be read */
 		limit.rlim_cur = RLIM_INFINITY;
@@ -308,9 +376,10 @@ set_ulimit(const struct limits *l, const
 	if (!setrlimit(l->resource, &limit))
 		return (0);
 #else
-	if (l->writable == false) {
+	if (l->writable == Nee) {
 	    /* check.t:ulimit-2 fails if we return 1 and/or do:
-		bi_errorf(Tf_ro, l->name);
+		kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+		    Tread_only, l->name);
 	    */
 		return (0);
 	}
@@ -318,9 +387,10 @@ set_ulimit(const struct limits *l, const
 		return (0);
 #endif
 	if (errno == EPERM)
-		bi_errorf("%s exceeds allowable %s limit", v, l->name);
+		kwarnf0(KWF_BIERR | KWF_NOERRNO,
+		    "%s exceeds allowable %s limit", v, l->name);
 	else
-		bi_errorf("bad %s limit: %s", l->name, cstrerror(errno));
+		kwarnf0(KWF_BIERR, "%s: bad %s limit", v, l->name);
 	return (1);
 }
 
@@ -328,6 +398,7 @@ static void
 print_ulimit(const struct limits *l, int how MKSH_A_UNUSED)
 {
 	RL_T val = (RL_T)0;
+	char numbuf[NUMBUFSZ];
 #if HAVE_RLIMIT
 	struct rlimit limit;
 
@@ -336,17 +407,17 @@ print_ulimit(const struct limits *l, int
 	if ((val = ulimit(l->resource, 0)) < 0)
 #endif
 	    {
-		shf_puts("unknown\n", shl_stdout);
-		return;
+		shf_puts("unknown", shl_stdout);
+		goto out;
 	}
 #if HAVE_RLIMIT
 	if (how & SOFT)
 		val = limit.rlim_cur;
-	else if (how & HARD)
+	else
 		val = limit.rlim_max;
 #endif
 	if (val == RL_U)
-		shf_puts("unlimited\n", shl_stdout);
+		shf_puts("unlimited", shl_stdout);
 	else {
 #if HAVE_RLIMIT
 		val /= l->factor;
@@ -355,6 +426,10 @@ print_ulimit(const struct limits *l, int
 			val = (RL_T)(((size_t)val - (size_t)&etext) /
 			    (size_t)1024);
 #endif
-		shprintf("%lu\n", (unsigned long)val);
+		shf_puts(mbiTYPE_ISU(RL_T) ?
+		    kuHfmt((kuH)val, FL_DEC, numbuf) :
+		    ksHfmt((ksH)val, FL_DEC, numbuf), shl_stdout);
 	}
+ out:
+	shf_putc('\n', shl_stdout);
 }
--- mksh-59c.orig/ulimits.opt
+++ mksh-59c/ulimits.opt
@@ -21,7 +21,7 @@
  */
 
 @RLIMITS_DEFNS
-__RCSID("$MirOS: src/bin/mksh/ulimits.opt,v 1.2 2020/07/24 20:50:11 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/ulimits.opt,v 1.3 2022/02/19 21:22:02 tg Exp $");
 @RLIMITS_ITEMS
 #define FN(lname,lg,ls,lw,lopt) (const struct limits *)(&rlimits_ ## lg),
 @@
@@ -38,9 +38,9 @@ __RCSID("$MirOS: src/bin/mksh/ulimits.op
 FN("file(blocks)", KSH_UL_GFIL, KSH_UL_SFIL, KSH_UL_WFIL
 
 >d|KSH_UL_GBRK
-FN("data(KiB)", KSH_UL_GBRK, 0, false
+FN("data(KiB)", KSH_UL_GBRK, 0, Nee
 
 >n|KSH_UL_GDES
-FN("nofiles(descriptors)", KSH_UL_GDES, 0, false
+FN("nofiles(descriptors)", KSH_UL_GDES, 0, Nee
 
 |RLIMITS_OPTCS
--- mksh-59c.orig/var.c
+++ mksh-59c/var.c
@@ -3,7 +3,7 @@
 /*-
  * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  *		 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018,
- *		 2019
+ *		 2019, 2021, 2022, 2023
  *	mirabilos <m@mirbsd.org>
  *
  * Provided that these terms and disclaimer and all copyright notices
@@ -25,11 +25,7 @@
 #include "sh.h"
 #include "mirhash.h"
 
-#if defined(__OpenBSD__)
-#include <sys/sysctl.h>
-#endif
-
-__RCSID("$MirOS: src/bin/mksh/var.c,v 1.237 2020/06/22 17:11:03 tg Exp $");
+__RCSID("$MirOS: src/bin/mksh/var.c,v 1.283 2024/02/02 04:04:22 tg Exp $");
 
 /*-
  * Variables
@@ -42,33 +38,43 @@ __RCSID("$MirOS: src/bin/mksh/var.c,v 1.
  */
 
 static struct table specials;
-static uint32_t lcg_state = 5381, qh_state = 4711;
+static k32 lcg_state = 5381U, qh_state = 4711U;
 /* may only be set by typeset() just before call to array_index_calc() */
 static enum namerefflag innermost_refflag = SRF_NOP;
 
-static void c_typeset_vardump(struct tbl *, uint32_t, int, int, bool, bool);
-static void c_typeset_vardump_recursive(struct block *, uint32_t, int, bool,
-    bool);
+/*
+ * Evil hack since casting uint to sint is implementation-defined
+ */
+typedef union {
+	mksh_ari_t i;
+	mksh_uari_t u;
+} mksh_ari_u;
+
+static void c_typeset_vardump(struct tbl *, kui, int, int, Wahr, Wahr);
+static void c_typeset_vardump_recursive(struct block *, kui, int, Wahr,
+    Wahr);
 static char *formatstr(struct tbl *, const char *);
 static void exportprep(struct tbl *, const char *, size_t);
 static int special(const char *);
 static void unspecial(const char *);
 static void getspec(struct tbl *);
 static void setspec(struct tbl *);
-static void unsetspec(struct tbl *, bool);
-static int getint(struct tbl *, mksh_ari_u *, bool);
-static const char *array_index_calc(const char *, bool *, uint32_t *);
-static struct tbl *vtypeset(int *, const char *, uint32_t, uint32_t, int, int);
+static void unsetspec(struct tbl *, Wahr);
+static int getint(struct tbl *, mksh_ari_u *, Wahr);
+static int getnum(const char *, mksh_ari_u *, Wahr, Wahr);
+static const char *array_index_calc(const char *, Wahr *, k32 *);
+static struct tbl *vtypeset(int *, const char *, kui, kui, int, int);
 
 /*
  * create a new block for function calls and simple commands
  * assume caller has allocated and set up e->loc
  */
+/* pre-initio() */
 void
 newblock(void)
 {
 	struct block *l;
-	static const char *empty[] = { null };
+	static const char *empty[] = { null, NULL };
 
 	l = alloc(sizeof(struct block), ATEMP);
 	l->flags = 0;
@@ -107,7 +113,7 @@ popblock(void)
 			if ((vq = global(vp->name))->flag & ISSET)
 				setspec(vq);
 			else
-				unsetspec(vq, false);
+				unsetspec(vq, Nee);
 		}
 	if (l->flags & BF_DOGETOPTS)
 		user_opt = l->getopts_state;
@@ -150,7 +156,7 @@ initvar(void)
 
 /* common code for several functions below and c_typeset() */
 struct block *
-varsearch(struct block *l, struct tbl **vpp, const char *vn, uint32_t h)
+varsearch(struct block *l, struct tbl **vpp, const char *vn, k32 h)
 {
 	register struct tbl *vp;
 
@@ -171,20 +177,23 @@ varsearch(struct block *l, struct tbl **
 
 /*
  * Used to calculate an array index for global()/local(). Sets *arrayp
- * to true if this is an array, sets *valp to the array index, returns
+ * to true if this is an array, sets *idxp to the array index, returns
  * the basename of the array. May only be called from global()/local()
  * and must be their first callee.
  */
 static const char *
-array_index_calc(const char *n, bool *arrayp, uint32_t *valp)
+array_index_calc(const char *n, Wahr *arrayp, k32 *idxp)
 {
 	const char *p;
 	size_t len;
 	char *ap = NULL;
 
-	*arrayp = false;
+	*arrayp = Nee;
  redo_from_ref:
-	p = skip_varname(n, false);
+	p = skip_varname(n, Nee);
+	if ((size_t)(p - n) > (size_t)(INT_MAX - X_EXTRA))
+		kerrf(KWF_ERR(255) | KWF_PREFIX | KWF_FILELINE | KWF_ONEMSG |
+		    KWF_NOERRNO, "parameter name too long");
 	if (innermost_refflag == SRF_NOP && (p != n) && ctype(n[0], C_ALPHX)) {
 		struct tbl *vp;
 		char *vn;
@@ -208,18 +217,18 @@ array_index_calc(const char *n, bool *ar
 
 	if (p != n && ord(*p) == ORD('[') && (len = array_ref_len(p))) {
 		char *sub, *tmp;
-		mksh_ari_t rval;
+		mksh_ari_u rval;
 		size_t tmplen = p - n;
 
 		/* calculate the value of the subscript */
-		*arrayp = true;
+		*arrayp = Ja;
 		len -= 2;
 		tmp = alloc((len > tmplen ? len : tmplen) + 1, ATEMP);
 		memcpy(tmp, p + 1, len);
 		tmp[len] = '\0';
 		sub = substitute(tmp, 0);
-		evaluate(sub, &rval, KSH_UNWIND_ERROR, true);
-		*valp = (uint32_t)rval;
+		evaluate(sub, &rval.i, KSH_UNWIND_ERROR, Ja);
+		*idxp = mbiMM(k32, K32_FM, rval.u);
 		afree(sub, ATEMP);
 		memcpy(tmp, n, tmplen);
 		tmp[tmplen] = '\0';
@@ -235,30 +244,32 @@ array_index_calc(const char *n, bool *ar
 struct tbl *
 global(const char *n)
 {
-	return (isglobal(n, true));
+	return (isglobal(n, Ja));
 }
 
 /* search for variable; if not found, return NULL or create globally */
 struct tbl *
-isglobal(const char *n, bool docreate)
+isglobal(const char *n, Wahr docreate)
 {
 	struct tbl *vp;
 	union mksh_cchack vname;
 	struct block *l = e->loc;
 	int c;
-	bool array;
-	uint32_t h, val;
+	Wahr array;
+	k32 h;
+	k32 idx;
 
 	/*
 	 * check to see if this is an array;
 	 * dereference namerefs; must come first
 	 */
-	vn = array_index_calc(n, &array, &val);
+	vn = array_index_calc(n, &array, &idx);
 	h = hash(vn);
 	c = (unsigned char)vn[0];
 	if (!ctype(c, C_ALPHX)) {
 		if (array)
-			errorf(Tbadsubst);
+			kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+			    KWF_ONEMSG | KWF_NOERRNO, Tbadsubst);
 		vp = vtemp;
 		vp->flag = DEFINED;
 		vp->type = 0;
@@ -311,10 +322,10 @@ isglobal(const char *n, bool docreate)
 	if (vp == NULL && docreate)
 		vp = ktenter(&l->vars, vn, h);
 	else
-		docreate = false;
+		docreate = Nee;
 	if (vp != NULL) {
 		if (array)
-			vp = arraysearch(vp, val);
+			vp = arraysearch(vp, idx);
 		if (docreate) {
 			vp->flag |= DEFINED;
 			if (special(vn))
@@ -332,19 +343,20 @@ isglobal(const char *n, bool docreate)
  * Search for local variable, if not found create locally.
  */
 struct tbl *
-local(const char *n, bool copy)
+local(const char *n, Wahr copy)
 {
 	struct tbl *vp;
 	union mksh_cchack vname;
 	struct block *l = e->loc;
-	bool array;
-	uint32_t h, val;
+	Wahr array;
+	k32 h;
+	k32 idx;
 
 	/*
 	 * check to see if this is an array;
 	 * dereference namerefs; must come first
 	 */
-	vn = array_index_calc(n, &array, &val);
+	vn = array_index_calc(n, &array, &idx);
 	h = hash(vn);
 	if (!ctype(*vn, C_ALPHX)) {
 		vp = vtemp;
@@ -368,7 +380,7 @@ local(const char *n, bool copy)
 		}
 	}
 	if (array)
-		vp = arraysearch(vp, val);
+		vp = arraysearch(vp, idx);
 	vp->flag |= DEFINED;
 	if (special(vn))
 		vp->flag |= SPECIAL;
@@ -414,21 +426,17 @@ str_val(struct tbl *vp)
 			n = (vp->val.i < 0) ? -vp->val.u : vp->val.u;
 		base = (vp->type == 0) ? 10U : (unsigned int)vp->type;
 
-		if (base == 1 && n == 0)
-			base = 2;
 		if (base == 1) {
-			size_t sz = 1;
-
-			*(s = strbuf) = '1';
+			s = strbuf;
 			s[1] = '#';
-			if (!UTFMODE)
-				s[2] = (unsigned char)n;
-			else if ((n & 0xFF80) == 0xEF80)
-				/* OPTU-16 -> raw octet */
-				s[2] = asc2rtt(n & 0xFF);
-			else
-				sz = utf_wctomb(s + 2, n);
-			s[2 + sz] = '\0';
+			if (n == 0) {
+				s[0] = '2';
+				s[2] = '0';
+				s[3] = '\0';
+			} else {
+				s[0] = '1';
+				s[2 + ez_ctomb(s + 2, n)] = '\0';
+			}
 		} else {
 			*--s = '\0';
 			do {
@@ -457,25 +465,34 @@ str_val(struct tbl *vp)
 int
 setstr(struct tbl *vq, const char *s, int error_ok)
 {
-	bool no_ro_check = tobool(error_ok & 0x4);
+	Wahr no_ro_check = isWahr(error_ok & 0x4);
 
 	error_ok &= ~0x4;
 	if ((vq->flag & RDONLY) && !no_ro_check) {
-		warningf(true, Tf_ro, vq->name);
+		kwarnf((error_ok ? KWF_WARNING : KWF_ERR(2)) | KWF_PREFIX |
+		    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+		    Tread_only, vq->name);
 		if (!error_ok)
-			errorfxz(2);
+			unwind(LERROR);
 		return (0);
 	}
 	if (!(vq->flag&INTEGER)) {
 		/* string dest */
 		char *salloc = NULL;
 		size_t cursz;
+#ifndef MKSH_SMALL
+		mbiPTR_U cmp_s, cmp_b, cmp_e;
+#endif
+
 		if ((vq->flag&ALLOC)) {
 			cursz = strlen(vq->val.s) + 1;
 #ifndef MKSH_SMALL
 			/* debugging */
-			if (s >= vq->val.s && s < (vq->val.s + cursz)) {
-				internal_errorf(
+			cmp_s = (mbiPTR_U)(const void *)s;
+			cmp_b = (mbiPTR_U)(void *)vq->val.s;
+			cmp_e = (mbiPTR_U)(void *)(vq->val.s + cursz);
+			if (cmp_s >= cmp_b && cmp_s < cmp_e) {
+				kerrf0(KWF_INTERNAL | KWF_ERR(0xFF) | KWF_NOERRNO,
 				    "setstr: %s=%s: assigning to self",
 				    vq->name, s);
 			}
@@ -494,10 +511,11 @@ setstr(struct tbl *vq, const char *s, in
 			vq->flag |= ALLOC;
 			vq->type = 0;
 		}
+		vq->flag &= ~IMPORT;
 		afree(salloc, ATEMP);
 	} else {
 		/* integer dest */
-		if (!v_evaluate(vq, s, error_ok, true))
+		if (!v_evaluate(vq, s, error_ok, Ja))
 			return (0);
 	}
 	vq->flag |= ISSET;
@@ -525,22 +543,28 @@ setint(struct tbl *vq, mksh_ari_t n)
 }
 
 static int
-getint(struct tbl *vp, mksh_ari_u *nump, bool arith)
+getint(struct tbl *vp, mksh_ari_u *nump, Wahr arith)
 {
-	mksh_uari_t c, num = 0, base = 10;
-	const char *s;
-	bool have_base = false, neg = false;
-
 	if (vp->flag & SPECIAL)
 		getspec(vp);
 	/* XXX is it possible for ISSET to be set and val.s to be NULL? */
-	if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL))
+	if (!(vp->flag & ISSET) || (!(vp->flag & INTEGER) && vp->val.s == NULL)) {
+		errno = EINVAL;
 		return (-1);
+	}
 	if (vp->flag & INTEGER) {
 		nump->i = vp->val.i;
 		return (vp->type);
 	}
-	s = vp->val.s + vp->type;
+	return (getnum(vp->val.s + vp->type, nump, arith,
+	    Flag(FPOSIX) && !(vp->flag & ZEROFIL)));
+}
+
+static int
+getnum(const char *s, mksh_ari_u *nump, Wahr arith, Wahr psxoctal)
+{
+	mksh_uari_t c, num = 0, base = 10;
+	Wahr have_base = Nee, neg = Nee;
 
 	do {
 		c = (unsigned char)*s++;
@@ -548,7 +572,7 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 
 	switch (c) {
 	case '-':
-		neg = true;
+		neg = Ja;
 		/* FALLTHROUGH */
 	case '+':
 		c = (unsigned char)*s++;
@@ -556,17 +580,16 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 	}
 
 	if (c == '0' && arith) {
-		if (ksh_eq(s[0], 'X', 'x')) {
+		if (isCh(s[0], 'X', 'x')) {
 			/* interpret as hexadecimal */
 			base = 16;
 			++s;
 			goto getint_c_style_base;
-		} else if (Flag(FPOSIX) && ctype(s[0], C_DIGIT) &&
-		    !(vp->flag & ZEROFIL)) {
+		} else if (psxoctal && ctype(s[0], C_DIGIT)) {
 			/* interpret as octal (deprecated) */
 			base = 8;
  getint_c_style_base:
-			have_base = true;
+			have_base = Ja;
 			c = (unsigned char)*s++;
 		}
 	}
@@ -574,28 +597,21 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 	do {
 		if (c == '#') {
 			/* ksh-style base determination */
-			if (have_base || num < 1)
+			if (have_base || num < 1) {
+				errno = EINVAL;
 				return (-1);
+			}
 			if ((base = num) == 1) {
 				/* mksh-specific extension */
 				unsigned int wc;
 
-				if (!UTFMODE)
-					wc = *(const unsigned char *)s;
-				else if (utf_mbtowc(&wc, s) == (size_t)-1)
-					/* OPTU-8 -> OPTU-16 */
-					/*
-					 * (with a twist: 1#\uEF80 converts
-					 * the same as 1#\x80 does, thus is
-					 * not round-tripping correctly XXX)
-					 */
-					wc = 0xEF00 + rtt2asc(*s);
+				ez_mbtoc(&wc, s);
 				nump->u = (mksh_uari_t)wc;
 				return (1);
 			} else if (base > 36)
 				base = 10;
 			num = 0;
-			have_base = true;
+			have_base = Ja;
 			continue;
 		}
 		if (ctype(c, C_DIGIT))
@@ -604,10 +620,14 @@ getint(struct tbl *vp, mksh_ari_u *nump,
 			c = ksh_numuc(c) + 10;
 		else if (ctype(c, C_LOWER))
 			c = ksh_numlc(c) + 10;
-		else
+		else {
+			errno = EINVAL;
 			return (-1);
-		if (c >= base)
+		}
+		if (c >= base) {
+			errno = EINVAL;
 			return (-1);
+		}
 		/* handle overflow as truncation */
 		num = num * base + c;
 	} while ((c = (unsigned char)*s++));
@@ -623,7 +643,7 @@ getint(struct tbl *vp, mksh_ari_u *nump,
  * (vq and vp may be the same)
  */
 struct tbl *
-setint_v(struct tbl *vq, struct tbl *vp, bool arith)
+setint_v(struct tbl *vq, struct tbl *vp, Wahr arith)
 {
 	int base;
 	mksh_ari_u num;
@@ -641,10 +661,11 @@ setint_v(struct tbl *vq, struct tbl *vp,
 void
 setint_n(struct tbl *vq, mksh_ari_t num, int newbase)
 {
-	if (!(vq->flag & INTEGER) && (vq->flag & ALLOC)) {
-		vq->flag &= ~ALLOC;
+	if (!(vq->flag & INTEGER)) {
+		if (vq->flag & ALLOC)
+			afree(vq->val.s, vq->areap);
+		vq->flag &= ~(ALLOC | IMPORT);
 		vq->type = 0;
-		afree(vq->val.s, vq->areap);
 	}
 	vq->val.i = num;
 	if (newbase != 0)
@@ -657,36 +678,39 @@ setint_n(struct tbl *vq, mksh_ari_t num,
 static char *
 formatstr(struct tbl *vp, const char *s)
 {
-	int olen, nlen;
 	char *p, *q;
-	size_t psiz;
-
-	olen = (int)utf_mbswidth(s);
 
-	if (vp->flag & (RJUST|LJUST)) {
+	if (vp->flag & (RJUST | LJUST)) {
+		int slen, nlen;
+		size_t psiz;
+
+		psiz = utf_mbswidth(s);
+		if (psiz > (size_t)INT_MAX) {
+			errno = EOVERFLOW;
+			kerrf0(KWF_ERR(0xFF) | KWF_PREFIX | KWF_FILELINE,
+			    "string width %zu", psiz);
+		}
+		slen = (int)psiz;
 		if (!vp->u2.field)
 			/* default field width */
-			vp->u2.field = olen;
+			vp->u2.field = slen;
 		nlen = vp->u2.field;
-	} else
-		nlen = olen;
 
-	p = alloc((psiz = nlen * /* MB_LEN_MAX */ 3 + 1), ATEMP);
-	if (vp->flag & (RJUST|LJUST)) {
-		int slen = olen;
+		p = alloc2(nlen + 1, /* MB_LEN_MAX */ 4, ATEMP);
+		psiz = ((size_t)nlen + 1U) * 4U;
 
 		if (vp->flag & RJUST) {
 			const char *qq;
 			int n = 0;
 
-			qq = utf_skipcols(s, slen, &slen);
+			qq = s + strlen(s);
 
 			/* strip trailing spaces (AT&T uses qq[-1] == ' ') */
 			while (qq > s && ctype(qq[-1], C_SPACE)) {
 				--qq;
 				--slen;
 			}
-			if (vp->flag & ZEROFIL && vp->flag & INTEGER) {
+			if (HAS(vp->flag, ZEROFIL | INTEGER)) {
 				if (!s[0] || !s[1])
 					goto uhm_no;
 				if (s[1] == '#')
@@ -721,7 +745,7 @@ formatstr(struct tbl *vp, const char *s)
 				vp->u2.field, vp->u2.field, s);
 		}
 	} else
-		memcpy(p, s, strlen(s) + 1);
+		strdupx(p, s, ATEMP);
 
 	if (vp->flag & UCASEV_AL) {
 		for (q = p; *q; q++)
@@ -750,7 +774,7 @@ exportprep(struct tbl *vp, const char *v
 	vp->val.s = aresizeif(cursz, cp, vp->type + vallen, vp->areap);
 	memmove(vp->val.s + vp->type, val == cp ? vp->val.s : val, vallen);
 	memcpy(vp->val.s, vp->name, namelen);
-	vp->val.s[namelen] = '=';
+	((char *)(vp->val.s))[namelen] = '=';
 }
 
 /*
@@ -759,12 +783,12 @@ exportprep(struct tbl *vp, const char *v
  * UCASEV_AL), and optionally set its value if an assignment.
  */
 struct tbl *
-typeset(const char *var, uint32_t set, uint32_t clr, int field, int base)
+typeset(const char *var, kui set, kui clr, int field, int base)
 {
 	return (vtypeset(NULL, var, set, clr, field, base));
 }
 static struct tbl *
-vtypeset(int *ep, const char *var, uint32_t set, uint32_t clr,
+vtypeset(int *ep, const char *var, kui set, kui clr,
     int field, int base)
 {
 	struct tbl *vp;
@@ -772,7 +796,7 @@ vtypeset(int *ep, const char *var, uint3
 	char *tvar, tvarbuf[32];
 	const char *val;
 	size_t len;
-	bool vappend = false;
+	Wahr vappend = Nee;
 	enum namerefflag new_refflag = SRF_NOP;
 
 	if (ep)
@@ -788,17 +812,18 @@ vtypeset(int *ep, const char *var, uint3
 	}
 
 	/* check for valid variable name, search for value */
-	val = skip_varname(var, false);
+	val = skip_varname(var, Nee);
 	if (val == var) {
 		/* no variable name given */
 		return (NULL);
 	}
 	if (ord(*val) == ORD('[')) {
 		if (new_refflag != SRF_NOP)
-			return (maybe_errorf(ep, 1, Tf_sD_s, var,
-			    "reference variable can't be an array"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    var, "reference variable can't be an array"));
 		len = array_ref_len(val);
-		if (len == 0)
+		if (len < 3)
 			return (NULL);
 		/*
 		 * IMPORT is only used when the shell starts up and is
@@ -808,39 +833,39 @@ vtypeset(int *ep, const char *var, uint3
 		 * would be a major security hole.
 		 */
 		if (set & IMPORT) {
-			size_t i;
+			mksh_ari_u num;
 
-			for (i = 1; i < len - 1; i++)
-				if (!ctype(val[i], C_DIGIT))
-					return (NULL);
+			len -= 2;
+			strnbdupx(tvar, val + 1, len, ATEMP, tvarbuf);
+			if (getnum(tvar, &num, Ja, Nee) == -1)
+				len = 0;
+			if (tvar != tvarbuf)
+				afree(tvar, ATEMP);
+			if (!len)
+				return (NULL);
+			len += 2;
 		}
 		val += len;
 	}
 	if (ord(val[0]) == ORD('=')) {
 		len = val - var;
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		++val;
 	} else if (set & IMPORT) {
 		/* environment invalid variable name or no assignment */
 		return (NULL);
 	} else if (ord(val[0]) == ORD('+') && ord(val[1]) == ORD('=')) {
 		len = val - var;
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		val += 2;
-		vappend = true;
+		vappend = Ja;
 	} else if (val[0] != '\0') {
 		/* other invalid variable names (not from environment) */
 		return (NULL);
 	} else {
 		/* just varname with no value part nor equals sign */
 		len = strlen(var);
-		tvar = len < sizeof(tvarbuf) ? tvarbuf : alloc(len + 1, ATEMP);
-		memcpy(tvar, var, len);
-		tvar[len] = '\0';
+		strnbdupx(tvar, var, len, ATEMP, tvarbuf);
 		val = NULL;
 		/* handle foo[*] => foo (whole array) mapping for R39b */
 		if (len > 3 && ord(tvar[len - 3]) == ORD('[') &&
@@ -854,8 +879,9 @@ vtypeset(int *ep, const char *var, uint3
 
 		/* bail out on 'nameref foo+=bar' */
 		if (vappend)
-			return (maybe_errorf(ep, 1,
-			    "appending not allowed for nameref"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+			    "appending not allowed for nameref"));
 		/* find value if variable already exists */
 		if ((qval = val) == NULL) {
 			varsearch(e->loc, &vp, tvar, hash(tvar));
@@ -864,7 +890,7 @@ vtypeset(int *ep, const char *var, uint3
 			qval = str_val(vp);
 		}
 		/* check target value for being a valid variable name */
-		ccp = skip_varname(qval, false);
+		ccp = skip_varname(qval, Nee);
 		if (ccp == qval) {
 			int c;
 
@@ -881,8 +907,9 @@ vtypeset(int *ep, const char *var, uint3
 				goto nameref_rhs_checked;
 			}
  nameref_empty:
-			return (maybe_errorf(ep, 1, Tf_sD_s, var,
-			    "empty nameref target"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    var, "empty nameref target"));
 		}
 		len = (ord(*ccp) == ORD('[')) ? array_ref_len(ccp) : 0;
 		if (ccp[len]) {
@@ -891,15 +918,17 @@ vtypeset(int *ep, const char *var, uint3
 			 * junk after it" and "invalid array"; in the
 			 * latter case, len is also 0 and points to '['
 			 */
-			return (maybe_errorf(ep, 1, Tf_sD_s, qval,
-			    "nameref target not a valid parameter name"), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+			    qval, "nameref target not a valid parameter name"));
 		}
  nameref_rhs_checked:
 		/* prevent nameref loops */
 		while (qval) {
 			if (!strcmp(qval, tvar))
-				return (maybe_errorf(ep, 1, Tf_sD_s, qval,
-				    "expression recurses on parameter"), NULL);
+				merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+				    KWF_FILELINE | KWF_TWOMSG | KWF_NOERRNO,
+				    qval, "expression recurses on parameter"));
 			varsearch(e->loc, &vp, qval, hash(qval));
 			qval = NULL;
 			if (vp && ((vp->flag & (ARRAY | ASSOC)) == ASSOC))
@@ -910,12 +939,16 @@ vtypeset(int *ep, const char *var, uint3
 	/* prevent typeset from creating a local PATH/ENV/SHELL */
 	if (Flag(FRESTRICTED) && (strcmp(tvar, TPATH) == 0 ||
 	    strcmp(tvar, TENV) == 0 || strcmp(tvar, TSHELL) == 0))
-		return (maybe_errorf(ep, 1, Tf_sD_s,
-		    tvar, "restricted"), NULL);
+		merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, tvar, "restricted"));
 
 	innermost_refflag = new_refflag;
-	vp = (set & LOCAL) ? local(tvar, tobool(set & LOCAL_COPY)) :
+	vp = (set & LOCAL) ? local(tvar, isWahr(set & LOCAL_COPY)) :
 	    global(tvar);
+	/* when importing environment, resolve duplicates as first-wins */
+	/* the EXPORT check is to permit overwriting the default $PATH */
+	if ((set & IMPORT) && (vp->flag & (ISSET | EXPORT)) == (ISSET | EXPORT))
+		return (NULL);
 	if (new_refflag == SRF_DISABLE && (vp->flag & (ARRAY|ASSOC)) == ASSOC)
 		vp->flag &= ~ASSOC;
 	else if (new_refflag == SRF_ENABLE) {
@@ -938,30 +971,31 @@ vtypeset(int *ep, const char *var, uint3
 
 	set &= ~(LOCAL|LOCAL_COPY);
 
-	vpbase = (vp->flag & ARRAY) ? global(arrayname(tvar)) : vp;
+	vpbase = (vp->flag & ARRAY) ? arraybase(tvar) : vp;
 
 	/*
-	 * only allow export and readonly flag to be set; AT&T ksh
+	 * only allow export and read-only flag to be set; AT&T ksh
 	 * allows any attribute to be changed which means it can be
 	 * truncated or modified (-L/-R/-Z/-i)
 	 */
 	if ((vpbase->flag & RDONLY) &&
 	    (val || clr || (set & ~(EXPORT | RDONLY))))
-		return (maybe_errorf(ep, 2, Tf_ro, tvar), NULL);
+		merrf(NULL, (ep, KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE |
+		    KWF_TWOMSG | KWF_NOERRNO, Tread_only, tvar));
 	if (tvar != tvarbuf)
 		afree(tvar, ATEMP);
 
 	/* most calls are with set/clr == 0 */
 	if (set | clr) {
-		bool ok = true;
+		Wahr ok = Ja;
 
 		/*
 		 * XXX if x[0] isn't set, there will be problems: need
 		 * to have one copy of attributes for arrays...
 		 */
 		for (t = vpbase; t; t = t->u.array) {
-			bool fake_assign;
-			char *s = NULL;
+			Wahr fake_assign;
+			const char *s = NULL;
 			char *free_me = NULL;
 
 			fake_assign = (t->flag & ISSET) && (!val || t != vp) &&
@@ -983,13 +1017,27 @@ vtypeset(int *ep, const char *var, uint3
 				t->type = 0;
 				t->flag &= ~ALLOC;
 			}
+			if (set & INTEGER) {
+				/*
+				 * Don't change base if assignment is to
+				 * be done, in case assignment fails.
+				 */
+				if (base > 0 && (!val || t != vp))
+					t->type = base;
+				/*
+				 * Do not permit content from the
+				 * environment to e.g. execute commands.
+				 */
+				if ((t->flag & IMPORT) && fake_assign) {
+					mksh_ari_u num;
+
+					if (getnum(s, &num, Ja,
+					    isWahr(Flag(FPOSIX))) == -1)
+						s = "0";
+					clr |= IMPORT;
+				}
+			}
 			t->flag = (t->flag | set) & ~clr;
-			/*
-			 * Don't change base if assignment is to be
-			 * done, in case assignment fails.
-			 */
-			if ((set & INTEGER) && base > 0 && (!val || t != vp))
-				t->type = base;
 			if (set & (LJUST|RJUST|ZEROFIL))
 				t->u2.field = field;
 			if (fake_assign) {
@@ -1000,7 +1048,7 @@ vtypeset(int *ep, const char *var, uint3
 					 * variable, but keep the flag
 					 * settings.
 					 */
-					ok = false;
+					ok = Nee;
 					if (t->flag & INTEGER)
 						t->flag &= ~ISSET;
 					else {
@@ -1014,12 +1062,14 @@ vtypeset(int *ep, const char *var, uint3
 			}
 		}
 		if (!ok)
-			return (maybe_errorf(ep, 1, NULL), NULL);
+			merrf(NULL, (ep, KWF_ERR(1) | KWF_PREFIX |
+			    KWF_FILELINE | KWF_ONEMSG | KWF_NOERRNO,
+			    "failed to set string value"));
 	}
 
 	if (vappend) {
 		size_t tlen;
-		if ((vp->flag & (ISSET|ALLOC|SPECIAL|INTEGER|UCASEV_AL|LCASEV|LJUST|RJUST)) != (ISSET|ALLOC)) {
+		if ((vp->flag & (ISSET|ALLOC|SPECIAL|INTEGER|UCASEV_AL|LCASEV|LJUST|RJUST|IMPORT)) != (ISSET|ALLOC)) {
 			/* cannot special-case this */
 			strdup2x(tvar, str_val(vp), val);
 			val = tvar;
@@ -1028,7 +1078,7 @@ vtypeset(int *ep, const char *var, uint3
 		/* trivial string appending */
 		len = strlen(vp->val.s);
 		tlen = strlen(val) + 1;
-		vp->val.s = aresize(vp->val.s, len + tlen, vp->areap);
+		vp->val.s = aresize1(vp->val.s, len, tlen, vp->areap);
 		memcpy(vp->val.s + len, val, tlen);
 	} else if (val != NULL) {
  vassign:
@@ -1038,9 +1088,11 @@ vtypeset(int *ep, const char *var, uint3
 			/* done after assignment to override default */
 			if (base > 0)
 				vp->type = base;
-		} else
-			/* setstr can't fail (readonly check already done) */
+		} else {
+			/* setstr can't fail (read-only check already done) */
 			setstr(vp, val, KSH_RETURN_ERROR | 0x4);
+			vp->flag |= (set & IMPORT);
+		}
 
 		/* came here from vappend? need to free temp val */
 		if (vappend)
@@ -1087,7 +1139,7 @@ unset(struct tbl *vp, int flags)
 	vp->flag &= SPECIAL | ((flags & 1) ? 0 : ARRAY|DEFINED);
 	if (vp->flag & SPECIAL)
 		/* responsible for 'unspecial'ing var */
-		unsetspec(vp, true);
+		unsetspec(vp, Ja);
 }
 
 /*
@@ -1096,7 +1148,7 @@ unset(struct tbl *vp, int flags)
  * the terminating NUL if whole string is legal).
  */
 const char *
-skip_varname(const char *s, bool aok)
+skip_varname(const char *s, Wahr aok)
 {
 	size_t alen;
 
@@ -1114,7 +1166,7 @@ skip_varname(const char *s, bool aok)
 const char *
 skip_wdvarname(const char *s,
     /* skip array de-reference? */
-    bool aok)
+    Wahr aok)
 {
 	if (s[0] == CHAR && ctype(s[1], C_ALPHX)) {
 		do {
@@ -1145,7 +1197,7 @@ skip_wdvarname(const char *s,
 
 /* Check if coded string s is a variable name */
 int
-is_wdvarname(const char *s, bool aok)
+is_wdvarname(const char *s, Wahr aok)
 {
 	const char *p = skip_wdvarname(s, aok);
 
@@ -1154,12 +1206,37 @@ is_wdvarname(const char *s, bool aok)
 
 /* Check if coded string s is a variable assignment */
 int
-is_wdvarassign(const char *s)
+is_wdvarassign(const char *s, Wahr needEOS)
 {
-	const char *p = skip_wdvarname(s, true);
+	const char *p = skip_wdvarname(s, Ja);
 
-	return (p != s && p[0] == CHAR &&
-	    (p[1] == '=' || (p[1] == '+' && p[2] == CHAR && p[3] == '=')));
+	if (p == s || p[0] != CHAR)
+		return (0);
+	switch (ord(p[1])) {
+	case ORD('='):
+		return (!needEOS || p[2] == EOS);
+	case ORD('+'):
+		if (p[2] != CHAR || ord(p[3]) != ORD('='))
+			return (0);
+		return (!needEOS || p[4] == EOS);
+	default:
+		return (0);
+	}
+}
+
+/* don’t leak internal hash table order */
+static int
+envsort(const void *a, const void *b)
+{
+	const kby *cp1 = *(const kby * const *)a;
+	const kby *cp2 = *(const kby * const *)b;
+
+	while (*cp1 == *cp2) {
+		if (*cp1 == '=' || *cp1++ == '\0')
+			return (0);
+		++cp2;
+	}
+	return ((int)asciibetical(*cp1) - (int)asciibetical(*cp2));
 }
 
 /*
@@ -1182,7 +1259,7 @@ makenv(void)
 			    (vp->flag&(ISSET|EXPORT)) == (ISSET|EXPORT)) {
 				struct block *l2;
 				struct tbl *vp2;
-				uint32_t h = hash(vp->name);
+				k32 h = hash(vp->name);
 
 				/* unexport any redefined instances */
 				for (l2 = l->next; l2 != NULL; l2 = l2->next) {
@@ -1210,6 +1287,7 @@ makenv(void)
 		if (l->flags & BF_STOPENV)
 			break;
 	}
+	qsort(XPptrv(denv), XPsize(denv), sizeof(void *), envsort);
 	XPput(denv, NULL);
 	return ((char **)XPclose(denv));
 }
@@ -1289,9 +1367,13 @@ getspec(struct tbl *vp)
 
 		vp->flag &= ~SPECIAL;
 		mksh_TIME(tv);
-		shf_snprintf(buf, sizeof(buf), "%u.%06u",
-		    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
-		setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
+		if (vp->flag & INTEGER)
+			setint(vp, (mksh_ari_t)tv.tv_sec);
+		else {
+			shf_snprintf(buf, sizeof(buf), "%u.%06u",
+			    (unsigned)tv.tv_sec, (unsigned)tv.tv_usec);
+			setstr(vp, buf, KSH_RETURN_ERROR | 0x4);
+		}
 		vp->flag |= SPECIAL;
 		return;
 	}
@@ -1370,7 +1452,7 @@ setspec(struct tbl *vp)
 		s = str_val(vp);
 		strdupx(path, s, APERM);
 		/* clear tracked aliases */
-		flushcom(true);
+		flushcom(Ja);
 		return;
 #ifndef MKSH_NO_CMDLINE_EDITING
 	case V_TERM:
@@ -1411,10 +1493,12 @@ setspec(struct tbl *vp)
 	case V_SECONDS:
 	case V_TMOUT:
 		vp->flag &= ~SPECIAL;
-		if (getint(vp, &num, false) == -1) {
+		if (getint(vp, &num, Nee) == -1) {
 			s = str_val(vp);
 			if (st != V_RANDOM)
-				errorf(Tf_sD_sD_s, vp->name, Tbadnum, s);
+				kerrf(KWF_ERR(1) | KWF_PREFIX | KWF_FILELINE |
+				    KWF_THREEMSG | KWF_NOERRNO,
+				    vp->name, Tbadnum, s);
 			num.u = hash(s);
 		}
 		vp->flag |= SPECIAL;
@@ -1474,7 +1558,7 @@ setspec(struct tbl *vp)
 }
 
 static void
-unsetspec(struct tbl *vp, bool dounset)
+unsetspec(struct tbl *vp, Wahr dounset)
 {
 	/*
 	 * AT&T ksh man page says OPTIND, OPTARG and _ lose special
@@ -1504,7 +1588,7 @@ unsetspec(struct tbl *vp, bool dounset)
 		afree(path, APERM);
 		strdupx(path, def_path, APERM);
 		/* clear tracked aliases */
-		flushcom(true);
+		flushcom(Ja);
 		return;
 #ifndef MKSH_NO_CMDLINE_EDITING
 	case V_TERM:
@@ -1546,38 +1630,37 @@ unsetspec(struct tbl *vp, bool dounset)
  * vp, indexed by val.
  */
 struct tbl *
-arraysearch(struct tbl *vp, uint32_t val)
+arraysearch(struct tbl *vp, k32 idx)
 {
 	struct tbl *prev, *curr, *news;
 	size_t len;
 
 	vp->flag = (vp->flag | (ARRAY | DEFINED)) & ~ASSOC;
 	/* the table entry is always [0] */
-	if (val == 0)
+	if (idx == 0)
 		return (vp);
 	prev = vp;
 	curr = vp->u.array;
-	while (curr && curr->ua.index < val) {
+	while (curr && curr->ua.index < idx) {
 		prev = curr;
 		curr = curr->u.array;
 	}
-	if (curr && curr->ua.index == val) {
+	if (curr && curr->ua.index == idx) {
 		if (curr->flag&ISSET)
 			return (curr);
 		news = curr;
 	} else
 		news = NULL;
 	if (!news) {
-		len = strlen(vp->name);
-		checkoktoadd(len, 1 + offsetof(struct tbl, name[0]));
-		news = alloc(offsetof(struct tbl, name[0]) + ++len, vp->areap);
+		len = strlen(vp->name) + 1U;
+		news = alloc(mbccFAMsz(struct tbl, name, len), vp->areap);
 		memcpy(news->name, vp->name, len);
 	}
 	news->flag = (vp->flag & ~(ALLOC|DEFINED|ISSET|SPECIAL)) | AINDEX;
 	news->type = vp->type;
 	news->areap = vp->areap;
 	news->u2.field = vp->u2.field;
-	news->ua.index = val;
+	news->ua.index = idx;
 
 	if (curr != news) {
 		/* not reusing old array entry */
@@ -1610,26 +1693,30 @@ array_ref_len(const char *cp)
 }
 
 /*
- * Make a copy of the base of an array name
+ * same effect as global(copy of the base of an array name)
  */
-char *
-arrayname(const char *str)
+struct tbl *
+arraybase(const char *str)
 {
 	const char *p;
-	char *rv;
+	char *s, sbuf[32];
+	size_t n;
+	struct tbl *rv;
 
-	if (!(p = cstrchr(str, '[')))
-		/* Shouldn't happen, but why worry? */
-		strdupx(rv, str, ATEMP);
-	else
-		strndupx(rv, str, p - str, ATEMP);
+	n = strlen(str);
+	if ((p = memchr(str, '[', n)))
+		n = p - str;
+	strnbdupx(s, str, n, ATEMP, sbuf);
+	rv = global(s);
+	if (s != sbuf)
+		afree(s, ATEMP);
 
 	return (rv);
 }
 
 /* set (or overwrite, if reset) the array variable var to the values in vals */
 mksh_uari_t
-set_array(const char *var, bool reset, const char **vals)
+set_array(const char *var, Wahr reset, const char **vals)
 {
 	struct tbl *vp, *vq;
 	mksh_uari_t i = 0, j = 0;
@@ -1641,7 +1728,7 @@ set_array(const char *var, bool reset, c
 	n = strlen(var);
 	if (n > 0 && var[n - 1] == '+') {
 		/* append mode */
-		reset = false;
+		reset = Nee;
 		strndupx(cp, var, n - 1, ATEMP);
 		ccp = cp;
 	}
@@ -1649,7 +1736,8 @@ set_array(const char *var, bool reset, c
 
 	/* Note: AT&T ksh allows set -A but not set +A of a read-only var */
 	if ((vp->flag&RDONLY))
-		errorfx(2, Tf_ro, ccp);
+		kerrf(KWF_ERR(2) | KWF_PREFIX | KWF_FILELINE | KWF_TWOMSG |
+		    KWF_NOERRNO, Tread_only, ccp);
 	/* This code is quite non-optimal */
 	if (reset) {
 		/* trash existing values and attributes */
@@ -1692,7 +1780,7 @@ set_array(const char *var, bool reset, c
 				strndupx(cp, vals[i] + 1, ccp - (vals[i] + 1),
 				    ATEMP);
 				evaluate(substitute(cp, 0), (mksh_ari_t *)&j,
-				    KSH_UNWIND_ERROR, true);
+				    KSH_UNWIND_ERROR, Ja);
 				afree(cp, ATEMP);
 				ccp += 2;
 			} else
@@ -1700,7 +1788,7 @@ set_array(const char *var, bool reset, c
 		}
 #endif
 
-		vq = arraysearch(vp, j);
+		vq = arraysearch(vp, mbiMM(k32, K32_FM, j));
 		/* would be nice to deal with errors here... (see above) */
 		setstr(vq, ccp, KSH_RETURN_ERROR);
 		i++;
@@ -1713,116 +1801,187 @@ set_array(const char *var, bool reset, c
 void
 change_winsz(void)
 {
-	struct timeval tv;
-
-	mksh_TIME(tv);
-	BAFHUpdateMem_mem(qh_state, &tv, sizeof(tv));
-
+	struct {
+		struct timeval tv;
 #ifdef TIOCGWINSZ
-	/* check if window size has changed */
-	if (tty_init_fd() < 2) {
 		struct winsize ws;
+		int tif;
+		int ioc;
+		int eno;
+#endif
+#ifdef SIGWINCH
+		sig_atomic_t gotsig;
+#endif
+	} z;
 
-		if (ioctl(tty_fd, TIOCGWINSZ, &ws) >= 0) {
-			if (ws.ws_col)
-				x_cols = ws.ws_col;
-			if (ws.ws_row)
-				x_lins = ws.ws_row;
+	memset(&z, 0, sizeof(z));
+	mksh_TIME(z.tv);
+#ifdef SIGWINCH
+	z.gotsig = got_winch;
+#endif
+
+#ifdef TIOCGWINSZ
+	if ((z.tif = tty_init_fd()) < 2) {
+		/* check if window size has changed */
+		z.ioc = ioctl(tty_fd, TIOCGWINSZ, &z.ws);
+		z.eno = errno;
+#ifdef SIGWINCH
+		got_winch = 0;
+#endif
+		if (z.ioc >= 0) {
+			if (z.ws.ws_col)
+				x_cols = z.ws.ws_col;
+			if (z.ws.ws_row)
+				x_lins = z.ws.ws_row;
 		}
 	}
+#elif defined(SIGWINCH)
+	got_winch = 0;
 #endif
+	rndpush(&z, sizeof(z));
 
 	/* bounds check for sane values, use defaults otherwise */
 	if (x_cols < MIN_COLS)
 		x_cols = 80;
 	if (x_lins < MIN_LINS)
 		x_lins = 24;
-
-#ifdef SIGWINCH
-	got_winch = 0;
-#endif
 }
 
-uint32_t
+k32
 hash(const void *s)
 {
-	register uint32_t h;
+	register k32 h;
 
 	BAFHInit(h);
-	BAFHUpdateStr_reg(h, s);
-	BAFHFinish_reg(h);
+	BAFHUpdateStr(h, s);
+	BAFHFinish(h);
 	return (h);
 }
 
-uint32_t
+void
 chvt_rndsetup(const void *bp, size_t sz)
 {
-	register uint32_t h;
+	register k32 h;
 
-	/* use LCG as seed but try to get them to deviate immediately */
 	h = lcg_state;
-	(void)rndget();
-	BAFHFinish_reg(h);
+	BAFHUpdateVLQ(h, size_t, sz);
+	BAFHFinish(h);
 	/* variation through pid, ppid, and the works */
-	BAFHUpdateMem_reg(h, &rndsetupstate, sizeof(rndsetupstate));
+	BAFHUpdateMem(h, &rndsetupstate, sizeof(rndsetupstate));
 	/* some variation, some possibly entropy, depending on OE */
-	BAFHUpdateMem_reg(h, bp, sz);
+	BAFHUpdateMem(h, bp, sz);
 	/* mix them all up */
-	BAFHFinish_reg(h);
-
-	return (h);
+	BAFHFinish(h);
+	lcg_state = h;
 }
 
-mksh_ari_t
+k32
 rndget(void)
 {
 	/*
 	 * this is the same Linear Congruential PRNG as Borland
 	 * C/C++ allegedly uses in its built-in rand() function
 	 */
-	return (((lcg_state = 22695477 * lcg_state + 1) >> 16) & 0x7FFF);
+	lcg_state = mbiMO(k32, K32_FM,
+	    mbiMO(k32, K32_FM, 22695477U, *, lcg_state), +, 1U);
+	return (mbiMO(k32, K32_FM,
+	    mbiMKshr(k32, K32_FM, lcg_state, 16), &, 0x7FFFU));
 }
 
+#ifndef KSH_USE_ARC4RANDOM
+#if HAVE_GETRANDOM || defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
+#define KSH_USE_ARC4RANDOM 0
+#elif defined(__OpenBSD__)
+#define KSH_USE_ARC4RANDOM 1
+#else
+#define KSH_USE_ARC4RANDOM 0
+#endif
+#endif
+
 void
 rndset(unsigned long v)
 {
-	register uint32_t h;
+	register k32 h;
 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
-	register uint32_t t;
+	register k32 t;
 #endif
 	struct {
 		struct timeval tv;
 		void *sp;
-		uint32_t qh;
+		k32 qh;
+#if HAVE_GETRANDOM
+		char xby[4];
+#endif
+#if KSH_USE_ARC4RANDOM
+		unsigned int xu32;
+#endif
 		pid_t pp;
-		short r;
+		unsigned short r;
 	} z;
+#if HAVE_GETRANDOM
+#ifdef GRND_INSECURE
+	static unsigned int grnd_iflag = GRND_INSECURE;
+#define grnd_flags (GRND_NONBLOCK | grnd_iflag)
+#else /* !GRND_INSECURE */
+#define grnd_flags GRND_NONBLOCK
+#endif /* !GRND_INSECURE */
+#endif /* HAVE_GETRANDOM */
 
 	/* clear the allocated space, for valgrind and to avoid UB */
 	memset(&z, 0, sizeof(z));
 
-	h = lcg_state;
-	BAFHFinish_reg(h);
-	BAFHUpdateMem_reg(h, &v, sizeof(v));
+	h = lcg_state ? lcg_state : (k32)1U;
+	BAFHFinish(h);
+	BAFHUpdateMem(h, &v, sizeof(v));
 
 	mksh_TIME(z.tv);
-	z.sp = &lcg_state;
+	z.sp = &z;
 	z.pp = procpid;
-	z.r = (short)rndget();
+	z.r = rndget();
+	/* nōn-blocking extra bytes from OS… if cheap and available */
+#if HAVE_GETRANDOM
+ try_getrandom:
+	if (getrandom(z.xby, sizeof(z.xby), grnd_flags) == -1)
+		switch (errno) {
+		case EINVAL:
+#ifdef GRND_INSECURE
+			if (grnd_iflag) {
+				/* try without again, old kernel? */
+				grnd_iflag = 0;
+				goto try_getrandom;
+			}
+#endif
+			/* FALLTHROUGH */
+		default:
+			/* warn for other errors */
+			kwarnf(KWF_WARNING | KWF_PREFIX | KWF_ONEMSG,
+			    "getrandom");
+			/* FALLTHROUGH */
+		case EAGAIN:
+		case ENOSYS:
+			/* ignore */
+			break;
+		case EINTR:
+			/* repeat */
+			goto try_getrandom;
+		}
+	/* otherwise, use whatever we got */
+#endif
+#if KSH_USE_ARC4RANDOM
+	z.xu32 = arc4random();
+#endif
 
 #if defined(arc4random_pushb_fast) || defined(MKSH_A4PB)
-	t = qh_state;
-	BAFHFinish_reg(t);
-	z.qh = (t & 0xFFFF8000) | rndget();
-	lcg_state = (t << 15) | rndget();
+	z.qh = (qh_state & 0xFFFF8000U) | rndget();
+	lcg_state = mbiMKshl(k32, K32_FM, qh_state, 15) | rndget();
 	/*
 	 * either we have very chap entropy get and push available,
 	 * with malloc() pulling in this code already anyway, or the
 	 * user requested us to use the old functions
 	 */
 	t = h;
-	BAFHUpdateMem_reg(t, &lcg_state, sizeof(lcg_state));
-	BAFHFinish_reg(t);
+	BAFHUpdateMem(t, &lcg_state, sizeof(lcg_state));
+	BAFHFinish(t);
 	lcg_state = t;
 #if defined(arc4random_pushb_fast)
 	arc4random_pushb_fast(&lcg_state, sizeof(lcg_state));
@@ -1830,23 +1989,23 @@ rndset(unsigned long v)
 #else
 	lcg_state = arc4random_pushb(&lcg_state, sizeof(lcg_state));
 #endif
-	BAFHUpdateMem_reg(h, &lcg_state, sizeof(lcg_state));
+	BAFHUpdateMem(h, &lcg_state, sizeof(lcg_state));
 #else
 	z.qh = qh_state;
 #endif
 
-	BAFHUpdateMem_reg(h, &z, sizeof(z));
-	BAFHFinish_reg(h);
+	BAFHUpdateMem(h, &z, sizeof(z));
+	BAFHFinish(h);
 	lcg_state = h;
 }
 
 void
-rndpush(const void *s)
+rndpush(const void *s, size_t n)
 {
-	register uint32_t h = qh_state;
+	register k32 h = qh_state ? qh_state : (k32)1U;
 
-	BAFHUpdateStr_reg(h, s);
-	BAFHUpdateOctet_reg(h, 0);
+	BAFHUpdateMem(h, s, n);
+	BAFHFinish(h);
 	qh_state = h;
 }
 
@@ -1856,7 +2015,7 @@ record_match(const char *istr)
 {
 	struct tbl *vp;
 
-	vp = local("KSH_MATCH", false);
+	vp = local("KSH_MATCH", Nee);
 	unset(vp, 1);
 	vp->flag = DEFINED | RDONLY;
 	setstr(vp, istr, 0x4);
@@ -1867,12 +2026,12 @@ int
 c_typeset(const char **wp)
 {
 	struct tbl *vp, **p;
-	uint32_t fset = 0, fclr = 0, flag;
+	kui fset = 0, fclr = 0, flag;
 	int thing = 0, field = 0, base = 0, i;
 	struct block *l;
 	const char *opts;
 	const char *fieldstr = NULL, *basestr = NULL;
-	bool localv = false, func = false, pflag = false, istset = true;
+	Wahr localv = Nee, func = Nee, pflag = Nee, istset = Ja;
 	enum namerefflag new_refflag = SRF_NOP;
 
 	switch (**wp) {
@@ -1880,13 +2039,13 @@ c_typeset(const char **wp)
 	/* export */
 	case 'e':
 		fset |= EXPORT;
-		istset = false;
+		istset = Nee;
 		break;
 
 	/* readonly */
 	case 'r':
 		fset |= RDONLY;
-		istset = false;
+		istset = Nee;
 		break;
 
 	/* set */
@@ -1896,7 +2055,7 @@ c_typeset(const char **wp)
 
 	/* typeset */
 	case 't':
-		localv = true;
+		localv = Ja;
 		break;
 	}
 
@@ -1944,10 +2103,10 @@ c_typeset(const char **wp)
 			 */
 			break;
 		case 'f':
-			func = true;
+			func = Ja;
 			break;
 		case 'g':
-			localv = (builtin_opt.info & GI_PLUS) ? true : false;
+			localv = isWahr(builtin_opt.info & GI_PLUS);
 			break;
 		case 'i':
 			flag = INTEGER;
@@ -1963,7 +2122,7 @@ c_typeset(const char **wp)
 		/* export, readonly: POSIX -p flag */
 		case 'p':
 			/* typeset: show values as well */
-			pflag = true;
+			pflag = Ja;
 			if (istset)
 				continue;
 			break;
@@ -1995,12 +2154,13 @@ c_typeset(const char **wp)
 	}
 
 	if (fieldstr && !getn(fieldstr, &field)) {
-		bi_errorf(Tf_sD_s, Tbadnum, fieldstr);
+		kwarnf(KWF_BIERR | KWF_TWOMSG, Tbadnum, fieldstr);
 		return (1);
 	}
 	if (basestr) {
 		if (!getn(basestr, &base)) {
-			bi_errorf(Tf_sD_s, "bad integer base", basestr);
+			kwarnf(KWF_BIERR | KWF_TWOMSG,
+			    "bad integer base", basestr);
 			return (1);
 		}
 		if (base < 1 || base > 36)
@@ -2017,7 +2177,8 @@ c_typeset(const char **wp)
 
 	if (func && (((fset|fclr) & ~(TRACE|UCASEV_AL|EXPORT)) ||
 	    new_refflag != SRF_NOP)) {
-		bi_errorf("only -t, -u and -x options may be used with -f");
+		kwarnf(KWF_BIERR | KWF_ONEMSG | KWF_NOERRNO,
+		    "only -t, -u and -x options may be used with -f");
 		return (1);
 	}
 	if (wp[builtin_opt.optind]) {
@@ -2067,7 +2228,7 @@ c_typeset(const char **wp)
 		for (i = builtin_opt.optind; wp[i]; i++) {
 			if (func) {
 				f = findfunc(wp[i], hash(wp[i]),
-				    tobool(fset & UCASEV_AL));
+				    isWahr(fset & UCASEV_AL));
 				if (!f) {
 					/* AT&T ksh does ++rv: bogus */
 					rv = 1;
@@ -2078,7 +2239,7 @@ c_typeset(const char **wp)
 					f->flag &= ~fclr;
 				} else {
 					fpFUNCTf(shl_stdout, 0,
-					    tobool(f->flag & FKSH),
+					    isWahr(f->flag & FKSH),
 					    wp[i], f->val.t);
 					shf_putc('\n', shl_stdout);
 				}
@@ -2086,7 +2247,8 @@ c_typeset(const char **wp)
 			    field, base)) {
 				if (x)
 					return (x);
-				bi_errorf(Tf_sD_s, wp[i], Tnot_ident);
+				kwarnf(KWF_BIERR | KWF_TWOMSG | KWF_NOERRNO,
+				    wp[i], Tnot_ident);
 				return (1);
 			}
 		}
@@ -2104,7 +2266,7 @@ c_typeset(const char **wp)
 					continue;
 				if (thing == '-')
 					fpFUNCTf(shl_stdout, 0,
-					    tobool(vp->flag & FKSH),
+					    isWahr(vp->flag & FKSH),
 					    vp->name, vp->val.t);
 				else
 					shf_puts(vp->name, shl_stdout);
@@ -2113,7 +2275,7 @@ c_typeset(const char **wp)
 		}
 	} else if (wp[builtin_opt.optind]) {
 		for (i = builtin_opt.optind; wp[i]; i++) {
-			vp = isglobal(wp[i], false);
+			vp = isglobal(wp[i], Nee);
 			c_typeset_vardump(vp, flag, thing,
 			    last_lookup_was_array ? 4 : 0, pflag, istset);
 		}
@@ -2123,8 +2285,8 @@ c_typeset(const char **wp)
 }
 
 static void
-c_typeset_vardump_recursive(struct block *l, uint32_t flag, int thing,
-    bool pflag, bool istset)
+c_typeset_vardump_recursive(struct block *l, kui flag, int thing,
+    Wahr pflag, Wahr istset)
 {
 	struct tbl **blockvars, *vp;
 
@@ -2137,11 +2299,10 @@ c_typeset_vardump_recursive(struct block
 }
 
 static void
-c_typeset_vardump(struct tbl *vp, uint32_t flag, int thing, int any_set,
-    bool pflag, bool istset)
+c_typeset_vardump(struct tbl *vp, kui flag, int thing, int any_set,
+    Wahr pflag, Wahr istset)
 {
 	struct tbl *tvp;
-	char *s;
 
 	if (!vp)
 		return;
@@ -2173,6 +2334,8 @@ c_typeset_vardump(struct tbl *vp, uint32
 		/* optimise later conditionals */
 		any_set = 0;
 	do {
+		Wahr baseone = Nee;
+
 		/*
 		 * Ignore array elements that aren't set unless there
 		 * are no set elements, in which case the first is
@@ -2191,11 +2354,16 @@ c_typeset_vardump(struct tbl *vp, uint32
 			 * leftadj, zerofill, etc., but POSIX says must
 			 * be suitable for re-entry...
 			 */
-			shprintf(Tf_s_s, Ttypeset, "");
+			shprintf(Tf_s_, Ttypeset);
 			if (((vp->flag & (ARRAY | ASSOC)) == ASSOC))
 				shprintf(Tf__c_, 'n');
-			if ((vp->flag & INTEGER))
-				shprintf(Tf__c_, 'i');
+			if ((vp->flag & INTEGER)) {
+				if (vp->type == 1) {
+					baseone = Ja;
+					shf_puts("-i1 ", shl_stdout);
+				} else
+					shprintf(Tf__c_, 'i');
+			}
 			if ((vp->flag & EXPORT))
 				shprintf(Tf__c_, 'x');
 			if ((vp->flag & RDONLY))
@@ -2215,22 +2383,28 @@ c_typeset_vardump(struct tbl *vp, uint32
 			if ((vp->flag & INT_U))
 				shprintf(Tf__c_, 'U');
 		} else if (pflag) {
-			shprintf(Tf_s_s, istset ? Ttypeset :
-			    (flag & EXPORT) ? Texport : Treadonly, "");
+			shprintf(Tf_s_, istset ? Ttypeset :
+			    (flag & EXPORT) ? Texport : Treadonly);
 		}
+		shf_puts(vp->name, shl_stdout);
 		if (any_set)
-			shprintf("%s[%lu]", vp->name, arrayindex(vp));
-		else
-			shf_puts(vp->name, shl_stdout);
-		if ((!thing && !flag && pflag) ||
-		    (thing == '-' && (vp->flag & ISSET))) {
-			s = str_val(vp);
+			shprintf(Tf_SQlu, arrayindex(vp));
+		if (((!thing && !flag && pflag) || thing == '-') &&
+		    (vp->flag & ISSET)) {
 			shf_putc('=', shl_stdout);
-			/* AT&T ksh can't have justified integers... */
-			if ((vp->flag & (INTEGER | LJUST | RJUST)) == INTEGER)
-				shf_puts(s, shl_stdout);
-			else
-				print_value_quoted(shl_stdout, s);
+			if (baseone)
+				shprintf(vp->val.u > 0xFF ? "16#%04X" :
+				    "16#%02X", (unsigned int)vp->val.u);
+			else {
+				const char *s = str_val(vp);
+
+				/* AT&T ksh can't have justified integers... */
+				if (IS(vp->flag, INTEGER | LJUST | RJUST,
+				    INTEGER))
+					shf_puts(s, shl_stdout);
+				else
+					print_value_quoted(shl_stdout, s);
+			}
 		}
 		shf_putc('\n', shl_stdout);
 
