commit 68d834030e84af7453405f5c51f2905abb24e1bc
parent b4204c783b8e03cfab757dd2757248a4519fd276
Author: xplshn <anto@xplshn.com.ar>
Date: Tue, 9 Jun 2026 01:23:20 -0300
Feature gating and warning fixes
Signed-off-by: xplshn <anto@xplshn.com.ar>
Diffstat:
136 files changed, 33764 insertions(+), 262 deletions(-)
diff --git a/Makefile b/Makefile
@@ -97,11 +97,12 @@ LIBUTILOBJ =\
shared/libutil/proc.o\
shared/libutil/tty.o\
shared/libutil/fconcat.o\
- shared/libutil/recurse_dir.o
+ shared/libutil/recurse_dir.o\
+ shared/libutil/sig.o
LIB = shared/libutf/libutf.a shared/libutil/libutil.a
-POSIX_BIN =\
+POSIX_BIN_ALL =\
cmd/posix/basename\
cmd/posix/cal\
cmd/posix/cat\
@@ -175,9 +176,12 @@ POSIX_BIN =\
cmd/posix/uuencode\
cmd/posix/wc\
cmd/posix/who\
- cmd/posix/xargs
+ cmd/posix/xargs\
+ cmd/posix/awk/awk\
+ cmd/posix/sh/sh\
+ cmd/posix/pax
-LINUX_BIN =\
+LINUX_BIN_ALL =\
cmd/linux/blkdiscard\
cmd/linux/chvt\
cmd/linux/ctrlaltdel\
@@ -207,7 +211,7 @@ LINUX_BIN =\
cmd/linux/uptime\
cmd/linux/vtallow
-NET_BIN =\
+NET_BIN_ALL =\
cmd/net/netcat\
cmd/net/tftp\
cmd/net/tunctl\
@@ -217,12 +221,12 @@ NET_BIN =\
cmd/net/host\
cmd/net/httpd
-XSI_BIN =\
+XSI_BIN_ALL =\
cmd/xsi/mknod\
cmd/xsi/passwd\
cmd/xsi/su
-PSEUDO_BIN =\
+PSEUDO_BIN_ALL =\
cmd/pseudo/chroot\
cmd/pseudo/clear\
cmd/pseudo/cols\
@@ -259,7 +263,8 @@ PSEUDO_BIN =\
cmd/pseudo/which\
cmd/pseudo/whoami\
cmd/pseudo/xinstall\
- cmd/pseudo/yes
+ cmd/pseudo/yes\
+ cmd/pseudo/base64
MAKEOBJ =\
cmd/posix/make/defaults.o\
@@ -268,13 +273,340 @@ MAKEOBJ =\
cmd/posix/make/posix.o\
cmd/posix/make/rules.o
+BIN_basename_1 = cmd/posix/basename
+BIN_cal_1 = cmd/posix/cal
+BIN_cat_1 = cmd/posix/cat
+BIN_chgrp_1 = cmd/posix/chgrp
+BIN_chmod_1 = cmd/posix/chmod
+BIN_chown_1 = cmd/posix/chown
+BIN_cksum_1 = cmd/posix/cksum
+BIN_cmp_1 = cmd/posix/cmp
+BIN_comm_1 = cmd/posix/comm
+BIN_cp_1 = cmd/posix/cp
+BIN_cut_1 = cmd/posix/cut
+BIN_date_1 = cmd/posix/date
+BIN_dd_1 = cmd/posix/dd
+BIN_df_1 = cmd/posix/df
+BIN_dirname_1 = cmd/posix/dirname
+BIN_du_1 = cmd/posix/du
+BIN_echo_1 = cmd/posix/echo
+BIN_ed_1 = cmd/posix/ed
+BIN_env_1 = cmd/posix/env
+BIN_expand_1 = cmd/posix/expand
+BIN_expr_1 = cmd/posix/expr
+BIN_false_1 = cmd/posix/false
+BIN_find_1 = cmd/posix/find
+BIN_fold_1 = cmd/posix/fold
+BIN_getconf_1 = cmd/posix/getconf
+BIN_grep_1 = cmd/posix/grep
+BIN_head_1 = cmd/posix/head
+BIN_id_1 = cmd/posix/id
+BIN_join_1 = cmd/posix/join
+BIN_kill_1 = cmd/posix/kill
+BIN_link_1 = cmd/posix/link
+BIN_ln_1 = cmd/posix/ln
+BIN_logger_1 = cmd/posix/logger
+BIN_logname_1 = cmd/posix/logname
+BIN_ls_1 = cmd/posix/ls
+BIN_mesg_1 = cmd/posix/mesg
+BIN_mkdir_1 = cmd/posix/mkdir
+BIN_mkfifo_1 = cmd/posix/mkfifo
+BIN_mv_1 = cmd/posix/mv
+BIN_nice_1 = cmd/posix/nice
+BIN_nl_1 = cmd/posix/nl
+BIN_nohup_1 = cmd/posix/nohup
+BIN_od_1 = cmd/posix/od
+BIN_paste_1 = cmd/posix/paste
+BIN_pathchk_1 = cmd/posix/pathchk
+BIN_printf_1 = cmd/posix/printf
+BIN_ps_1 = cmd/posix/ps
+BIN_pwd_1 = cmd/posix/pwd
+BIN_readlink_1 = cmd/posix/readlink
+BIN_renice_1 = cmd/posix/renice
+BIN_rm_1 = cmd/posix/rm
+BIN_rmdir_1 = cmd/posix/rmdir
+BIN_sed_1 = cmd/posix/sed
+BIN_sleep_1 = cmd/posix/sleep
+BIN_sort_1 = cmd/posix/sort
+BIN_split_1 = cmd/posix/split
+BIN_tail_1 = cmd/posix/tail
+BIN_tee_1 = cmd/posix/tee
+BIN_test_1 = cmd/posix/test
+BIN_time_1 = cmd/posix/time
+BIN_touch_1 = cmd/posix/touch
+BIN_tr_1 = cmd/posix/tr
+BIN_true_1 = cmd/posix/true
+BIN_tsort_1 = cmd/posix/tsort
+BIN_tty_1 = cmd/posix/tty
+BIN_uname_1 = cmd/posix/uname
+BIN_unexpand_1 = cmd/posix/unexpand
+BIN_uniq_1 = cmd/posix/uniq
+BIN_unlink_1 = cmd/posix/unlink
+BIN_uudecode_1 = cmd/posix/uudecode
+BIN_uuencode_1 = cmd/posix/uuencode
+BIN_wc_1 = cmd/posix/wc
+BIN_who_1 = cmd/posix/who
+BIN_xargs_1 = cmd/posix/xargs
+BIN_awk_1 = cmd/posix/awk/awk
+BIN_sh_1 = cmd/posix/sh/sh
+BIN_pax_1 = cmd/posix/pax
+
+BIN_blkdiscard_1 = cmd/linux/blkdiscard
+BIN_chvt_1 = cmd/linux/chvt
+BIN_ctrlaltdel_1 = cmd/linux/ctrlaltdel
+BIN_dmesg_1 = cmd/linux/dmesg
+BIN_eject_1 = cmd/linux/eject
+BIN_fallocate_1 = cmd/linux/fallocate
+BIN_free_1 = cmd/linux/free
+BIN_freeramdisk_1 = cmd/linux/freeramdisk
+BIN_fsfreeze_1 = cmd/linux/fsfreeze
+BIN_hwclock_1 = cmd/linux/hwclock
+BIN_insmod_1 = cmd/linux/insmod
+BIN_lsmod_1 = cmd/linux/lsmod
+BIN_mkswap_1 = cmd/linux/mkswap
+BIN_mount_1 = cmd/linux/mount
+BIN_mountpoint_1 = cmd/linux/mountpoint
+BIN_pidof_1 = cmd/linux/pidof
+BIN_pivot_root_1 = cmd/linux/pivot_root
+BIN_pwdx_1 = cmd/linux/pwdx
+BIN_readahead_1 = cmd/linux/readahead
+BIN_rmmod_1 = cmd/linux/rmmod
+BIN_swaplabel_1 = cmd/linux/swaplabel
+BIN_swapoff_1 = cmd/linux/swapoff
+BIN_swapon_1 = cmd/linux/swapon
+BIN_switch_root_1 = cmd/linux/switch_root
+BIN_umount_1 = cmd/linux/umount
+BIN_unshare_1 = cmd/linux/unshare
+BIN_uptime_1 = cmd/linux/uptime
+BIN_vtallow_1 = cmd/linux/vtallow
+
+BIN_netcat_1 = cmd/net/netcat
+BIN_tftp_1 = cmd/net/tftp
+BIN_tunctl_1 = cmd/net/tunctl
+BIN_wget_1 = cmd/net/wget
+BIN_ping_1 = cmd/net/ping
+BIN_ifconfig_1 = cmd/net/ifconfig
+BIN_host_1 = cmd/net/host
+BIN_httpd_1 = cmd/net/httpd
+
+BIN_mknod_1 = cmd/xsi/mknod
+BIN_passwd_1 = cmd/xsi/passwd
+BIN_su_1 = cmd/xsi/su
+
+BIN_chroot_1 = cmd/pseudo/chroot
+BIN_clear_1 = cmd/pseudo/clear
+BIN_cols_1 = cmd/pseudo/cols
+BIN_cron_1 = cmd/pseudo/cron
+BIN_flock_1 = cmd/pseudo/flock
+BIN_getty_1 = cmd/pseudo/getty
+BIN_halt_1 = cmd/pseudo/halt
+BIN_hostname_1 = cmd/pseudo/hostname
+BIN_killall5_1 = cmd/pseudo/killall5
+BIN_last_1 = cmd/pseudo/last
+BIN_lastlog_1 = cmd/pseudo/lastlog
+BIN_login_1 = cmd/pseudo/login
+BIN_md5sum_1 = cmd/pseudo/md5sum
+BIN_mktemp_1 = cmd/pseudo/mktemp
+BIN_nologin_1 = cmd/pseudo/nologin
+BIN_pagesize_1 = cmd/pseudo/pagesize
+BIN_printenv_1 = cmd/pseudo/printenv
+BIN_respawn_1 = cmd/pseudo/respawn
+BIN_rev_1 = cmd/pseudo/rev
+BIN_seq_1 = cmd/pseudo/seq
+BIN_setsid_1 = cmd/pseudo/setsid
+BIN_sha1sum_1 = cmd/pseudo/sha1sum
+BIN_sha224sum_1 = cmd/pseudo/sha224sum
+BIN_sha256sum_1 = cmd/pseudo/sha256sum
+BIN_sha384sum_1 = cmd/pseudo/sha384sum
+BIN_sha512sum_1 = cmd/pseudo/sha512sum
+BIN_sha512_224sum_1 = cmd/pseudo/sha512-224sum
+BIN_sha512_256sum_1 = cmd/pseudo/sha512-256sum
+BIN_sponge_1 = cmd/pseudo/sponge
+BIN_stat_1 = cmd/pseudo/stat
+BIN_tar_1 = cmd/pseudo/tar
+BIN_truncate_1 = cmd/pseudo/truncate
+BIN_watch_1 = cmd/pseudo/watch
+BIN_which_1 = cmd/pseudo/which
+BIN_whoami_1 = cmd/pseudo/whoami
+BIN_xinstall_1 = cmd/pseudo/xinstall
+BIN_yes_1 = cmd/pseudo/yes
+BIN_base64_1 = cmd/pseudo/base64
+
+BIN_make_tool_1 = cmd/posix/make/make
+
+POSIX_BIN = \
+ $(BIN_basename_$(BUILD_POSIX_BASENAME)) \
+ $(BIN_cal_$(BUILD_POSIX_CAL)) \
+ $(BIN_cat_$(BUILD_POSIX_CAT)) \
+ $(BIN_chgrp_$(BUILD_POSIX_CHGRP)) \
+ $(BIN_chmod_$(BUILD_POSIX_CHMOD)) \
+ $(BIN_chown_$(BUILD_POSIX_CHOWN)) \
+ $(BIN_cksum_$(BUILD_POSIX_CKSUM)) \
+ $(BIN_cmp_$(BUILD_POSIX_CMP)) \
+ $(BIN_comm_$(BUILD_POSIX_COMM)) \
+ $(BIN_cp_$(BUILD_POSIX_CP)) \
+ $(BIN_cut_$(BUILD_POSIX_CUT)) \
+ $(BIN_date_$(BUILD_POSIX_DATE)) \
+ $(BIN_dd_$(BUILD_POSIX_DD)) \
+ $(BIN_df_$(BUILD_POSIX_DF)) \
+ $(BIN_dirname_$(BUILD_POSIX_DIRNAME)) \
+ $(BIN_du_$(BUILD_POSIX_DU)) \
+ $(BIN_echo_$(BUILD_POSIX_ECHO)) \
+ $(BIN_ed_$(BUILD_POSIX_ED)) \
+ $(BIN_env_$(BUILD_POSIX_ENV)) \
+ $(BIN_expand_$(BUILD_POSIX_EXPAND)) \
+ $(BIN_expr_$(BUILD_POSIX_EXPR)) \
+ $(BIN_false_$(BUILD_POSIX_FALSE)) \
+ $(BIN_find_$(BUILD_POSIX_FIND)) \
+ $(BIN_fold_$(BUILD_POSIX_FOLD)) \
+ $(BIN_getconf_$(BUILD_POSIX_GETCONF)) \
+ $(BIN_grep_$(BUILD_POSIX_GREP)) \
+ $(BIN_head_$(BUILD_POSIX_HEAD)) \
+ $(BIN_id_$(BUILD_POSIX_ID)) \
+ $(BIN_join_$(BUILD_POSIX_JOIN)) \
+ $(BIN_kill_$(BUILD_POSIX_KILL)) \
+ $(BIN_link_$(BUILD_POSIX_LINK)) \
+ $(BIN_ln_$(BUILD_POSIX_LN)) \
+ $(BIN_logger_$(BUILD_POSIX_LOGGER)) \
+ $(BIN_logname_$(BUILD_POSIX_LOGNAME)) \
+ $(BIN_ls_$(BUILD_POSIX_LS)) \
+ $(BIN_mesg_$(BUILD_POSIX_MESG)) \
+ $(BIN_mkdir_$(BUILD_POSIX_MKDIR)) \
+ $(BIN_mkfifo_$(BUILD_POSIX_MKFIFO)) \
+ $(BIN_mv_$(BUILD_POSIX_MV)) \
+ $(BIN_nice_$(BUILD_POSIX_NICE)) \
+ $(BIN_nl_$(BUILD_POSIX_NL)) \
+ $(BIN_nohup_$(BUILD_POSIX_NOHUP)) \
+ $(BIN_od_$(BUILD_POSIX_OD)) \
+ $(BIN_paste_$(BUILD_POSIX_PASTE)) \
+ $(BIN_pathchk_$(BUILD_POSIX_PATHCHK)) \
+ $(BIN_printf_$(BUILD_POSIX_PRINTF)) \
+ $(BIN_ps_$(BUILD_POSIX_PS)) \
+ $(BIN_pwd_$(BUILD_POSIX_PWD)) \
+ $(BIN_readlink_$(BUILD_POSIX_READLINK)) \
+ $(BIN_renice_$(BUILD_POSIX_RENICE)) \
+ $(BIN_rm_$(BUILD_POSIX_RM)) \
+ $(BIN_rmdir_$(BUILD_POSIX_RMDIR)) \
+ $(BIN_sed_$(BUILD_POSIX_SED)) \
+ $(BIN_sleep_$(BUILD_POSIX_SLEEP)) \
+ $(BIN_sort_$(BUILD_POSIX_SORT)) \
+ $(BIN_split_$(BUILD_POSIX_SPLIT)) \
+ $(BIN_tail_$(BUILD_POSIX_TAIL)) \
+ $(BIN_tee_$(BUILD_POSIX_TEE)) \
+ $(BIN_test_$(BUILD_POSIX_TEST)) \
+ $(BIN_time_$(BUILD_POSIX_TIME)) \
+ $(BIN_touch_$(BUILD_POSIX_TOUCH)) \
+ $(BIN_tr_$(BUILD_POSIX_TR)) \
+ $(BIN_true_$(BUILD_POSIX_TRUE)) \
+ $(BIN_tsort_$(BUILD_POSIX_TSORT)) \
+ $(BIN_tty_$(BUILD_POSIX_TTY)) \
+ $(BIN_uname_$(BUILD_POSIX_UNAME)) \
+ $(BIN_unexpand_$(BUILD_POSIX_UNEXPAND)) \
+ $(BIN_uniq_$(BUILD_POSIX_UNIQ)) \
+ $(BIN_unlink_$(BUILD_POSIX_UNLINK)) \
+ $(BIN_uudecode_$(BUILD_POSIX_UUDECODE)) \
+ $(BIN_uuencode_$(BUILD_POSIX_UUENCODE)) \
+ $(BIN_wc_$(BUILD_POSIX_WC)) \
+ $(BIN_who_$(BUILD_POSIX_WHO)) \
+ $(BIN_xargs_$(BUILD_POSIX_XARGS)) \
+ $(BIN_awk_$(BUILD_POSIX_AWK)) \
+ $(BIN_sh_$(BUILD_POSIX_SH)) \
+ $(BIN_pax_$(BUILD_POSIX_PAX))
+
+LINUX_BIN = \
+ $(BIN_blkdiscard_$(BUILD_LINUX_BLKDISCARD)) \
+ $(BIN_chvt_$(BUILD_LINUX_CHVT)) \
+ $(BIN_ctrlaltdel_$(BUILD_LINUX_CTRLALTDEL)) \
+ $(BIN_dmesg_$(BUILD_LINUX_DMESG)) \
+ $(BIN_eject_$(BUILD_LINUX_EJECT)) \
+ $(BIN_fallocate_$(BUILD_LINUX_FALLOCATE)) \
+ $(BIN_free_$(BUILD_LINUX_FREE)) \
+ $(BIN_freeramdisk_$(BUILD_LINUX_FREERAMDISK)) \
+ $(BIN_fsfreeze_$(BUILD_LINUX_FSFREEZE)) \
+ $(BIN_hwclock_$(BUILD_LINUX_HWCLOCK)) \
+ $(BIN_insmod_$(BUILD_LINUX_INSMOD)) \
+ $(BIN_lsmod_$(BUILD_LINUX_LSMOD)) \
+ $(BIN_mkswap_$(BUILD_LINUX_MKSWAP)) \
+ $(BIN_mount_$(BUILD_LINUX_MOUNT)) \
+ $(BIN_mountpoint_$(BUILD_LINUX_MOUNTPOINT)) \
+ $(BIN_pidof_$(BUILD_LINUX_PIDOF)) \
+ $(BIN_pivot_root_$(BUILD_LINUX_PIVOT_ROOT)) \
+ $(BIN_pwdx_$(BUILD_LINUX_PWDX)) \
+ $(BIN_readahead_$(BUILD_LINUX_READAHEAD)) \
+ $(BIN_rmmod_$(BUILD_LINUX_RMMOD)) \
+ $(BIN_swaplabel_$(BUILD_LINUX_SWAPLABEL)) \
+ $(BIN_swapoff_$(BUILD_LINUX_SWAPOFF)) \
+ $(BIN_swapon_$(BUILD_LINUX_SWAPON)) \
+ $(BIN_switch_root_$(BUILD_LINUX_SWITCH_ROOT)) \
+ $(BIN_umount_$(BUILD_LINUX_UMOUNT)) \
+ $(BIN_unshare_$(BUILD_LINUX_UNSHARE)) \
+ $(BIN_uptime_$(BUILD_LINUX_UPTIME)) \
+ $(BIN_vtallow_$(BUILD_LINUX_VTALLOW))
+
+NET_BIN = \
+ $(BIN_netcat_$(BUILD_NET_NETCAT)) \
+ $(BIN_tftp_$(BUILD_NET_TFTP)) \
+ $(BIN_tunctl_$(BUILD_NET_TUNCTL)) \
+ $(BIN_wget_$(BUILD_NET_WGET)) \
+ $(BIN_ping_$(BUILD_NET_PING)) \
+ $(BIN_ifconfig_$(BUILD_NET_IFCONFIG)) \
+ $(BIN_host_$(BUILD_NET_HOST)) \
+ $(BIN_httpd_$(BUILD_NET_HTTPD))
+
+XSI_BIN = \
+ $(BIN_mknod_$(BUILD_XSI_MKNOD)) \
+ $(BIN_passwd_$(BUILD_XSI_PASSWD)) \
+ $(BIN_su_$(BUILD_XSI_SU))
+
+PSEUDO_BIN = \
+ $(BIN_chroot_$(BUILD_PSEUDO_CHROOT)) \
+ $(BIN_clear_$(BUILD_PSEUDO_CLEAR)) \
+ $(BIN_cols_$(BUILD_PSEUDO_COLS)) \
+ $(BIN_cron_$(BUILD_PSEUDO_CRON)) \
+ $(BIN_flock_$(BUILD_PSEUDO_FLOCK)) \
+ $(BIN_getty_$(BUILD_PSEUDO_GETTY)) \
+ $(BIN_halt_$(BUILD_PSEUDO_HALT)) \
+ $(BIN_hostname_$(BUILD_PSEUDO_HOSTNAME)) \
+ $(BIN_killall5_$(BUILD_PSEUDO_KILLALL5)) \
+ $(BIN_last_$(BUILD_PSEUDO_LAST)) \
+ $(BIN_lastlog_$(BUILD_PSEUDO_LASTLOG)) \
+ $(BIN_login_$(BUILD_PSEUDO_LOGIN)) \
+ $(BIN_md5sum_$(BUILD_PSEUDO_MD5SUM)) \
+ $(BIN_mktemp_$(BUILD_PSEUDO_MKTEMP)) \
+ $(BIN_nologin_$(BUILD_PSEUDO_NOLOGIN)) \
+ $(BIN_pagesize_$(BUILD_PSEUDO_PAGESIZE)) \
+ $(BIN_printenv_$(BUILD_PSEUDO_PRINTENV)) \
+ $(BIN_respawn_$(BUILD_PSEUDO_RESPAWN)) \
+ $(BIN_rev_$(BUILD_PSEUDO_REV)) \
+ $(BIN_seq_$(BUILD_PSEUDO_SEQ)) \
+ $(BIN_setsid_$(BUILD_PSEUDO_SETSID)) \
+ $(BIN_sha1sum_$(BUILD_PSEUDO_SHA1SUM)) \
+ $(BIN_sha224sum_$(BUILD_PSEUDO_SHA224SUM)) \
+ $(BIN_sha256sum_$(BUILD_PSEUDO_SHA256SUM)) \
+ $(BIN_sha384sum_$(BUILD_PSEUDO_SHA384SUM)) \
+ $(BIN_sha512sum_$(BUILD_PSEUDO_SHA512SUM)) \
+ $(BIN_sha512_224sum_$(BUILD_PSEUDO_SHA512_224SUM)) \
+ $(BIN_sha512_256sum_$(BUILD_PSEUDO_SHA512_256SUM)) \
+ $(BIN_sponge_$(BUILD_PSEUDO_SPONGE)) \
+ $(BIN_stat_$(BUILD_PSEUDO_STAT)) \
+ $(BIN_tar_$(BUILD_PSEUDO_TAR)) \
+ $(BIN_truncate_$(BUILD_PSEUDO_TRUNCATE)) \
+ $(BIN_watch_$(BUILD_PSEUDO_WATCH)) \
+ $(BIN_which_$(BUILD_PSEUDO_WHICH)) \
+ $(BIN_whoami_$(BUILD_PSEUDO_WHOAMI)) \
+ $(BIN_xinstall_$(BUILD_PSEUDO_XINSTALL)) \
+ $(BIN_yes_$(BUILD_PSEUDO_YES)) \
+ $(BIN_base64_$(BUILD_PSEUDO_BASE64))
+
+MAKE_BIN = $(BIN_make_tool_$(BUILD_MAKE_MAKE))
+
OBJ = $(LIBUTFOBJ) $(LIBUTILOBJ) $(MAKEOBJ)
-all: $(LIB) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN) cmd/posix/make/make
+all: $(LIB) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN) $(MAKE_BIN)
-$(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN): $(LIB)
+$(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL): $(LIB)
-$(OBJ) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN): $(HDR)
+$(OBJ) $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL): $(HDR)
.o:
$(CC) $(LDFLAGS) -o $@ $< $(LIB) $(LDLIBS)
@@ -315,7 +647,106 @@ box: $(LIB)
scripts/mkbox
clean:
- rm -f shared/libutf/*.o shared/libutil/*.o cmd/posix/make/*.o
- rm -f $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN) $(LIB)
+ rm -f shared/libutf/*.o shared/libutil/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o
+ rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) $(LIB)
rm -f cmd/posix/make/make cmd/posix/getconf.h cmd/posix/bc.c
+ rm -f cmd/posix/awk/awk cmd/posix/awk/maketab cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c
+ rm -f cmd/posix/sh/sh cmd/posix/sh/mknodes cmd/posix/sh/mksyntax
+ rm -f cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h cmd/posix/sh/token.h
rm -rf aruu-box .box
+
+AWKOBJ =\
+ cmd/posix/awk/b.o\
+ cmd/posix/awk/main.o\
+ cmd/posix/awk/parse.o\
+ cmd/posix/awk/proctab.o\
+ cmd/posix/awk/tran.o\
+ cmd/posix/awk/lib.o\
+ cmd/posix/awk/run.o\
+ cmd/posix/awk/lex.o\
+ cmd/posix/awk/math.o\
+ cmd/posix/awk/awkgram.tab.o
+
+SH_GENHDRS =\
+ cmd/posix/sh/syntax.h\
+ cmd/posix/sh/nodes.h\
+ cmd/posix/sh/builtins.h\
+ cmd/posix/sh/token.h
+
+SHOBJ =\
+ cmd/posix/sh/alias.o\
+ cmd/posix/sh/arith_yacc.o\
+ cmd/posix/sh/arith_yylex.o\
+ cmd/posix/sh/cd.o\
+ cmd/posix/sh/echo.o\
+ cmd/posix/sh/error.o\
+ cmd/posix/sh/eval.o\
+ cmd/posix/sh/exec.o\
+ cmd/posix/sh/expand.o\
+ cmd/posix/sh/histedit.o\
+ cmd/posix/sh/input.o\
+ cmd/posix/sh/jobs.o\
+ cmd/posix/sh/kill.o\
+ cmd/posix/sh/mail.o\
+ cmd/posix/sh/main.o\
+ cmd/posix/sh/memalloc.o\
+ cmd/posix/sh/miscbltin.o\
+ cmd/posix/sh/mystring.o\
+ cmd/posix/sh/options.o\
+ cmd/posix/sh/output.o\
+ cmd/posix/sh/parser.o\
+ cmd/posix/sh/printf.o\
+ cmd/posix/sh/redir.o\
+ cmd/posix/sh/show.o\
+ cmd/posix/sh/test.o\
+ cmd/posix/sh/trap.o\
+ cmd/posix/sh/var.o\
+ cmd/posix/sh/builtins.o\
+ cmd/posix/sh/nodes.o\
+ cmd/posix/sh/syntax.o
+
+cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h: cmd/posix/awk/awkgram.y
+ $(YACC) -d -o cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.y
+
+cmd/posix/awk/maketab: cmd/posix/awk/maketab.c cmd/posix/awk/awkgram.tab.h
+ $(CC) $(CFLAGS) -o $@ cmd/posix/awk/maketab.c
+
+cmd/posix/awk/proctab.c: cmd/posix/awk/maketab
+ cmd/posix/awk/maketab cmd/posix/awk/awkgram.tab.h > $@
+
+$(AWKOBJ): cmd/posix/awk/awk.h cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proto.h
+
+cmd/posix/awk/%.o: cmd/posix/awk/%.c
+ $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -o $@ -c $<
+
+cmd/posix/awk/awk: $(AWKOBJ) $(LIB)
+ $(CC) $(LDFLAGS) -o $@ $(AWKOBJ) $(LIB) $(LDLIBS) -lm
+
+cmd/posix/sh/mknodes: cmd/posix/sh/mknodes.c
+ $(CC) $(CFLAGS) -o $@ cmd/posix/sh/mknodes.c
+
+cmd/posix/sh/mksyntax: cmd/posix/sh/mksyntax.c
+ $(CC) $(CPPFLAGS) -Icmd/posix/sh $(CFLAGS) -o $@ cmd/posix/sh/mksyntax.c
+
+cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h: cmd/posix/sh/mksyntax
+ cd cmd/posix/sh && ./mksyntax
+
+cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h: cmd/posix/sh/mknodes cmd/posix/sh/nodetypes cmd/posix/sh/nodes.c.pat
+ cd cmd/posix/sh && ./mknodes nodetypes nodes.c.pat
+
+cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h: cmd/posix/sh/mkbuiltins cmd/posix/sh/builtins.def cmd/posix/sh/shell.h
+ cd cmd/posix/sh && sh mkbuiltins .
+
+cmd/posix/sh/token.h: cmd/posix/sh/mktokens
+ cd cmd/posix/sh && sh mktokens
+
+$(SHOBJ): $(SH_GENHDRS)
+
+cmd/posix/sh/%.o: cmd/posix/sh/%.c
+ $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -o $@ -c $<
+
+cmd/posix/sh/sh: $(SHOBJ) $(LIB)
+ $(CC) $(LDFLAGS) -o $@ $(SHOBJ) $(LIB) $(LDLIBS)
+
+cmd/pseudo/base64: cmd/pseudo/base64.o $(LIB)
+ $(CC) $(LDFLAGS) -o $@ cmd/pseudo/base64.o $(LIB) $(LDLIBS)
diff --git a/cmd/linux/blkdiscard.c b/cmd/linux/blkdiscard.c
@@ -39,9 +39,9 @@ main(int argc, char *argv[])
if (fd < 0)
eprintf("open: %s:", argv[0]);
range[OFFSET_IDX] = 0;
- if (ioctl(fd, BLKGETSIZE64, &range[LENGTH_IDX]) < 0)
+ if (ioctl(fd, (int)BLKGETSIZE64, &range[LENGTH_IDX]) < 0)
eprintf("BLKGETSIZE64: %s:", argv[0]);
- if (ioctl(fd, BLKDISCARD, range) < 0)
+ if (ioctl(fd, (int)BLKDISCARD, range) < 0)
eprintf("BLKDISCARD: %s:", argv[0]);
close(fd);
return 0;
diff --git a/cmd/linux/fallocate.c b/cmd/linux/fallocate.c
@@ -24,10 +24,10 @@ main(int argc, char *argv[])
ARGBEGIN {
case 'l':
- size = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
+ size = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'o':
- offset = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ offset = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
default:
usage();
diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c
@@ -20,7 +20,7 @@ readrtctm(struct tm *tm, int fd)
struct rtc_time rt;
memset(&rt, 0, sizeof(rt));
- if (ioctl(fd, RTC_RD_TIME, &rt) < 0)
+ if (ioctl(fd, (int)RTC_RD_TIME, &rt) < 0)
eprintf("RTC_RD_TIME:");
tm->tm_sec = rt.tm_sec;
tm->tm_min = rt.tm_min;
@@ -47,7 +47,7 @@ writertctm(struct tm *tm, int fd)
rt.tm_wday = tm->tm_wday;
rt.tm_yday = tm->tm_yday;
rt.tm_isdst = tm->tm_isdst;
- if (ioctl(fd, RTC_SET_TIME, &rt) < 0)
+ if (ioctl(fd, (int)RTC_SET_TIME, &rt) < 0)
eprintf("RTC_SET_TIME:");
}
diff --git a/cmd/linux/mkswap.c b/cmd/linux/mkswap.c
@@ -72,7 +72,7 @@ main(int argc, char *argv[])
hdr = (struct swap_hdr *)buf;
hdr->version = 1;
hdr->last_page = pages - 1;
- strncpy(buf + pagesize - 10, "SWAPSPACE2", 10);
+ memcpy(buf + pagesize - 10, "SWAPSPACE2", 10);
printf("Setting up swapspace version 1, size = %luKiB\n",
(pages - 1) * pagesize / 1024);
diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c
@@ -264,9 +264,10 @@ main(int argc, char *argv[])
target = me->mnt_dir;
source = me->mnt_fsname;
}
- if (!fsopts[0])
+ if (!fsopts[0]) {
estrlcat(fsopts, me->mnt_opts, sizeof(fsopts));
parseopts(fsopts, &flags, data, sizeof(data));
+ }
if (!types)
types = me->mnt_type;
goto mountsingle;
diff --git a/cmd/linux/pwdx.c b/cmd/linux/pwdx.c
@@ -31,7 +31,7 @@ main(int argc, char *argv[])
for (; argc > 0; argc--, argv++) {
n = snprintf(path, sizeof(path), "/proc/%s/cwd", *argv);
- if (n < 0 || n >= sizeof(path)) {
+ if (n < 0 || (size_t)n >= sizeof(path)) {
errno = ESRCH;
} else {
n = readlink(path, target, sizeof(target) - 1);
diff --git a/cmd/net/tftp.c b/cmd/net/tftp.c
@@ -99,7 +99,7 @@ unpackerrc(unsigned char *buf)
int errc;
errc = (buf[2] << 8) | (buf[3] & 0xff);
- if (errc < 0 || errc >= LEN(errtext))
+ if (errc < 0 || (size_t)errc >= LEN(errtext))
eprintf("bad error code: %d\n", errc);
return errc;
}
diff --git a/cmd/net/wget.c b/cmd/net/wget.c
@@ -130,13 +130,18 @@ find_header(const char *headers, const char *name)
static int
stream_getc(struct Stream *s)
{
+ ssize_t r;
+
if (s->idx < s->len) {
return (unsigned char)s->buf[s->idx++];
}
s->idx = 0;
- s->len = read(s->fd, s->buf, sizeof(s->buf));
- if (s->len <= 0)
+ r = read(s->fd, s->buf, sizeof(s->buf));
+ if (r <= 0) {
+ s->len = 0;
return EOF;
+ }
+ s->len = (size_t)r;
return (unsigned char)s->buf[s->idx++];
}
@@ -146,6 +151,7 @@ stream_read(struct Stream *s, void *ptr, size_t size)
size_t total = 0;
size_t n;
char *p = ptr;
+ ssize_t r;
while (total < size) {
if (s->idx < s->len) {
@@ -155,9 +161,12 @@ stream_read(struct Stream *s, void *ptr, size_t size)
total += n;
} else {
s->idx = 0;
- s->len = read(s->fd, s->buf, sizeof(s->buf));
- if (s->len <= 0)
+ r = read(s->fd, s->buf, sizeof(s->buf));
+ if (r <= 0) {
+ s->len = 0;
break;
+ }
+ s->len = (size_t)r;
}
}
return total;
diff --git a/cmd/posix/awk/awk.h b/cmd/posix/awk/awk.h
@@ -0,0 +1,283 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#include <assert.h>
+#include <stdint.h>
+
+#ifndef bool
+#define bool int
+#define true 1
+#define false 0
+#endif
+
+#if __STDC_VERSION__ <= 199901L
+#define noreturn
+#else
+#include <stdnoreturn.h>
+#endif
+
+typedef double Awkfloat;
+
+/* unsigned char is more trouble than it's worth */
+
+typedef unsigned char uschar;
+
+#define xfree(a) { free((void *)(intptr_t)(a)); (a) = NULL; }
+/*
+ * We sometimes cheat writing read-only pointers to NUL-terminate them
+ * and then put back the original value
+ */
+#define setptr(ptr, a) (*(char *)(intptr_t)(ptr)) = (a)
+
+#define NN(p) ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF
+*/
+#define DEBUG
+#ifdef DEBUG
+# define DPRINTF(...) if (dbg) printf(__VA_ARGS__)
+#else
+# define DPRINTF(...)
+#endif
+
+extern enum compile_states {
+ RUNNING,
+ COMPILING,
+ ERROR_PRINTING
+} compile_time;
+
+extern bool safe; /* false => unsafe, true => safe */
+
+#define RECSIZE (8 * 1024) /* sets limit on records, fields, etc., etc. */
+extern int recsize; /* size of current record, orig RECSIZE */
+
+extern size_t awk_mb_cur_max; /* max size of a multi-byte character */
+
+extern char EMPTY[]; /* this avoid -Wwritable-strings issues */
+extern char **FS;
+extern char **RS;
+extern char **ORS;
+extern char **OFS;
+extern char **OFMT;
+extern Awkfloat *NR;
+extern Awkfloat *FNR;
+extern Awkfloat *NF;
+extern char **FILENAME;
+extern char **SUBSEP;
+extern Awkfloat *RSTART;
+extern Awkfloat *RLENGTH;
+
+extern bool CSV; /* true for csv input */
+
+extern char *record; /* points to $0 */
+extern int lineno; /* line number in awk program */
+extern int errorflag; /* 1 if error has occurred */
+extern bool donefld; /* true if record broken into fields */
+extern bool donerec; /* true if record is valid (no fld has changed */
+extern int dbg;
+
+extern const char *patbeg; /* beginning of pattern matched */
+extern int patlen; /* length of pattern matched. set in b.c */
+
+/* Cell: all information about a variable or constant */
+
+typedef struct Cell {
+ uschar ctype; /* OCELL, OBOOL, OJUMP, etc. */
+ uschar csub; /* CCON, CTEMP, CFLD, etc. */
+ char *nval; /* name, for variables only */
+ char *sval; /* string value */
+ Awkfloat fval; /* value as number */
+ int tval; /* type info: STR|NUM|ARR|FCN|FLD|CON|DONTFREE|CONVC|CONVO */
+ char *fmt; /* CONVFMT/OFMT value used to convert from number */
+ struct Cell *cnext; /* ptr to next if chained */
+} Cell;
+
+typedef struct Array { /* symbol table array */
+ int nelem; /* elements in table right now */
+ int size; /* size of tab */
+ Cell **tab; /* hash table pointers */
+} Array;
+
+#define NSYMTAB 50 /* initial size of a symbol table */
+extern Array *symtab;
+
+extern Cell *nrloc; /* NR */
+extern Cell *fnrloc; /* FNR */
+extern Cell *fsloc; /* FS */
+extern Cell *nfloc; /* NF */
+extern Cell *ofsloc; /* OFS */
+extern Cell *orsloc; /* ORS */
+extern Cell *rsloc; /* RS */
+extern Cell *rstartloc; /* RSTART */
+extern Cell *rlengthloc; /* RLENGTH */
+extern Cell *subseploc; /* SUBSEP */
+extern Cell *symtabloc; /* SYMTAB */
+
+/* Cell.tval values: */
+#define NUM 01 /* number value is valid */
+#define STR 02 /* string value is valid */
+#define DONTFREE 04 /* string space is not freeable */
+#define CON 010 /* this is a constant */
+#define ARR 020 /* this is an array */
+#define FCN 040 /* this is a function name */
+#define FLD 0100 /* this is a field $1, $2, ... */
+#define REC 0200 /* this is $0 */
+#define CONVC 0400 /* string was converted from number via CONVFMT */
+#define CONVO 01000 /* string was converted from number via OFMT */
+
+
+/* function types */
+#define FLENGTH 1
+#define FSQRT 2
+#define FEXP 3
+#define FLOG 4
+#define FINT 5
+#define FSYSTEM 6
+#define FRAND 7
+#define FSRAND 8
+#define FSIN 9
+#define FCOS 10
+#define FATAN 11
+#define FTOUPPER 12
+#define FTOLOWER 13
+#define FFLUSH 14
+
+/* Node: parse tree is made of nodes, with Cell's at bottom */
+
+typedef struct Node {
+ int ntype;
+ struct Node *nnext;
+ int lineno;
+ int nobj;
+ struct Node *narg[1]; /* variable: actual size set by calling malloc */
+} Node;
+
+#define NIL ((Node *) 0)
+
+extern Node *winner;
+extern Node *nullnode;
+
+/* ctypes */
+#define OCELL 1
+#define OBOOL 2
+#define OJUMP 3
+
+/* Cell subtypes: csub */
+#define CFREE 7
+#define CCOPY 6
+#define CCON 5
+#define CTEMP 4
+#define CNAME 3
+#define CVAR 2
+#define CFLD 1
+#define CUNK 0
+
+/* bool subtypes */
+#define BTRUE 11
+#define BFALSE 12
+
+/* jump subtypes */
+#define JEXIT 21
+#define JNEXT 22
+#define JBREAK 23
+#define JCONT 24
+#define JRET 25
+#define JNEXTFILE 26
+
+/* node types */
+#define NVALUE 1
+#define NSTAT 2
+#define NEXPR 3
+
+
+extern int pairstack[], paircnt;
+
+#define notlegal(n) (n <= FIRSTTOKEN || n >= LASTTOKEN || proctab[n-FIRSTTOKEN] == nullproc)
+#define isvalue(n) ((n)->ntype == NVALUE)
+#define isexpr(n) ((n)->ntype == NEXPR)
+#define isjump(n) ((n)->ctype == OJUMP)
+#define isexit(n) ((n)->csub == JEXIT)
+#define isbreak(n) ((n)->csub == JBREAK)
+#define iscont(n) ((n)->csub == JCONT)
+#define isnext(n) ((n)->csub == JNEXT || (n)->csub == JNEXTFILE)
+#define isret(n) ((n)->csub == JRET)
+#define isrec(n) ((n)->tval & REC)
+#define isfld(n) ((n)->tval & FLD)
+#define isstr(n) ((n)->tval & STR)
+#define isnum(n) ((n)->tval & NUM)
+#define isarr(n) ((n)->tval & ARR)
+#define isfcn(n) ((n)->tval & FCN)
+#define istrue(n) ((n)->csub == BTRUE)
+#define istemp(n) ((n)->csub == CTEMP)
+#define isargument(n) ((n)->nobj == ARG)
+/* #define freeable(p) (!((p)->tval & DONTFREE)) */
+#define freeable(p) ( ((p)->tval & (STR|DONTFREE)) == STR )
+
+/* structures used by regular expression matching machinery, mostly b.c: */
+
+#define NCHARS (1256+3) /* 256 handles 8-bit chars; 128 does 7-bit */
+ /* BUG: some overflows (caught) if we use 256 */
+ /* watch out in match(), etc. */
+#define HAT (NCHARS+2) /* matches ^ in regular expr */
+#define NSTATES 32
+
+typedef struct rrow {
+ long ltype; /* long avoids pointer warnings on 64-bit */
+ union {
+ int i;
+ Node *np;
+ uschar *up;
+ int *rp; /* rune representation of char class */
+ } lval; /* because Al stores a pointer in it! */
+ int *lfollow;
+} rrow;
+
+typedef struct gtte { /* gototab entry */
+ unsigned int ch;
+ unsigned int state;
+} gtte;
+
+#define GOTO_DIRECT 128 /* size of ASCII direct-index fast path */
+
+typedef struct gtt { /* gototab */
+ size_t allocated;
+ size_t inuse;
+ gtte *entries;
+ int direct[GOTO_DIRECT]; /* fast path for ASCII; 0 == miss */
+} gtt;
+
+typedef struct fa {
+ gtt *gototab;
+ uschar *out;
+ uschar *restr;
+ int **posns;
+ int state_count;
+ bool anchor;
+ int use;
+ int initstat;
+ int curstat;
+ int accept;
+ struct rrow re[1]; /* variable: actual size set by calling malloc */
+} fa;
+
+
+#include "proto.h"
diff --git a/cmd/posix/awk/awkgram.y b/cmd/posix/awk/awkgram.y
@@ -0,0 +1,497 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+%{
+#include <stdio.h>
+#include <string.h>
+#include "awk.h"
+
+void checkdup(Node *list, Cell *item);
+int yywrap(void) { return(1); }
+
+Node *beginloc = 0;
+Node *endloc = 0;
+bool infunc = false; /* = true if in arglist or body of func */
+int inloop = 0; /* >= 1 if in while, for, do; can't be bool, since loops can next */
+char *curfname = 0; /* current function name */
+Node *arglist = 0; /* list of args for current function */
+%}
+
+%union {
+ Node *p;
+ Cell *cp;
+ int i;
+ char *s;
+}
+
+%token <i> FIRSTTOKEN /* must be first */
+%token <p> PROGRAM PASTAT PASTAT2 XBEGIN XEND
+%token <i> NL ',' '{' '(' '|' ';' '/' ')' '}' '[' ']'
+%token <i> ARRAY
+%token <i> MATCH NOTMATCH MATCHOP
+%token <i> FINAL DOT ALL CCL NCCL CHAR OR STAR QUEST PLUS EMPTYRE ZERO
+%token <i> AND BOR APPEND EQ GE GT LE LT NE IN
+%token <i> ARG BLTIN BREAK CLOSE CONTINUE DELETE DO EXIT FOR FUNC
+%token <i> SUB GSUB IF INDEX LSUBSTR MATCHFCN NEXT NEXTFILE
+%token <i> ADD MINUS MULT DIVIDE MOD
+%token <i> ASSIGN ASGNOP ADDEQ SUBEQ MULTEQ DIVEQ MODEQ POWEQ
+%token <i> PRINT PRINTF SPRINTF
+%token <p> ELSE INTEST CONDEXPR
+%token <i> POSTINCR PREINCR POSTDECR PREDECR
+%token <cp> VAR IVAR VARNF CALL NUMBER STRING
+%token <s> REGEXPR
+
+%type <p> pas pattern ppattern plist pplist patlist prarg term re
+%type <p> pa_pat pa_stat pa_stats
+%type <s> reg_expr
+%type <p> simple_stmt opt_simple_stmt stmt stmtlist
+%type <p> var varname funcname varlist
+%type <p> for if else while
+%type <i> do st
+%type <i> pst opt_pst lbrace rbrace rparen comma nl opt_nl and bor
+%type <i> subop print
+%type <cp> string
+
+%right ASGNOP
+%right '?'
+%right ':'
+%left BOR
+%left AND
+%left GETLINE
+%nonassoc APPEND EQ GE GT LE LT NE MATCHOP IN '|'
+%left ARG BLTIN BREAK CALL CLOSE CONTINUE DELETE DO EXIT FOR FUNC
+%left GSUB IF INDEX LSUBSTR MATCHFCN NEXT NUMBER
+%left PRINT PRINTF RETURN SPLIT SPRINTF STRING SUB SUBSTR
+%left REGEXPR VAR VARNF IVAR WHILE '('
+%left CAT
+%left '+' '-'
+%left '*' '/' '%'
+%left NOT UMINUS UPLUS
+%right POWER
+%right DECR INCR
+%left INDIRECT
+%token LASTTOKEN /* must be last */
+
+%%
+
+program:
+ pas { if (errorflag==0)
+ winner = (Node *)stat3(PROGRAM, beginloc, $1, endloc); }
+ | error { yyclearin; bracecheck(); SYNTAX("bailing out"); }
+ ;
+
+and:
+ AND | and NL
+ ;
+
+bor:
+ BOR | bor NL
+ ;
+
+comma:
+ ',' | comma NL
+ ;
+
+do:
+ DO | do NL
+ ;
+
+else:
+ ELSE | else NL
+ ;
+
+for:
+ FOR '(' opt_simple_stmt ';' opt_nl pattern ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt
+ { --inloop; $$ = stat4(FOR, $3, notnull($6), $9, $12); }
+ | FOR '(' opt_simple_stmt ';' ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt
+ { --inloop; $$ = stat4(FOR, $3, NIL, $7, $10); }
+ | FOR '(' varname IN varname rparen {inloop++;} stmt
+ { --inloop; $$ = stat3(IN, $3, makearr($5), $8); }
+ ;
+
+funcname:
+ VAR { setfname($1); }
+ | CALL { setfname($1); }
+ ;
+
+if:
+ IF '(' pattern rparen { $$ = notnull($3); }
+ ;
+
+lbrace:
+ '{' | lbrace NL
+ ;
+
+nl:
+ NL | nl NL
+ ;
+
+opt_nl:
+ /* empty */ { $$ = 0; }
+ | nl
+ ;
+
+opt_pst:
+ /* empty */ { $$ = 0; }
+ | pst
+ ;
+
+
+opt_simple_stmt:
+ /* empty */ { $$ = 0; }
+ | simple_stmt
+ ;
+
+pas:
+ opt_pst { $$ = 0; }
+ | opt_pst pa_stats opt_pst { $$ = $2; }
+ ;
+
+pa_pat:
+ pattern { $$ = notnull($1); }
+ ;
+
+pa_stat:
+ pa_pat { $$ = stat2(PASTAT, $1, stat2(PRINT, rectonode(), NIL)); }
+ | pa_pat lbrace stmtlist '}' { $$ = stat2(PASTAT, $1, $3); }
+ | pa_pat ',' opt_nl pa_pat { $$ = pa2stat($1, $4, stat2(PRINT, rectonode(), NIL)); }
+ | pa_pat ',' opt_nl pa_pat lbrace stmtlist '}' { $$ = pa2stat($1, $4, $6); }
+ | lbrace stmtlist '}' { $$ = stat2(PASTAT, NIL, $2); }
+ | XBEGIN lbrace stmtlist '}'
+ { beginloc = linkum(beginloc, $3); $$ = 0; }
+ | XEND lbrace stmtlist '}'
+ { endloc = linkum(endloc, $3); $$ = 0; }
+ | FUNC funcname '(' varlist rparen {infunc = true;} lbrace stmtlist '}'
+ { infunc = false; curfname=0; defn((Cell *)$2, $4, $8); $$ = 0; }
+ ;
+
+pa_stats:
+ pa_stat
+ | pa_stats opt_pst pa_stat { $$ = linkum($1, $3); }
+ ;
+
+patlist:
+ pattern
+ | patlist comma pattern { $$ = linkum($1, $3); }
+ ;
+
+ppattern:
+ var ASGNOP ppattern { $$ = op2($2, $1, $3); }
+ | ppattern '?' ppattern ':' ppattern %prec '?'
+ { $$ = op3(CONDEXPR, notnull($1), $3, $5); }
+ | ppattern bor ppattern %prec BOR
+ { $$ = op2(BOR, notnull($1), notnull($3)); }
+ | ppattern and ppattern %prec AND
+ { $$ = op2(AND, notnull($1), notnull($3)); }
+ | ppattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); free($3); }
+ | ppattern MATCHOP ppattern
+ { if (constnode($3)) {
+ $$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0));
+ free($3);
+ } else
+ $$ = op3($2, (Node *)1, $1, $3); }
+ | ppattern IN varname { $$ = op2(INTEST, $1, makearr($3)); }
+ | '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); }
+ | ppattern term %prec CAT { $$ = op2(CAT, $1, $2); }
+ | re
+ | term
+ ;
+
+pattern:
+ var ASGNOP pattern { $$ = op2($2, $1, $3); }
+ | pattern '?' pattern ':' pattern %prec '?'
+ { $$ = op3(CONDEXPR, notnull($1), $3, $5); }
+ | pattern bor pattern %prec BOR
+ { $$ = op2(BOR, notnull($1), notnull($3)); }
+ | pattern and pattern %prec AND
+ { $$ = op2(AND, notnull($1), notnull($3)); }
+ | pattern EQ pattern { $$ = op2($2, $1, $3); }
+ | pattern GE pattern { $$ = op2($2, $1, $3); }
+ | pattern GT pattern { $$ = op2($2, $1, $3); }
+ | pattern LE pattern { $$ = op2($2, $1, $3); }
+ | pattern LT pattern { $$ = op2($2, $1, $3); }
+ | pattern NE pattern { $$ = op2($2, $1, $3); }
+ | pattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); free($3); }
+ | pattern MATCHOP pattern
+ { if (constnode($3)) {
+ $$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0));
+ free($3);
+ } else
+ $$ = op3($2, (Node *)1, $1, $3); }
+ | pattern IN varname { $$ = op2(INTEST, $1, makearr($3)); }
+ | '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); }
+ | pattern '|' GETLINE var {
+ if (safe) SYNTAX("cmd | getline is unsafe");
+ else $$ = op3(GETLINE, $4, itonp($2), $1); }
+ | pattern '|' GETLINE {
+ if (safe) SYNTAX("cmd | getline is unsafe");
+ else $$ = op3(GETLINE, (Node*)0, itonp($2), $1); }
+ | pattern term %prec CAT { $$ = op2(CAT, $1, $2); }
+ | re
+ | term
+ ;
+
+plist:
+ pattern comma pattern { $$ = linkum($1, $3); }
+ | plist comma pattern { $$ = linkum($1, $3); }
+ ;
+
+pplist:
+ ppattern
+ | pplist comma ppattern { $$ = linkum($1, $3); }
+ ;
+
+prarg:
+ /* empty */ { $$ = rectonode(); }
+ | pplist
+ | '(' plist ')' { $$ = $2; }
+ ;
+
+print:
+ PRINT | PRINTF
+ ;
+
+pst:
+ NL | ';' | pst NL | pst ';'
+ ;
+
+rbrace:
+ '}' | rbrace NL
+ ;
+
+re:
+ reg_expr
+ { $$ = op3(MATCH, NIL, rectonode(), (Node*)makedfa($1, 0)); free($1); }
+ | NOT re { $$ = op1(NOT, notnull($2)); }
+ ;
+
+reg_expr:
+ '/' {startreg();} REGEXPR '/' { $$ = $3; }
+ ;
+
+rparen:
+ ')' | rparen NL
+ ;
+
+simple_stmt:
+ print prarg '|' term {
+ if (safe) SYNTAX("print | is unsafe");
+ else $$ = stat3($1, $2, itonp($3), $4); }
+ | print prarg APPEND term {
+ if (safe) SYNTAX("print >> is unsafe");
+ else $$ = stat3($1, $2, itonp($3), $4); }
+ | print prarg GT term {
+ if (safe) SYNTAX("print > is unsafe");
+ else $$ = stat3($1, $2, itonp($3), $4); }
+ | print prarg { $$ = stat3($1, $2, NIL, NIL); }
+ | DELETE varname '[' patlist ']' { $$ = stat2(DELETE, makearr($2), $4); }
+ | DELETE varname { $$ = stat2(DELETE, makearr($2), 0); }
+ | pattern { $$ = exptostat($1); }
+ | error { yyclearin; SYNTAX("illegal statement"); }
+ ;
+
+st:
+ nl
+ | ';' opt_nl
+ ;
+
+stmt:
+ BREAK st { if (!inloop) SYNTAX("break illegal outside of loops");
+ $$ = stat1(BREAK, NIL); }
+ | CONTINUE st { if (!inloop) SYNTAX("continue illegal outside of loops");
+ $$ = stat1(CONTINUE, NIL); }
+ | do {inloop++;} stmt {--inloop;} WHILE '(' pattern ')' st
+ { $$ = stat2(DO, $3, notnull($7)); }
+ | EXIT pattern st { $$ = stat1(EXIT, $2); }
+ | EXIT st { $$ = stat1(EXIT, NIL); }
+ | for
+ | if stmt else stmt { $$ = stat3(IF, $1, $2, $4); }
+ | if stmt { $$ = stat3(IF, $1, $2, NIL); }
+ | lbrace stmtlist rbrace { $$ = $2; }
+ | NEXT st { if (infunc)
+ SYNTAX("next is illegal inside a function");
+ $$ = stat1(NEXT, NIL); }
+ | NEXTFILE st { if (infunc)
+ SYNTAX("nextfile is illegal inside a function");
+ $$ = stat1(NEXTFILE, NIL); }
+ | RETURN pattern st { $$ = stat1(RETURN, $2); }
+ | RETURN st { $$ = stat1(RETURN, NIL); }
+ | simple_stmt st
+ | while {inloop++;} stmt { --inloop; $$ = stat2(WHILE, $1, $3); }
+ | ';' opt_nl { $$ = 0; }
+ ;
+
+stmtlist:
+ stmt
+ | stmtlist stmt { $$ = linkum($1, $2); }
+ ;
+
+subop:
+ SUB | GSUB
+ ;
+
+string:
+ STRING
+ | string STRING { $$ = catstr($1, $2); }
+ ;
+
+term:
+ term '/' ASGNOP term { $$ = op2(DIVEQ, $1, $4); }
+ | term '+' term { $$ = op2(ADD, $1, $3); }
+ | term '-' term { $$ = op2(MINUS, $1, $3); }
+ | term '*' term { $$ = op2(MULT, $1, $3); }
+ | term '/' term { $$ = op2(DIVIDE, $1, $3); }
+ | term '%' term { $$ = op2(MOD, $1, $3); }
+ | term POWER term { $$ = op2(POWER, $1, $3); }
+ | '-' term %prec UMINUS { $$ = op1(UMINUS, $2); }
+ | '+' term %prec UMINUS { $$ = op1(UPLUS, $2); }
+ | NOT term %prec UMINUS { $$ = op1(NOT, notnull($2)); }
+ | BLTIN '(' ')' { $$ = op2(BLTIN, itonp($1), rectonode()); }
+ | BLTIN '(' patlist ')' { $$ = op2(BLTIN, itonp($1), $3); }
+ | BLTIN { $$ = op2(BLTIN, itonp($1), rectonode()); }
+ | CALL '(' ')' { $$ = op2(CALL, celltonode($1,CVAR), NIL); }
+ | CALL '(' patlist ')' { $$ = op2(CALL, celltonode($1,CVAR), $3); }
+ | CLOSE term { $$ = op1(CLOSE, $2); }
+ | DECR var { $$ = op1(PREDECR, $2); }
+ | INCR var { $$ = op1(PREINCR, $2); }
+ | var DECR { $$ = op1(POSTDECR, $1); }
+ | var INCR { $$ = op1(POSTINCR, $1); }
+ | GETLINE var LT term { $$ = op3(GETLINE, $2, itonp($3), $4); }
+ | GETLINE LT term { $$ = op3(GETLINE, NIL, itonp($2), $3); }
+ | GETLINE var { $$ = op3(GETLINE, $2, NIL, NIL); }
+ | GETLINE { $$ = op3(GETLINE, NIL, NIL, NIL); }
+ | INDEX '(' pattern comma pattern ')'
+ { $$ = op2(INDEX, $3, $5); }
+ | INDEX '(' pattern comma reg_expr ')'
+ { SYNTAX("index() doesn't permit regular expressions");
+ $$ = op2(INDEX, $3, (Node*)$5); }
+ | '(' pattern ')' { $$ = $2; }
+ | MATCHFCN '(' pattern comma reg_expr ')'
+ { $$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa($5, 1)); free($5); }
+ | MATCHFCN '(' pattern comma pattern ')'
+ { if (constnode($5)) {
+ $$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa(strnode($5), 1));
+ free($5);
+ } else
+ $$ = op3(MATCHFCN, (Node *)1, $3, $5); }
+ | NUMBER { $$ = celltonode($1, CCON); }
+ | SPLIT '(' pattern comma varname comma pattern ')' /* string */
+ { $$ = op4(SPLIT, $3, makearr($5), $7, (Node*)STRING); }
+ | SPLIT '(' pattern comma varname comma reg_expr ')' /* const /regexp/ */
+ { $$ = op4(SPLIT, $3, makearr($5), (Node*)makedfa($7, 1), (Node *)REGEXPR); free($7); }
+ | SPLIT '(' pattern comma varname ')'
+ { $$ = op4(SPLIT, $3, makearr($5), NIL, (Node*)STRING); } /* default */
+ | SPRINTF '(' patlist ')' { $$ = op1($1, $3); }
+ | string { $$ = celltonode($1, CCON); }
+ | subop '(' reg_expr comma pattern ')'
+ { $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, rectonode()); free($3); }
+ | subop '(' pattern comma pattern ')'
+ { if (constnode($3)) {
+ $$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, rectonode());
+ free($3);
+ } else
+ $$ = op4($1, (Node *)1, $3, $5, rectonode()); }
+ | subop '(' reg_expr comma pattern comma var ')'
+ { $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, $7); free($3); }
+ | subop '(' pattern comma pattern comma var ')'
+ { if (constnode($3)) {
+ $$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, $7);
+ free($3);
+ } else
+ $$ = op4($1, (Node *)1, $3, $5, $7); }
+ | SUBSTR '(' pattern comma pattern comma pattern ')'
+ { $$ = op3(SUBSTR, $3, $5, $7); }
+ | SUBSTR '(' pattern comma pattern ')'
+ { $$ = op3(SUBSTR, $3, $5, NIL); }
+ | var
+ ;
+
+var:
+ varname
+ | varname '[' patlist ']' { $$ = op2(ARRAY, makearr($1), $3); }
+ | IVAR { $$ = op1(INDIRECT, celltonode($1, CVAR)); }
+ | INDIRECT term { $$ = op1(INDIRECT, $2); }
+ ;
+
+varlist:
+ /* nothing */ { arglist = $$ = 0; }
+ | VAR { arglist = $$ = celltonode($1,CVAR); }
+ | varlist comma VAR {
+ checkdup($1, $3);
+ arglist = $$ = linkum($1,celltonode($3,CVAR)); }
+ ;
+
+varname:
+ VAR { $$ = celltonode($1, CVAR); }
+ | ARG { $$ = op1(ARG, itonp($1)); }
+ | VARNF { $$ = op1(VARNF, (Node *) $1); }
+ ;
+
+
+while:
+ WHILE '(' pattern rparen { $$ = notnull($3); }
+ ;
+
+%%
+
+void setfname(Cell *p)
+{
+ if (isarr(p))
+ SYNTAX("%s is an array, not a function", p->nval);
+ else if (isfcn(p))
+ SYNTAX("you can't define function %s more than once", p->nval);
+ curfname = p->nval;
+}
+
+int constnode(Node *p)
+{
+ return isvalue(p) && ((Cell *) (p->narg[0]))->csub == CCON;
+}
+
+char *strnode(Node *p)
+{
+ return ((Cell *)(p->narg[0]))->sval;
+}
+
+Node *notnull(Node *n)
+{
+ switch (n->nobj) {
+ case LE: case LT: case EQ: case NE: case GT: case GE:
+ case BOR: case AND: case NOT:
+ return n;
+ default:
+ return op2(NE, n, nullnode);
+ }
+}
+
+void checkdup(Node *vl, Cell *cp) /* check if name already in list */
+{
+ char *s = cp->nval;
+ for ( ; vl; vl = vl->nnext) {
+ if (strcmp(s, ((Cell *)(vl->narg[0]))->nval) == 0) {
+ SYNTAX("duplicate argument %s", s);
+ break;
+ }
+ }
+}
diff --git a/cmd/posix/awk/b.c b/cmd/posix/awk/b.c
@@ -0,0 +1,1599 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+/* lasciate ogne speranza, voi ch'intrate. */
+
+#define DEBUG
+
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "awk.h"
+#include "awkgram.tab.h"
+
+#define MAXLIN 22
+
+#define type(v) (v)->nobj /* badly overloaded here */
+#define info(v) (v)->ntype /* badly overloaded here */
+#define left(v) (v)->narg[0]
+#define right(v) (v)->narg[1]
+#define parent(v) (v)->nnext
+
+#define LEAF case CCL: case NCCL: case CHAR: case DOT: case FINAL: case ALL:
+#define ELEAF case EMPTYRE: /* empty string in regexp */
+#define UNARY case STAR: case PLUS: case QUEST:
+
+/* encoding in tree Nodes:
+ leaf (CCL, NCCL, CHAR, DOT, FINAL, ALL, EMPTYRE):
+ left is index, right contains value or pointer to value
+ unary (STAR, PLUS, QUEST): left is child, right is null
+ binary (CAT, OR): left and right are children
+ parent contains pointer to parent
+*/
+
+
+int *setvec;
+int *tmpset;
+int maxsetvec = 0;
+
+int rtok; /* next token in current re */
+int rlxval;
+static const uschar *rlxstr;
+static const uschar *prestr; /* current position in current re */
+static const uschar *lastre; /* origin of last re */
+static const uschar *lastatom; /* origin of last Atom */
+static const uschar *starttok;
+static const uschar *basestr; /* starts with original, replaced during
+ repetition processing */
+static const uschar *firstbasestr;
+
+static int setcnt;
+static int poscnt;
+
+const char *patbeg;
+int patlen;
+
+#define NFA 128 /* cache this many dynamic fa's */
+fa *fatab[NFA];
+int nfatab = 0; /* entries in fatab */
+
+extern int u8_nextlen(const char *s);
+
+
+/* utf-8 mechanism:
+
+ For most of Awk, utf-8 strings just "work", since they look like
+ null-terminated sequences of 8-bit bytes.
+
+ Functions like length(), index(), and substr() have to operate
+ in units of utf-8 characters. The u8_* functions in run.c
+ handle this.
+
+ Regular expressions are more complicated, since the basic
+ mechanism of the goto table used 8-bit byte indices into the
+ gototab entries to compute the next state. Unicode is a lot
+ bigger, so the gototab entries are now structs with a character
+ and a next state. These are sorted by code point and binary
+ searched.
+
+ Throughout the RE mechanism in b.c, utf-8 characters are
+ converted to their utf-32 value. This mostly shows up in
+ cclenter, which expands character class ranges like a-z and now
+ alpha-omega. The size of a gototab array is still about 256.
+ This should be dynamic, but for now things work ok for a single
+ code page of Unicode, which is the most likely case.
+
+ The code changes are localized in run.c and b.c. I have added a
+ handful of functions to somewhat better hide the implementation,
+ but a lot more could be done.
+
+ */
+
+static int entry_cmp(const void *l, const void *r);
+static int get_gototab(fa*, int, int);
+static int set_gototab(fa*, int, int, int);
+static void clear_gototab(fa*, int);
+extern int u8_rune(int *, const char *);
+
+static int *
+intalloc(size_t n, const char *f)
+{
+ int *p = (int *) calloc(n, sizeof(int));
+ if (p == NULL)
+ overflo(f);
+ return p;
+}
+
+static void
+resizesetvec(const char *f)
+{
+ if (maxsetvec == 0)
+ maxsetvec = MAXLIN;
+ else
+ maxsetvec *= 4;
+ setvec = (int *) realloc(setvec, maxsetvec * sizeof(*setvec));
+ tmpset = (int *) realloc(tmpset, maxsetvec * sizeof(*tmpset));
+ if (setvec == NULL || tmpset == NULL)
+ overflo(f);
+}
+
+static void
+resize_state(fa *f, int state)
+{
+ gtt *p;
+ uschar *p2;
+ int **p3;
+ int i, new_count;
+
+ if (++state < f->state_count)
+ return;
+
+ new_count = state + 10; /* needs to be tuned */
+
+ p = (gtt *) realloc(f->gototab, new_count * sizeof(gtt));
+ if (p == NULL)
+ goto out;
+ f->gototab = p;
+
+ p2 = (uschar *) realloc(f->out, new_count * sizeof(f->out[0]));
+ if (p2 == NULL)
+ goto out;
+ f->out = p2;
+
+ p3 = (int **) realloc(f->posns, new_count * sizeof(f->posns[0]));
+ if (p3 == NULL)
+ goto out;
+ f->posns = p3;
+
+ for (i = f->state_count; i < new_count; ++i) {
+ memset(f->gototab[i].direct, 0, sizeof(f->gototab[i].direct));
+ f->gototab[i].entries = (gtte *) calloc(NCHARS, sizeof(gtte));
+ if (f->gototab[i].entries == NULL)
+ goto out;
+ f->gototab[i].allocated = NCHARS;
+ f->gototab[i].inuse = 0;
+ f->out[i] = 0;
+ f->posns[i] = NULL;
+ }
+ f->state_count = new_count;
+ return;
+out:
+ overflo(__func__);
+}
+
+fa *makedfa(const char *s, bool anchor) /* returns dfa for reg expr s */
+{
+ int i, use, nuse;
+ fa *pfa;
+ static int now = 1;
+
+ if (setvec == NULL) { /* first time through any RE */
+ resizesetvec(__func__);
+ }
+
+ if (compile_time != RUNNING) /* a constant for sure */
+ return mkdfa(s, anchor);
+ for (i = 0; i < nfatab; i++) /* is it there already? */
+ if (fatab[i]->anchor == anchor
+ && strcmp((const char *) fatab[i]->restr, s) == 0) {
+ fatab[i]->use = now++;
+ return fatab[i];
+ }
+ pfa = mkdfa(s, anchor);
+ if (nfatab < NFA) { /* room for another */
+ fatab[nfatab] = pfa;
+ fatab[nfatab]->use = now++;
+ nfatab++;
+ return pfa;
+ }
+ use = fatab[0]->use; /* replace least-recently used */
+ nuse = 0;
+ for (i = 1; i < nfatab; i++)
+ if (fatab[i]->use < use) {
+ use = fatab[i]->use;
+ nuse = i;
+ }
+ freefa(fatab[nuse]);
+ fatab[nuse] = pfa;
+ pfa->use = now++;
+ return pfa;
+}
+
+fa *mkdfa(const char *s, bool anchor) /* does the real work of making a dfa */
+ /* anchor = true for anchored matches, else false */
+{
+ Node *p, *p1;
+ fa *f;
+
+ firstbasestr = (const uschar *) s;
+ basestr = firstbasestr;
+ p = reparse(s);
+ p1 = op2(CAT, op2(STAR, op2(ALL, NIL, NIL), NIL), p);
+ /* put ALL STAR in front of reg. exp. */
+ p1 = op2(CAT, p1, op2(FINAL, NIL, NIL));
+ /* put FINAL after reg. exp. */
+
+ poscnt = 0;
+ penter(p1); /* enter parent pointers and leaf indices */
+ if ((f = (fa *) calloc(1, sizeof(fa) + poscnt * sizeof(rrow))) == NULL)
+ overflo(__func__);
+ f->accept = poscnt-1; /* penter has computed number of positions in re */
+ cfoll(f, p1); /* set up follow sets */
+ freetr(p1);
+ resize_state(f, 1);
+ f->posns[0] = intalloc(*(f->re[0].lfollow), __func__);
+ f->posns[1] = intalloc(1, __func__);
+ *f->posns[1] = 0;
+ f->initstat = makeinit(f, anchor);
+ f->anchor = anchor;
+ f->restr = (uschar *) tostring(s);
+ if (firstbasestr != basestr) {
+ if (basestr)
+ xfree(basestr);
+ }
+ return f;
+}
+
+int makeinit(fa *f, bool anchor)
+{
+ int i, k;
+
+ f->curstat = 2;
+ f->out[2] = 0;
+ k = *(f->re[0].lfollow);
+ xfree(f->posns[2]);
+ f->posns[2] = intalloc(k + 1, __func__);
+ for (i = 0; i <= k; i++) {
+ (f->posns[2])[i] = (f->re[0].lfollow)[i];
+ }
+ if ((f->posns[2])[1] == f->accept)
+ f->out[2] = 1;
+ clear_gototab(f, 2);
+ f->curstat = cgoto(f, 2, HAT);
+ if (anchor) {
+ *f->posns[2] = k-1; /* leave out position 0 */
+ for (i = 0; i < k; i++) {
+ (f->posns[0])[i] = (f->posns[2])[i];
+ }
+
+ f->out[0] = f->out[2];
+ if (f->curstat != 2)
+ --(*f->posns[f->curstat]);
+ }
+ return f->curstat;
+}
+
+void penter(Node *p) /* set up parent pointers and leaf indices */
+{
+ switch (type(p)) {
+ ELEAF
+ LEAF
+ info(p) = poscnt;
+ poscnt++;
+ break;
+ UNARY
+ penter(left(p));
+ parent(left(p)) = p;
+ break;
+ case CAT:
+ case OR:
+ penter(left(p));
+ penter(right(p));
+ parent(left(p)) = p;
+ parent(right(p)) = p;
+ break;
+ case ZERO:
+ break;
+ default: /* can't happen */
+ FATAL("can't happen: unknown type %d in penter", type(p));
+ break;
+ }
+}
+
+void freetr(Node *p) /* free parse tree */
+{
+ switch (type(p)) {
+ ELEAF
+ LEAF
+ xfree(p);
+ break;
+ UNARY
+ case ZERO:
+ freetr(left(p));
+ xfree(p);
+ break;
+ case CAT:
+ case OR:
+ freetr(left(p));
+ freetr(right(p));
+ xfree(p);
+ break;
+ default: /* can't happen */
+ FATAL("can't happen: unknown type %d in freetr", type(p));
+ break;
+ }
+}
+
+/* in the parsing of regular expressions, metacharacters like . have */
+/* to be seen literally; \056 is not a metacharacter. */
+
+int hexstr(const uschar **pp, int max) /* find and eval hex string at pp, return new p */
+{ /* only pick up one 8-bit byte (2 chars) */
+ const uschar *p;
+ int n = 0;
+ int i;
+
+ for (i = 0, p = *pp; i < max && isxdigit(*p); i++, p++) {
+ if (isdigit((int) *p))
+ n = 16 * n + *p - '0';
+ else if (*p >= 'a' && *p <= 'f')
+ n = 16 * n + *p - 'a' + 10;
+ else if (*p >= 'A' && *p <= 'F')
+ n = 16 * n + *p - 'A' + 10;
+ }
+ *pp = p;
+ return n;
+}
+
+
+
+#define isoctdigit(c) ((c) >= '0' && (c) <= '7') /* multiple use of arg */
+
+int quoted(const uschar **pp) /* pick up next thing after a \\ */
+ /* and increment *pp */
+{
+ const uschar *p = *pp;
+ int c;
+
+/* BUG: should advance by utf-8 char even if makes no sense */
+
+ switch ((c = *p++)) {
+ case 't':
+ c = '\t';
+ break;
+ case 'n':
+ c = '\n';
+ break;
+ case 'f':
+ c = '\f';
+ break;
+ case 'r':
+ c = '\r';
+ break;
+ case 'b':
+ c = '\b';
+ break;
+ case 'v':
+ c = '\v';
+ break;
+ case 'a':
+ c = '\a';
+ break;
+ case '\\':
+ c = '\\';
+ break;
+ case 'x': /* 2 hex digits follow */
+ c = hexstr(&p, 2); /* this adds a null if number is invalid */
+ break;
+ case 'u': /* unicode char number up to 8 hex digits */
+ c = hexstr(&p, 8);
+ break;
+ default:
+ if (isoctdigit(c)) { /* \d \dd \ddd */
+ int n = c - '0';
+ if (isoctdigit(*p)) {
+ n = 8 * n + *p++ - '0';
+ if (isoctdigit(*p))
+ n = 8 * n + *p++ - '0';
+ }
+ c = n;
+ }
+ }
+
+ *pp = p;
+ return c;
+}
+
+int *cclenter(const char *argp) /* add a character class */
+{
+ int i, c, c2;
+ int n;
+ const uschar *p = (const uschar *) argp;
+ int *bp, *retp;
+ static int *buf = NULL;
+ static int bufsz = 100;
+
+ if (buf == NULL && (buf = (int *) calloc(bufsz, sizeof(int))) == NULL)
+ FATAL("out of space for character class [%.10s...] 1", p);
+ bp = buf;
+ for (i = 0; *p != 0; ) {
+ n = u8_rune(&c, (const char *) p);
+ p += n;
+ if (c == '\\') {
+ c = quoted(&p);
+ } else if (c == '-' && i > 0 && bp[-1] != 0) {
+ if (*p != 0) {
+ c = bp[-1];
+ /* c2 = *p++; */
+ n = u8_rune(&c2, (const char *) p);
+ p += n;
+ if (c2 == '\\')
+ c2 = quoted(&p); /* BUG: sets p, has to be u8 size */
+ if (c > c2) { /* empty; ignore */
+ bp--;
+ i--;
+ continue;
+ }
+ while (c < c2) {
+ if (i >= bufsz) {
+ bufsz *= 2;
+ buf = (int *) realloc(buf, bufsz * sizeof(int));
+ if (buf == NULL)
+ FATAL("out of space for character class [%.10s...] 2", p);
+ bp = buf + i;
+ }
+ *bp++ = ++c;
+ i++;
+ }
+ continue;
+ }
+ }
+ if (i >= bufsz) {
+ bufsz *= 2;
+ buf = (int *) realloc(buf, bufsz * sizeof(int));
+ if (buf == NULL)
+ FATAL("out of space for character class [%.10s...] 2", p);
+ bp = buf + i;
+ }
+ *bp++ = c;
+ i++;
+ }
+ *bp = 0;
+ /* DPRINTF("cclenter: in = |%s|, out = |%s|\n", op, buf); BUG: can't print array of int */
+ /* xfree(op); BUG: what are we freeing here? */
+ retp = (int *) calloc(bp-buf+1, sizeof(int));
+ for (i = 0; i < bp-buf+1; i++)
+ retp[i] = buf[i];
+ return retp;
+}
+
+void overflo(const char *s)
+{
+ FATAL("regular expression too big: out of space in %.30s...", s);
+}
+
+void cfoll(fa *f, Node *v) /* enter follow set of each leaf of vertex v into lfollow[leaf] */
+{
+ int i;
+ int *p;
+
+ switch (type(v)) {
+ ELEAF
+ LEAF
+ f->re[info(v)].ltype = type(v);
+ f->re[info(v)].lval.np = right(v);
+ while (f->accept >= maxsetvec) { /* guessing here! */
+ resizesetvec(__func__);
+ }
+ for (i = 0; i <= f->accept; i++)
+ setvec[i] = 0;
+ setcnt = 0;
+ follow(v); /* computes setvec and setcnt */
+ p = intalloc(setcnt + 1, __func__);
+ f->re[info(v)].lfollow = p;
+ *p = setcnt;
+ for (i = f->accept; i >= 0; i--)
+ if (setvec[i] == 1)
+ *++p = i;
+ break;
+ UNARY
+ cfoll(f,left(v));
+ break;
+ case CAT:
+ case OR:
+ cfoll(f,left(v));
+ cfoll(f,right(v));
+ break;
+ case ZERO:
+ break;
+ default: /* can't happen */
+ FATAL("can't happen: unknown type %d in cfoll", type(v));
+ }
+}
+
+int first(Node *p) /* collects initially active leaves of p into setvec */
+ /* returns 0 if p matches empty string */
+{
+ int b, lp;
+
+ switch (type(p)) {
+ ELEAF
+ LEAF
+ lp = info(p); /* look for high-water mark of subscripts */
+ while (setcnt >= maxsetvec || lp >= maxsetvec) { /* guessing here! */
+ resizesetvec(__func__);
+ }
+ if (type(p) == EMPTYRE) {
+ setvec[lp] = 0;
+ return(0);
+ }
+ if (setvec[lp] != 1) {
+ setvec[lp] = 1;
+ setcnt++;
+ }
+ if (type(p) == CCL && (*(int *) right(p)) == 0)
+ return(0); /* empty CCL */
+ return(1);
+ case PLUS:
+ if (first(left(p)) == 0)
+ return(0);
+ return(1);
+ case STAR:
+ case QUEST:
+ first(left(p));
+ return(0);
+ case CAT:
+ if (first(left(p)) == 0 && first(right(p)) == 0) return(0);
+ return(1);
+ case OR:
+ b = first(right(p));
+ if (first(left(p)) == 0 || b == 0) return(0);
+ return(1);
+ case ZERO:
+ return 0;
+ }
+ FATAL("can't happen: unknown type %d in first", type(p)); /* can't happen */
+ return(-1);
+}
+
+void follow(Node *v) /* collects leaves that can follow v into setvec */
+{
+ Node *p;
+
+ if (type(v) == FINAL)
+ return;
+ p = parent(v);
+ switch (type(p)) {
+ case STAR:
+ case PLUS:
+ first(v);
+ follow(p);
+ return;
+
+ case OR:
+ case QUEST:
+ follow(p);
+ return;
+
+ case CAT:
+ if (v == left(p)) { /* v is left child of p */
+ if (first(right(p)) == 0) {
+ follow(p);
+ return;
+ }
+ } else /* v is right child */
+ follow(p);
+ return;
+ }
+}
+
+int member(int c, int *sarg) /* is c in s? */
+{
+ int *s = (int *) sarg;
+
+ while (*s)
+ if (c == *s++)
+ return(1);
+ return(0);
+}
+
+static void resize_gototab(fa *f, int state)
+{
+ size_t new_size = f->gototab[state].allocated * 2;
+ gtte *p = (gtte *) realloc(f->gototab[state].entries, new_size * sizeof(gtte));
+ if (p == NULL)
+ overflo(__func__);
+
+ // need to initialize the new memory to zero
+ size_t orig_size = f->gototab[state].allocated; // 2nd half of new mem is this size
+ memset(p + orig_size, 0, orig_size * sizeof(gtte)); // clean it out
+
+ f->gototab[state].allocated = new_size; // update gototab info
+ f->gototab[state].entries = p;
+}
+
+static int get_gototab(fa *f, int state, int ch) /* hide gototab implementation */
+{
+ gtte key;
+ gtte *item;
+
+ if ((unsigned)ch < GOTO_DIRECT)
+ return f->gototab[state].direct[ch];
+
+ key.ch = ch;
+ key.state = 0; /* irrelevant */
+ item = (gtte *) bsearch(& key, f->gototab[state].entries,
+ f->gototab[state].inuse, sizeof(gtte),
+ entry_cmp);
+
+ if (item == NULL)
+ return 0;
+ else
+ return item->state;
+}
+
+static int entry_cmp(const void *l, const void *r)
+{
+ const gtte *left, *right;
+
+ left = (const gtte *) l;
+ right = (const gtte *) r;
+
+ return left->ch - right->ch;
+}
+
+static int set_gototab(fa *f, int state, int ch, int val) /* hide gototab implementation */
+{
+ if ((unsigned)ch < GOTO_DIRECT) {
+ f->gototab[state].direct[ch] = val;
+ return val;
+ }
+
+ if (f->gototab[state].inuse == 0) {
+ f->gototab[state].entries[0].ch = ch;
+ f->gototab[state].entries[0].state = val;
+ f->gototab[state].inuse++;
+ return val;
+ } else if ((unsigned)ch > f->gototab[state].entries[f->gototab[state].inuse-1].ch) {
+ // not seen yet, insert and return
+ gtt *tab = & f->gototab[state];
+ if (tab->inuse + 1 >= tab->allocated)
+ resize_gototab(f, state);
+
+ f->gototab[state].entries[f->gototab[state].inuse].ch = ch;
+ f->gototab[state].entries[f->gototab[state].inuse].state = val;
+ f->gototab[state].inuse++;
+ return val;
+ } else {
+ // maybe we have it, maybe we don't
+ gtte key;
+ gtte *item;
+
+ key.ch = ch;
+ key.state = 0; /* irrelevant */
+ item = (gtte *) bsearch(& key, f->gototab[state].entries,
+ f->gototab[state].inuse, sizeof(gtte),
+ entry_cmp);
+
+ if (item != NULL) {
+ // we have it, update state and return
+ item->state = val;
+ return item->state;
+ }
+ // otherwise, fall through to insert and reallocate.
+ }
+
+ gtt *tab = & f->gototab[state];
+ if (tab->inuse + 1 >= tab->allocated)
+ resize_gototab(f, state);
+ f->gototab[state].entries[tab->inuse].ch = ch;
+ f->gototab[state].entries[tab->inuse].state = val;
+ ++tab->inuse;
+
+ qsort(f->gototab[state].entries,
+ f->gototab[state].inuse, sizeof(gtte), entry_cmp);
+
+ return val; /* not used anywhere at the moment */
+}
+
+static void clear_gototab(fa *f, int state)
+{
+ memset(f->gototab[state].direct, 0, sizeof(f->gototab[state].direct));
+ memset(f->gototab[state].entries, 0,
+ f->gototab[state].allocated * sizeof(gtte));
+ f->gototab[state].inuse = 0;
+}
+
+int match(fa *f, const char *p0) /* shortest match ? */
+{
+ int s, ns;
+ int n;
+ int rune;
+ const uschar *p = (const uschar *) p0;
+
+ /* return pmatch(f, p0); does it matter whether longest or shortest? */
+
+ s = f->initstat;
+ assert (s < f->state_count);
+
+ if (f->out[s])
+ return(1);
+ do {
+ /* assert(*p < NCHARS); */
+ n = u8_rune(&rune, (const char *) p);
+ if ((ns = get_gototab(f, s, rune)) != 0)
+ s = ns;
+ else
+ s = cgoto(f, s, rune);
+ if (f->out[s])
+ return(1);
+ if (*p == 0)
+ break;
+ p += n;
+ } while (1); /* was *p++ != 0 */
+ return(0);
+}
+
+int pmatch(fa *f, const char *p0) /* longest match, for sub */
+{
+ int s, ns;
+ int n;
+ int rune;
+ const uschar *p = (const uschar *) p0;
+ const uschar *q;
+
+ s = f->initstat;
+ assert(s < f->state_count);
+
+ patbeg = (const char *)p;
+ patlen = -1;
+ do {
+ q = p;
+ do {
+ if (f->out[s]) /* final state */
+ patlen = q-p;
+ /* assert(*q < NCHARS); */
+ n = u8_rune(&rune, (const char *) q);
+ if ((ns = get_gototab(f, s, rune)) != 0)
+ s = ns;
+ else
+ s = cgoto(f, s, rune);
+
+ assert(s < f->state_count);
+
+ if (s == 1) { /* no transition */
+ if (patlen >= 0) {
+ patbeg = (const char *) p;
+ return(1);
+ }
+ else
+ goto nextin; /* no match */
+ }
+ if (*q == 0)
+ break;
+ q += n;
+ } while (1);
+ q++; /* was *q++ */
+ if (f->out[s])
+ patlen = q-p-1; /* don't count $ */
+ if (patlen >= 0) {
+ patbeg = (const char *) p;
+ return(1);
+ }
+ nextin:
+ s = 2;
+ if (*p == 0)
+ break;
+ n = u8_rune(&rune, (const char *) p);
+ p += n;
+ } while (1); /* was *p++ */
+ return (0);
+}
+
+int nematch(fa *f, const char *p0) /* non-empty match, for sub */
+{
+ int s, ns;
+ int n;
+ int rune;
+ const uschar *p = (const uschar *) p0;
+ const uschar *q;
+
+ s = f->initstat;
+ assert(s < f->state_count);
+
+ patbeg = (const char *)p;
+ patlen = -1;
+ while (*p) {
+ q = p;
+ do {
+ if (f->out[s]) /* final state */
+ patlen = q-p;
+ /* assert(*q < NCHARS); */
+ n = u8_rune(&rune, (const char *) q);
+ if ((ns = get_gototab(f, s, rune)) != 0)
+ s = ns;
+ else
+ s = cgoto(f, s, rune);
+ if (s == 1) { /* no transition */
+ if (patlen > 0) {
+ patbeg = (const char *) p;
+ return(1);
+ } else
+ goto nnextin; /* no nonempty match */
+ }
+ if (*q == 0)
+ break;
+ q += n;
+ } while (1);
+ q++;
+ if (f->out[s])
+ patlen = q-p-1; /* don't count $ */
+ if (patlen > 0 ) {
+ patbeg = (const char *) p;
+ return(1);
+ }
+ nnextin:
+ s = 2;
+ p++;
+ }
+ return (0);
+}
+
+
+/*
+ * NAME
+ * fnematch
+ *
+ * DESCRIPTION
+ * A stream-fed version of nematch which transfers characters to a
+ * null-terminated buffer. All characters up to and including the last
+ * character of the matching text or EOF are placed in the buffer. If
+ * a match is found, patbeg and patlen are set appropriately.
+ *
+ * RETURN VALUES
+ * false No match found.
+ * true Match found.
+ */
+
+bool fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum)
+{
+ char *i, *j, *k, *buf = *pbuf;
+ int bufsize = *pbufsize;
+ int c, n, ns, s;
+
+ s = pfa->initstat;
+ patlen = 0;
+
+ /*
+ * buf <= i <= j <= k <= buf+bufsize
+ *
+ * i: origin of active substring
+ * j: current character
+ * k: destination of the next getc
+ */
+
+ i = j = k = buf;
+
+ do {
+ /*
+ * Call u8_rune with at least awk_mb_cur_max ahead in
+ * the buffer until EOF interferes.
+ */
+ if (k - j < (int)awk_mb_cur_max) {
+ if (k + awk_mb_cur_max > buf + bufsize) {
+ char *obuf = buf;
+ adjbuf((char **) &buf, &bufsize,
+ bufsize + awk_mb_cur_max,
+ quantum, 0, "fnematch");
+
+ /* buf resized, maybe moved. update pointers */
+ *pbufsize = bufsize;
+ if (obuf != buf) {
+ i = buf + (i - obuf);
+ j = buf + (j - obuf);
+ k = buf + (k - obuf);
+ *pbuf = buf;
+ if (patlen)
+ patbeg = buf + (patbeg - obuf);
+ }
+ }
+ for (n = awk_mb_cur_max ; n > 0; n--) {
+ *k++ = (c = getc(f)) != EOF ? c : 0;
+ if (c == EOF) {
+ if (ferror(f))
+ FATAL("fnematch: getc error");
+ break;
+ }
+ }
+ }
+
+ j += u8_rune(&c, j);
+
+ if ((ns = get_gototab(pfa, s, c)) != 0)
+ s = ns;
+ else
+ s = cgoto(pfa, s, c);
+
+ if (pfa->out[s]) { /* final state */
+ patbeg = i;
+ patlen = j - i;
+ if (c == 0) /* don't count $ */
+ patlen--;
+ }
+
+ if (c && s != 1)
+ continue; /* origin i still viable, next j */
+ if (patlen)
+ break; /* best match found */
+
+ /* no match at origin i, next i and start over */
+ i += u8_rune(&c, i);
+ if (c == 0)
+ break; /* no match */
+ j = i;
+ s = 2;
+ } while (1);
+
+ if (patlen) {
+ /*
+ * Under no circumstances is the last character fed to
+ * the automaton part of the match. It is EOF's nullbyte,
+ * or it sent the automaton into a state with no further
+ * transitions available (s==1), or both. Room for a
+ * terminating nullbyte is guaranteed.
+ *
+ * ungetc any chars after the end of matching text
+ * (except for EOF's nullbyte, if present) and null
+ * terminate the buffer.
+ */
+ do
+ if (*--k && ungetc(*k, f) == EOF)
+ FATAL("unable to ungetc '%c'", *k);
+ while (k > patbeg + patlen);
+ *k = '\0';
+ return true;
+ }
+ else
+ return false;
+}
+
+Node *reparse(const char *p) /* parses regular expression pointed to by p */
+{ /* uses relex() to scan regular expression */
+ Node *np;
+
+ DPRINTF("reparse <%s>\n", p);
+ lastre = prestr = (const uschar *) p; /* prestr points to string to be parsed */
+ rtok = relex();
+ /* GNU compatibility: an empty regexp matches anything */
+ if (rtok == '\0') {
+ /* FATAL("empty regular expression"); previous */
+ return(op2(EMPTYRE, NIL, NIL));
+ }
+ np = regexp();
+ if (rtok != '\0')
+ FATAL("syntax error in regular expression %s at %s", lastre, prestr);
+ return(np);
+}
+
+Node *regexp(void) /* top-level parse of reg expr */
+{
+ return (alt(concat(primary())));
+}
+
+Node *primary(void)
+{
+ Node *np;
+ int savelastatom;
+
+ switch (rtok) {
+ case CHAR:
+ lastatom = starttok;
+ np = op2(CHAR, NIL, itonp(rlxval));
+ rtok = relex();
+ return (unary(np));
+ case ALL:
+ rtok = relex();
+ return (unary(op2(ALL, NIL, NIL)));
+ case EMPTYRE:
+ rtok = relex();
+ return (unary(op2(EMPTYRE, NIL, NIL)));
+ case DOT:
+ lastatom = starttok;
+ rtok = relex();
+ return (unary(op2(DOT, NIL, NIL)));
+ case CCL:
+ np = op2(CCL, NIL, (Node*) cclenter((const char *) rlxstr));
+ lastatom = starttok;
+ rtok = relex();
+ return (unary(np));
+ case NCCL:
+ np = op2(NCCL, NIL, (Node *) cclenter((const char *) rlxstr));
+ lastatom = starttok;
+ rtok = relex();
+ return (unary(np));
+ case '^':
+ rtok = relex();
+ return (unary(op2(CHAR, NIL, itonp(HAT))));
+ case '$':
+ rtok = relex();
+ return (unary(op2(CHAR, NIL, NIL)));
+ case '(':
+ lastatom = starttok;
+ savelastatom = starttok - basestr; /* Retain over recursion */
+ rtok = relex();
+ if (rtok == ')') { /* special pleading for () */
+ rtok = relex();
+ return unary(op2(CCL, NIL, (Node *) cclenter("")));
+ }
+ np = regexp();
+ if (rtok == ')') {
+ lastatom = basestr + savelastatom; /* Restore */
+ rtok = relex();
+ return (unary(np));
+ }
+ else {
+ FATAL("syntax error in regular expression %s at %s", lastre, prestr);
+ break;
+ }
+ default:
+ FATAL("illegal primary in regular expression %s at %s", lastre, prestr);
+ }
+ return 0; /*NOTREACHED*/
+}
+
+Node *concat(Node *np)
+{
+ switch (rtok) {
+ case CHAR: case DOT: case ALL: case CCL: case NCCL: case '$': case '(':
+ return (concat(op2(CAT, np, primary())));
+ case EMPTYRE:
+ rtok = relex();
+ return (concat(op2(CAT, op2(CCL, NIL, (Node *) cclenter("")),
+ primary())));
+ }
+ return (np);
+}
+
+Node *alt(Node *np)
+{
+ if (rtok == OR) {
+ rtok = relex();
+ return (alt(op2(OR, np, concat(primary()))));
+ }
+ return (np);
+}
+
+Node *unary(Node *np)
+{
+ switch (rtok) {
+ case STAR:
+ rtok = relex();
+ return (unary(op2(STAR, np, NIL)));
+ case PLUS:
+ rtok = relex();
+ return (unary(op2(PLUS, np, NIL)));
+ case QUEST:
+ rtok = relex();
+ return (unary(op2(QUEST, np, NIL)));
+ case ZERO:
+ rtok = relex();
+ return (unary(op2(ZERO, np, NIL)));
+ default:
+ return (np);
+ }
+}
+
+/*
+ * Character class definitions conformant to the POSIX locale as
+ * defined in IEEE P1003.1 draft 7 of June 2001, assuming the source
+ * and operating character sets are both ASCII (ISO646) or supersets
+ * thereof.
+ *
+ * Note that to avoid overflowing the temporary buffer used in
+ * relex(), the expanded character class (prior to range expansion)
+ * must be less than twice the size of their full name.
+ */
+
+/* Because isblank doesn't show up in any of the header files on any
+ * system i use, it's defined here. if some other locale has a richer
+ * definition of "blank", define HAS_ISBLANK and provide your own
+ * version.
+ * the parentheses here are an attempt to find a path through the maze
+ * of macro definition and/or function and/or version provided. thanks
+ * to nelson beebe for the suggestion; let's see if it works everywhere.
+ */
+
+/* #define HAS_ISBLANK */
+#ifndef HAS_ISBLANK
+
+int (xisblank)(int c)
+{
+ return c==' ' || c=='\t';
+}
+
+#endif
+
+static const struct charclass {
+ const char *cc_name;
+ int cc_namelen;
+ int (*cc_func)(int);
+} charclasses[] = {
+ { "alnum", 5, isalnum },
+ { "alpha", 5, isalpha },
+#ifndef HAS_ISBLANK
+ { "blank", 5, xisblank },
+#else
+ { "blank", 5, isblank },
+#endif
+ { "cntrl", 5, iscntrl },
+ { "digit", 5, isdigit },
+ { "graph", 5, isgraph },
+ { "lower", 5, islower },
+ { "print", 5, isprint },
+ { "punct", 5, ispunct },
+ { "space", 5, isspace },
+ { "upper", 5, isupper },
+ { "xdigit", 6, isxdigit },
+ { NULL, 0, NULL },
+};
+
+#define REPEAT_SIMPLE 0
+#define REPEAT_PLUS_APPENDED 1
+#define REPEAT_WITH_Q 2
+#define REPEAT_ZERO 3
+
+static int
+replace_repeat(const uschar *reptok, int reptoklen, const uschar *atom,
+ int atomlen, int firstnum, int secondnum, int special_case)
+{
+ int i, j;
+ uschar *buf = 0;
+ int ret = 1;
+ int init_q = (firstnum == 0); /* first added char will be ? */
+ int n_q_reps = secondnum-firstnum; /* m>n, so reduce until {1,m-n} left */
+ int prefix_length = reptok - basestr; /* prefix includes first rep */
+ int suffix_length = strlen((const char *) reptok) - reptoklen; /* string after rep specifier */
+ int size = prefix_length + suffix_length;
+
+ if (firstnum > 1) { /* add room for reps 2 through firstnum */
+ size += atomlen*(firstnum-1);
+ }
+
+ /* Adjust size of buffer for special cases */
+ if (special_case == REPEAT_PLUS_APPENDED) {
+ size++; /* for the final + */
+ } else if (special_case == REPEAT_WITH_Q) {
+ size += init_q + (atomlen+1)* (n_q_reps-init_q);
+ } else if (special_case == REPEAT_ZERO) {
+ size += 2; /* just a null ERE: () */
+ }
+ if ((buf = (uschar *) malloc(size + 1)) == NULL)
+ FATAL("out of space in reg expr %.10s..", lastre);
+ memcpy(buf, basestr, prefix_length); /* copy prefix */
+ j = prefix_length;
+ if (special_case == REPEAT_ZERO) {
+ j -= atomlen;
+ buf[j++] = '(';
+ buf[j++] = ')';
+ }
+ for (i = 1; i < firstnum; i++) { /* copy x reps */
+ memcpy(&buf[j], atom, atomlen);
+ j += atomlen;
+ }
+ if (special_case == REPEAT_PLUS_APPENDED) {
+ buf[j++] = '+';
+ } else if (special_case == REPEAT_WITH_Q) {
+ if (init_q)
+ buf[j++] = '?';
+ for (i = init_q; i < n_q_reps; i++) { /* copy x? reps */
+ memcpy(&buf[j], atom, atomlen);
+ j += atomlen;
+ buf[j++] = '?';
+ }
+ }
+ memcpy(&buf[j], reptok+reptoklen, suffix_length);
+ j += suffix_length;
+ buf[j] = '\0';
+ /* free old basestr */
+ if (firstbasestr != basestr) {
+ if (basestr)
+ xfree(basestr);
+ }
+ basestr = buf;
+ prestr = buf + prefix_length;
+ if (special_case == REPEAT_ZERO) {
+ prestr -= atomlen;
+ ret++;
+ }
+ return ret;
+}
+
+static int repeat(const uschar *reptok, int reptoklen, const uschar *atom,
+ int atomlen, int firstnum, int secondnum)
+{
+ if (atom == NULL)
+ return 0;
+
+ /*
+ In general, the repetition specifier or "bound" is replaced here
+ by an equivalent ERE string, repeating the immediately previous atom
+ and appending ? and + as needed. Note that the first copy of the
+ atom is left in place, except in the special_case of a zero-repeat
+ (i.e., {0}).
+ */
+ if (secondnum < 0) { /* means {n,} -> repeat n-1 times followed by PLUS */
+ if (firstnum < 2) {
+ /* 0 or 1: should be handled before you get here */
+ FATAL("internal error");
+ } else {
+ return replace_repeat(reptok, reptoklen, atom, atomlen,
+ firstnum, secondnum, REPEAT_PLUS_APPENDED);
+ }
+ } else if (firstnum == secondnum) { /* {n} or {n,n} -> simply repeat n-1 times */
+ if (firstnum == 0) { /* {0} or {0,0} */
+ /* This case is unusual because the resulting
+ replacement string might actually be SMALLER than
+ the original ERE */
+ return replace_repeat(reptok, reptoklen, atom, atomlen,
+ firstnum, secondnum, REPEAT_ZERO);
+ } else { /* (firstnum >= 1) */
+ return replace_repeat(reptok, reptoklen, atom, atomlen,
+ firstnum, secondnum, REPEAT_SIMPLE);
+ }
+ } else if (firstnum < secondnum) { /* {n,m} -> repeat n-1 times then alternate */
+ /* x{n,m} => xx...x{1, m-n+1} => xx...x?x?x?..x? */
+ return replace_repeat(reptok, reptoklen, atom, atomlen,
+ firstnum, secondnum, REPEAT_WITH_Q);
+ } else { /* Error - shouldn't be here (n>m) */
+ FATAL("internal error");
+ }
+ return 0;
+}
+
+int relex(void) /* lexical analyzer for reparse */
+{
+ int c, n;
+ int cflag;
+ static uschar *buf = NULL;
+ static int bufsz = 100;
+ uschar *bp;
+ const struct charclass *cc;
+ int i;
+ int num, m;
+ bool commafound, digitfound;
+ const uschar *startreptok;
+ static int parens = 0;
+
+rescan:
+ starttok = prestr;
+
+ if ((n = u8_rune(&rlxval, (const char *) prestr)) > 1) {
+ prestr += n;
+ starttok = prestr;
+ return CHAR;
+ }
+
+ switch (c = *prestr++) {
+ case '|': return OR;
+ case '*': return STAR;
+ case '+': return PLUS;
+ case '?': return QUEST;
+ case '.': return DOT;
+ case '\0': prestr--; return '\0';
+ case '^':
+ case '$':
+ return c;
+ case '(':
+ parens++;
+ return c;
+ case ')':
+ if (parens) {
+ parens--;
+ return c;
+ }
+ /* unmatched close parenthesis; per POSIX, treat as literal */
+ rlxval = c;
+ return CHAR;
+ case '\\':
+ rlxval = quoted(&prestr);
+ return CHAR;
+ default:
+ rlxval = c;
+ return CHAR;
+ case '[':
+ if (buf == NULL && (buf = (uschar *) malloc(bufsz)) == NULL)
+ FATAL("out of space in reg expr %.10s..", lastre);
+ bp = buf;
+ if (*prestr == '^') {
+ cflag = 1;
+ prestr++;
+ }
+ else
+ cflag = 0;
+ n = 5 * strlen((const char *) prestr)+1; /* BUG: was 2. what value? */
+ if (!adjbuf((char **) &buf, &bufsz, n, n, (char **) &bp, "relex1"))
+ FATAL("out of space for reg expr %.10s...", lastre);
+ for (; ; ) {
+ if ((n = u8_rune(&rlxval, (const char *) prestr)) > 1) {
+ for (i = 0; i < n; i++)
+ *bp++ = *prestr++;
+ continue;
+ }
+ if ((c = *prestr++) == '\\') {
+ *bp++ = '\\';
+ if ((c = *prestr++) == '\0')
+ FATAL("nonterminated character class %.20s...", lastre);
+ *bp++ = c;
+ /* } else if (c == '\n') { */
+ /* FATAL("newline in character class %.20s...", lastre); */
+ } else if (c == '[' && *prestr == ':') {
+ /* POSIX char class names, Dag-Erling Smorgrav, des@ofug.org */
+ for (cc = charclasses; cc->cc_name; cc++)
+ if (strncmp((const char *) prestr + 1, (const char *) cc->cc_name, cc->cc_namelen) == 0)
+ break;
+ if (cc->cc_name != NULL && prestr[1 + cc->cc_namelen] == ':' &&
+ prestr[2 + cc->cc_namelen] == ']') {
+ prestr += cc->cc_namelen + 3;
+ /*
+ * BUG: We begin at 1, instead of 0, since we
+ * would otherwise prematurely terminate the
+ * string for classes like [[:cntrl:]]. This
+ * means that we can't match the NUL character,
+ * not without first adapting the entire
+ * program to track each string's length.
+ */
+ for (i = 1; i <= UCHAR_MAX; i++) {
+ if (!adjbuf((char **) &buf, &bufsz, bp-buf+2, 100, (char **) &bp, "relex2"))
+ FATAL("out of space for reg expr %.10s...", lastre);
+ if (cc->cc_func(i)) {
+ /* escape backslash */
+ if (i == '\\') {
+ *bp++ = '\\';
+ n++;
+ }
+
+ *bp++ = i;
+ n++;
+ }
+ }
+ } else
+ *bp++ = c;
+ } else if (c == '[' && *prestr == '.') {
+ char collate_char;
+ prestr++;
+ collate_char = *prestr++;
+ if (*prestr == '.' && prestr[1] == ']') {
+ prestr += 2;
+ /* Found it: map via locale TBD: for
+ now, simply return this char. This
+ is sufficient to pass conformance
+ test awk.ex 156
+ */
+ if (*prestr == ']') {
+ prestr++;
+ rlxval = collate_char;
+ return CHAR;
+ }
+ }
+ } else if (c == '[' && *prestr == '=') {
+ char equiv_char;
+ prestr++;
+ equiv_char = *prestr++;
+ if (*prestr == '=' && prestr[1] == ']') {
+ prestr += 2;
+ /* Found it: map via locale TBD: for now
+ simply return this char. This is
+ sufficient to pass conformance test
+ awk.ex 156
+ */
+ if (*prestr == ']') {
+ prestr++;
+ rlxval = equiv_char;
+ return CHAR;
+ }
+ }
+ } else if (c == '\0') {
+ FATAL("nonterminated character class %.20s", lastre);
+ } else if (bp == buf) { /* 1st char is special */
+ *bp++ = c;
+ } else if (c == ']') {
+ *bp++ = 0;
+ rlxstr = (uschar *) tostring((char *) buf);
+ if (cflag == 0)
+ return CCL;
+ else
+ return NCCL;
+ } else
+ *bp++ = c;
+ }
+ break;
+ case '{':
+ if (isdigit((int) *(prestr))) {
+ num = 0; /* Process as a repetition */
+ n = -1; m = -1;
+ commafound = false;
+ digitfound = false;
+ startreptok = prestr-1;
+ /* Remember start of previous atom here ? */
+ } else { /* just a { char, not a repetition */
+ rlxval = c;
+ return CHAR;
+ }
+ for (; ; ) {
+ if ((c = *prestr++) == '}') {
+ if (commafound) {
+ if (digitfound) { /* {n,m} */
+ m = num;
+ if (m < n)
+ FATAL("illegal repetition expression: class %.20s",
+ lastre);
+ if (n == 0 && m == 1) {
+ return QUEST;
+ }
+ } else { /* {n,} */
+ if (n == 0)
+ return STAR;
+ else if (n == 1)
+ return PLUS;
+ }
+ } else {
+ if (digitfound) { /* {n} same as {n,n} */
+ n = num;
+ m = num;
+ } else { /* {} */
+ FATAL("illegal repetition expression: class %.20s",
+ lastre);
+ }
+ }
+ if (repeat(starttok, prestr-starttok, lastatom,
+ startreptok - lastatom, n, m) > 0) {
+ if (n == 0 && m == 0) {
+ return ZERO;
+ }
+ /* must rescan input for next token */
+ goto rescan;
+ }
+ /* Failed to replace: eat up {...} characters
+ and treat like just PLUS */
+ return PLUS;
+ } else if (c == '\0') {
+ FATAL("nonterminated character class %.20s",
+ lastre);
+ } else if (isdigit(c)) {
+ num = 10 * num + c - '0';
+ if (num > 255)
+ FATAL("repetition count %.20s too large",
+ lastre);
+ digitfound = true;
+ } else if (c == ',') {
+ if (commafound)
+ FATAL("illegal repetition expression: class %.20s",
+ lastre);
+ /* looking for {n,} or {n,m} */
+ commafound = true;
+ n = num;
+ digitfound = false; /* reset */
+ num = 0;
+ } else {
+ FATAL("illegal repetition expression: class %.20s",
+ lastre);
+ }
+ }
+ break;
+ }
+}
+
+int cgoto(fa *f, int s, int c)
+{
+ int *p, *q;
+ int i, j, k;
+
+ /* assert(c == HAT || c < NCHARS); BUG: seg fault if disable test */
+ while (f->accept >= maxsetvec) { /* guessing here! */
+ resizesetvec(__func__);
+ }
+ for (i = 0; i <= f->accept; i++)
+ setvec[i] = 0;
+ setcnt = 0;
+ resize_state(f, s);
+ /* compute positions of gototab[s,c] into setvec */
+ p = f->posns[s];
+ for (i = 1; i <= *p; i++) {
+ if ((k = f->re[p[i]].ltype) != FINAL) {
+ if ((k == CHAR && c == ptoi(f->re[p[i]].lval.np))
+ || (k == DOT && c != 0 && c != HAT)
+ || (k == ALL && c != 0)
+ || (k == EMPTYRE && c != 0)
+ || (k == CCL && member(c, (int *) f->re[p[i]].lval.rp))
+ || (k == NCCL && !member(c, (int *) f->re[p[i]].lval.rp) && c != 0 && c != HAT)) {
+ q = f->re[p[i]].lfollow;
+ for (j = 1; j <= *q; j++) {
+ if (q[j] >= maxsetvec) {
+ resizesetvec(__func__);
+ }
+ if (setvec[q[j]] == 0) {
+ setcnt++;
+ setvec[q[j]] = 1;
+ }
+ }
+ }
+ }
+ }
+ /* determine if setvec is a previous state */
+ tmpset[0] = setcnt;
+ j = 1;
+ for (i = f->accept; i >= 0; i--)
+ if (setvec[i]) {
+ tmpset[j++] = i;
+ }
+ resize_state(f, f->curstat > s ? f->curstat : s);
+ /* tmpset == previous state? */
+ for (i = 1; i <= f->curstat; i++) {
+ p = f->posns[i];
+ if ((k = tmpset[0]) != p[0])
+ goto different;
+ for (j = 1; j <= k; j++)
+ if (tmpset[j] != p[j])
+ goto different;
+ /* setvec is state i */
+ if (c != HAT)
+ set_gototab(f, s, c, i);
+ return i;
+ different:;
+ }
+
+ /* add tmpset to current set of states */
+ ++(f->curstat);
+ resize_state(f, f->curstat);
+ clear_gototab(f, f->curstat);
+ xfree(f->posns[f->curstat]);
+ p = intalloc(setcnt + 1, __func__);
+
+ f->posns[f->curstat] = p;
+ if (c != HAT)
+ set_gototab(f, s, c, f->curstat);
+ for (i = 0; i <= setcnt; i++)
+ p[i] = tmpset[i];
+ if (setvec[f->accept])
+ f->out[f->curstat] = 1;
+ else
+ f->out[f->curstat] = 0;
+ return f->curstat;
+}
+
+
+void freefa(fa *f) /* free a finite automaton */
+{
+ int i;
+
+ if (f == NULL)
+ return;
+ for (i = 0; i < f->state_count; i++)
+ xfree(f->gototab[i].entries);
+ xfree(f->gototab);
+ for (i = 0; i <= f->curstat; i++)
+ xfree(f->posns[i]);
+ for (i = 0; i <= f->accept; i++) {
+ xfree(f->re[i].lfollow);
+ if (f->re[i].ltype == CCL || f->re[i].ltype == NCCL)
+ xfree(f->re[i].lval.np);
+ }
+ xfree(f->restr);
+ xfree(f->out);
+ xfree(f->posns);
+ xfree(f->gototab);
+ xfree(f);
+}
diff --git a/cmd/posix/awk/lex.c b/cmd/posix/awk/lex.c
@@ -0,0 +1,630 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "awk.h"
+#include "awkgram.tab.h"
+
+extern YYSTYPE yylval;
+extern bool infunc;
+
+int lineno = 1;
+int bracecnt = 0;
+int brackcnt = 0;
+int parencnt = 0;
+
+typedef struct Keyword {
+ const char *word;
+ int sub;
+ int type;
+} Keyword;
+
+const Keyword keywords[] = { /* keep sorted: binary searched */
+ { "BEGIN", XBEGIN, XBEGIN },
+ { "END", XEND, XEND },
+ { "NF", VARNF, VARNF },
+ { "atan2", FATAN, BLTIN },
+ { "break", BREAK, BREAK },
+ { "close", CLOSE, CLOSE },
+ { "continue", CONTINUE, CONTINUE },
+ { "cos", FCOS, BLTIN },
+ { "delete", DELETE, DELETE },
+ { "do", DO, DO },
+ { "else", ELSE, ELSE },
+ { "exit", EXIT, EXIT },
+ { "exp", FEXP, BLTIN },
+ { "fflush", FFLUSH, BLTIN },
+ { "for", FOR, FOR },
+ { "func", FUNC, FUNC },
+ { "function", FUNC, FUNC },
+ { "getline", GETLINE, GETLINE },
+ { "gsub", GSUB, GSUB },
+ { "if", IF, IF },
+ { "in", IN, IN },
+ { "index", INDEX, INDEX },
+ { "int", FINT, BLTIN },
+ { "length", FLENGTH, BLTIN },
+ { "log", FLOG, BLTIN },
+ { "match", MATCHFCN, MATCHFCN },
+ { "next", NEXT, NEXT },
+ { "nextfile", NEXTFILE, NEXTFILE },
+ { "print", PRINT, PRINT },
+ { "printf", PRINTF, PRINTF },
+ { "rand", FRAND, BLTIN },
+ { "return", RETURN, RETURN },
+ { "sin", FSIN, BLTIN },
+ { "split", SPLIT, SPLIT },
+ { "sprintf", SPRINTF, SPRINTF },
+ { "sqrt", FSQRT, BLTIN },
+ { "srand", FSRAND, BLTIN },
+ { "sub", SUB, SUB },
+ { "substr", SUBSTR, SUBSTR },
+ { "system", FSYSTEM, BLTIN },
+ { "tolower", FTOLOWER, BLTIN },
+ { "toupper", FTOUPPER, BLTIN },
+ { "while", WHILE, WHILE },
+};
+
+#define RET(x) { if(dbg)printf("lex %s\n", tokname(x)); return(x); }
+
+static int peek(void)
+{
+ int c = input();
+ unput(c);
+ return c;
+}
+
+static int gettok(char **pbuf, int *psz) /* get next input token */
+{
+ int c, retc;
+ char *buf = *pbuf;
+ int sz = *psz;
+ char *bp = buf;
+
+ c = input();
+ if (c == 0)
+ return 0;
+ buf[0] = c;
+ buf[1] = 0;
+ if (!isalnum(c) && c != '.' && c != '_')
+ return c;
+
+ *bp++ = c;
+ if (isalpha(c) || c == '_') { /* it's a varname */
+ for ( ; (c = input()) != 0; ) {
+ if (bp-buf >= sz)
+ if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok"))
+ FATAL( "out of space for name %.10s...", buf );
+ if (isalnum(c) || c == '_')
+ *bp++ = c;
+ else {
+ *bp = 0;
+ unput(c);
+ break;
+ }
+ }
+ *bp = 0;
+ retc = 'a'; /* alphanumeric */
+ } else { /* maybe it's a number, but could be . */
+ char *rem;
+ /* read input until can't be a number */
+ for ( ; (c = input()) != 0; ) {
+ if (bp-buf >= sz)
+ if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok"))
+ FATAL( "out of space for number %.10s...", buf );
+ if (isdigit(c) || c == 'e' || c == 'E'
+ || c == '.' || c == '+' || c == '-')
+ *bp++ = c;
+ else {
+ unput(c);
+ break;
+ }
+ }
+ *bp = 0;
+ strtod(buf, &rem); /* parse the number */
+ if (rem == buf) { /* it wasn't a valid number at all */
+ buf[1] = 0; /* return one character as token */
+ retc = (uschar)buf[0]; /* character is its own type */
+ unputstr(rem+1); /* put rest back for later */
+ } else { /* some prefix was a number */
+ unputstr(rem); /* put rest back for later */
+ rem[0] = 0; /* truncate buf after number part */
+ retc = '0'; /* type is number */
+ }
+ }
+ *pbuf = buf;
+ *psz = sz;
+ return retc;
+}
+
+int word(char *);
+int string(void);
+int regexpr(void);
+bool sc = false; /* true => return a } right now */
+bool reg = false; /* true => return a REGEXPR now */
+
+int yylex(void)
+{
+ int c;
+ static char *buf = NULL;
+ static int bufsize = 5; /* BUG: setting this small causes core dump! */
+
+ if (buf == NULL && (buf = (char *) malloc(bufsize)) == NULL)
+ FATAL( "out of space in yylex" );
+ if (sc) {
+ sc = false;
+ RET('}');
+ }
+ if (reg) {
+ reg = false;
+ return regexpr();
+ }
+ for (;;) {
+ c = gettok(&buf, &bufsize);
+ if (c == 0)
+ return 0;
+ if (isalpha(c) || c == '_')
+ return word(buf);
+ if (isdigit(c)) {
+ char *cp = tostring(buf);
+ double result;
+
+ if (is_number(cp, & result))
+ yylval.cp = setsymtab(buf, cp, result, CON|NUM, symtab);
+ else
+ yylval.cp = setsymtab(buf, cp, 0.0, STR, symtab);
+ free(cp);
+ /* should this also have STR set? */
+ RET(NUMBER);
+ }
+
+ yylval.i = c;
+ switch (c) {
+ case '\n': /* {EOL} */
+ lineno++;
+ RET(NL);
+ case '\r': /* assume \n is coming */
+ case ' ': /* {WS}+ */
+ case '\t':
+ break;
+ case '#': /* #.* strip comments */
+ while ((c = input()) != '\n' && c != 0)
+ ;
+ unput(c);
+ break;
+ case ';':
+ RET(';');
+ case '\\':
+ if (peek() == '\n') {
+ input();
+ lineno++;
+ } else if (peek() == '\r') {
+ input(); input(); /* \n */
+ lineno++;
+ } else {
+ RET(c);
+ }
+ break;
+ case '&':
+ if (peek() == '&') {
+ input(); RET(AND);
+ } else
+ RET('&');
+ case '|':
+ if (peek() == '|') {
+ input(); RET(BOR);
+ } else
+ RET('|');
+ case '!':
+ if (peek() == '=') {
+ input(); yylval.i = NE; RET(NE);
+ } else if (peek() == '~') {
+ input(); yylval.i = NOTMATCH; RET(MATCHOP);
+ } else
+ RET(NOT);
+ case '~':
+ yylval.i = MATCH;
+ RET(MATCHOP);
+ case '<':
+ if (peek() == '=') {
+ input(); yylval.i = LE; RET(LE);
+ } else {
+ yylval.i = LT; RET(LT);
+ }
+ case '=':
+ if (peek() == '=') {
+ input(); yylval.i = EQ; RET(EQ);
+ } else {
+ yylval.i = ASSIGN; RET(ASGNOP);
+ }
+ case '>':
+ if (peek() == '=') {
+ input(); yylval.i = GE; RET(GE);
+ } else if (peek() == '>') {
+ input(); yylval.i = APPEND; RET(APPEND);
+ } else {
+ yylval.i = GT; RET(GT);
+ }
+ case '+':
+ if (peek() == '+') {
+ input(); yylval.i = INCR; RET(INCR);
+ } else if (peek() == '=') {
+ input(); yylval.i = ADDEQ; RET(ASGNOP);
+ } else
+ RET('+');
+ case '-':
+ if (peek() == '-') {
+ input(); yylval.i = DECR; RET(DECR);
+ } else if (peek() == '=') {
+ input(); yylval.i = SUBEQ; RET(ASGNOP);
+ } else
+ RET('-');
+ case '*':
+ if (peek() == '=') { /* *= */
+ input(); yylval.i = MULTEQ; RET(ASGNOP);
+ } else if (peek() == '*') { /* ** or **= */
+ input(); /* eat 2nd * */
+ if (peek() == '=') {
+ input(); yylval.i = POWEQ; RET(ASGNOP);
+ } else {
+ RET(POWER);
+ }
+ } else
+ RET('*');
+ case '/':
+ RET('/');
+ case '%':
+ if (peek() == '=') {
+ input(); yylval.i = MODEQ; RET(ASGNOP);
+ } else
+ RET('%');
+ case '^':
+ if (peek() == '=') {
+ input(); yylval.i = POWEQ; RET(ASGNOP);
+ } else
+ RET(POWER);
+
+ case '$':
+ /* BUG: awkward, if not wrong */
+ c = gettok(&buf, &bufsize);
+ if (isalpha(c)) {
+ if (strcmp(buf, "NF") == 0) { /* very special */
+ unputstr("(NF)");
+ RET(INDIRECT);
+ }
+ c = peek();
+ if (c == '(' || c == '[' || (infunc && isarg(buf) >= 0)) {
+ unputstr(buf);
+ RET(INDIRECT);
+ }
+ yylval.cp = setsymtab(buf, "", 0.0, STR|NUM, symtab);
+ RET(IVAR);
+ } else if (c == 0) { /* */
+ SYNTAX( "unexpected end of input after $" );
+ RET(';');
+ } else {
+ unputstr(buf);
+ RET(INDIRECT);
+ }
+
+ case '}':
+ if (--bracecnt < 0)
+ SYNTAX( "extra }" );
+ sc = true;
+ RET(';');
+ case ']':
+ if (--brackcnt < 0)
+ SYNTAX( "extra ]" );
+ RET(']');
+ case ')':
+ if (--parencnt < 0)
+ SYNTAX( "extra )" );
+ RET(')');
+ case '{':
+ bracecnt++;
+ RET('{');
+ case '[':
+ brackcnt++;
+ RET('[');
+ case '(':
+ parencnt++;
+ RET('(');
+
+ case '"':
+ return string(); /* BUG: should be like tran.c ? */
+
+ default:
+ RET(c);
+ }
+ }
+}
+
+extern int runetochar(char *str, int c);
+
+int string(void)
+{
+ int c, n;
+ char *s, *bp;
+ static char *buf = NULL;
+ static int bufsz = 500;
+
+ if (buf == NULL && (buf = (char *) malloc(bufsz)) == NULL)
+ FATAL("out of space for strings");
+ for (bp = buf; (c = input()) != '"'; ) {
+ if (!adjbuf(&buf, &bufsz, bp-buf+2, 500, &bp, "string"))
+ FATAL("out of space for string %.10s...", buf);
+ switch (c) {
+ case '\n':
+ case '\r':
+ case 0:
+ *bp = '\0';
+ SYNTAX( "non-terminated string %.10s...", buf );
+ if (c == 0) /* hopeless */
+ FATAL( "giving up" );
+ lineno++;
+ break;
+ case '\\':
+ c = input();
+ switch (c) {
+ case '\n': break;
+ case '"': *bp++ = '"'; break;
+ case 'n': *bp++ = '\n'; break;
+ case 't': *bp++ = '\t'; break;
+ case 'f': *bp++ = '\f'; break;
+ case 'r': *bp++ = '\r'; break;
+ case 'b': *bp++ = '\b'; break;
+ case 'v': *bp++ = '\v'; break;
+ case 'a': *bp++ = '\a'; break;
+ case '\\': *bp++ = '\\'; break;
+
+ case '0': case '1': case '2': /* octal: \d \dd \ddd */
+ case '3': case '4': case '5': case '6': case '7':
+ n = c - '0';
+ if ((c = peek()) >= '0' && c < '8') {
+ n = 8 * n + input() - '0';
+ if ((c = peek()) >= '0' && c < '8')
+ n = 8 * n + input() - '0';
+ }
+ *bp++ = n;
+ break;
+
+ case 'x': /* hex \x0-9a-fA-F (exactly two) */
+ {
+ int i;
+
+ if (!isxdigit(peek())) {
+ unput(c);
+ break;
+ }
+ n = 0;
+ for (i = 0; i < 2; i++) {
+ c = input();
+ if (c == 0)
+ break;
+ if (isxdigit(c)) {
+ c = tolower(c);
+ n *= 16;
+ if (isdigit(c))
+ n += (c - '0');
+ else
+ n += 10 + (c - 'a');
+ } else {
+ unput(c);
+ break;
+ }
+ }
+ if (i)
+ *bp++ = n;
+ break;
+ }
+
+ case 'u': /* utf \u0-9a-fA-F (1..8) */
+ {
+ int i;
+
+ n = 0;
+ for (i = 0; i < 8; i++) {
+ c = input();
+ if (!isxdigit(c) || c == 0)
+ break;
+ c = tolower(c);
+ n *= 16;
+ if (isdigit(c))
+ n += (c - '0');
+ else
+ n += 10 + (c - 'a');
+ }
+ unput(c);
+ bp += runetochar(bp, n);
+ break;
+ }
+
+ default:
+ *bp++ = c;
+ break;
+ }
+ break;
+ default:
+ *bp++ = c;
+ break;
+ }
+ }
+ *bp = 0;
+ s = tostring(buf);
+ *bp++ = ' '; *bp++ = '\0';
+ yylval.cp = setsymtab(buf, s, 0.0, CON|STR|DONTFREE, symtab);
+ free(s);
+ RET(STRING);
+}
+
+
+static int binsearch(char *w, const Keyword *kp, int n)
+{
+ int cond, low, mid, high;
+
+ low = 0;
+ high = n - 1;
+ while (low <= high) {
+ mid = (low + high) / 2;
+ if ((cond = strcmp(w, kp[mid].word)) < 0)
+ high = mid - 1;
+ else if (cond > 0)
+ low = mid + 1;
+ else
+ return mid;
+ }
+ return -1;
+}
+
+int word(char *w)
+{
+ const Keyword *kp;
+ int c, n;
+
+ n = binsearch(w, keywords, sizeof(keywords)/sizeof(keywords[0]));
+ if (n != -1) { /* found in table */
+ kp = keywords + n;
+ yylval.i = kp->sub;
+ switch (kp->type) { /* special handling */
+ case BLTIN:
+ if (kp->sub == FSYSTEM && safe)
+ SYNTAX( "system is unsafe" );
+ RET(kp->type);
+ case FUNC:
+ if (infunc)
+ SYNTAX( "illegal nested function" );
+ RET(kp->type);
+ case RETURN:
+ if (!infunc)
+ SYNTAX( "return not in function" );
+ RET(kp->type);
+ case VARNF:
+ yylval.cp = setsymtab("NF", "", 0.0, NUM, symtab);
+ RET(VARNF);
+ default:
+ RET(kp->type);
+ }
+ }
+ c = peek(); /* look for '(' */
+ if (c != '(' && infunc && (n=isarg(w)) >= 0) {
+ yylval.i = n;
+ RET(ARG);
+ } else {
+ yylval.cp = setsymtab(w, "", 0.0, STR|NUM|DONTFREE, symtab);
+ if (c == '(') {
+ RET(CALL);
+ } else {
+ RET(VAR);
+ }
+ }
+}
+
+void startreg(void) /* next call to yylex will return a regular expression */
+{
+ reg = true;
+}
+
+int regexpr(void)
+{
+ int c;
+ static char *buf = NULL;
+ static int bufsz = 500;
+ char *bp;
+
+ if (buf == NULL && (buf = (char *) malloc(bufsz)) == NULL)
+ FATAL("out of space for reg expr");
+ bp = buf;
+ for ( ; (c = input()) != '/' && c != 0; ) {
+ if (!adjbuf(&buf, &bufsz, bp-buf+3, 500, &bp, "regexpr"))
+ FATAL("out of space for reg expr %.10s...", buf);
+ if (c == '\n') {
+ *bp = '\0';
+ SYNTAX( "newline in regular expression %.10s...", buf );
+ unput('\n');
+ break;
+ } else if (c == '\\') {
+ *bp++ = '\\';
+ *bp++ = input();
+ } else {
+ *bp++ = c;
+ }
+ }
+ *bp = 0;
+ if (c == 0)
+ SYNTAX("non-terminated regular expression %.10s...", buf);
+ yylval.s = tostring(buf);
+ unput('/');
+ RET(REGEXPR);
+}
+
+/* low-level lexical stuff, sort of inherited from lex */
+
+char ebuf[300];
+char *ep = ebuf;
+char yysbuf[100]; /* pushback buffer */
+char *yysptr = yysbuf;
+FILE *yyin = NULL;
+
+int input(void) /* get next lexical input character */
+{
+ int c;
+ extern char *lexprog;
+
+ if (yysptr > yysbuf)
+ c = (uschar)*--yysptr;
+ else if (lexprog != NULL) { /* awk '...' */
+ if ((c = (uschar)*lexprog) != 0)
+ lexprog++;
+ } else /* awk -f ... */
+ c = pgetc();
+ if (c == EOF)
+ c = 0;
+ if (ep >= ebuf + sizeof ebuf)
+ ep = ebuf;
+ *ep = c;
+ if (c != 0) {
+ ep++;
+ }
+ return (c);
+}
+
+void unput(int c) /* put lexical character back on input */
+{
+ if (yysptr >= yysbuf + sizeof(yysbuf))
+ FATAL("pushed back too much: %.20s...", yysbuf);
+ *yysptr++ = c;
+ if (--ep < ebuf)
+ ep = ebuf + sizeof(ebuf) - 1;
+}
+
+void unputstr(const char *s) /* put a string back on input */
+{
+ int i;
+
+ for (i = strlen(s)-1; i >= 0; i--)
+ unput(s[i]);
+}
diff --git a/cmd/posix/awk/lib.c b/cmd/posix/awk/lib.c
@@ -0,0 +1,921 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#define DEBUG
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <limits.h>
+#include <math.h>
+#include "awk.h"
+
+extern int u8_nextlen(const char *s);
+
+char EMPTY[] = { '\0' };
+FILE *infile = NULL;
+bool innew; /* true = infile has not been read by readrec */
+char *file = EMPTY;
+char *record;
+int recsize = RECSIZE;
+char *fields;
+int fieldssize = RECSIZE;
+
+Cell **fldtab; /* pointers to Cells */
+static size_t len_inputFS = 0;
+static char *inputFS = NULL; /* FS at time of input, for field splitting */
+
+#define MAXFLD 2
+int nfields = MAXFLD; /* last allocated slot for $i */
+
+bool donefld; /* true = implies rec broken into fields */
+bool donerec; /* true = record is valid (no flds have changed) */
+
+int lastfld = 0; /* last used field */
+int argno = 1; /* current input argument number */
+extern Awkfloat *ARGC;
+
+static Cell dollar0 = { OCELL, CFLD, NULL, EMPTY, 0.0, REC|STR|DONTFREE, NULL, NULL };
+static Cell dollar1 = { OCELL, CFLD, NULL, EMPTY, 0.0, FLD|STR|DONTFREE, NULL, NULL };
+
+void recinit(unsigned int n)
+{
+ if ( (record = (char *) malloc(n)) == NULL
+ || (fields = (char *) malloc(n+1)) == NULL
+ || (fldtab = (Cell **) calloc(nfields+2, sizeof(*fldtab))) == NULL
+ || (fldtab[0] = (Cell *) malloc(sizeof(**fldtab))) == NULL)
+ FATAL("out of space for $0 and fields");
+ *record = '\0';
+ *fldtab[0] = dollar0;
+ fldtab[0]->sval = record;
+ fldtab[0]->nval = tostring("0");
+ makefields(1, nfields);
+}
+
+void makefields(int n1, int n2) /* create $n1..$n2 inclusive */
+{
+ char temp[50];
+ int i;
+
+ for (i = n1; i <= n2; i++) {
+ fldtab[i] = (Cell *) malloc(sizeof(**fldtab));
+ if (fldtab[i] == NULL)
+ FATAL("out of space in makefields %d", i);
+ *fldtab[i] = dollar1;
+ snprintf(temp, sizeof(temp), "%d", i);
+ fldtab[i]->nval = tostring(temp);
+ }
+}
+
+void initgetrec(void)
+{
+ int i;
+ char *p;
+
+ for (i = 1; i < *ARGC; i++) {
+ p = getargv(i); /* find 1st real filename */
+ if (p == NULL || *p == '\0') { /* deleted or zapped */
+ argno++;
+ continue;
+ }
+ if (!isclvar(p)) {
+ setsval(lookup("FILENAME", symtab), p);
+ return;
+ }
+ setclvar(p); /* a commandline assignment before filename */
+ argno++;
+ }
+ infile = stdin; /* no filenames, so use stdin */
+ innew = true;
+}
+
+/*
+ * POSIX specifies that fields are supposed to be evaluated as if they were
+ * split using the value of FS at the time that the record's value ($0) was
+ * read.
+ *
+ * Since field-splitting is done lazily, we save the current value of FS
+ * whenever a new record is read in (implicitly or via getline), or when
+ * a new value is assigned to $0.
+ */
+void savefs(void)
+{
+ size_t len;
+ if ((len = strlen(getsval(fsloc))) < len_inputFS) {
+ strcpy(inputFS, *FS); /* for subsequent field splitting */
+ return;
+ }
+
+ len_inputFS = len + 1;
+ inputFS = (char *) realloc(inputFS, len_inputFS);
+ if (inputFS == NULL)
+ FATAL("field separator %.10s... is too long", *FS);
+ memcpy(inputFS, *FS, len_inputFS);
+}
+
+static bool firsttime = true;
+
+int getrec(char **pbuf, int *pbufsize, bool isrecord) /* get next input record */
+{ /* note: cares whether buf == record */
+ int c;
+ char *buf = *pbuf;
+ uschar saveb0;
+ int bufsize = *pbufsize, savebufsize = bufsize;
+
+ if (firsttime) {
+ firsttime = false;
+ initgetrec();
+ }
+ DPRINTF("RS=<%s>, FS=<%s>, ARGC=%g, FILENAME=%s\n",
+ *RS, *FS, *ARGC, *FILENAME);
+ saveb0 = buf[0];
+ buf[0] = 0;
+ while (argno < *ARGC || infile == stdin) {
+ DPRINTF("argno=%d, file=|%s|\n", argno, file);
+ if (infile == NULL) { /* have to open a new file */
+ file = getargv(argno);
+ if (file == NULL || *file == '\0') { /* deleted or zapped */
+ argno++;
+ continue;
+ }
+ if (isclvar(file)) { /* a var=value arg */
+ setclvar(file);
+ argno++;
+ continue;
+ }
+ *FILENAME = file;
+ DPRINTF("opening file %s\n", file);
+ if (*file == '-' && *(file+1) == '\0')
+ infile = stdin;
+ else if ((infile = fopen(file, "r")) == NULL)
+ FATAL("can't open file %s", file);
+ innew = true;
+ setfval(fnrloc, 0.0);
+ }
+ c = readrec(&buf, &bufsize, infile, innew);
+ if (innew)
+ innew = false;
+ if (c != 0 || buf[0] != '\0') { /* normal record */
+ if (isrecord) {
+ double result;
+
+ if (freeable(fldtab[0]))
+ xfree(fldtab[0]->sval);
+ fldtab[0]->sval = buf; /* buf == record */
+ fldtab[0]->tval = REC | STR | DONTFREE;
+ if (is_number(fldtab[0]->sval, & result)) {
+ fldtab[0]->fval = result;
+ fldtab[0]->tval |= NUM;
+ }
+ donefld = false;
+ donerec = true;
+ savefs();
+ }
+ setfval(nrloc, nrloc->fval+1);
+ setfval(fnrloc, fnrloc->fval+1);
+ *pbuf = buf;
+ *pbufsize = bufsize;
+ return 1;
+ }
+ /* EOF arrived on this file; set up next */
+ if (infile != stdin)
+ fclose(infile);
+ infile = NULL;
+ argno++;
+ }
+ buf[0] = saveb0;
+ *pbuf = buf;
+ *pbufsize = savebufsize;
+ return 0; /* true end of file */
+}
+
+void nextfile(void)
+{
+ if (infile != NULL && infile != stdin)
+ fclose(infile);
+ infile = NULL;
+ argno++;
+}
+
+extern int readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag);
+
+int readrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* read one record into buf */
+{
+ int sep, c, isrec; // POTENTIAL BUG? isrec is a macro in awk.h
+ char *rr = *pbuf, *buf = *pbuf;
+ int bufsize = *pbufsize;
+ char *rs = getsval(rsloc);
+
+ if (CSV) {
+ c = readcsvrec(&buf, &bufsize, inf, newflag);
+ isrec = (c == EOF && rr == buf) ? false : true;
+ } else if (*rs && rs[1]) {
+ bool found;
+
+ memset(buf, 0, bufsize);
+ fa *pfa = makedfa(rs, 1);
+ if (newflag)
+ found = fnematch(pfa, inf, &buf, &bufsize, recsize);
+ else {
+ int tempstat = pfa->initstat;
+ pfa->initstat = 2;
+ found = fnematch(pfa, inf, &buf, &bufsize, recsize);
+ pfa->initstat = tempstat;
+ }
+ if (found)
+ setptr(patbeg, '\0');
+ isrec = (found == 0 && *buf == '\0') ? false : true;
+
+ } else {
+ if ((sep = *rs) == 0) {
+ sep = '\n';
+ while ((c=getc(inf)) == '\n' && c != EOF) /* skip leading \n's */
+ ;
+ if (c != EOF)
+ ungetc(c, inf);
+ }
+ for (rr = buf; ; ) {
+ for (; (c=getc(inf)) != sep && c != EOF; ) {
+ if (rr-buf+1 > bufsize)
+ if (!adjbuf(&buf, &bufsize, 1+rr-buf,
+ recsize, &rr, "readrec 1"))
+ FATAL("input record `%.30s...' too long", buf);
+ *rr++ = c;
+ }
+ if (*rs == sep || c == EOF)
+ break;
+ if ((c = getc(inf)) == '\n' || c == EOF) /* 2 in a row */
+ break;
+ if (!adjbuf(&buf, &bufsize, 2+rr-buf, recsize, &rr,
+ "readrec 2"))
+ FATAL("input record `%.30s...' too long", buf);
+ *rr++ = '\n';
+ *rr++ = c;
+ }
+ if (!adjbuf(&buf, &bufsize, 1+rr-buf, recsize, &rr, "readrec 3"))
+ FATAL("input record `%.30s...' too long", buf);
+ *rr = 0;
+ isrec = (c == EOF && rr == buf) ? false : true;
+ }
+ *pbuf = buf;
+ *pbufsize = bufsize;
+ DPRINTF("readrec saw <%s>, returns %d\n", buf, isrec);
+ return isrec;
+}
+
+
+/*******************
+ * loose ends here:
+ * \r\n should become \n
+ * what about bare \r? Excel uses that for embedded newlines
+ * can't have "" in unquoted fields, according to RFC 4180
+*/
+
+
+int readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* csv can have \n's */
+{ /* so read a complete record that might be multiple lines */
+ int sep, c;
+
+ (void)newflag;
+ char *rr = *pbuf, *buf = *pbuf;
+ int bufsize = *pbufsize;
+ bool in_quote = false;
+
+ sep = '\n'; /* the only separator; have to skip over \n embedded in "..." */
+ rr = buf;
+ while ((c = getc(inf)) != EOF) {
+ if (c == sep) {
+ if (! in_quote)
+ break;
+ if (rr > buf && rr[-1] == '\r') // remove \r if was \r\n
+ rr--;
+ }
+
+ if (rr-buf+1 > bufsize)
+ if (!adjbuf(&buf, &bufsize, 1+rr-buf,
+ recsize, &rr, "readcsvrec 1"))
+ FATAL("input record `%.30s...' too long", buf);
+ *rr++ = c;
+ if (c == '"')
+ in_quote = ! in_quote;
+ }
+ if (c == '\n' && rr > buf && rr[-1] == '\r') // remove \r if was \r\n
+ rr--;
+
+ if (!adjbuf(&buf, &bufsize, 1+rr-buf, recsize, &rr, "readcsvrec 4"))
+ FATAL("input record `%.30s...' too long", buf);
+ *rr = 0;
+ *pbuf = buf;
+ *pbufsize = bufsize;
+ DPRINTF("readcsvrec saw <%s>, returns %d\n", buf, c);
+ return c;
+}
+
+char *getargv(int n) /* get ARGV[n] */
+{
+ Array *ap;
+ Cell *x;
+ char *s, temp[50];
+ extern Cell *ARGVcell;
+
+ ap = (Array *)ARGVcell->sval;
+ snprintf(temp, sizeof(temp), "%d", n);
+ if (lookup(temp, ap) == NULL)
+ return NULL;
+ x = setsymtab(temp, "", 0.0, STR, ap);
+ s = getsval(x);
+ DPRINTF("getargv(%d) returns |%s|\n", n, s);
+ return s;
+}
+
+void setclvar(char *s) /* set var=value from s */
+{
+ char *e, *p;
+ Cell *q;
+ double result;
+
+/* commit f3d9187d4e0f02294fb1b0e31152070506314e67 broke T.argv test */
+/* I don't understand why it was changed. */
+
+ for (p=s; *p != '='; p++)
+ ;
+ e = p;
+ *p++ = 0;
+ p = qstring(p, '\0');
+ q = setsymtab(s, p, 0.0, STR, symtab);
+ setsval(q, p);
+ if (is_number(q->sval, & result)) {
+ q->fval = result;
+ q->tval |= NUM;
+ }
+ DPRINTF("command line set %s to |%s|\n", s, p);
+ free(p);
+ *e = '=';
+}
+
+
+void fldbld(void) /* create fields from current record */
+{
+ /* this relies on having fields[] the same length as $0 */
+ /* the fields are all stored in this one array with \0's */
+ /* possibly with a final trailing \0 not associated with any field */
+ char *r, *fr, sep;
+ Cell *p;
+ int i, j, n;
+
+ if (donefld)
+ return;
+ if (!isstr(fldtab[0]))
+ getsval(fldtab[0]);
+ r = fldtab[0]->sval;
+ n = strlen(r);
+ if (n > fieldssize) {
+ xfree(fields);
+ if ((fields = (char *) malloc(n+2)) == NULL) /* possibly 2 final \0s */
+ FATAL("out of space for fields in fldbld %d", n);
+ fieldssize = n;
+ }
+ fr = fields;
+ i = 0; /* number of fields accumulated here */
+ if (inputFS == NULL) /* make sure we have a copy of FS */
+ savefs();
+ if (!CSV && strlen(inputFS) > 1) { /* it's a regular expression */
+ i = refldbld(r, inputFS);
+ } else if (!CSV && (sep = *inputFS) == ' ') { /* default whitespace */
+ for (i = 0; ; ) {
+ while (*r == ' ' || *r == '\t' || *r == '\n')
+ r++;
+ if (*r == 0)
+ break;
+ i++;
+ if (i > nfields)
+ growfldtab(i);
+ if (freeable(fldtab[i]))
+ xfree(fldtab[i]->sval);
+ fldtab[i]->sval = fr;
+ fldtab[i]->tval = FLD | STR | DONTFREE;
+ do
+ *fr++ = *r++;
+ while (*r != ' ' && *r != '\t' && *r != '\n' && *r != '\0');
+ *fr++ = 0;
+ }
+ *fr = 0;
+ } else if (CSV) { /* CSV processing. no error handling */
+ if (*r != 0) {
+ for (;;) {
+ i++;
+ if (i > nfields)
+ growfldtab(i);
+ if (freeable(fldtab[i]))
+ xfree(fldtab[i]->sval);
+ fldtab[i]->sval = fr;
+ fldtab[i]->tval = FLD | STR | DONTFREE;
+ if (*r == '"' ) { /* start of "..." */
+ for (r++ ; *r != '\0'; ) {
+ if (*r == '"' && r[1] != '\0' && r[1] == '"') {
+ r += 2; /* doubled quote */
+ *fr++ = '"';
+ } else if (*r == '"' && (r[1] == '\0' || r[1] == ',')) {
+ r++; /* skip over closing quote */
+ break;
+ } else {
+ *fr++ = *r++;
+ }
+ }
+ *fr++ = 0;
+ } else { /* unquoted field */
+ while (*r != ',' && *r != '\0')
+ *fr++ = *r++;
+ *fr++ = 0;
+ }
+ if (*r++ == 0)
+ break;
+
+ }
+ }
+ *fr = 0;
+ } else if ((sep = *inputFS) == 0) { /* new: FS="" => 1 char/field */
+ for (i = 0; *r != '\0'; ) {
+ char buf[10];
+ i++;
+ if (i > nfields)
+ growfldtab(i);
+ if (freeable(fldtab[i]))
+ xfree(fldtab[i]->sval);
+ n = u8_nextlen(r);
+ for (j = 0; j < n; j++)
+ buf[j] = *r++;
+ buf[j] = '\0';
+ fldtab[i]->sval = tostring(buf);
+ fldtab[i]->tval = FLD | STR;
+ }
+ *fr = 0;
+ } else if (*r != 0) { /* if 0, it's a null field */
+ /* subtle case: if length(FS) == 1 && length(RS > 0)
+ * \n is NOT a field separator (cf awk book 61,84).
+ * this variable is tested in the inner while loop.
+ */
+ int rtest = '\n'; /* normal case */
+ if (strlen(*RS) > 0)
+ rtest = '\0';
+ for (;;) {
+ i++;
+ if (i > nfields)
+ growfldtab(i);
+ if (freeable(fldtab[i]))
+ xfree(fldtab[i]->sval);
+ fldtab[i]->sval = fr;
+ fldtab[i]->tval = FLD | STR | DONTFREE;
+ while (*r != sep && *r != rtest && *r != '\0') /* \n is always a separator */
+ *fr++ = *r++;
+ *fr++ = 0;
+ if (*r++ == 0)
+ break;
+ }
+ *fr = 0;
+ }
+ if (i > nfields)
+ FATAL("record `%.30s...' has too many fields; can't happen", r);
+ cleanfld(i+1, lastfld); /* clean out junk from previous record */
+ lastfld = i;
+ donefld = true;
+ for (j = 1; j <= lastfld; j++) {
+ double result;
+
+ p = fldtab[j];
+ if(is_number(p->sval, & result)) {
+ p->fval = result;
+ p->tval |= NUM;
+ }
+ }
+ setfval(nfloc, (Awkfloat) lastfld);
+ donerec = true; /* restore */
+ if (dbg) {
+ for (j = 0; j <= lastfld; j++) {
+ p = fldtab[j];
+ printf("field %d (%s): |%s|\n", j, p->nval, p->sval);
+ }
+ }
+}
+
+void cleanfld(int n1, int n2) /* clean out fields n1 .. n2 inclusive */
+{ /* nvals remain intact */
+ Cell *p;
+ int i;
+
+ for (i = n1; i <= n2; i++) {
+ p = fldtab[i];
+ if (freeable(p))
+ xfree(p->sval);
+ p->sval = EMPTY,
+ p->tval = FLD | STR | DONTFREE;
+ }
+}
+
+void newfld(int n) /* add field n after end of existing lastfld */
+{
+ if (n > nfields)
+ growfldtab(n);
+ cleanfld(lastfld+1, n);
+ lastfld = n;
+ setfval(nfloc, (Awkfloat) n);
+}
+
+void setlastfld(int n) /* set lastfld cleaning fldtab cells if necessary */
+{
+ if (n < 0)
+ FATAL("cannot set NF to a negative value");
+ if (n > nfields)
+ growfldtab(n);
+
+ if (lastfld < n)
+ cleanfld(lastfld+1, n);
+ else
+ cleanfld(n+1, lastfld);
+
+ lastfld = n;
+}
+
+Cell *fieldadr(int n) /* get nth field */
+{
+ if (n < 0)
+ FATAL("trying to access out of range field %d", n);
+ if (n > nfields) /* fields after NF are empty */
+ growfldtab(n); /* but does not increase NF */
+ return(fldtab[n]);
+}
+
+void growfldtab(int n) /* make new fields up to at least $n */
+{
+ int nf = 2 * nfields;
+ size_t s;
+
+ if (n > nf)
+ nf = n;
+ s = (nf+1) * (sizeof (struct Cell *)); /* freebsd: how much do we need? */
+ if (s / sizeof(struct Cell *) - 1 == (size_t)nf) /* didn't overflow */
+ fldtab = (Cell **) realloc(fldtab, s);
+ else /* overflow sizeof int */
+ xfree(fldtab); /* make it null */
+ if (fldtab == NULL)
+ FATAL("out of space creating %d fields", nf);
+ makefields(nfields+1, nf);
+ nfields = nf;
+}
+
+int refldbld(const char *rec, const char *fs) /* build fields from reg expr in FS */
+{
+ /* this relies on having fields[] the same length as $0 */
+ /* the fields are all stored in this one array with \0's */
+ char *fr;
+ int i, tempstat, n;
+ fa *pfa;
+
+ n = strlen(rec);
+ if (n > fieldssize) {
+ xfree(fields);
+ if ((fields = (char *) malloc(n+1)) == NULL)
+ FATAL("out of space for fields in refldbld %d", n);
+ fieldssize = n;
+ }
+ fr = fields;
+ *fr = '\0';
+ if (*rec == '\0')
+ return 0;
+ pfa = makedfa(fs, 1);
+ DPRINTF("into refldbld, rec = <%s>, pat = <%s>\n", rec, fs);
+ tempstat = pfa->initstat;
+ for (i = 1; ; i++) {
+ if (i > nfields)
+ growfldtab(i);
+ if (freeable(fldtab[i]))
+ xfree(fldtab[i]->sval);
+ fldtab[i]->tval = FLD | STR | DONTFREE;
+ fldtab[i]->sval = fr;
+ DPRINTF("refldbld: i=%d\n", i);
+ if (nematch(pfa, rec)) {
+ pfa->initstat = 2; /* horrible coupling to b.c */
+ DPRINTF("match %s (%d chars)\n", patbeg, patlen);
+ strncpy(fr, rec, patbeg-rec);
+ fr += patbeg - rec + 1;
+ *(fr-1) = '\0';
+ rec = patbeg + patlen;
+ } else {
+ DPRINTF("no match %s\n", rec);
+ strcpy(fr, rec);
+ pfa->initstat = tempstat;
+ break;
+ }
+ }
+ return i;
+}
+
+void recbld(void) /* create $0 from $1..$NF if necessary */
+{
+ int i;
+ char *r, *p;
+ char *sep = getsval(ofsloc);
+
+ if (donerec)
+ return;
+ r = record;
+ for (i = 1; i <= *NF; i++) {
+ p = getsval(fldtab[i]);
+ if (!adjbuf(&record, &recsize, 1+strlen(p)+r-record, recsize, &r, "recbld 1"))
+ FATAL("created $0 `%.30s...' too long", record);
+ while ((*r = *p++) != 0)
+ r++;
+ if (i < *NF) {
+ if (!adjbuf(&record, &recsize, 2+strlen(sep)+r-record, recsize, &r, "recbld 2"))
+ FATAL("created $0 `%.30s...' too long", record);
+ for (p = sep; (*r = *p++) != 0; )
+ r++;
+ }
+ }
+ if (!adjbuf(&record, &recsize, 2+r-record, recsize, &r, "recbld 3"))
+ FATAL("built giant record `%.30s...'", record);
+ *r = '\0';
+ DPRINTF("in recbld inputFS=%s, fldtab[0]=%p\n", inputFS, (void*)fldtab[0]);
+
+ if (freeable(fldtab[0]))
+ xfree(fldtab[0]->sval);
+ fldtab[0]->tval = REC | STR | DONTFREE;
+ fldtab[0]->sval = record;
+
+ DPRINTF("in recbld inputFS=%s, fldtab[0]=%p\n", inputFS, (void*)fldtab[0]);
+ DPRINTF("recbld = |%s|\n", record);
+ donerec = true;
+}
+
+int errorflag = 0;
+
+void yyerror(const char *s)
+{
+ SYNTAX("%s", s);
+}
+
+void SYNTAX(const char *fmt, ...)
+{
+ extern char *cmdname, *curfname;
+ static int been_here = 0;
+ va_list varg;
+
+ if (been_here++ > 2)
+ return;
+ fprintf(stderr, "%s: ", cmdname);
+ va_start(varg, fmt);
+ vfprintf(stderr, fmt, varg);
+ va_end(varg);
+ fprintf(stderr, " at source line %d", lineno);
+ if (curfname != NULL)
+ fprintf(stderr, " in function %s", curfname);
+ if (compile_time == COMPILING && cursource() != NULL)
+ fprintf(stderr, " source file %s", cursource());
+ fprintf(stderr, "\n");
+ errorflag = 2;
+ eprint();
+}
+
+extern int bracecnt, brackcnt, parencnt;
+
+void bracecheck(void)
+{
+ int c;
+ static int beenhere = 0;
+
+ if (beenhere++)
+ return;
+ while ((c = input()) != EOF && c != '\0')
+ bclass(c);
+ bcheck2(bracecnt, '{', '}');
+ bcheck2(brackcnt, '[', ']');
+ bcheck2(parencnt, '(', ')');
+}
+
+void bcheck2(int n, int c1, int c2)
+{
+ (void)c1;
+ if (n == 1)
+ fprintf(stderr, "\tmissing %c\n", c2);
+ else if (n > 1)
+ fprintf(stderr, "\t%d missing %c's\n", n, c2);
+ else if (n == -1)
+ fprintf(stderr, "\textra %c\n", c2);
+ else if (n < -1)
+ fprintf(stderr, "\t%d extra %c's\n", -n, c2);
+}
+
+void FATAL(const char *fmt, ...)
+{
+ extern char *cmdname;
+ va_list varg;
+
+ fflush(stdout);
+ fprintf(stderr, "%s: ", cmdname);
+ va_start(varg, fmt);
+ vfprintf(stderr, fmt, varg);
+ va_end(varg);
+ error();
+ if (dbg > 1) /* core dump if serious debugging on */
+ abort();
+ exit(2);
+}
+
+void WARNING(const char *fmt, ...)
+{
+ extern char *cmdname;
+ va_list varg;
+
+ fflush(stdout);
+ fprintf(stderr, "%s: ", cmdname);
+ va_start(varg, fmt);
+ vfprintf(stderr, fmt, varg);
+ va_end(varg);
+ error();
+}
+
+void error()
+{
+ extern Node *curnode;
+
+ fprintf(stderr, "\n");
+ if (compile_time != ERROR_PRINTING) {
+ if (NR && *NR > 0) {
+ fprintf(stderr, " input record number %d", (int) (*FNR));
+ if (strcmp(*FILENAME, "-") != 0)
+ fprintf(stderr, ", file %s", *FILENAME);
+ fprintf(stderr, "\n");
+ }
+ if (curnode)
+ fprintf(stderr, " source line number %d", curnode->lineno);
+ else if (lineno)
+ fprintf(stderr, " source line number %d", lineno);
+ if (compile_time == COMPILING && cursource() != NULL)
+ fprintf(stderr, " source file %s", cursource());
+ fprintf(stderr, "\n");
+ eprint();
+ }
+}
+
+void eprint(void) /* try to print context around error */
+{
+ char *p, *q;
+ int c;
+ static int been_here = 0;
+ extern char ebuf[], *ep;
+
+ if (compile_time != COMPILING || been_here++ > 0 || ebuf == ep)
+ return;
+ if (ebuf == ep)
+ return;
+ p = ep - 1;
+ if (p > ebuf && *p == '\n')
+ p--;
+ for ( ; p > ebuf && *p != '\n' && *p != '\0'; p--)
+ ;
+ while (*p == '\n')
+ p++;
+ fprintf(stderr, " context is\n\t");
+ for (q=ep-1; q>=p && *q!=' ' && *q!='\t' && *q!='\n'; q--)
+ ;
+ for ( ; p < q; p++)
+ if (*p)
+ putc(*p, stderr);
+ fprintf(stderr, " >>> ");
+ for ( ; p < ep; p++)
+ if (*p)
+ putc(*p, stderr);
+ fprintf(stderr, " <<< ");
+ if (*ep)
+ while ((c = input()) != '\n' && c != '\0' && c != EOF) {
+ putc(c, stderr);
+ bclass(c);
+ }
+ putc('\n', stderr);
+ ep = ebuf;
+}
+
+void bclass(int c)
+{
+ switch (c) {
+ case '{': bracecnt++; break;
+ case '}': bracecnt--; break;
+ case '[': brackcnt++; break;
+ case ']': brackcnt--; break;
+ case '(': parencnt++; break;
+ case ')': parencnt--; break;
+ }
+}
+
+int isclvar(const char *s) /* is s of form var=something ? */
+{
+ const char *os = s;
+
+ if (!isalpha((int) *s) && *s != '_')
+ return 0;
+ for ( ; *s; s++)
+ if (!(isalnum((int) *s) || *s == '_'))
+ break;
+ return *s == '=' && s > os;
+}
+
+/* strtod is supposed to be a proper test of what's a valid number */
+/* appears to be broken in gcc on linux: thinks 0x123 is a valid FP number */
+/* wrong: violates 4.10.1.4 of ansi C standard */
+
+/* well, not quite. As of C99, hex floating point is allowed. so this is
+ * a bit of a mess. We work around the mess by checking for a hexadecimal
+ * value and disallowing it. Similarly, we now follow gawk and allow only
+ * +nan, -nan, +inf, and -inf for NaN and infinity values.
+ */
+
+/*
+ * This routine now has a more complicated interface, the main point
+ * being to avoid the double conversion of a string to double, and
+ * also to convey out, if requested, the information that the numeric
+ * value was a leading string or is all of the string. The latter bit
+ * is used in getfval().
+ */
+
+bool is_valid_number(const char *s, bool trailing_stuff_ok,
+ bool *no_trailing, double *result)
+{
+ double r;
+ char *ep;
+ bool retval = false;
+ bool is_nan = false;
+ bool is_inf = false;
+
+ if (no_trailing)
+ *no_trailing = false;
+
+ while (isspace((int) *s))
+ s++;
+
+ /* no hex floating point, sorry */
+ if (s[0] == '0' && tolower(s[1]) == 'x' && isxdigit(s[2]))
+ return false;
+
+ /* allow +nan, -nan, +inf, -inf, any other letter, no */
+ if (s[0] == '+' || s[0] == '-') {
+ is_nan = (strncasecmp(s+1, "nan", 3) == 0);
+ is_inf = (strncasecmp(s+1, "inf", 3) == 0);
+ if ((is_nan || is_inf)
+ && (isspace((int) s[4]) || s[4] == '\0'))
+ goto convert;
+ else if (! isdigit(s[1]) && s[1] != '.')
+ return false;
+ }
+ else if (! isdigit(s[0]) && s[0] != '.')
+ return false;
+
+convert:
+ errno = 0;
+ r = strtod(s, &ep);
+ if (ep == s || errno == ERANGE)
+ return false;
+
+ if (isnan(r) && s[0] == '-' && signbit(r) == 0)
+ r = -r;
+
+ if (result != NULL)
+ *result = r;
+
+ /*
+ * check for trailing stuff
+ */
+ while (isspace((int) *ep))
+ ep++;
+
+ if (no_trailing != NULL)
+ *no_trailing = (*ep == '\0');
+
+ /* return true if found the end, or trailing stuff is allowed */
+ retval = *ep == '\0' || trailing_stuff_ok;
+
+ return retval;
+}
diff --git a/cmd/posix/awk/main.c b/cmd/posix/awk/main.c
@@ -0,0 +1,296 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+const char *version = "version 20260426";
+
+#define DEBUG
+#include <stdio.h>
+#include <ctype.h>
+#include <locale.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include "awk.h"
+
+extern char **environ;
+extern int nfields;
+
+int dbg = 0;
+Awkfloat srand_seed = 1;
+char *cmdname; /* gets argv[0] for error messages */
+extern FILE *yyin; /* lex input file */
+char *lexprog; /* points to program argument if it exists */
+extern int errorflag; /* non-zero if any syntax errors; set by yyerror */
+enum compile_states compile_time = ERROR_PRINTING;
+
+static char **pfile; /* program filenames from -f's */
+static size_t maxpfile; /* max program filename */
+static size_t npfile; /* number of filenames */
+static size_t curpfile; /* current filename */
+
+bool CSV = false; /* true for csv input */
+
+bool safe = false; /* true => "safe" mode */
+
+size_t awk_mb_cur_max = 1;
+
+static noreturn void fpecatch(int n
+#ifdef SA_SIGINFO
+ , siginfo_t *si, void *uc
+#endif
+)
+{
+ (void)n;
+#ifdef SA_SIGINFO
+ (void)uc;
+#endif
+#ifdef SA_SIGINFO
+ const char *mesg = NULL;
+
+ switch (si->si_code) {
+ case FPE_INTDIV:
+ mesg = "Integer divide by zero";
+ break;
+ case FPE_INTOVF:
+ mesg = "Integer overflow";
+ break;
+ case FPE_FLTDIV:
+ mesg = "Floating point divide by zero";
+ break;
+ case FPE_FLTOVF:
+ mesg = "Floating point overflow";
+ break;
+ case FPE_FLTUND:
+ mesg = "Floating point underflow";
+ break;
+ case FPE_FLTRES:
+ mesg = "Floating point inexact result";
+ break;
+ case FPE_FLTINV:
+ mesg = "Invalid Floating point operation";
+ break;
+ case FPE_FLTSUB:
+ mesg = "Subscript out of range";
+ break;
+ case 0:
+ default:
+ mesg = "Unknown error";
+ break;
+ }
+#endif
+ FATAL("floating point exception"
+#ifdef SA_SIGINFO
+ ": %s", mesg
+#endif
+ );
+}
+
+/* Can this work with recursive calls? I don't think so.
+void segvcatch(int n)
+{
+ FATAL("segfault. Do you have an unbounded recursive call?", n);
+}
+*/
+
+static const char *
+setfs(char *p)
+{
+ /* wart: t=>\t */
+ if (p[0] == 't' && p[1] == '\0')
+ return "\t";
+ return p;
+}
+
+static char *
+getarg(int *argc, char ***argv, const char *msg)
+{
+ if ((*argv)[1][2] != '\0') { /* arg is -fsomething */
+ return &(*argv)[1][2];
+ } else { /* arg is -f something */
+ (*argc)--; (*argv)++;
+ if (*argc <= 1)
+ FATAL("%s", msg);
+ return (*argv)[1];
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ const char *fs = NULL;
+ char *fn, *vn;
+
+ setlocale(LC_CTYPE, "");
+ setlocale(LC_NUMERIC, "C"); /* for parsing cmdline & prog */
+ awk_mb_cur_max = MB_CUR_MAX;
+ cmdname = argv[0];
+ if (argc == 1) {
+ fprintf(stderr,
+ "usage: %s [-F fs | --csv] [-v var=value] [-f progfile | 'prog'] [file ...]\n",
+ cmdname);
+ exit(1);
+ }
+#ifdef SA_SIGINFO
+ {
+ struct sigaction sa;
+ sa.sa_sigaction = fpecatch;
+ sa.sa_flags = SA_SIGINFO;
+ sigemptyset(&sa.sa_mask);
+ (void)sigaction(SIGFPE, &sa, NULL);
+ }
+#else
+ (void)signal(SIGFPE, fpecatch);
+#endif
+ /*signal(SIGSEGV, segvcatch); experiment */
+
+ /* Set and keep track of the random seed */
+ srand_seed = 1;
+ srandom((unsigned long) srand_seed);
+
+ yyin = NULL;
+ symtab = makesymtab(NSYMTAB/NSYMTAB);
+ while (argc > 1 && argv[1][0] == '-' && argv[1][1] != '\0') {
+ if (strcmp(argv[1], "-version") == 0 || strcmp(argv[1], "--version") == 0) {
+ printf("awk %s\n", version);
+ return 0;
+ }
+ if (strcmp(argv[1], "--") == 0) { /* explicit end of args */
+ argc--;
+ argv++;
+ break;
+ }
+ if (strcmp(argv[1], "--csv") == 0) { /* turn on csv input processing */
+ CSV = true;
+ argc--;
+ argv++;
+ continue;
+ }
+ switch (argv[1][1]) {
+ case 's':
+ if (strcmp(argv[1], "-safe") == 0)
+ safe = true;
+ break;
+ case 'f': /* next argument is program filename */
+ fn = getarg(&argc, &argv, "no program filename");
+ if (npfile >= maxpfile) {
+ maxpfile += 20;
+ pfile = (char **) realloc(pfile, maxpfile * sizeof(*pfile));
+ if (pfile == NULL)
+ FATAL("error allocating space for -f options");
+ }
+ pfile[npfile++] = fn;
+ break;
+ case 'F': /* set field separator */
+ fs = setfs(getarg(&argc, &argv, "no field separator"));
+ break;
+ case 'v': /* -v a=1 to be done NOW. one -v for each */
+ vn = getarg(&argc, &argv, "no variable name");
+ if (isclvar(vn))
+ setclvar(vn);
+ else
+ FATAL("invalid -v option argument: %s", vn);
+ break;
+ case 'd':
+ dbg = atoi(&argv[1][2]);
+ if (dbg == 0)
+ dbg = 1;
+ printf("awk %s\n", version);
+ break;
+ default:
+ WARNING("unknown option %s ignored", argv[1]);
+ break;
+ }
+ argc--;
+ argv++;
+ }
+
+ if (CSV && (fs != NULL || lookup("FS", symtab) != NULL))
+ WARNING("danger: don't set FS when --csv is in effect");
+
+ /* argv[1] is now the first argument */
+ if (npfile == 0) { /* no -f; first argument is program */
+ if (argc <= 1) {
+ if (dbg)
+ exit(0);
+ FATAL("no program given");
+ }
+ DPRINTF("program = |%s|\n", argv[1]);
+ lexprog = argv[1];
+ argc--;
+ argv++;
+ }
+ recinit(recsize);
+ syminit();
+ compile_time = COMPILING;
+ argv[0] = cmdname; /* put prog name at front of arglist */
+ DPRINTF("argc=%d, argv[0]=%s\n", argc, argv[0]);
+ arginit(argc, argv);
+ if (!safe)
+ envinit(environ);
+ yyparse();
+#if 0
+ // Doing this would comply with POSIX, but is not compatible with
+ // other awks and with what most users expect. So comment it out.
+ setlocale(LC_NUMERIC, ""); /* back to whatever it is locally */
+#endif
+ if (fs)
+ *FS = qstring(fs, '\0');
+ DPRINTF("errorflag=%d\n", errorflag);
+ if (errorflag == 0) {
+ compile_time = RUNNING;
+ run(winner);
+ } else
+ bracecheck();
+ return(errorflag);
+}
+
+int pgetc(void) /* get 1 character from awk program */
+{
+ int c;
+
+ for (;;) {
+ if (yyin == NULL) {
+ if (curpfile >= npfile)
+ return EOF;
+ if (strcmp(pfile[curpfile], "-") == 0)
+ yyin = stdin;
+ else if ((yyin = fopen(pfile[curpfile], "r")) == NULL)
+ FATAL("can't open file %s", pfile[curpfile]);
+ lineno = 1;
+ }
+ if ((c = getc(yyin)) != EOF)
+ return c;
+ if (yyin != stdin)
+ fclose(yyin);
+ yyin = NULL;
+ curpfile++;
+ }
+}
+
+char *cursource(void) /* current source file name */
+{
+ if (npfile > 0)
+ return pfile[curpfile < npfile ? curpfile : curpfile - 1];
+ else
+ return NULL;
+}
diff --git a/cmd/posix/awk/maketab.c b/cmd/posix/awk/maketab.c
@@ -0,0 +1,193 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+/*
+ * this program makes the table to link function names
+ * and type indices that is used by execute() in run.c.
+ * it finds the indices in awkgram.tab.h, produced by bison.
+ */
+
+#define _POSIX_C_SOURCE 200809L
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "awk.h"
+#include "awkgram.tab.h"
+
+struct xx
+{ int token;
+ const char *name;
+ const char *pname;
+} proc[] = {
+ { PROGRAM, "program", NULL },
+ { BOR, "boolop", " || " },
+ { AND, "boolop", " && " },
+ { NOT, "boolop", " !" },
+ { NE, "relop", " != " },
+ { EQ, "relop", " == " },
+ { LE, "relop", " <= " },
+ { LT, "relop", " < " },
+ { GE, "relop", " >= " },
+ { GT, "relop", " > " },
+ { ARRAY, "array", NULL },
+ { INDIRECT, "indirect", "$(" },
+ { SUBSTR, "substr", "substr" },
+ { SUB, "dosub", "sub" },
+ { GSUB, "dosub", "gsub" },
+ { INDEX, "sindex", "sindex" },
+ { SPRINTF, "awksprintf", "sprintf " },
+ { ADD, "arith", " + " },
+ { MINUS, "arith", " - " },
+ { MULT, "arith", " * " },
+ { DIVIDE, "arith", " / " },
+ { MOD, "arith", " % " },
+ { UMINUS, "arith", " -" },
+ { UPLUS, "arith", " +" },
+ { POWER, "arith", " **" },
+ { PREINCR, "incrdecr", "++" },
+ { POSTINCR, "incrdecr", "++" },
+ { PREDECR, "incrdecr", "--" },
+ { POSTDECR, "incrdecr", "--" },
+ { CAT, "cat", " " },
+ { PASTAT, "pastat", NULL },
+ { PASTAT2, "dopa2", NULL },
+ { MATCH, "matchop", " ~ " },
+ { NOTMATCH, "matchop", " !~ " },
+ { MATCHFCN, "matchop", "matchop" },
+ { INTEST, "intest", "intest" },
+ { PRINTF, "awkprintf", "printf" },
+ { PRINT, "printstat", "print" },
+ { CLOSE, "closefile", "closefile" },
+ { DELETE, "awkdelete", "awkdelete" },
+ { SPLIT, "split", "split" },
+ { ASSIGN, "assign", " = " },
+ { ADDEQ, "assign", " += " },
+ { SUBEQ, "assign", " -= " },
+ { MULTEQ, "assign", " *= " },
+ { DIVEQ, "assign", " /= " },
+ { MODEQ, "assign", " %= " },
+ { POWEQ, "assign", " ^= " },
+ { CONDEXPR, "condexpr", " ?: " },
+ { IF, "ifstat", "if(" },
+ { WHILE, "whilestat", "while(" },
+ { FOR, "forstat", "for(" },
+ { DO, "dostat", "do" },
+ { IN, "instat", "instat" },
+ { NEXT, "jump", "next" },
+ { NEXTFILE, "jump", "nextfile" },
+ { EXIT, "jump", "exit" },
+ { BREAK, "jump", "break" },
+ { CONTINUE, "jump", "continue" },
+ { RETURN, "jump", "ret" },
+ { BLTIN, "bltin", "bltin" },
+ { CALL, "call", "call" },
+ { ARG, "arg", "arg" },
+ { VARNF, "getnf", "NF" },
+ { GETLINE, "awkgetline", "getline" },
+ { 0, "", "" },
+};
+
+#define SIZE (LASTTOKEN - FIRSTTOKEN + 1)
+const char *table[SIZE];
+char *names[SIZE];
+
+int main(int argc, char *argv[])
+{
+ const struct xx *p;
+ int i, n, tok;
+ char c;
+ FILE *fp;
+ char buf[200], name[200], def[200];
+ enum { TOK_UNKNOWN, TOK_ENUM, TOK_DEFINE } tokentype = TOK_UNKNOWN;
+
+ printf("#include <stdio.h>\n");
+ printf("#include \"awk.h\"\n");
+ printf("#include \"awkgram.tab.h\"\n\n");
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: maketab YTAB_H\n");
+ exit(1);
+ }
+ if ((fp = fopen(argv[1], "r")) == NULL) {
+ fprintf(stderr, "maketab can't open %s!\n", argv[1]);
+ exit(1);
+ }
+ printf("static const char * const printname[%d] = {\n", SIZE);
+ i = 0;
+ while (fgets(buf, sizeof buf, fp) != NULL) {
+ // 199 is sizeof(def) - 1
+ if (tokentype != TOK_ENUM) {
+ n = sscanf(buf, "%1c %199s %199s %d", &c, def, name,
+ &tok);
+ if (n == 4 && c == '#' && strcmp(def, "define") == 0) {
+ tokentype = TOK_DEFINE;
+ } else if (tokentype != TOK_UNKNOWN) {
+ continue;
+ }
+ }
+ if (tokentype != TOK_DEFINE) {
+ /* not a valid #define, bison uses enums now */
+ n = sscanf(buf, "%199s = %d,\n", name, &tok);
+ if (n != 2)
+ continue;
+ tokentype = TOK_ENUM;
+ }
+ if (strcmp(name, "YYSTYPE_IS_DECLARED") == 0) {
+ tokentype = TOK_UNKNOWN;
+ continue;
+ }
+ if (tok < FIRSTTOKEN || tok > LASTTOKEN) {
+ tokentype = TOK_UNKNOWN;
+ /* fprintf(stderr, "maketab funny token %d %s ignored\n", tok, buf); */
+ continue;
+ }
+ names[tok-FIRSTTOKEN] = strdup(name);
+ if (names[tok-FIRSTTOKEN] == NULL) {
+ fprintf(stderr, "maketab out of space copying %s", name);
+ continue;
+ }
+ printf("\t\"%s\",\t/* %d */\n", name, tok);
+ i++;
+ }
+ printf("};\n\n");
+
+ for (p=proc; p->token!=0; p++)
+ table[p->token-FIRSTTOKEN] = p->name;
+ printf("\nCell *(*proctab[%d])(Node **, int) = {\n", SIZE);
+ for (i=0; i<SIZE; i++)
+ printf("\t%s,\t/* %s */\n",
+ table[i] ? table[i] : "nullproc", names[i] ? names[i] : "");
+ printf("};\n\n");
+
+ printf("const char *tokname(int n)\n"); /* print a tokname() function */
+ printf("{\n");
+ printf("\tstatic char buf[100];\n\n");
+ printf("\tif (n < FIRSTTOKEN || n > LASTTOKEN) {\n");
+ printf("\t\tsnprintf(buf, sizeof(buf), \"token %%d\", n);\n");
+ printf("\t\treturn buf;\n");
+ printf("\t}\n");
+ printf("\treturn printname[n-FIRSTTOKEN];\n");
+ printf("}\n");
+ return 0;
+}
diff --git a/cmd/posix/awk/math.c b/cmd/posix/awk/math.c
@@ -0,0 +1,97 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wunknown-pragmas"
+#endif
+#pragma STDC FENV_ACCESS ON
+
+#include <errno.h>
+#include <fenv.h>
+#include <math.h>
+#include <stdio.h>
+
+#include "awk.h"
+
+#ifndef FE_DIVBYZERO
+#define FE_DIVBYZERO 0
+#endif
+
+#ifndef FE_INVALID
+#define FE_INVALID 0
+#endif
+
+#ifndef FE_OVERFLOW
+#define FE_OVERFLOW 0
+#endif
+
+#ifndef FE_UNDERFLOW
+#define FE_UNDERFLOW 0
+#endif
+
+#define errclear() \
+ do { \
+ errno = 0; \
+ feclearexcept(FE_ALL_EXCEPT); \
+ } while (0)
+
+static double errcheck(double x, const char *s)
+{
+ if (errno == EDOM || fetestexcept(FE_INVALID)) {
+ errno = 0;
+ WARNING("%s argument out of domain", s);
+ x = 1;
+ } else if (errno == ERANGE || fetestexcept(FE_DIVBYZERO | FE_OVERFLOW |
+ FE_UNDERFLOW)) {
+ errno = 0;
+ WARNING("%s result out of range", s);
+ x = 1;
+ }
+
+ return x;
+}
+
+double exp_errcheck(double x)
+{
+ errclear();
+ return errcheck(exp(x), "exp");
+}
+
+double log_errcheck(double x)
+{
+ errclear();
+ return errcheck(log(x), "log");
+}
+
+double pow_errcheck(double x, double y)
+{
+ errclear();
+ return errcheck(pow(x, y), "pow");
+}
+
+double sqrt_errcheck(double x)
+{
+ errclear();
+ return errcheck(sqrt(x), "sqrt");
+}
diff --git a/cmd/posix/awk/parse.c b/cmd/posix/awk/parse.c
@@ -0,0 +1,276 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#define DEBUG
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "awk.h"
+#include "awkgram.tab.h"
+
+Node *nodealloc(size_t n)
+{
+ Node *x;
+
+ x = (Node *) malloc(sizeof(*x) + (n-1) * sizeof(x));
+ if (x == NULL)
+ FATAL("out of space in nodealloc");
+ x->nnext = NULL;
+ x->lineno = lineno;
+ return(x);
+}
+
+Node *exptostat(Node *a)
+{
+ a->ntype = NSTAT;
+ return(a);
+}
+
+Node *node1(int a, Node *b)
+{
+ Node *x;
+
+ x = nodealloc(1);
+ x->nobj = a;
+ x->narg[0]=b;
+ return(x);
+}
+
+Node *node2(int a, Node *b, Node *c)
+{
+ Node *x;
+
+ x = nodealloc(2);
+ x->nobj = a;
+ x->narg[0] = b;
+ x->narg[1] = c;
+ return(x);
+}
+
+Node *node3(int a, Node *b, Node *c, Node *d)
+{
+ Node *x;
+
+ x = nodealloc(3);
+ x->nobj = a;
+ x->narg[0] = b;
+ x->narg[1] = c;
+ x->narg[2] = d;
+ return(x);
+}
+
+Node *node4(int a, Node *b, Node *c, Node *d, Node *e)
+{
+ Node *x;
+
+ x = nodealloc(4);
+ x->nobj = a;
+ x->narg[0] = b;
+ x->narg[1] = c;
+ x->narg[2] = d;
+ x->narg[3] = e;
+ return(x);
+}
+
+Node *stat1(int a, Node *b)
+{
+ Node *x;
+
+ x = node1(a,b);
+ x->ntype = NSTAT;
+ return(x);
+}
+
+Node *stat2(int a, Node *b, Node *c)
+{
+ Node *x;
+
+ x = node2(a,b,c);
+ x->ntype = NSTAT;
+ return(x);
+}
+
+Node *stat3(int a, Node *b, Node *c, Node *d)
+{
+ Node *x;
+
+ x = node3(a,b,c,d);
+ x->ntype = NSTAT;
+ return(x);
+}
+
+Node *stat4(int a, Node *b, Node *c, Node *d, Node *e)
+{
+ Node *x;
+
+ x = node4(a,b,c,d,e);
+ x->ntype = NSTAT;
+ return(x);
+}
+
+Node *op1(int a, Node *b)
+{
+ Node *x;
+
+ x = node1(a,b);
+ x->ntype = NEXPR;
+ return(x);
+}
+
+Node *op2(int a, Node *b, Node *c)
+{
+ Node *x;
+
+ x = node2(a,b,c);
+ x->ntype = NEXPR;
+ return(x);
+}
+
+Node *op3(int a, Node *b, Node *c, Node *d)
+{
+ Node *x;
+
+ x = node3(a,b,c,d);
+ x->ntype = NEXPR;
+ return(x);
+}
+
+Node *op4(int a, Node *b, Node *c, Node *d, Node *e)
+{
+ Node *x;
+
+ x = node4(a,b,c,d,e);
+ x->ntype = NEXPR;
+ return(x);
+}
+
+Node *celltonode(Cell *a, int b)
+{
+ Node *x;
+
+ a->ctype = OCELL;
+ a->csub = b;
+ x = node1(0, (Node *) a);
+ x->ntype = NVALUE;
+ return(x);
+}
+
+Node *rectonode(void) /* make $0 into a Node */
+{
+ extern Cell *literal0;
+ return op1(INDIRECT, celltonode(literal0, CUNK));
+}
+
+Node *makearr(Node *p)
+{
+ Cell *cp;
+
+ if (isvalue(p)) {
+ cp = (Cell *) (p->narg[0]);
+ if (isfcn(cp))
+ SYNTAX( "%s is a function, not an array", cp->nval );
+ else if (!isarr(cp)) {
+ xfree(cp->sval);
+ cp->sval = (char *) makesymtab(NSYMTAB);
+ cp->tval = ARR;
+ }
+ }
+ return p;
+}
+
+#define PA2NUM 50 /* max number of pat,pat patterns allowed */
+int paircnt; /* number of them in use */
+int pairstack[PA2NUM]; /* state of each pat,pat */
+
+Node *pa2stat(Node *a, Node *b, Node *c) /* pat, pat {...} */
+{
+ Node *x;
+
+ x = node4(PASTAT2, a, b, c, itonp(paircnt));
+ if (paircnt++ >= PA2NUM)
+ SYNTAX( "limited to %d pat,pat statements", PA2NUM );
+ x->ntype = NSTAT;
+ return(x);
+}
+
+Node *linkum(Node *a, Node *b)
+{
+ Node *c;
+
+ if (errorflag) /* don't link things that are wrong */
+ return a;
+ if (a == NULL)
+ return(b);
+ else if (b == NULL)
+ return(a);
+ for (c = a; c->nnext != NULL; c = c->nnext)
+ ;
+ c->nnext = b;
+ return(a);
+}
+
+void defn(Cell *v, Node *vl, Node *st) /* turn on FCN bit in definition, */
+{ /* body of function, arglist */
+ Node *p;
+ int n;
+
+ if (isarr(v)) {
+ SYNTAX( "`%s' is an array name and a function name", v->nval );
+ return;
+ }
+ if (isarg(v->nval) != -1) {
+ SYNTAX( "`%s' is both function name and argument name", v->nval );
+ return;
+ }
+
+ v->tval = FCN;
+ v->sval = (char *) st;
+ n = 0; /* count arguments */
+ for (p = vl; p; p = p->nnext)
+ n++;
+ v->fval = n;
+ DPRINTF("defining func %s (%d args)\n", v->nval, n);
+}
+
+int isarg(const char *s) /* is s in argument list for current function? */
+{ /* return -1 if not, otherwise arg # */
+ extern Node *arglist;
+ Node *p = arglist;
+ int n;
+
+ for (n = 0; p != NULL; p = p->nnext, n++)
+ if (strcmp(((Cell *)(p->narg[0]))->nval, s) == 0)
+ return n;
+ return -1;
+}
+
+int ptoi(void *p) /* convert pointer to integer */
+{
+ return (int) (long) p; /* swearing that p fits, of course */
+}
+
+Node *itonp(int i) /* and vice versa */
+{
+ return (Node *) (long) i;
+}
diff --git a/cmd/posix/awk/proto.h b/cmd/posix/awk/proto.h
@@ -0,0 +1,204 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+extern int yywrap(void);
+extern void setfname(Cell *);
+extern int constnode(Node *);
+extern char *strnode(Node *);
+extern Node *notnull(Node *);
+extern int yyparse(void);
+
+extern int yylex(void);
+extern void startreg(void);
+extern int input(void);
+extern void unput(int);
+extern void unputstr(const char *);
+
+extern fa *makedfa(const char *, bool);
+extern fa *mkdfa(const char *, bool);
+extern int makeinit(fa *, bool);
+extern void penter(Node *);
+extern void freetr(Node *);
+extern int quoted(const uschar **);
+extern int *cclenter(const char *);
+extern noreturn void overflo(const char *);
+extern void cfoll(fa *, Node *);
+extern int first(Node *);
+extern void follow(Node *);
+extern int member(int, int *);
+extern int match(fa *, const char *);
+extern int pmatch(fa *, const char *);
+extern int nematch(fa *, const char *);
+extern bool fnematch(fa *, FILE *, char **, int *, int);
+extern Node *reparse(const char *);
+extern Node *regexp(void);
+extern Node *primary(void);
+extern Node *concat(Node *);
+extern Node *alt(Node *);
+extern Node *unary(Node *);
+extern int relex(void);
+extern int cgoto(fa *, int, int);
+extern void freefa(fa *);
+
+extern int pgetc(void);
+extern char *cursource(void);
+
+extern Node *nodealloc(size_t);
+extern Node *exptostat(Node *);
+extern Node *node1(int, Node *);
+extern Node *node2(int, Node *, Node *);
+extern Node *node3(int, Node *, Node *, Node *);
+extern Node *node4(int, Node *, Node *, Node *, Node *);
+extern Node *stat3(int, Node *, Node *, Node *);
+extern Node *op2(int, Node *, Node *);
+extern Node *op1(int, Node *);
+extern Node *stat1(int, Node *);
+extern Node *op3(int, Node *, Node *, Node *);
+extern Node *op4(int, Node *, Node *, Node *, Node *);
+extern Node *stat2(int, Node *, Node *);
+extern Node *stat4(int, Node *, Node *, Node *, Node *);
+extern Node *celltonode(Cell *, int);
+extern Node *rectonode(void);
+extern Node *makearr(Node *);
+extern Node *pa2stat(Node *, Node *, Node *);
+extern Node *linkum(Node *, Node *);
+extern void defn(Cell *, Node *, Node *);
+extern int isarg(const char *);
+extern const char *tokname(int);
+extern Cell *(*proctab[])(Node **, int);
+extern int ptoi(void *);
+extern Node *itonp(int);
+
+extern void syminit(void);
+extern void arginit(int, char **);
+extern void envinit(char **);
+extern Array *makesymtab(int);
+extern void freesymtab(Cell *);
+extern void freeelem(Cell *, const char *);
+extern Cell *setsymtab(const char *, const char *, double, unsigned int, Array *);
+extern int hash(const char *, int);
+extern void rehash(Array *);
+extern Cell *lookup(const char *, Array *);
+extern double setfval(Cell *, double);
+extern void funnyvar(Cell *, const char *);
+extern char *setsval(Cell *, const char *);
+extern double getfval(Cell *);
+extern char *getsval(Cell *);
+extern char *getpssval(Cell *); /* for print */
+extern char *tostring(const char *);
+extern char *tostringN(const char *, size_t);
+extern char *qstring(const char *, int);
+extern Cell *catstr(Cell *, Cell *);
+
+extern void recinit(unsigned int);
+extern void initgetrec(void);
+extern void makefields(int, int);
+extern void growfldtab(int n);
+extern void savefs(void);
+extern int getrec(char **, int *, bool);
+extern void nextfile(void);
+extern int readrec(char **buf, int *bufsize, FILE *inf, bool isnew);
+extern char *getargv(int);
+extern void setclvar(char *);
+extern void fldbld(void);
+extern void cleanfld(int, int);
+extern void newfld(int);
+extern void setlastfld(int);
+extern int refldbld(const char *, const char *);
+extern void recbld(void);
+extern Cell *fieldadr(int);
+extern void yyerror(const char *);
+extern void bracecheck(void);
+extern void bcheck2(int, int, int);
+extern void SYNTAX(const char *, ...)
+ __attribute__((__format__(__printf__, 1, 2)));
+extern noreturn void FATAL(const char *, ...)
+ __attribute__((__format__(__printf__, 1, 2)));
+extern void WARNING(const char *, ...)
+ __attribute__((__format__(__printf__, 1, 2)));
+extern void error(void);
+extern void eprint(void);
+extern void bclass(int);
+extern int isclvar(const char *);
+extern bool is_valid_number(const char *s, bool trailing_stuff_ok,
+ bool *no_trailing, double *result);
+#define is_number(s, val) is_valid_number(s, false, NULL, val)
+
+extern int adjbuf(char **pb, int *sz, int min, int q, char **pbp, const char *what);
+extern void run(Node *);
+extern Cell *execute(Node *);
+extern Cell *program(Node **, int);
+extern Cell *call(Node **, int);
+extern Cell *copycell(Cell *);
+extern Cell *arg(Node **, int);
+extern Cell *jump(Node **, int);
+extern Cell *awkgetline(Node **, int);
+extern Cell *getnf(Node **, int);
+extern Cell *array(Node **, int);
+extern Cell *awkdelete(Node **, int);
+extern Cell *intest(Node **, int);
+extern Cell *matchop(Node **, int);
+extern Cell *boolop(Node **, int);
+extern Cell *relop(Node **, int);
+extern void tfree(Cell *);
+extern Cell *gettemp(void);
+extern Cell *indirect(Node **, int);
+extern Cell *substr(Node **, int);
+extern Cell *sindex(Node **, int);
+extern int format(char **, int *, const char *, Node *);
+extern Cell *awksprintf(Node **, int);
+extern Cell *awkprintf(Node **, int);
+extern Cell *arith(Node **, int);
+extern double ipow(double, int);
+extern Cell *incrdecr(Node **, int);
+extern Cell *assign(Node **, int);
+extern Cell *cat(Node **, int);
+extern Cell *pastat(Node **, int);
+extern Cell *dopa2(Node **, int);
+extern Cell *split(Node **, int);
+extern Cell *condexpr(Node **, int);
+extern Cell *ifstat(Node **, int);
+extern Cell *whilestat(Node **, int);
+extern Cell *dostat(Node **, int);
+extern Cell *forstat(Node **, int);
+extern Cell *instat(Node **, int);
+extern Cell *bltin(Node **, int);
+extern Cell *printstat(Node **, int);
+extern Cell *nullproc(Node **, int);
+extern FILE *redirect(int, Node *);
+extern FILE *openfile(int, const char *, bool *);
+extern const char *filename(FILE *);
+extern Cell *closefile(Node **, int);
+extern void closeall(void);
+extern Cell *dosub(Node **, int);
+
+extern FILE *popen(const char *, const char *);
+extern int pclose(FILE *);
+
+extern const char *flags2str(int flags);
+
+extern double exp_errcheck(double);
+extern double log_errcheck(double);
+extern double pow_errcheck(double, double);
+extern double sqrt_errcheck(double);
diff --git a/cmd/posix/awk/run.c b/cmd/posix/awk/run.c
@@ -0,0 +1,2626 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+#endif
+
+#define DEBUG
+#include <stdio.h>
+#include <ctype.h>
+#include <wctype.h>
+#include <fcntl.h>
+#include <setjmp.h>
+#include <limits.h>
+#include <math.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include "awk.h"
+#include "awkgram.tab.h"
+
+
+static void stdinit(void);
+static void flush_all(void);
+static char *wide_char_to_byte_str(int rune, size_t *outlen);
+
+#if 1
+#define tempfree(x) do { if (istemp(x)) tfree(x); } while (/*CONSTCOND*/0)
+#else
+void tempfree(Cell *p) {
+ if (p->ctype == OCELL && (p->csub < CUNK || p->csub > CFREE)) {
+ WARNING("bad csub %d in Cell %d %s",
+ p->csub, p->ctype, p->sval);
+ }
+ if (istemp(p))
+ tfree(p);
+}
+#endif
+
+/* do we really need these? */
+/* #ifdef _NFILE */
+/* #ifndef FOPEN_MAX */
+/* #define FOPEN_MAX _NFILE */
+/* #endif */
+/* #endif */
+
+/* #ifndef FOPEN_MAX */
+/* #define FOPEN_MAX 40 */ /* max number of open files */
+/* #endif */
+
+
+jmp_buf env;
+extern int pairstack[];
+extern Awkfloat srand_seed;
+
+Node *winner = NULL; /* root of parse tree */
+Cell *tmps; /* free temporary cells for execution */
+
+static Cell truecell ={ OBOOL, BTRUE, 0, 0, 1.0, NUM, NULL, NULL };
+Cell *True = &truecell;
+static Cell falsecell ={ OBOOL, BFALSE, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *False = &falsecell;
+static Cell breakcell ={ OJUMP, JBREAK, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jbreak = &breakcell;
+static Cell contcell ={ OJUMP, JCONT, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jcont = &contcell;
+static Cell nextcell ={ OJUMP, JNEXT, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jnext = &nextcell;
+static Cell nextfilecell ={ OJUMP, JNEXTFILE, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jnextfile = &nextfilecell;
+static Cell exitcell ={ OJUMP, JEXIT, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jexit = &exitcell;
+static Cell retcell ={ OJUMP, JRET, 0, 0, 0.0, NUM, NULL, NULL };
+Cell *jret = &retcell;
+static Cell tempcell ={ OCELL, CTEMP, 0, EMPTY, 0.0, NUM|STR|DONTFREE, NULL, NULL };
+
+Node *curnode = NULL; /* the node being executed, for debugging */
+
+/* buffer memory management */
+int adjbuf(char **pbuf, int *psiz, int minlen, int quantum, char **pbptr,
+ const char *whatrtn)
+/* pbuf: address of pointer to buffer being managed
+ * psiz: address of buffer size variable
+ * minlen: minimum length of buffer needed
+ * quantum: buffer size quantum
+ * pbptr: address of movable pointer into buffer, or 0 if none
+ * whatrtn: name of the calling routine if failure should cause fatal error
+ *
+ * return 0 for realloc failure, !=0 for success
+ */
+{
+ if (minlen > *psiz) {
+ char *tbuf;
+ int rminlen = quantum ? minlen % quantum : 0;
+ int boff = pbptr ? *pbptr - *pbuf : 0;
+ /* round up to next multiple of quantum */
+ if (rminlen)
+ minlen += quantum - rminlen;
+ tbuf = (char *) realloc(*pbuf, minlen);
+ DPRINTF("adjbuf %s: %d %d (pbuf=%p, tbuf=%p)\n", whatrtn, *psiz, minlen, (void*)*pbuf, (void*)tbuf);
+ if (tbuf == NULL) {
+ if (whatrtn)
+ FATAL("out of memory in %s", whatrtn);
+ return 0;
+ }
+ *pbuf = tbuf;
+ *psiz = minlen;
+ if (pbptr)
+ *pbptr = tbuf + boff;
+ }
+ return 1;
+}
+
+void run(Node *a) /* execution of parse tree starts here */
+{
+
+ stdinit();
+ execute(a);
+ closeall();
+}
+
+Cell *execute(Node *u) /* execute a node of the parse tree */
+{
+ Cell *(*proc)(Node **, int);
+ Cell *x;
+ Node *a;
+
+ if (u == NULL)
+ return(True);
+ for (a = u; ; a = a->nnext) {
+ curnode = a;
+ if (isvalue(a)) {
+ x = (Cell *) (a->narg[0]);
+ if (isfld(x) && !donefld)
+ fldbld();
+ else if (isrec(x) && !donerec)
+ recbld();
+ return(x);
+ }
+ if (notlegal(a->nobj)) /* probably a Cell* but too risky to print */
+ FATAL("illegal statement");
+ proc = proctab[a->nobj-FIRSTTOKEN];
+ x = (*proc)(a->narg, a->nobj);
+ if (isfld(x) && !donefld)
+ fldbld();
+ else if (isrec(x) && !donerec)
+ recbld();
+ if (isexpr(a))
+ return(x);
+ if (isjump(x))
+ return(x);
+ if (a->nnext == NULL)
+ return(x);
+ tempfree(x);
+ }
+}
+
+
+Cell *program(Node **a, int n) /* execute an awk program */
+{ /* a[0] = BEGIN, a[1] = body, a[2] = END */
+ Cell *x;
+
+ if (setjmp(env) != 0)
+ goto ex;
+ if (a[0]) { /* BEGIN */
+ x = execute(a[0]);
+ if (isexit(x))
+ return(True);
+ if (isjump(x))
+ FATAL("illegal break, continue, next or nextfile from BEGIN");
+ tempfree(x);
+ }
+ if (a[1] || a[2])
+ while (getrec(&record, &recsize, true) > 0) {
+ x = execute(a[1]);
+ if (isexit(x))
+ break;
+ tempfree(x);
+ }
+ ex:
+ if (setjmp(env) != 0) /* handles exit within END */
+ goto ex1;
+ if (a[2]) { /* END */
+ x = execute(a[2]);
+ if (isbreak(x) || isnext(x) || iscont(x))
+ FATAL("illegal break, continue, next or nextfile from END");
+ tempfree(x);
+ }
+ ex1:
+ return(True);
+}
+
+struct Frame { /* stack frame for awk function calls */
+ int nargs; /* number of arguments in this call */
+ Cell *fcncell; /* pointer to Cell for function */
+ Cell **args; /* pointer to array of arguments after execute */
+ Cell *retval; /* return value */
+};
+
+#define NARGS 50 /* max args in a call */
+
+struct Frame *frame = NULL; /* base of stack frames; dynamically allocated */
+int nframe = 0; /* number of frames allocated */
+struct Frame *frp = NULL; /* frame pointer. bottom level unused */
+
+Cell *call(Node **a, int n) /* function call. very kludgy and fragile */
+{
+ static const Cell newcopycell = { OCELL, CCOPY, 0, EMPTY, 0.0, NUM|STR|DONTFREE, NULL, NULL };
+ int i, ncall, ndef;
+ int freed = 0; /* handles potential double freeing when fcn & param share a tempcell */
+ Node *x;
+ Cell *args[NARGS], *oargs[NARGS]; /* BUG: fixed size arrays */
+ Cell *y, *z, *fcn;
+ char *s;
+
+ fcn = execute(a[0]); /* the function itself */
+ s = fcn->nval;
+ if (!isfcn(fcn))
+ FATAL("calling undefined function %s", s);
+ if (frame == NULL) {
+ frp = frame = (struct Frame *) calloc(nframe += 100, sizeof(*frame));
+ if (frame == NULL)
+ FATAL("out of space for stack frames calling %s", s);
+ }
+ for (ncall = 0, x = a[1]; x != NULL; x = x->nnext) /* args in call */
+ ncall++;
+ ndef = (int) fcn->fval; /* args in defn */
+ DPRINTF("calling %s, %d args (%d in defn), frp=%d\n", s, ncall, ndef, (int) (frp-frame));
+ if (ncall > ndef)
+ WARNING("function %s called with %d args, uses only %d",
+ s, ncall, ndef);
+ if (ncall + ndef > NARGS)
+ FATAL("function %s has %d arguments, limit %d", s, ncall+ndef, NARGS);
+ for (i = 0, x = a[1]; x != NULL; i++, x = x->nnext) { /* get call args */
+ DPRINTF("evaluate args[%d], frp=%d:\n", i, (int) (frp-frame));
+ y = execute(x);
+ oargs[i] = y;
+ DPRINTF("args[%d]: %s %f <%s>, t=%o\n",
+ i, NN(y->nval), y->fval, isarr(y) ? "(array)" : NN(y->sval), y->tval);
+ if (isfcn(y))
+ FATAL("can't use function %s as argument in %s", y->nval, s);
+ if (isarr(y))
+ args[i] = y; /* arrays by ref */
+ else
+ args[i] = copycell(y);
+ tempfree(y);
+ }
+ for ( ; i < ndef; i++) { /* add null args for ones not provided */
+ args[i] = gettemp();
+ *args[i] = newcopycell;
+ }
+ frp++; /* now ok to up frame */
+ if (frp >= frame + nframe) {
+ int dfp = frp - frame; /* old index */
+ frame = (struct Frame *) realloc(frame, (nframe += 100) * sizeof(*frame));
+ if (frame == NULL)
+ FATAL("out of space for stack frames in %s", s);
+ frp = frame + dfp;
+ }
+ frp->fcncell = fcn;
+ frp->args = args;
+ frp->nargs = ndef; /* number defined with (excess are locals) */
+ frp->retval = gettemp();
+
+ DPRINTF("start exec of %s, frp=%d\n", s, (int) (frp-frame));
+ y = execute((Node *)(fcn->sval)); /* execute body */
+ DPRINTF("finished exec of %s, frp=%d\n", s, (int) (frp-frame));
+
+ for (i = 0; i < ndef; i++) {
+ Cell *t = frp->args[i];
+ if (isarr(t)) {
+ if (t->csub == CCOPY) {
+ if (i >= ncall) {
+ freesymtab(t);
+ t->csub = CTEMP;
+ tempfree(t);
+ } else {
+ oargs[i]->tval = t->tval;
+ oargs[i]->tval &= ~(STR|NUM|DONTFREE);
+ oargs[i]->sval = t->sval;
+ tempfree(t);
+ }
+ }
+ } else if (t != y) { /* kludge to prevent freeing twice */
+ t->csub = CTEMP;
+ tempfree(t);
+ } else if (t == y && t->csub == CCOPY) {
+ t->csub = CTEMP;
+ tempfree(t);
+ freed = 1;
+ }
+ }
+ tempfree(fcn);
+ if (isexit(y) || isnext(y))
+ return y;
+ if (freed == 0) {
+ tempfree(y); /* don't free twice! */
+ }
+ z = frp->retval; /* return value */
+ DPRINTF("%s returns %g |%s| %o\n", s, getfval(z), getsval(z), z->tval);
+ frp--;
+ return(z);
+}
+
+Cell *copycell(Cell *x) /* make a copy of a cell in a temp */
+{
+ Cell *y;
+
+ /* copy is not constant or field */
+
+ y = gettemp();
+ y->tval = x->tval & ~(CON|FLD|REC);
+ y->csub = CCOPY; /* prevents freeing until call is over */
+ y->nval = x->nval; /* BUG? */
+ if (isstr(x) /* || x->ctype == OCELL */) {
+ y->sval = tostring(x->sval);
+ y->tval &= ~DONTFREE;
+ } else
+ y->tval |= DONTFREE;
+ y->fval = x->fval;
+ return y;
+}
+
+Cell *arg(Node **a, int n) /* nth argument of a function */
+{
+
+ n = ptoi(a[0]); /* argument number, counting from 0 */
+ DPRINTF("arg(%d), frp->nargs=%d\n", n, frp->nargs);
+ if (n+1 > frp->nargs)
+ FATAL("argument #%d of function %s was not supplied",
+ n+1, frp->fcncell->nval);
+ return frp->args[n];
+}
+
+Cell *jump(Node **a, int n) /* break, continue, next, nextfile, return */
+{
+ Cell *y;
+
+ switch (n) {
+ case EXIT:
+ if (a[0] != NULL) {
+ y = execute(a[0]);
+ errorflag = (int) getfval(y);
+ tempfree(y);
+ }
+ longjmp(env, 1);
+ case RETURN:
+ if (a[0] != NULL) {
+ y = execute(a[0]);
+ if ((y->tval & (STR|NUM)) == (STR|NUM)) {
+ setsval(frp->retval, getsval(y));
+ frp->retval->fval = getfval(y);
+ frp->retval->tval |= NUM;
+ }
+ else if (y->tval & STR)
+ setsval(frp->retval, getsval(y));
+ else if (y->tval & NUM)
+ setfval(frp->retval, getfval(y));
+ else /* can't happen */
+ FATAL("bad type variable %d", y->tval);
+ tempfree(y);
+ }
+ return(jret);
+ case NEXT:
+ return(jnext);
+ case NEXTFILE:
+ nextfile();
+ return(jnextfile);
+ case BREAK:
+ return(jbreak);
+ case CONTINUE:
+ return(jcont);
+ default: /* can't happen */
+ FATAL("illegal jump type %d", n);
+ }
+ return 0; /* not reached */
+}
+
+Cell *awkgetline(Node **a, int n) /* get next line from specific input */
+{ /* a[0] is variable, a[1] is operator, a[2] is filename */
+ Cell *r, *x;
+ extern Cell **fldtab;
+ FILE *fp;
+ char *buf;
+ int bufsize = recsize;
+ int mode;
+ bool newflag;
+ double result;
+
+ if ((buf = (char *) malloc(bufsize)) == NULL)
+ FATAL("out of memory in getline");
+
+ fflush(stdout); /* in case someone is waiting for a prompt */
+ r = gettemp();
+ if (a[1] != NULL) { /* getline < file */
+ x = execute(a[2]); /* filename */
+ mode = ptoi(a[1]);
+ if (mode == '|') /* input pipe */
+ mode = LE; /* arbitrary flag */
+ fp = openfile(mode, getsval(x), &newflag);
+ tempfree(x);
+ if (fp == NULL)
+ n = -1;
+ else
+ n = readrec(&buf, &bufsize, fp, newflag);
+ if (n <= 0) {
+ ;
+ } else if (a[0] != NULL) { /* getline var <file */
+ x = execute(a[0]);
+ setsval(x, buf);
+ if (is_number(x->sval, & result)) {
+ x->fval = result;
+ x->tval |= NUM;
+ }
+ tempfree(x);
+ } else { /* getline <file */
+ setsval(fldtab[0], buf);
+ if (is_number(fldtab[0]->sval, & result)) {
+ fldtab[0]->fval = result;
+ fldtab[0]->tval |= NUM;
+ }
+ }
+ } else { /* bare getline; use current input */
+ if (a[0] == NULL) /* getline */
+ n = getrec(&record, &recsize, true);
+ else { /* getline var */
+ n = getrec(&buf, &bufsize, false);
+ if (n > 0) {
+ x = execute(a[0]);
+ setsval(x, buf);
+ if (is_number(x->sval, & result)) {
+ x->fval = result;
+ x->tval |= NUM;
+ }
+ tempfree(x);
+ }
+ }
+ }
+ setfval(r, (Awkfloat) n);
+ free(buf);
+ return r;
+}
+
+Cell *getnf(Node **a, int n) /* get NF */
+{
+ if (!donefld)
+ fldbld();
+ return (Cell *) a[0];
+}
+
+static char *
+makearraystring(Node *p, const char *func)
+{
+ char *buf;
+ int bufsz = recsize;
+ size_t blen;
+
+ if ((buf = (char *) malloc(bufsz)) == NULL) {
+ FATAL("%s: out of memory", func);
+ }
+
+ blen = 0;
+ buf[blen] = '\0';
+
+ for (; p; p = p->nnext) {
+ Cell *x = execute(p); /* expr */
+ char *s = getsval(x);
+ size_t seplen = strlen(getsval(subseploc));
+ size_t nsub = p->nnext ? seplen : 0;
+ size_t slen = strlen(s);
+ size_t tlen = blen + slen + nsub;
+
+ if (!adjbuf(&buf, &bufsz, tlen + 1, recsize, 0, func)) {
+ FATAL("%s: out of memory %s[%s...]",
+ func, x->nval, buf);
+ }
+ memcpy(buf + blen, s, slen);
+ if (nsub) {
+ memcpy(buf + blen + slen, *SUBSEP, nsub);
+ }
+ buf[tlen] = '\0';
+ blen = tlen;
+ tempfree(x);
+ }
+ return buf;
+}
+
+Cell *array(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */
+{
+ Cell *x, *z;
+ char *buf;
+
+ x = execute(a[0]); /* Cell* for symbol table */
+ buf = makearraystring(a[1], __func__);
+ if (!isarr(x)) {
+ DPRINTF("making %s into an array\n", NN(x->nval));
+ if (freeable(x))
+ xfree(x->sval);
+ x->tval &= ~(STR|NUM|DONTFREE);
+ x->tval |= ARR;
+ x->sval = (char *) makesymtab(NSYMTAB);
+ }
+ z = setsymtab(buf, "", 0.0, STR|NUM, (Array *) x->sval);
+ z->ctype = OCELL;
+ z->csub = CVAR;
+ tempfree(x);
+ free(buf);
+ return(z);
+}
+
+Cell *awkdelete(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */
+{
+ Cell *x;
+
+ x = execute(a[0]); /* Cell* for symbol table */
+ if (x == symtabloc) {
+ FATAL("cannot delete SYMTAB or its elements");
+ }
+ if (!isarr(x))
+ return True;
+ if (a[1] == NULL) { /* delete the elements, not the table */
+ freesymtab(x);
+ x->tval &= ~STR;
+ x->tval |= ARR;
+ x->sval = (char *) makesymtab(NSYMTAB);
+ } else {
+ char *buf = makearraystring(a[1], __func__);
+ freeelem(x, buf);
+ free(buf);
+ }
+ tempfree(x);
+ return True;
+}
+
+Cell *intest(Node **a, int n) /* a[0] is index (list), a[1] is symtab */
+{
+ Cell *ap, *k;
+ char *buf;
+
+ ap = execute(a[1]); /* array name */
+ if (!isarr(ap)) {
+ DPRINTF("making %s into an array\n", ap->nval);
+ if (freeable(ap))
+ xfree(ap->sval);
+ ap->tval &= ~(STR|NUM|DONTFREE);
+ ap->tval |= ARR;
+ ap->sval = (char *) makesymtab(NSYMTAB);
+ }
+ buf = makearraystring(a[0], __func__);
+ k = lookup(buf, (Array *) ap->sval);
+ tempfree(ap);
+ free(buf);
+ if (k == NULL)
+ return(False);
+ else
+ return(True);
+}
+
+
+/* ======== utf-8 code ========== */
+
+/*
+ * Awk strings can contain ascii, random 8-bit items (eg Latin-1),
+ * or utf-8. u8_isutf tests whether a string starts with a valid
+ * utf-8 sequence, and returns 0 if not (e.g., high bit set).
+ * u8_nextlen returns length of next valid sequence, which is
+ * 1 for ascii, 2..4 for utf-8, or 1 for high bit non-utf.
+ * u8_strlen returns length of string in valid utf-8 sequences
+ * and/or high-bit bytes. Conversion functions go between byte
+ * number and character number.
+ *
+ * In theory, this behaves the same as before for non-utf8 bytes.
+ *
+ * Limited checking! This is a potential security hole.
+ */
+
+/* is s the beginning of a valid utf-8 string? */
+/* return length 1..4 if yes, 0 if no */
+int u8_isutf(const char *s)
+{
+ int n, ret;
+ unsigned char c;
+
+ c = s[0];
+ if (c < 128 || awk_mb_cur_max == 1)
+ return 1; /* what if it's 0? */
+
+ n = strlen(s);
+ if (n >= 2 && ((c>>5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) {
+ ret = 2; /* 110xxxxx 10xxxxxx */
+ } else if (n >= 3 && ((c>>4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80
+ && (s[2] & 0xC0) == 0x80) {
+ ret = 3; /* 1110xxxx 10xxxxxx 10xxxxxx */
+ } else if (n >= 4 && ((c>>3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80
+ && (s[2] & 0xC0) == 0x80 && (s[3] & 0xC0) == 0x80) {
+ ret = 4; /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ } else {
+ ret = 0;
+ }
+ return ret;
+}
+
+/* Convert (prefix of) utf8 string to utf-32 rune. */
+/* Sets *rune to the value, returns the length. */
+/* No error checking: watch out. */
+int u8_rune(int *rune, const char *s)
+{
+ int n, ret;
+ unsigned char c;
+
+ c = s[0];
+ if (c < 128 || awk_mb_cur_max == 1) {
+ *rune = c;
+ return 1;
+ }
+
+ n = strlen(s);
+ if (n >= 2 && ((c>>5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) {
+ *rune = ((c & 0x1F) << 6) | (s[1] & 0x3F); /* 110xxxxx 10xxxxxx */
+ ret = 2;
+ } else if (n >= 3 && ((c>>4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80
+ && (s[2] & 0xC0) == 0x80) {
+ *rune = ((c & 0xF) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F);
+ /* 1110xxxx 10xxxxxx 10xxxxxx */
+ ret = 3;
+ } else if (n >= 4 && ((c>>3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80
+ && (s[2] & 0xC0) == 0x80 && (s[3] & 0xC0) == 0x80) {
+ *rune = ((c & 0x7) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F);
+ /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ ret = 4;
+ } else {
+ *rune = c;
+ ret = 1;
+ }
+ return ret; /* returns one byte if sequence doesn't look like utf */
+}
+
+/* return length of next sequence: 1 for ascii or random, 2..4 for valid utf8 */
+int u8_nextlen(const char *s)
+{
+ int len;
+
+ len = u8_isutf(s);
+ if (len == 0)
+ len = 1;
+ return len;
+}
+
+/* return number of utf characters or single non-utf bytes */
+int u8_strlen(const char *s)
+{
+ int i, len, n, totlen;
+ unsigned char c;
+
+ n = strlen(s);
+ totlen = 0;
+ for (i = 0; i < n; i += len) {
+ c = s[i];
+ if (c < 128 || awk_mb_cur_max == 1) {
+ len = 1;
+ } else {
+ len = u8_nextlen(&s[i]);
+ }
+ totlen++;
+ if (i > n)
+ FATAL("bad utf count [%s] n=%d i=%d\n", s, n, i);
+ }
+ return totlen;
+}
+
+/* convert utf-8 char number in a string to its byte offset */
+int u8_char2byte(const char *s, int charnum)
+{
+ int n;
+ int bytenum = 0;
+
+ while (charnum > 0) {
+ n = u8_nextlen(s);
+ s += n;
+ bytenum += n;
+ charnum--;
+ }
+ return bytenum;
+}
+
+/* convert byte offset in s to utf-8 char number that starts there */
+int u8_byte2char(const char *s, int bytenum)
+{
+ int i, len, b;
+ int charnum = 0; /* BUG: what origin? */
+ /* should be 0 to match start==0 which means no match */
+
+ b = strlen(s);
+ if (bytenum > b) {
+ return -1; /* ??? */
+ }
+ for (i = 0; i <= bytenum; i += len) {
+ len = u8_nextlen(s+i);
+ charnum++;
+ }
+ return charnum;
+}
+
+/* runetochar() adapted from rune.c in the Plan 9 distribution */
+
+enum
+{
+ Runeerror = 128, /* from somewhere else */
+ Runemax = 0x10FFFF,
+
+ Bit1 = 7,
+ Bitx = 6,
+ Bit2 = 5,
+ Bit3 = 4,
+ Bit4 = 3,
+ Bit5 = 2,
+
+ T1 = ((1<<(Bit1+1))-1) ^ 0xFF, /* 0000 0000 */
+ Tx = ((1<<(Bitx+1))-1) ^ 0xFF, /* 1000 0000 */
+ T2 = ((1<<(Bit2+1))-1) ^ 0xFF, /* 1100 0000 */
+ T3 = ((1<<(Bit3+1))-1) ^ 0xFF, /* 1110 0000 */
+ T4 = ((1<<(Bit4+1))-1) ^ 0xFF, /* 1111 0000 */
+ T5 = ((1<<(Bit5+1))-1) ^ 0xFF, /* 1111 1000 */
+
+ Rune1 = (1<<(Bit1+0*Bitx))-1, /* 0000 0000 0000 0000 0111 1111 */
+ Rune2 = (1<<(Bit2+1*Bitx))-1, /* 0000 0000 0000 0111 1111 1111 */
+ Rune3 = (1<<(Bit3+2*Bitx))-1, /* 0000 0000 1111 1111 1111 1111 */
+ Rune4 = (1<<(Bit4+3*Bitx))-1, /* 0011 1111 1111 1111 1111 1111 */
+
+ Maskx = (1<<Bitx)-1, /* 0011 1111 */
+ Testx = Maskx ^ 0xFF, /* 1100 0000 */
+
+};
+
+int runetochar(char *str, int c)
+{
+ /* one character sequence 00000-0007F => 00-7F */
+ if (c <= Rune1) {
+ str[0] = c;
+ return 1;
+ }
+
+ /* two character sequence 00080-007FF => T2 Tx */
+ if (c <= Rune2) {
+ str[0] = T2 | (c >> 1*Bitx);
+ str[1] = Tx | (c & Maskx);
+ return 2;
+ }
+
+ /* three character sequence 00800-0FFFF => T3 Tx Tx */
+ if (c > Runemax)
+ c = Runeerror;
+ if (c <= Rune3) {
+ str[0] = T3 | (c >> 2*Bitx);
+ str[1] = Tx | ((c >> 1*Bitx) & Maskx);
+ str[2] = Tx | (c & Maskx);
+ return 3;
+ }
+
+ /* four character sequence 010000-1FFFFF => T4 Tx Tx Tx */
+ str[0] = T4 | (c >> 3*Bitx);
+ str[1] = Tx | ((c >> 2*Bitx) & Maskx);
+ str[2] = Tx | ((c >> 1*Bitx) & Maskx);
+ str[3] = Tx | (c & Maskx);
+ return 4;
+}
+
+
+/* ========== end of utf8 code =========== */
+
+
+
+Cell *matchop(Node **a, int n) /* ~ and match() */
+{
+ Cell *x, *y, *z;
+ char *s, *t;
+ int i;
+ int cstart, cpatlen, len;
+ fa *pfa;
+ int (*mf)(fa *, const char *) = match, mode = 0;
+
+ if (n == MATCHFCN) {
+ mf = pmatch;
+ mode = 1;
+ }
+ x = execute(a[1]); /* a[1] = target text */
+ s = getsval(x);
+ if (a[0] == NULL) /* a[1] == 0: already-compiled reg expr */
+ i = (*mf)((fa *) a[2], s);
+ else {
+ y = execute(a[2]); /* a[2] = regular expr */
+ t = getsval(y);
+ pfa = makedfa(t, mode);
+ i = (*mf)(pfa, s);
+ tempfree(y);
+ }
+ z = x;
+ if (n == MATCHFCN) {
+ int start = patbeg - s + 1; /* origin 1 */
+ if (patlen < 0) {
+ start = 0; /* not found */
+ } else {
+ cstart = u8_byte2char(s, start-1);
+ cpatlen = 0;
+ for (i = 0; i < patlen; i += len) {
+ len = u8_nextlen(patbeg+i);
+ cpatlen++;
+ }
+
+ start = cstart;
+ patlen = cpatlen;
+ }
+
+ setfval(rstartloc, (Awkfloat) start);
+ setfval(rlengthloc, (Awkfloat) patlen);
+ x = gettemp();
+ x->tval = NUM;
+ x->fval = start;
+ } else if ((n == MATCH && i == 1) || (n == NOTMATCH && i == 0))
+ x = True;
+ else
+ x = False;
+
+ tempfree(z);
+ return x;
+}
+
+
+Cell *boolop(Node **a, int n) /* a[0] || a[1], a[0] && a[1], !a[0] */
+{
+ Cell *x, *y;
+ int i;
+
+ x = execute(a[0]);
+ i = istrue(x);
+ tempfree(x);
+ switch (n) {
+ case BOR:
+ if (i) return(True);
+ y = execute(a[1]);
+ i = istrue(y);
+ tempfree(y);
+ if (i) return(True);
+ else return(False);
+ case AND:
+ if ( !i ) return(False);
+ y = execute(a[1]);
+ i = istrue(y);
+ tempfree(y);
+ if (i) return(True);
+ else return(False);
+ case NOT:
+ if (i) return(False);
+ else return(True);
+ default: /* can't happen */
+ FATAL("unknown boolean operator %d", n);
+ }
+ return 0; /*NOTREACHED*/
+}
+
+Cell *relop(Node **a, int n) /* a[0 < a[1], etc. */
+{
+ int i;
+ Cell *x, *y;
+ Awkfloat j;
+ bool x_is_nan, y_is_nan;
+
+ x = execute(a[0]);
+ y = execute(a[1]);
+ x_is_nan = isnan(x->fval);
+ y_is_nan = isnan(y->fval);
+ if (x->tval&NUM && y->tval&NUM) {
+ if ((x_is_nan || y_is_nan) && n != NE)
+ return(False);
+ j = x->fval - y->fval;
+ i = j<0? -1: (j>0? 1: 0);
+ } else {
+ i = strcmp(getsval(x), getsval(y));
+ }
+ tempfree(x);
+ tempfree(y);
+ switch (n) {
+ case LT: if (i<0) return(True);
+ else return(False);
+ case LE: if (i<=0) return(True);
+ else return(False);
+ case NE: if (x_is_nan && y_is_nan) return(True);
+ else if (i!=0) return(True);
+ else return(False);
+ case EQ: if (i == 0) return(True);
+ else return(False);
+ case GE: if (i>=0) return(True);
+ else return(False);
+ case GT: if (i>0) return(True);
+ else return(False);
+ default: /* can't happen */
+ FATAL("unknown relational operator %d", n);
+ }
+ return 0; /*NOTREACHED*/
+}
+
+void tfree(Cell *a) /* free a tempcell */
+{
+ if (freeable(a)) {
+ DPRINTF("freeing %s %s %o\n", NN(a->nval), NN(a->sval), a->tval);
+ xfree(a->sval);
+ }
+ if (a == tmps)
+ FATAL("tempcell list is curdled");
+ a->cnext = tmps;
+ tmps = a;
+}
+
+Cell *gettemp(void) /* get a tempcell */
+{ int i;
+ Cell *x;
+
+ if (!tmps) {
+ tmps = (Cell *) calloc(100, sizeof(*tmps));
+ if (!tmps)
+ FATAL("out of space for temporaries");
+ for (i = 1; i < 100; i++)
+ tmps[i-1].cnext = &tmps[i];
+ tmps[i-1].cnext = NULL;
+ }
+ x = tmps;
+ tmps = x->cnext;
+ *x = tempcell;
+ return(x);
+}
+
+Cell *indirect(Node **a, int n) /* $( a[0] ) */
+{
+ Awkfloat val;
+ Cell *x;
+ int m;
+
+ x = execute(a[0]);
+ val = getfval(x); /* freebsd: defend against super large field numbers */
+ if ((Awkfloat)INT_MAX < val)
+ FATAL("trying to access out of range field %s", x->nval);
+ m = (int) val;
+ tempfree(x);
+ x = fieldadr(m);
+ x->ctype = OCELL; /* BUG? why are these needed? */
+ x->csub = CFLD;
+ return(x);
+}
+
+Cell *substr(Node **a, int nnn) /* substr(a[0], a[1], a[2]) */
+{
+ int k, m, n;
+ int mb, nb;
+ char *s;
+ int temp;
+ Cell *x, *y, *z = NULL;
+
+ x = execute(a[0]);
+ y = execute(a[1]);
+ if (a[2] != NULL)
+ z = execute(a[2]);
+ s = getsval(x);
+ k = u8_strlen(s) + 1;
+ if (k <= 1) {
+ tempfree(x);
+ tempfree(y);
+ if (a[2] != NULL) {
+ tempfree(z);
+ }
+ x = gettemp();
+ setsval(x, "");
+ return(x);
+ }
+ m = (int) getfval(y);
+ if (m <= 0)
+ m = 1;
+ else if (m > k)
+ m = k;
+ tempfree(y);
+ if (a[2] != NULL) {
+ n = (int) getfval(z);
+ tempfree(z);
+ } else
+ n = k - 1;
+ if (n < 0)
+ n = 0;
+ else if (n > k - m)
+ n = k - m;
+ /* m is start, n is length from there */
+ DPRINTF("substr: m=%d, n=%d, s=%s\n", m, n, s);
+ y = gettemp();
+ mb = u8_char2byte(s, m-1); /* byte offset of start char in s */
+ nb = u8_char2byte(s, m-1+n); /* byte offset of end+1 char in s */
+
+ temp = s[nb]; /* with thanks to John Linderman */
+ s[nb] = '\0';
+ setsval(y, s + mb);
+ s[nb] = temp;
+ tempfree(x);
+ return(y);
+}
+
+Cell *sindex(Node **a, int nnn) /* index(a[0], a[1]) */
+{
+ Cell *x, *y, *z;
+ char *s1, *s2, *p1, *p2, *q;
+ Awkfloat v = 0.0;
+
+ x = execute(a[0]);
+ s1 = getsval(x);
+ y = execute(a[1]);
+ s2 = getsval(y);
+
+ z = gettemp();
+ for (p1 = s1; *p1 != '\0'; p1++) {
+ for (q = p1, p2 = s2; *p2 != '\0' && *q == *p2; q++, p2++)
+ continue;
+ if (*p2 == '\0') {
+ /* v = (Awkfloat) (p1 - s1 + 1); origin 1 */
+
+ /* should be a function: used in match() as well */
+ int i, len;
+ v = 0;
+ for (i = 0; i < p1-s1+1; i += len) {
+ len = u8_nextlen(s1+i);
+ v++;
+ }
+ break;
+ }
+ }
+ tempfree(x);
+ tempfree(y);
+ setfval(z, v);
+ return(z);
+}
+
+int has_utf8(char *s) /* return 1 if s contains any utf-8 (2 bytes or more) character */
+{
+ int n;
+
+ for (n = 0; *s != 0; s += n) {
+ n = u8_nextlen(s);
+ if (n > 1)
+ return 1;
+ }
+ return 0;
+}
+
+#define MAXNUMSIZE 50
+
+int format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conversions */
+{
+ char *fmt;
+ char *p, *t;
+ const char *os;
+ Cell *x;
+ int flag = 0, n;
+ int fmtwd; /* format width */
+ int fmtsz = recsize;
+ char *buf = *pbuf;
+ int bufsize = *pbufsize;
+#define FMTSZ(a) (fmtsz - ((a) - fmt))
+#define BUFSZ(a) (bufsize - ((a) - buf))
+
+ static bool first = true;
+ static bool have_a_format = false;
+
+ if (first) {
+ char xbuf[100];
+
+ snprintf(xbuf, sizeof(xbuf), "%a", 42.0);
+ have_a_format = (strcmp(xbuf, "0x1.5p+5") == 0);
+ first = false;
+ }
+
+ os = s;
+ p = buf;
+ if ((fmt = (char *) malloc(fmtsz)) == NULL)
+ FATAL("out of memory in format()");
+ while (*s) {
+ adjbuf(&buf, &bufsize, MAXNUMSIZE+1+p-buf, recsize, &p, "format1");
+ if (*s != '%') {
+ *p++ = *s++;
+ continue;
+ }
+ if (*(s+1) == '%') {
+ *p++ = '%';
+ s += 2;
+ continue;
+ }
+ fmtwd = atoi(s+1);
+ if (fmtwd < 0)
+ fmtwd = -fmtwd;
+ adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format2");
+ for (t = fmt; (*t++ = *s) != '\0'; s++) {
+ if (!adjbuf(&fmt, &fmtsz, MAXNUMSIZE+1+t-fmt, recsize, &t, "format3"))
+ FATAL("format item %.30s... ran format() out of memory", os);
+ /* Ignore size specifiers */
+ if (strchr("hjLlqtz", *s) != NULL) { /* the ansi panoply */
+ t--;
+ continue;
+ }
+ if (isalpha((uschar)*s))
+ break;
+ if (*s == '$') {
+ FATAL("'$' not permitted in awk formats");
+ }
+ if (*s == '*') {
+ if (a == NULL) {
+ FATAL("not enough args in printf(%s)", os);
+ }
+ x = execute(a);
+ a = a->nnext;
+ snprintf(t - 1, FMTSZ(t - 1),
+ "%d", fmtwd=(int) getfval(x));
+ if (fmtwd < 0)
+ fmtwd = -fmtwd;
+ adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format");
+ t = fmt + strlen(fmt);
+ tempfree(x);
+ }
+ }
+ *t = '\0';
+ if (fmtwd < 0)
+ fmtwd = -fmtwd;
+ adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format4");
+ switch (*s) {
+ case 'a': case 'A':
+ if (have_a_format)
+ flag = *s;
+ else
+ flag = 'f';
+ break;
+ case 'f': case 'e': case 'g': case 'E': case 'G':
+ flag = 'f';
+ break;
+ case 'd': case 'i': case 'o': case 'x': case 'X': case 'u':
+ flag = (*s == 'd' || *s == 'i') ? 'd' : 'u';
+ *(t-1) = 'j';
+ *t = *s;
+ *++t = '\0';
+ break;
+ case 's':
+ flag = 's';
+ break;
+ case 'c':
+ flag = 'c';
+ break;
+ default:
+ WARNING("weird printf conversion %s", fmt);
+ flag = '?';
+ break;
+ }
+ if (a == NULL)
+ FATAL("not enough args in printf(%s)", os);
+ x = execute(a);
+ a = a->nnext;
+ n = MAXNUMSIZE;
+ if (fmtwd > n)
+ n = fmtwd;
+ adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, "format5");
+ switch (flag) {
+ case '?':
+ snprintf(p, BUFSZ(p), "%s", fmt); /* unknown, so dump it too */
+ t = getsval(x);
+ n = strlen(t);
+ if (fmtwd > n)
+ n = fmtwd;
+ adjbuf(&buf, &bufsize, 1+strlen(p)+n+p-buf, recsize, &p, "format6");
+ p += strlen(p);
+ snprintf(p, BUFSZ(p), "%s", t);
+ break;
+ case 'a':
+ case 'A':
+ case 'f': snprintf(p, BUFSZ(p), fmt, getfval(x)); break;
+ case 'd': snprintf(p, BUFSZ(p), fmt, (intmax_t) getfval(x)); break;
+ case 'u': snprintf(p, BUFSZ(p), fmt, (uintmax_t) getfval(x)); break;
+
+ case 's': {
+ t = getsval(x);
+ n = strlen(t);
+ /* if simple format or no utf-8 in the string, sprintf works */
+ if (!has_utf8(t) || strcmp(fmt,"%s") == 0) {
+ if (fmtwd > n)
+ n = fmtwd;
+ if (!adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, "format7"))
+ FATAL("huge string/format (%d chars) in printf %.30s..." \
+ " ran format() out of memory", n, t);
+ snprintf(p, BUFSZ(p), fmt, t);
+ break;
+ }
+
+ /* get here if string has utf-8 chars and fmt is not plain %s */
+ /* "%-w.ps", where -, w and .p are all optional */
+ /* '0' before the w is a flag character */
+ /* fmt points at % */
+ int ljust = 0, wid = 0, prec = n, pad = 0;
+ char *f = fmt+1;
+ if (f[0] == '-') {
+ ljust = 1;
+ f++;
+ }
+ // flags '0' and '+' are recognized but skipped
+ if (f[0] == '0') {
+ f++;
+ if (f[0] == '+')
+ f++;
+ }
+ if (f[0] == '+') {
+ f++;
+ if (f[0] == '0')
+ f++;
+ }
+ if (isdigit(f[0])) { /* there is a wid */
+ wid = strtol(f, &f, 10);
+ }
+ if (f[0] == '.') { /* there is a .prec */
+ prec = strtol(++f, &f, 10);
+ }
+ if (prec > u8_strlen(t))
+ prec = u8_strlen(t);
+ pad = wid>prec ? wid - prec : 0; // has to be >= 0
+ int i, k, n;
+
+ if (ljust) { // print prec chars from t, then pad blanks
+ n = u8_char2byte(t, prec);
+ for (k = 0; k < n; k++) {
+ //putchar(t[k]);
+ *p++ = t[k];
+ }
+ for (i = 0; i < pad; i++) {
+ //printf(" ");
+ *p++ = ' ';
+ }
+ } else { // print pad blanks, then prec chars from t
+ for (i = 0; i < pad; i++) {
+ //printf(" ");
+ *p++ = ' ';
+ }
+ n = u8_char2byte(t, prec);
+ for (k = 0; k < n; k++) {
+ //putchar(t[k]);
+ *p++ = t[k];
+ }
+ }
+ *p = 0;
+ break;
+ }
+
+ case 'c': {
+ /*
+ * If a numeric value is given, awk should just turn
+ * it into a character and print it:
+ * BEGIN { printf("%c\n", 65) }
+ * prints "A".
+ *
+ * But what if the numeric value is > 128 and
+ * represents a valid Unicode code point?!? We do
+ * our best to convert it back into UTF-8. If we
+ * can't, we output the encoding of the Unicode
+ * "invalid character", 0xFFFD.
+ */
+ if (isnum(x)) {
+ int charval = (int) getfval(x);
+
+ if (charval != 0) {
+ if (charval < 128 || awk_mb_cur_max == 1)
+ snprintf(p, BUFSZ(p), fmt, charval);
+ else {
+ // possible unicode character
+ size_t count;
+ char *bs = wide_char_to_byte_str(charval, &count);
+
+ if (bs == NULL) { // invalid character
+ // use unicode invalid character, 0xFFFD
+ static char invalid_char[] = "\357\277\275";
+ bs = invalid_char;
+ count = 3;
+ }
+ t = bs;
+ n = count;
+ goto format_percent_c;
+ }
+ } else {
+ *p++ = '\0'; /* explicit null byte */
+ *p = '\0'; /* next output will start here */
+ }
+ break;
+ }
+ t = getsval(x);
+ n = u8_nextlen(t);
+ format_percent_c:
+ if (n < 2) { /* not utf8 */
+ snprintf(p, BUFSZ(p), fmt, getsval(x)[0]);
+ break;
+ }
+
+ // utf8 character, almost same song and dance as for %s
+ int ljust = 0, wid = 0, prec = n, pad = 0;
+ char *f = fmt+1;
+ if (f[0] == '-') {
+ ljust = 1;
+ f++;
+ }
+ // flags '0' and '+' are recognized but skipped
+ if (f[0] == '0') {
+ f++;
+ if (f[0] == '+')
+ f++;
+ }
+ if (f[0] == '+') {
+ f++;
+ if (f[0] == '0')
+ f++;
+ }
+ if (isdigit(f[0])) { /* there is a wid */
+ wid = strtol(f, &f, 10);
+ }
+ if (f[0] == '.') { /* there is a .prec */
+ prec = strtol(++f, &f, 10);
+ }
+ if (prec > 1) // %c --> only one character
+ prec = 1;
+ pad = wid>prec ? wid - prec : 0; // has to be >= 0
+ int i;
+
+ if (ljust) { // print one char from t, then pad blanks
+ for (i = 0; i < n; i++)
+ *p++ = t[i];
+ for (i = 0; i < pad; i++) {
+ //printf(" ");
+ *p++ = ' ';
+ }
+ } else { // print pad blanks, then prec chars from t
+ for (i = 0; i < pad; i++) {
+ //printf(" ");
+ *p++ = ' ';
+ }
+ for (i = 0; i < n; i++)
+ *p++ = t[i];
+ }
+ *p = 0;
+ break;
+ }
+ default:
+ FATAL("can't happen: bad conversion %c in format()", flag);
+ }
+
+ tempfree(x);
+ p += strlen(p);
+ s++;
+ }
+ *p = '\0';
+ free(fmt);
+ for ( ; a; a = a->nnext) { /* evaluate any remaining args */
+ x = execute(a);
+ tempfree(x);
+ }
+ *pbuf = buf;
+ *pbufsize = bufsize;
+ return p - buf;
+}
+
+Cell *awksprintf(Node **a, int n) /* sprintf(a[0]) */
+{
+ Cell *x;
+ Node *y;
+ char *buf;
+ int bufsz=3*recsize;
+
+ if ((buf = (char *) malloc(bufsz)) == NULL)
+ FATAL("out of memory in awksprintf");
+ y = a[0]->nnext;
+ x = execute(a[0]);
+ if (format(&buf, &bufsz, getsval(x), y) == -1)
+ FATAL("sprintf string %.30s... too long. can't happen.", buf);
+ tempfree(x);
+ x = gettemp();
+ x->sval = buf;
+ x->tval = STR;
+ return(x);
+}
+
+Cell *awkprintf(Node **a, int n) /* printf */
+{ /* a[0] is list of args, starting with format string */
+ /* a[1] is redirection operator, a[2] is redirection file */
+ FILE *fp;
+ Cell *x;
+ Node *y;
+ char *buf;
+ int len;
+ int bufsz=3*recsize;
+
+ if ((buf = (char *) malloc(bufsz)) == NULL)
+ FATAL("out of memory in awkprintf");
+ y = a[0]->nnext;
+ x = execute(a[0]);
+ if ((len = format(&buf, &bufsz, getsval(x), y)) == -1)
+ FATAL("printf string %.30s... too long. can't happen.", buf);
+ tempfree(x);
+ if (a[1] == NULL) {
+ /* fputs(buf, stdout); */
+ fwrite(buf, len, 1, stdout);
+ if (ferror(stdout))
+ FATAL("write error on stdout");
+ } else {
+ fp = redirect(ptoi(a[1]), a[2]);
+ /* fputs(buf, fp); */
+ fwrite(buf, len, 1, fp);
+ fflush(fp);
+ if (ferror(fp))
+ FATAL("write error on %s", filename(fp));
+ }
+ free(buf);
+ return(True);
+}
+
+Cell *arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */
+{
+ Awkfloat i, j = 0;
+ double v;
+ Cell *x, *y, *z;
+
+ x = execute(a[0]);
+ i = getfval(x);
+ tempfree(x);
+ if (n != UMINUS && n != UPLUS) {
+ y = execute(a[1]);
+ j = getfval(y);
+ tempfree(y);
+ }
+ z = gettemp();
+ switch (n) {
+ case ADD:
+ i += j;
+ break;
+ case MINUS:
+ i -= j;
+ break;
+ case MULT:
+ i *= j;
+ break;
+ case DIVIDE:
+ if (j == 0)
+ FATAL("division by zero");
+ i /= j;
+ break;
+ case MOD:
+ if (j == 0)
+ FATAL("division by zero in mod");
+ modf(i/j, &v);
+ i = i - j * v;
+ break;
+ case UMINUS:
+ i = -i;
+ break;
+ case UPLUS: /* handled by getfval(), above */
+ break;
+ case POWER:
+ if (j >= 0 && modf(j, &v) == 0.0) /* pos integer exponent */
+ i = ipow(i, (int) j);
+ else
+ i = pow_errcheck(i, j);
+ break;
+ default: /* can't happen */
+ FATAL("illegal arithmetic operator %d", n);
+ }
+ setfval(z, i);
+ return(z);
+}
+
+double ipow(double x, int n) /* x**n. ought to be done by pow, but isn't always */
+{
+ double v;
+
+ if (n <= 0)
+ return 1;
+ v = ipow(x, n/2);
+ if (n % 2 == 0)
+ return v * v;
+ else
+ return x * v * v;
+}
+
+Cell *incrdecr(Node **a, int n) /* a[0]++, etc. */
+{
+ Cell *x, *z;
+ int k;
+ Awkfloat xf;
+
+ x = execute(a[0]);
+ xf = getfval(x);
+ k = (n == PREINCR || n == POSTINCR) ? 1 : -1;
+ if (n == PREINCR || n == PREDECR) {
+ setfval(x, xf + k);
+ return(x);
+ }
+ z = gettemp();
+ setfval(z, xf);
+ setfval(x, xf + k);
+ tempfree(x);
+ return(z);
+}
+
+Cell *assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc. */
+{ /* this is subtle; don't muck with it. */
+ Cell *x, *y;
+ Awkfloat xf, yf;
+ double v;
+
+ y = execute(a[1]);
+ x = execute(a[0]);
+ if (n == ASSIGN) { /* ordinary assignment */
+ if (x == y && !(x->tval & (FLD|REC)) && x != nfloc)
+ ; /* self-assignment: leave alone unless it's a field or NF */
+ else if ((y->tval & (STR|NUM)) == (STR|NUM)) {
+ yf = getfval(y);
+ setsval(x, getsval(y));
+ x->fval = yf;
+ x->tval |= NUM;
+ }
+ else if (isstr(y))
+ setsval(x, getsval(y));
+ else if (isnum(y))
+ setfval(x, getfval(y));
+ else
+ funnyvar(y, "read value of");
+ tempfree(y);
+ return(x);
+ }
+ xf = getfval(x);
+ yf = getfval(y);
+ switch (n) {
+ case ADDEQ:
+ xf += yf;
+ break;
+ case SUBEQ:
+ xf -= yf;
+ break;
+ case MULTEQ:
+ xf *= yf;
+ break;
+ case DIVEQ:
+ if ((x->tval & CON) != 0)
+ FATAL("non-constant required for left side of /=");
+ if (yf == 0)
+ FATAL("division by zero in /=");
+ xf /= yf;
+ break;
+ case MODEQ:
+ if (yf == 0)
+ FATAL("division by zero in %%=");
+ modf(xf/yf, &v);
+ xf = xf - yf * v;
+ break;
+ case POWEQ:
+ if (yf >= 0 && modf(yf, &v) == 0.0) /* pos integer exponent */
+ xf = ipow(xf, (int) yf);
+ else
+ xf = pow_errcheck(xf, yf);
+ break;
+ default:
+ FATAL("illegal assignment operator %d", n);
+ break;
+ }
+ tempfree(y);
+ setfval(x, xf);
+ return(x);
+}
+
+Cell *cat(Node **a, int q) /* a[0] cat a[1] */
+{
+ Cell *x, *y, *z;
+ int n1, n2;
+ char *s = NULL;
+ int ssz = 0;
+
+ x = execute(a[0]);
+ n1 = strlen(getsval(x));
+ adjbuf(&s, &ssz, n1 + 1, recsize, 0, "cat1");
+ memcpy(s, x->sval, n1);
+
+ tempfree(x);
+
+ y = execute(a[1]);
+ n2 = strlen(getsval(y));
+ adjbuf(&s, &ssz, n1 + n2 + 1, recsize, 0, "cat2");
+ memcpy(s + n1, y->sval, n2);
+ s[n1 + n2] = '\0';
+
+ tempfree(y);
+
+ z = gettemp();
+ z->sval = s;
+ z->tval = STR;
+
+ return(z);
+}
+
+Cell *pastat(Node **a, int n) /* a[0] { a[1] } */
+{
+ Cell *x;
+
+ if (a[0] == NULL)
+ x = execute(a[1]);
+ else {
+ x = execute(a[0]);
+ if (istrue(x)) {
+ tempfree(x);
+ x = execute(a[1]);
+ }
+ }
+ return x;
+}
+
+Cell *dopa2(Node **a, int n) /* a[0], a[1] { a[2] } */
+{
+ Cell *x;
+ int pair;
+
+ pair = ptoi(a[3]);
+ if (pairstack[pair] == 0) {
+ x = execute(a[0]);
+ if (istrue(x))
+ pairstack[pair] = 1;
+ tempfree(x);
+ }
+ if (pairstack[pair] == 1) {
+ x = execute(a[1]);
+ if (istrue(x))
+ pairstack[pair] = 0;
+ tempfree(x);
+ x = execute(a[2]);
+ return(x);
+ }
+ return(False);
+}
+
+Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */
+{
+ Cell *x = NULL, *y, *ap;
+ const char *s, *origs, *t;
+ const char *fs = NULL;
+ char *origfs = NULL;
+ int sep;
+ char temp, num[50];
+ int n, tempstat, arg3type;
+ int j;
+ double result;
+
+ y = execute(a[0]); /* source string */
+ origs = s = strdup(getsval(y));
+ tempfree(y);
+ arg3type = ptoi(a[3]);
+ if (a[2] == NULL) { /* BUG: CSV should override implicit fs but not explicit */
+ fs = getsval(fsloc);
+ } else if (arg3type == STRING) { /* split(str,arr,"string") */
+ x = execute(a[2]);
+ fs = origfs = strdup(getsval(x));
+ tempfree(x);
+ } else if (arg3type == REGEXPR) {
+ fs = "(regexpr)"; /* split(str,arr,/regexpr/) */
+ } else {
+ FATAL("illegal type of split");
+ }
+ sep = *fs;
+ ap = execute(a[1]); /* array name */
+/* BUG 7/26/22: this appears not to reset array: see C1/asplit */
+ freesymtab(ap);
+ DPRINTF("split: s=|%s|, a=%s, sep=|%s|\n", s, NN(ap->nval), fs);
+ ap->tval &= ~STR;
+ ap->tval |= ARR;
+ ap->sval = (char *) makesymtab(NSYMTAB);
+
+ n = 0;
+ if (arg3type == REGEXPR && strlen((char*)((fa*)a[2])->restr) == 0) {
+ /* split(s, a, //); have to arrange that it looks like empty sep */
+ arg3type = 0;
+ fs = "";
+ sep = 0;
+ }
+ if (*s != '\0' && (strlen(fs) > 1 || arg3type == REGEXPR)) { /* reg expr */
+ fa *pfa;
+ if (arg3type == REGEXPR) { /* it's ready already */
+ pfa = (fa *) a[2];
+ } else {
+ pfa = makedfa(fs, 1);
+ }
+ if (nematch(pfa,s)) {
+ tempstat = pfa->initstat;
+ pfa->initstat = 2;
+ do {
+ n++;
+ snprintf(num, sizeof(num), "%d", n);
+ temp = *patbeg;
+ setptr(patbeg, '\0');
+ if (is_number(s, & result))
+ setsymtab(num, s, result, STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, s, 0.0, STR, (Array *) ap->sval);
+ setptr(patbeg, temp);
+ s = patbeg + patlen;
+ if (*(patbeg+patlen-1) == '\0' || *s == '\0') {
+ n++;
+ snprintf(num, sizeof(num), "%d", n);
+ setsymtab(num, "", 0.0, STR, (Array *) ap->sval);
+ pfa->initstat = tempstat;
+ goto spdone;
+ }
+ } while (nematch(pfa,s));
+ pfa->initstat = tempstat; /* bwk: has to be here to reset */
+ /* cf gsub and refldbld */
+ }
+ n++;
+ snprintf(num, sizeof(num), "%d", n);
+ if (is_number(s, & result))
+ setsymtab(num, s, result, STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, s, 0.0, STR, (Array *) ap->sval);
+ spdone:
+ pfa = NULL;
+
+ } else if (a[2] == NULL && CSV) { /* CSV only if no explicit separator */
+ char *newt = (char *) malloc(strlen(s) + 1); /* for building new string; reuse for each field */
+ if (newt == NULL)
+ FATAL("out of space in split");
+ for (;;) {
+ char *fr = newt;
+ n++;
+ if (*s == '"' ) { /* start of "..." */
+ for (s++ ; *s != '\0'; ) {
+ if (*s == '"' && s[1] != '\0' && s[1] == '"') {
+ s += 2; /* doubled quote */
+ *fr++ = '"';
+ } else if (*s == '"' && (s[1] == '\0' || s[1] == ',')) {
+ s++; /* skip over closing quote */
+ break;
+ } else {
+ *fr++ = *s++;
+ }
+ }
+ *fr++ = 0;
+ } else { /* unquoted field */
+ while (*s != ',' && *s != '\0')
+ *fr++ = *s++;
+ *fr++ = 0;
+ }
+ snprintf(num, sizeof(num), "%d", n);
+ if (is_number(newt, &result))
+ setsymtab(num, newt, result, STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, newt, 0.0, STR, (Array *) ap->sval);
+ if (*s++ == '\0')
+ break;
+ }
+ free(newt);
+
+ } else if (!CSV && sep == ' ') { /* usual case: split on white space */
+ for (n = 0; ; ) {
+#define ISWS(c) ((c) == ' ' || (c) == '\t' || (c) == '\n')
+ while (ISWS(*s))
+ s++;
+ if (*s == '\0')
+ break;
+ n++;
+ t = s;
+ do
+ s++;
+ while (*s != '\0' && !ISWS(*s));
+ temp = *s;
+ setptr(s, '\0');
+ snprintf(num, sizeof(num), "%d", n);
+ if (is_number(t, & result))
+ setsymtab(num, t, result, STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, t, 0.0, STR, (Array *) ap->sval);
+ setptr(s, temp);
+ if (*s != '\0')
+ s++;
+ }
+
+ } else if (sep == 0) { /* new: split(s, a, "") => 1 char/elem */
+ for (n = 0; *s != '\0'; s += u8_nextlen(s)) {
+ char buf[10];
+ n++;
+ snprintf(num, sizeof(num), "%d", n);
+
+ for (j = 0; j < u8_nextlen(s); j++) {
+ buf[j] = s[j];
+ }
+ buf[j] = '\0';
+
+ if (isdigit((uschar)buf[0]))
+ setsymtab(num, buf, atof(buf), STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, buf, 0.0, STR, (Array *) ap->sval);
+ }
+
+ } else if (*s != '\0') { /* some random single character */
+ for (;;) {
+ n++;
+ t = s;
+ while (*s != sep && *s != '\0')
+ s++;
+ temp = *s;
+ setptr(s, '\0');
+ snprintf(num, sizeof(num), "%d", n);
+ if (is_number(t, & result))
+ setsymtab(num, t, result, STR|NUM, (Array *) ap->sval);
+ else
+ setsymtab(num, t, 0.0, STR, (Array *) ap->sval);
+ setptr(s, temp);
+ if (*s++ == '\0')
+ break;
+ }
+ }
+ tempfree(ap);
+ xfree(origs);
+ xfree(origfs);
+ x = gettemp();
+ x->tval = NUM;
+ x->fval = n;
+ return(x);
+}
+
+Cell *condexpr(Node **a, int n) /* a[0] ? a[1] : a[2] */
+{
+ Cell *x;
+
+ x = execute(a[0]);
+ if (istrue(x)) {
+ tempfree(x);
+ x = execute(a[1]);
+ } else {
+ tempfree(x);
+ x = execute(a[2]);
+ }
+ return(x);
+}
+
+Cell *ifstat(Node **a, int n) /* if (a[0]) a[1]; else a[2] */
+{
+ Cell *x;
+
+ x = execute(a[0]);
+ if (istrue(x)) {
+ tempfree(x);
+ x = execute(a[1]);
+ } else if (a[2] != NULL) {
+ tempfree(x);
+ x = execute(a[2]);
+ }
+ return(x);
+}
+
+Cell *whilestat(Node **a, int n) /* while (a[0]) a[1] */
+{
+ Cell *x;
+
+ for (;;) {
+ x = execute(a[0]);
+ if (!istrue(x))
+ return(x);
+ tempfree(x);
+ x = execute(a[1]);
+ if (isbreak(x)) {
+ x = True;
+ return(x);
+ }
+ if (isnext(x) || isexit(x) || isret(x))
+ return(x);
+ tempfree(x);
+ }
+}
+
+Cell *dostat(Node **a, int n) /* do a[0]; while(a[1]) */
+{
+ Cell *x;
+
+ for (;;) {
+ x = execute(a[0]);
+ if (isbreak(x))
+ return True;
+ if (isnext(x) || isexit(x) || isret(x))
+ return(x);
+ tempfree(x);
+ x = execute(a[1]);
+ if (!istrue(x))
+ return(x);
+ tempfree(x);
+ }
+}
+
+Cell *forstat(Node **a, int n) /* for (a[0]; a[1]; a[2]) a[3] */
+{
+ Cell *x;
+
+ x = execute(a[0]);
+ tempfree(x);
+ for (;;) {
+ if (a[1]!=NULL) {
+ x = execute(a[1]);
+ if (!istrue(x)) return(x);
+ else tempfree(x);
+ }
+ x = execute(a[3]);
+ if (isbreak(x)) /* turn off break */
+ return True;
+ if (isnext(x) || isexit(x) || isret(x))
+ return(x);
+ tempfree(x);
+ x = execute(a[2]);
+ tempfree(x);
+ }
+}
+
+Cell *instat(Node **a, int n) /* for (a[0] in a[1]) a[2] */
+{
+ Cell *x, *vp, *arrayp, *cp, *ncp;
+ Array *tp;
+ int i;
+
+ vp = execute(a[0]);
+ arrayp = execute(a[1]);
+ if (!isarr(arrayp)) {
+ return True;
+ }
+ tp = (Array *) arrayp->sval;
+ tempfree(arrayp);
+ for (i = 0; i < tp->size; i++) { /* this routine knows too much */
+ for (cp = tp->tab[i]; cp != NULL; cp = ncp) {
+ setsval(vp, cp->nval);
+ ncp = cp->cnext;
+ x = execute(a[2]);
+ if (isbreak(x)) {
+ tempfree(vp);
+ return True;
+ }
+ if (isnext(x) || isexit(x) || isret(x)) {
+ tempfree(vp);
+ return(x);
+ }
+ tempfree(x);
+ }
+ }
+ return True;
+}
+
+static char *nawk_convert(const char *s, int (*fun_c)(int),
+ wint_t (*fun_wc)(wint_t))
+{
+ char *buf = NULL;
+ char *pbuf = NULL;
+ const char *ps = NULL;
+ size_t n = 0;
+ wchar_t wc;
+ const size_t sz = awk_mb_cur_max;
+ int unused;
+
+ if (sz == 1) {
+ buf = tostring(s);
+
+ for (pbuf = buf; *pbuf; pbuf++)
+ *pbuf = fun_c((uschar)*pbuf);
+
+ return buf;
+ } else {
+ /* upper/lower character may be shorter/longer */
+ buf = tostringN(s, strlen(s) * sz + 1);
+
+ (void) mbtowc(NULL, NULL, 0); /* reset internal state */
+ /*
+ * Reset internal state here too.
+ * Assign result to avoid a compiler warning. (Casting to void
+ * doesn't work.)
+ * Increment said variable to avoid a different warning.
+ */
+ unused = wctomb(NULL, L'\0');
+ unused++;
+
+ ps = s;
+ pbuf = buf;
+ while (n = mbtowc(&wc, ps, sz),
+ n > 0 && n != (size_t)-1 && n != (size_t)-2)
+ {
+ ps += n;
+
+ n = wctomb(pbuf, fun_wc(wc));
+ if (n == (size_t)-1)
+ FATAL("illegal wide character %s", s);
+
+ pbuf += n;
+ }
+
+ *pbuf = '\0';
+
+ if (n)
+ FATAL("illegal byte sequence %s", s);
+
+ return buf;
+ }
+}
+
+#ifdef __DJGPP__
+static wint_t towupper(wint_t wc)
+{
+ if (wc >= 0 && wc < 256)
+ return toupper(wc & 0xFF);
+
+ return wc;
+}
+
+static wint_t towlower(wint_t wc)
+{
+ if (wc >= 0 && wc < 256)
+ return tolower(wc & 0xFF);
+
+ return wc;
+}
+#endif
+
+static char *nawk_toupper(const char *s)
+{
+ return nawk_convert(s, toupper, towupper);
+}
+
+static char *nawk_tolower(const char *s)
+{
+ return nawk_convert(s, tolower, towlower);
+}
+
+
+
+Cell *bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */
+{
+ Cell *x, *y;
+ Awkfloat u = 0;
+ int t;
+ Awkfloat tmp;
+ char *buf;
+ Node *nextarg;
+ FILE *fp;
+ int status = 0;
+ int estatus = 0;
+
+ t = ptoi(a[0]);
+ x = execute(a[1]);
+ nextarg = a[1]->nnext;
+ switch (t) {
+ case FLENGTH:
+ if (isarr(x))
+ u = ((Array *) x->sval)->nelem; /* GROT. should be function*/
+ else
+ u = u8_strlen(getsval(x));
+ break;
+ case FLOG:
+ u = log_errcheck(getfval(x));
+ break;
+ case FINT:
+ modf(getfval(x), &u); break;
+ case FEXP:
+ u = exp_errcheck(getfval(x));
+ break;
+ case FSQRT:
+ u = sqrt_errcheck(getfval(x));
+ break;
+ case FSIN:
+ u = sin(getfval(x)); break;
+ case FCOS:
+ u = cos(getfval(x)); break;
+ case FATAN:
+ if (nextarg == NULL) {
+ WARNING("atan2 requires two arguments; returning 1.0");
+ u = 1.0;
+ } else {
+ y = execute(a[1]->nnext);
+ u = atan2(getfval(x), getfval(y));
+ tempfree(y);
+ nextarg = nextarg->nnext;
+ }
+ break;
+ case FSYSTEM:
+ fflush(stdout); /* in case something is buffered already */
+ estatus = status = system(getsval(x));
+ if (status != -1) {
+ if (WIFEXITED(status)) {
+ estatus = WEXITSTATUS(status);
+ } else if (WIFSIGNALED(status)) {
+ estatus = WTERMSIG(status) + 256;
+#ifdef WCOREDUMP
+ if (WCOREDUMP(status))
+ estatus += 256;
+#endif
+ } else /* something else?!? */
+ estatus = 0;
+ }
+ /* else estatus was set to -1 */
+ u = estatus;
+ break;
+ case FRAND:
+ /* random() returns numbers in [0..2^31-1]
+ * in order to get a number in [0, 1), divide it by 2^31
+ */
+ do {
+ /* exact if Awkfloat wide enough */
+ u = (Awkfloat) random();
+ u /= 0x80000000; /* should be exact */
+ } while (u >= 1.0); /* in case Awkfloat is narrow */
+ break;
+ case FSRAND:
+ if (isrec(x)) /* no argument provided */
+ u = time((time_t *)0);
+ else
+ u = getfval(x);
+ tmp = u;
+ srandom((unsigned long) u);
+ u = srand_seed;
+ srand_seed = tmp;
+ break;
+ case FTOUPPER:
+ case FTOLOWER:
+ if (t == FTOUPPER)
+ buf = nawk_toupper(getsval(x));
+ else
+ buf = nawk_tolower(getsval(x));
+ tempfree(x);
+ x = gettemp();
+ setsval(x, buf);
+ free(buf);
+ return x;
+ case FFLUSH:
+ if (isrec(x) || strlen(getsval(x)) == 0) {
+ flush_all(); /* fflush() or fflush("") -> all */
+ u = 0;
+ } else if ((fp = openfile(FFLUSH, getsval(x), NULL)) == NULL)
+ u = EOF;
+ else
+ u = fflush(fp);
+ break;
+ default: /* can't happen */
+ FATAL("illegal function type %d", t);
+ break;
+ }
+ tempfree(x);
+ x = gettemp();
+ setfval(x, u);
+ if (nextarg != NULL) {
+ WARNING("warning: function has too many arguments");
+ for ( ; nextarg; nextarg = nextarg->nnext) {
+ y = execute(nextarg);
+ tempfree(y);
+ }
+ }
+ return(x);
+}
+
+Cell *printstat(Node **a, int n) /* print a[0] */
+{
+ Node *x;
+ Cell *y;
+ FILE *fp;
+
+ if (a[1] == NULL) /* a[1] is redirection operator, a[2] is file */
+ fp = stdout;
+ else
+ fp = redirect(ptoi(a[1]), a[2]);
+ for (x = a[0]; x != NULL; x = x->nnext) {
+ y = execute(x);
+ fputs(getpssval(y), fp);
+ tempfree(y);
+ if (x->nnext == NULL)
+ fputs(getsval(orsloc), fp);
+ else
+ fputs(getsval(ofsloc), fp);
+ }
+ if (a[1] != NULL)
+ fflush(fp);
+ if (ferror(fp))
+ FATAL("write error on %s", filename(fp));
+ return(True);
+}
+
+Cell *nullproc(Node **a, int n)
+{
+ return 0;
+}
+
+
+FILE *redirect(int a, Node *b) /* set up all i/o redirections */
+{
+ FILE *fp;
+ Cell *x;
+ char *fname;
+
+ x = execute(b);
+ fname = getsval(x);
+ fp = openfile(a, fname, NULL);
+ if (fp == NULL)
+ FATAL("can't open file %s", fname);
+ tempfree(x);
+ return fp;
+}
+
+struct files {
+ FILE *fp;
+ const char *fname;
+ int mode; /* '|', 'a', 'w' => LE/LT, GT */
+} *files;
+
+size_t nfiles;
+
+static void stdinit(void) /* in case stdin, etc., are not constants */
+{
+ nfiles = FOPEN_MAX;
+ files = (struct files *) calloc(nfiles, sizeof(*files));
+ if (files == NULL)
+ FATAL("can't allocate file memory for %zu files", nfiles);
+ files[0].fp = stdin;
+ files[0].fname = tostring("/dev/stdin");
+ files[0].mode = LT;
+ files[1].fp = stdout;
+ files[1].fname = tostring("/dev/stdout");
+ files[1].mode = GT;
+ files[2].fp = stderr;
+ files[2].fname = tostring("/dev/stderr");
+ files[2].mode = GT;
+}
+
+FILE *openfile(int a, const char *us, bool *pnewflag)
+{
+ const char *s = us;
+ size_t i;
+ int m;
+ FILE *fp = NULL;
+ struct stat sbuf;
+
+ if (*s == '\0')
+ FATAL("null file name in print or getline");
+
+ for (i = 0; i < nfiles; i++)
+ if (files[i].fname && strcmp(s, files[i].fname) == 0 &&
+ (a == files[i].mode || (a==APPEND && files[i].mode==GT) ||
+ a == FFLUSH)) {
+ if (pnewflag)
+ *pnewflag = false;
+ return files[i].fp;
+ }
+ if (a == FFLUSH) /* didn't find it, so don't create it! */
+ return NULL;
+ for (i = 0; i < nfiles; i++)
+ if (files[i].fp == NULL)
+ break;
+ if (i >= nfiles) {
+ struct files *nf;
+ size_t nnf = nfiles + FOPEN_MAX;
+ nf = (struct files *) realloc(files, nnf * sizeof(*nf));
+ if (nf == NULL)
+ FATAL("cannot grow files for %s and %zu files", s, nnf);
+ memset(&nf[nfiles], 0, FOPEN_MAX * sizeof(*nf));
+ nfiles = nnf;
+ files = nf;
+ }
+
+ fflush(stdout); /* force a semblance of order */
+
+ /* don't try to read or write a directory */
+ if (a == LT || a == GT || a == APPEND)
+ if (stat(s, &sbuf) == 0 && S_ISDIR(sbuf.st_mode))
+ return NULL;
+
+ m = a;
+ if (a == GT) {
+ fp = fopen(s, "w");
+ } else if (a == APPEND) {
+ fp = fopen(s, "a");
+ m = GT; /* so can mix > and >> */
+ } else if (a == '|') { /* output pipe */
+ fp = popen(s, "w");
+ } else if (a == LE) { /* input pipe */
+ fp = popen(s, "r");
+ } else if (a == LT) { /* getline <file */
+ fp = strcmp(s, "-") == 0 ? stdin : fopen(s, "r"); /* "-" is stdin */
+ } else /* can't happen */
+ FATAL("illegal redirection %d", a);
+ if (fp != NULL) {
+ files[i].fname = tostring(s);
+ files[i].fp = fp;
+ files[i].mode = m;
+ if (pnewflag)
+ *pnewflag = true;
+ if (fp != stdin && fp != stdout && fp != stderr)
+ (void) fcntl(fileno(fp), F_SETFD, FD_CLOEXEC);
+ }
+ return fp;
+}
+
+const char *filename(FILE *fp)
+{
+ size_t i;
+
+ for (i = 0; i < nfiles; i++)
+ if (fp == files[i].fp)
+ return files[i].fname;
+ return "???";
+}
+
+Cell *closefile(Node **a, int n)
+{
+ Cell *x;
+ size_t i;
+ bool stat;
+
+ x = execute(a[0]);
+ getsval(x);
+ stat = true;
+ for (i = 0; i < nfiles; i++) {
+ if (!files[i].fname || strcmp(x->sval, files[i].fname) != 0)
+ continue;
+ if (files[i].mode == GT || files[i].mode == '|')
+ fflush(files[i].fp);
+ if (ferror(files[i].fp)) {
+ if ((files[i].mode == GT && files[i].fp != stderr)
+ || files[i].mode == '|')
+ FATAL("write error on %s", files[i].fname);
+ else
+ WARNING("i/o error occurred on %s", files[i].fname);
+ }
+ if (files[i].fp == stdin || files[i].fp == stdout ||
+ files[i].fp == stderr)
+ stat = freopen("/dev/null", "r+", files[i].fp) == NULL;
+ else if (files[i].mode == '|' || files[i].mode == LE)
+ stat = pclose(files[i].fp) == -1;
+ else
+ stat = fclose(files[i].fp) == EOF;
+ if (stat)
+ WARNING("i/o error occurred closing %s", files[i].fname);
+ xfree(files[i].fname);
+ files[i].fname = NULL; /* watch out for ref thru this */
+ files[i].fp = NULL;
+ break;
+ }
+ tempfree(x);
+ x = gettemp();
+ setfval(x, (Awkfloat) (stat ? -1 : 0));
+ return(x);
+}
+
+void closeall(void)
+{
+ size_t i;
+ bool stat = false;
+
+ for (i = 0; i < nfiles; i++) {
+ if (! files[i].fp)
+ continue;
+ if (files[i].mode == GT || files[i].mode == '|')
+ fflush(files[i].fp);
+ if (ferror(files[i].fp)) {
+ if ((files[i].mode == GT && files[i].fp != stderr)
+ || files[i].mode == '|')
+ FATAL("write error on %s", files[i].fname);
+ else
+ WARNING("i/o error occurred on %s", files[i].fname);
+ }
+ if (files[i].fp == stdin || files[i].fp == stdout ||
+ files[i].fp == stderr)
+ continue;
+ if (files[i].mode == '|' || files[i].mode == LE)
+ stat = pclose(files[i].fp) == -1;
+ else
+ stat = fclose(files[i].fp) == EOF;
+ if (stat)
+ WARNING("i/o error occurred while closing %s", files[i].fname);
+ }
+}
+
+static void flush_all(void)
+{
+ size_t i;
+
+ for (i = 0; i < nfiles; i++)
+ if (files[i].fp)
+ fflush(files[i].fp);
+}
+
+void backsub(char **pb_ptr, const char **sptr_ptr);
+
+Cell *dosub(Node **a, int subop) /* sub and gsub */
+{
+ fa *pfa;
+ int tempstat = 0;
+ char *repl;
+ Cell *x;
+
+ char *buf = NULL;
+ char *pb = NULL;
+ int bufsz = recsize;
+
+ const char *r, *s;
+ const char *start;
+ const char *noempty = NULL; /* empty match disallowed here */
+ size_t m = 0; /* match count */
+ size_t whichm = 0; /* which match to select, 0 = global */
+ int mtype; /* match type */
+
+ if (a[0] == NULL) { /* 0 => a[1] is already-compiled regexpr */
+ pfa = (fa *) a[1];
+ } else {
+ x = execute(a[1]);
+ pfa = makedfa(getsval(x), 1);
+ tempfree(x);
+ }
+
+ x = execute(a[2]); /* replacement string */
+ repl = tostring(getsval(x));
+ tempfree(x);
+
+ switch (subop) {
+ case SUB:
+ whichm = 1;
+ x = execute(a[3]); /* source string */
+ break;
+ case GSUB:
+ whichm = 0;
+ x = execute(a[3]); /* source string */
+ break;
+ default:
+ FATAL("dosub: unrecognized subop: %d", subop);
+ }
+
+ start = getsval(x);
+ while (pmatch(pfa, start)) {
+ if (buf == NULL) {
+ if ((pb = buf = (char *) malloc(bufsz)) == NULL)
+ FATAL("out of memory in dosub");
+ tempstat = pfa->initstat;
+ pfa->initstat = 2;
+ }
+
+ /* match types */
+ #define MT_IGNORE 0 /* unselected or invalid */
+ #define MT_INSERT 1 /* selected, empty */
+ #define MT_REPLACE 2 /* selected, not empty */
+
+ /* an empty match just after replacement is invalid */
+
+ if (patbeg == noempty && patlen == 0) {
+ mtype = MT_IGNORE; /* invalid, not counted */
+ } else if (whichm == ++m || whichm == 0) {
+ mtype = patlen ? MT_REPLACE : MT_INSERT;
+ } else {
+ mtype = MT_IGNORE; /* unselected, but counted */
+ }
+
+ /* leading text: */
+ if (patbeg > start) {
+ adjbuf(&buf, &bufsz, (pb - buf) + (patbeg - start),
+ recsize, &pb, "dosub");
+ s = start;
+ while (s < patbeg)
+ *pb++ = *s++;
+ }
+
+ if (mtype == MT_IGNORE)
+ goto matching_text; /* skip replacement text */
+
+ r = repl;
+ while (*r != 0) {
+ adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "dosub");
+ if (*r == '\\') {
+ backsub(&pb, &r);
+ } else if (*r == '&') {
+ r++;
+ adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize,
+ &pb, "dosub");
+ for (s = patbeg; s < patbeg+patlen; )
+ *pb++ = *s++;
+ } else {
+ *pb++ = *r++;
+ }
+ }
+
+matching_text:
+ if (mtype == MT_REPLACE || *patbeg == '\0')
+ goto next_search; /* skip matching text */
+
+ if (patlen == 0)
+ patlen = u8_nextlen(patbeg);
+ adjbuf(&buf, &bufsz, (pb-buf) + patlen, recsize, &pb, "dosub");
+ s = patbeg;
+ while (s < patbeg + patlen)
+ *pb++ = *s++;
+
+next_search:
+ start = patbeg + patlen;
+ if (m == whichm || *patbeg == '\0')
+ break;
+ if (mtype == MT_REPLACE)
+ noempty = start;
+
+ #undef MT_IGNORE
+ #undef MT_INSERT
+ #undef MT_REPLACE
+ }
+
+ if (repl) {
+ free(repl);
+ }
+
+ if (buf != NULL) {
+ pfa->initstat = tempstat;
+
+ /* trailing text */
+ adjbuf(&buf, &bufsz, 1+strlen(start)+pb-buf, 0, &pb, "dosub");
+ while ((*pb++ = *start++) != '\0')
+ ;
+
+ setsval(x, buf);
+ free(buf);
+ }
+
+ tempfree(x);
+ x = gettemp();
+ x->tval = NUM;
+ x->fval = m;
+ return x;
+}
+
+void backsub(char **pb_ptr, const char **sptr_ptr) /* handle \\& variations */
+{ /* sptr[0] == '\\' */
+ char *pb = *pb_ptr;
+ const char *sptr = *sptr_ptr;
+ static bool first = true;
+ static bool do_posix = false;
+
+ if (first) {
+ first = false;
+ do_posix = (getenv("POSIXLY_CORRECT") != NULL);
+ }
+
+ if (sptr[1] == '\\') {
+ if (sptr[2] == '\\' && sptr[3] == '&') { /* \\\& -> \& */
+ *pb++ = '\\';
+ *pb++ = '&';
+ sptr += 4;
+ } else if (sptr[2] == '&') { /* \\& -> \ + matched */
+ *pb++ = '\\';
+ sptr += 2;
+ } else if (do_posix) { /* \\x -> \x */
+ sptr++;
+ *pb++ = *sptr++;
+ } else { /* \\x -> \\x */
+ *pb++ = *sptr++;
+ *pb++ = *sptr++;
+ }
+ } else if (sptr[1] == '&') { /* literal & */
+ sptr++;
+ *pb++ = *sptr++;
+ } else /* literal \ */
+ *pb++ = *sptr++;
+
+ *pb_ptr = pb;
+ *sptr_ptr = sptr;
+}
+
+static char *wide_char_to_byte_str(int rune, size_t *outlen)
+{
+ static char buf[5];
+ int len;
+
+ if (rune < 0 || rune > 0x10FFFF)
+ return NULL;
+
+ memset(buf, 0, sizeof(buf));
+
+ len = 0;
+ if (rune <= 0x0000007F) {
+ buf[len++] = rune;
+ } else if (rune <= 0x000007FF) {
+ // 110xxxxx 10xxxxxx
+ buf[len++] = 0xC0 | (rune >> 6);
+ buf[len++] = 0x80 | (rune & 0x3F);
+ } else if (rune <= 0x0000FFFF) {
+ // 1110xxxx 10xxxxxx 10xxxxxx
+ buf[len++] = 0xE0 | (rune >> 12);
+ buf[len++] = 0x80 | ((rune >> 6) & 0x3F);
+ buf[len++] = 0x80 | (rune & 0x3F);
+
+ } else {
+ // 0x00010000 - 0x10FFFF
+ // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ buf[len++] = 0xF0 | (rune >> 18);
+ buf[len++] = 0x80 | ((rune >> 12) & 0x3F);
+ buf[len++] = 0x80 | ((rune >> 6) & 0x3F);
+ buf[len++] = 0x80 | (rune & 0x3F);
+ }
+
+ *outlen = len;
+ buf[len++] = '\0';
+
+ return buf;
+}
diff --git a/cmd/posix/awk/tran.c b/cmd/posix/awk/tran.c
@@ -0,0 +1,650 @@
+/****************************************************************
+Copyright (C) Lucent Technologies 1997
+All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and
+its documentation for any purpose and without fee is hereby
+granted, provided that the above copyright notice appear in all
+copies and that both that the copyright notice and this
+permission notice and warranty disclaimer appear in supporting
+documentation, and that the name Lucent Technologies or any of
+its entities not be used in advertising or publicity pertaining
+to distribution of the software without specific, written prior
+permission.
+
+LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
+SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
+IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
+****************************************************************/
+
+#define DEBUG
+#include <stdio.h>
+#include <math.h>
+#include <ctype.h>
+#include <string.h>
+#include <stdlib.h>
+#include "awk.h"
+
+#define FULLTAB 2 /* rehash when table gets this x full */
+#define GROWTAB 4 /* grow table by this factor */
+
+Array *symtab; /* main symbol table */
+
+char **FS; /* initial field sep */
+char **RS; /* initial record sep */
+char **OFS; /* output field sep */
+char **ORS; /* output record sep */
+char **OFMT; /* output format for numbers */
+char **CONVFMT; /* format for conversions in getsval */
+Awkfloat *NF; /* number of fields in current record */
+Awkfloat *NR; /* number of current record */
+Awkfloat *FNR; /* number of current record in current file */
+char **FILENAME; /* current filename argument */
+Awkfloat *ARGC; /* number of arguments from command line */
+char **SUBSEP; /* subscript separator for a[i,j,k]; default \034 */
+Awkfloat *RSTART; /* start of re matched with ~; origin 1 (!) */
+Awkfloat *RLENGTH; /* length of same */
+
+Cell *fsloc; /* FS */
+Cell *nrloc; /* NR */
+Cell *nfloc; /* NF */
+Cell *fnrloc; /* FNR */
+Cell *ofsloc; /* OFS */
+Cell *orsloc; /* ORS */
+Cell *rsloc; /* RS */
+Cell *ARGVcell; /* cell with symbol table containing ARGV[...] */
+Cell *rstartloc; /* RSTART */
+Cell *rlengthloc; /* RLENGTH */
+Cell *subseploc; /* SUBSEP */
+Cell *symtabloc; /* SYMTAB */
+
+Cell *nullloc; /* a guaranteed empty cell */
+Node *nullnode; /* zero&null, converted into a node for comparisons */
+Cell *literal0;
+
+extern Cell **fldtab;
+
+void syminit(void) /* initialize symbol table with builtin vars */
+{
+ literal0 = setsymtab("0", "0", 0.0, NUM|STR|CON|DONTFREE, symtab);
+ /* this is used for if(x)... tests: */
+ nullloc = setsymtab("$zero&null", "", 0.0, NUM|STR|CON|DONTFREE, symtab);
+ nullnode = celltonode(nullloc, CCON);
+
+ fsloc = setsymtab("FS", " ", 0.0, STR|DONTFREE, symtab);
+ FS = &fsloc->sval;
+ rsloc = setsymtab("RS", "\n", 0.0, STR|DONTFREE, symtab);
+ RS = &rsloc->sval;
+ ofsloc = setsymtab("OFS", " ", 0.0, STR|DONTFREE, symtab);
+ OFS = &ofsloc->sval;
+ orsloc = setsymtab("ORS", "\n", 0.0, STR|DONTFREE, symtab);
+ ORS = &orsloc->sval;
+ OFMT = &setsymtab("OFMT", "%.6g", 0.0, STR|DONTFREE, symtab)->sval;
+ CONVFMT = &setsymtab("CONVFMT", "%.6g", 0.0, STR|DONTFREE, symtab)->sval;
+ FILENAME = &setsymtab("FILENAME", "", 0.0, STR|DONTFREE, symtab)->sval;
+ nfloc = setsymtab("NF", "", 0.0, NUM, symtab);
+ NF = &nfloc->fval;
+ nrloc = setsymtab("NR", "", 0.0, NUM, symtab);
+ NR = &nrloc->fval;
+ fnrloc = setsymtab("FNR", "", 0.0, NUM, symtab);
+ FNR = &fnrloc->fval;
+ subseploc = setsymtab("SUBSEP", "\034", 0.0, STR|DONTFREE, symtab);
+ SUBSEP = &subseploc->sval;
+ rstartloc = setsymtab("RSTART", "", 0.0, NUM, symtab);
+ RSTART = &rstartloc->fval;
+ rlengthloc = setsymtab("RLENGTH", "", 0.0, NUM, symtab);
+ RLENGTH = &rlengthloc->fval;
+ symtabloc = setsymtab("SYMTAB", "", 0.0, ARR, symtab);
+ free(symtabloc->sval);
+ symtabloc->sval = (char *) symtab;
+}
+
+void arginit(int ac, char **av) /* set up ARGV and ARGC */
+{
+ Array *ap;
+ Cell *cp;
+ int i;
+ char temp[50];
+
+ ARGC = &setsymtab("ARGC", "", (Awkfloat) ac, NUM, symtab)->fval;
+ cp = setsymtab("ARGV", "", 0.0, ARR, symtab);
+ ap = makesymtab(NSYMTAB); /* could be (int) ARGC as well */
+ free(cp->sval);
+ cp->sval = (char *) ap;
+ for (i = 0; i < ac; i++) {
+ double result;
+
+ sprintf(temp, "%d", i);
+ if (is_number(*av, & result))
+ setsymtab(temp, *av, result, STR|NUM, ap);
+ else
+ setsymtab(temp, *av, 0.0, STR, ap);
+ av++;
+ }
+ ARGVcell = cp;
+}
+
+void envinit(char **envp) /* set up ENVIRON variable */
+{
+ Array *ap;
+ Cell *cp;
+ char *p;
+
+ cp = setsymtab("ENVIRON", "", 0.0, ARR, symtab);
+ ap = makesymtab(NSYMTAB);
+ free(cp->sval);
+ cp->sval = (char *) ap;
+ for ( ; *envp; envp++) {
+ double result;
+
+ if ((p = strchr(*envp, '=')) == NULL)
+ continue;
+ if( p == *envp ) /* no left hand side name in env string */
+ continue;
+ *p++ = 0; /* split into two strings at = */
+ if (is_number(p, & result))
+ setsymtab(*envp, p, result, STR|NUM, ap);
+ else
+ setsymtab(*envp, p, 0.0, STR, ap);
+ p[-1] = '='; /* restore in case env is passed down to a shell */
+ }
+}
+
+Array *makesymtab(int n) /* make a new symbol table */
+{
+ Array *ap;
+ Cell **tp;
+
+ ap = (Array *) malloc(sizeof(*ap));
+ tp = (Cell **) calloc(n, sizeof(*tp));
+ if (ap == NULL || tp == NULL)
+ FATAL("out of space in makesymtab");
+ ap->nelem = 0;
+ ap->size = n;
+ ap->tab = tp;
+ return(ap);
+}
+
+void freesymtab(Cell *ap) /* free a symbol table */
+{
+ Cell *cp, *temp;
+ Array *tp;
+ int i;
+
+ if (!isarr(ap))
+ return;
+ tp = (Array *) ap->sval;
+ if (tp == NULL)
+ return;
+ for (i = 0; i < tp->size; i++) {
+ for (cp = tp->tab[i]; cp != NULL; cp = temp) {
+ xfree(cp->nval);
+ if (freeable(cp))
+ xfree(cp->sval);
+ temp = cp->cnext; /* avoids freeing then using */
+ free(cp);
+ tp->nelem--;
+ }
+ tp->tab[i] = NULL;
+ }
+ if (tp->nelem != 0)
+ WARNING("can't happen: inconsistent element count freeing %s", ap->nval);
+ free(tp->tab);
+ free(tp);
+}
+
+void freeelem(Cell *ap, const char *s) /* free elem s from ap (i.e., ap["s"] */
+{
+ Array *tp;
+ Cell *p, *prev = NULL;
+ int h;
+
+ tp = (Array *) ap->sval;
+ h = hash(s, tp->size);
+ for (p = tp->tab[h]; p != NULL; prev = p, p = p->cnext)
+ if (strcmp(s, p->nval) == 0) {
+ if (prev == NULL) /* 1st one */
+ tp->tab[h] = p->cnext;
+ else /* middle somewhere */
+ prev->cnext = p->cnext;
+ if (freeable(p))
+ xfree(p->sval);
+ free(p->nval);
+ free(p);
+ tp->nelem--;
+ return;
+ }
+}
+
+Cell *setsymtab(const char *n, const char *s, Awkfloat f, unsigned t, Array *tp)
+{
+ int h;
+ Cell *p;
+
+ if (n != NULL && (p = lookup(n, tp)) != NULL) {
+ DPRINTF("setsymtab found %p: n=%s s=\"%s\" f=%g t=%o\n",
+ (void*)p, NN(p->nval), NN(p->sval), p->fval, p->tval);
+ return(p);
+ }
+ p = (Cell *) malloc(sizeof(*p));
+ if (p == NULL)
+ FATAL("out of space for symbol table at %s", n);
+ p->nval = tostring(n);
+ p->sval = s ? tostring(s) : tostring("");
+ p->fval = f;
+ p->tval = t;
+ p->csub = CUNK;
+ p->ctype = OCELL;
+ tp->nelem++;
+ if (tp->nelem > FULLTAB * tp->size)
+ rehash(tp);
+ h = hash(n, tp->size);
+ p->cnext = tp->tab[h];
+ tp->tab[h] = p;
+ DPRINTF("setsymtab set %p: n=%s s=\"%s\" f=%g t=%o\n",
+ (void*)p, p->nval, p->sval, p->fval, p->tval);
+ return(p);
+}
+
+int hash(const char *s, int n) /* form hash value for string s */
+{
+ unsigned hashval;
+
+ for (hashval = 0; *s != '\0'; s++)
+ hashval = (*s + 31 * hashval);
+ return hashval % n;
+}
+
+void rehash(Array *tp) /* rehash items in small table into big one */
+{
+ int i, nh, nsz;
+ Cell *cp, *op, **np;
+
+ nsz = GROWTAB * tp->size;
+ np = (Cell **) calloc(nsz, sizeof(*np));
+ if (np == NULL) /* can't do it, but can keep running. */
+ return; /* someone else will run out later. */
+ for (i = 0; i < tp->size; i++) {
+ for (cp = tp->tab[i]; cp; cp = op) {
+ op = cp->cnext;
+ nh = hash(cp->nval, nsz);
+ cp->cnext = np[nh];
+ np[nh] = cp;
+ }
+ }
+ free(tp->tab);
+ tp->tab = np;
+ tp->size = nsz;
+}
+
+Cell *lookup(const char *s, Array *tp) /* look for s in tp */
+{
+ Cell *p;
+ int h;
+
+ h = hash(s, tp->size);
+ for (p = tp->tab[h]; p != NULL; p = p->cnext)
+ if (strcmp(s, p->nval) == 0)
+ return(p); /* found it */
+ return(NULL); /* not found */
+}
+
+Awkfloat setfval(Cell *vp, Awkfloat f) /* set float val of a Cell */
+{
+ int fldno;
+
+ f += 0.0; /* normalise negative zero to positive zero */
+ if ((vp->tval & (NUM | STR)) == 0)
+ funnyvar(vp, "assign to");
+ if (isfld(vp)) {
+ donerec = false; /* mark $0 invalid */
+ fldno = atoi(vp->nval);
+ if (fldno > *NF)
+ newfld(fldno);
+ DPRINTF("setting field %d to %g\n", fldno, f);
+ } else if (&vp->fval == NF) {
+ donerec = false; /* mark $0 invalid */
+ setlastfld(f);
+ DPRINTF("setfval: setting NF to %g\n", f);
+ } else if (isrec(vp)) {
+ donefld = false; /* mark $1... invalid */
+ donerec = true;
+ savefs();
+ } else if (vp == ofsloc) {
+ if (!donerec)
+ recbld();
+ }
+ if (freeable(vp))
+ xfree(vp->sval); /* free any previous string */
+ vp->tval &= ~(STR|CONVC|CONVO); /* mark string invalid */
+ vp->fmt = NULL;
+ vp->tval |= NUM; /* mark number ok */
+ if (f == -0) /* who would have thought this possible? */
+ f = 0;
+ DPRINTF("setfval %p: %s = %g, t=%o\n", (void*)vp, NN(vp->nval), f, vp->tval);
+ return vp->fval = f;
+}
+
+void funnyvar(Cell *vp, const char *rw)
+{
+ if (isarr(vp))
+ FATAL("can't %s %s; it's an array name.", rw, vp->nval);
+ if (vp->tval & FCN)
+ FATAL("can't %s %s; it's a function.", rw, vp->nval);
+ WARNING("funny variable %p: n=%s s=\"%s\" f=%g t=%o",
+ (void *)vp, vp->nval, vp->sval, vp->fval, vp->tval);
+}
+
+char *setsval(Cell *vp, const char *s) /* set string val of a Cell */
+{
+ char *t;
+ int fldno;
+ Awkfloat f;
+
+ DPRINTF("starting setsval %p: %s = \"%s\", t=%o, r,f=%d,%d\n",
+ (void*)vp, NN(vp->nval), s, vp->tval, donerec, donefld);
+ if ((vp->tval & (NUM | STR)) == 0)
+ funnyvar(vp, "assign to");
+ if (CSV && (vp == rsloc))
+ WARNING("danger: don't set RS when --csv is in effect");
+ if (CSV && (vp == fsloc))
+ WARNING("danger: don't set FS when --csv is in effect");
+ if (isfld(vp)) {
+ donerec = false; /* mark $0 invalid */
+ fldno = atoi(vp->nval);
+ if (fldno > *NF)
+ newfld(fldno);
+ DPRINTF("setting field %d to %s (%p)\n", fldno, s, (const void*)s);
+ } else if (isrec(vp)) {
+ donefld = false; /* mark $1... invalid */
+ donerec = true;
+ savefs();
+ } else if (vp == ofsloc) {
+ if (!donerec)
+ recbld();
+ }
+ t = s ? tostring(s) : tostring(""); /* in case it's self-assign */
+ if (freeable(vp))
+ xfree(vp->sval);
+ vp->tval &= ~(NUM|DONTFREE|CONVC|CONVO);
+ vp->tval |= STR;
+ vp->fmt = NULL;
+ DPRINTF("setsval %p: %s = \"%s (%p) \", t=%o r,f=%d,%d\n",
+ (void*)vp, NN(vp->nval), t, (void*)t, vp->tval, donerec, donefld);
+ vp->sval = t;
+ if (&vp->fval == NF) {
+ donerec = false; /* mark $0 invalid */
+ f = getfval(vp);
+ setlastfld(f);
+ DPRINTF("setsval: setting NF to %g\n", f);
+ }
+
+ return(vp->sval);
+}
+
+Awkfloat getfval(Cell *vp) /* get float val of a Cell */
+{
+ if ((vp->tval & (NUM | STR)) == 0)
+ funnyvar(vp, "read value of");
+ if (isfld(vp) && !donefld)
+ fldbld();
+ else if (isrec(vp) && !donerec)
+ recbld();
+ if (!isnum(vp)) { /* not a number */
+ double fval;
+ bool no_trailing;
+
+ if (is_valid_number(vp->sval, true, & no_trailing, & fval)) {
+ vp->fval = fval;
+ if (no_trailing && !(vp->tval&CON))
+ vp->tval |= NUM; /* make NUM only sparingly */
+ } else
+ vp->fval = 0.0;
+ }
+ DPRINTF("getfval %p: %s = %g, t=%o\n",
+ (void*)vp, NN(vp->nval), vp->fval, vp->tval);
+ return(vp->fval);
+}
+
+static const char *get_inf_nan(double d)
+{
+ if (isinf(d)) {
+ return (d < 0 ? "-inf" : "+inf");
+ } else if (isnan(d)) {
+ return (signbit(d) != 0 ? "-nan" : "+nan");
+ } else
+ return NULL;
+}
+
+static char *get_str_val(Cell *vp, char **fmt) /* get string val of a Cell */
+{
+ char s[256];
+ double dtemp;
+ const char *p;
+
+ if ((vp->tval & (NUM | STR)) == 0)
+ funnyvar(vp, "read value of");
+ if (isfld(vp) && ! donefld)
+ fldbld();
+ else if (isrec(vp) && ! donerec)
+ recbld();
+
+ /*
+ * ADR: This is complicated and more fragile than is desirable.
+ * Retrieving a string value for a number associates the string
+ * value with the scalar. Previously, the string value was
+ * sticky, meaning if converted via OFMT that became the value
+ * (even though POSIX wants it to be via CONVFMT). Or if CONVFMT
+ * changed after a string value was retrieved, the original value
+ * was maintained and used. Also not per POSIX.
+ *
+ * We work around this design by adding two additional flags,
+ * CONVC and CONVO, indicating how the string value was
+ * obtained (via CONVFMT or OFMT) and _also_ maintaining a copy
+ * of the pointer to the xFMT format string used for the
+ * conversion. This pointer is only read, **never** dereferenced.
+ * The next time we do a conversion, if it's coming from the same
+ * xFMT as last time, and the pointer value is different, we
+ * know that the xFMT format string changed, and we need to
+ * redo the conversion. If it's the same, we don't have to.
+ *
+ * There are also several cases where we don't do a conversion,
+ * such as for a field (see the checks below).
+ */
+
+ /* Don't duplicate the code for actually updating the value */
+#define update_str_val(vp) \
+ { \
+ if (freeable(vp)) \
+ xfree(vp->sval); \
+ if ((p = get_inf_nan(vp->fval)) != NULL) \
+ strcpy(s, p); \
+ else if (modf(vp->fval, &dtemp) == 0) /* it's integral */ \
+ snprintf(s, sizeof (s), "%.30g", vp->fval); \
+ else \
+ snprintf(s, sizeof (s), *fmt, vp->fval); \
+ vp->sval = tostring(s); \
+ vp->tval &= ~DONTFREE; \
+ vp->tval |= STR; \
+ }
+
+ if (isstr(vp) == 0) {
+ update_str_val(vp);
+ if (fmt == OFMT) {
+ vp->tval &= ~CONVC;
+ vp->tval |= CONVO;
+ } else {
+ /* CONVFMT */
+ vp->tval &= ~CONVO;
+ vp->tval |= CONVC;
+ }
+ vp->fmt = *fmt;
+ } else if ((vp->tval & DONTFREE) != 0 || ! isnum(vp) || isfld(vp)) {
+ goto done;
+ } else if (isstr(vp)) {
+ if (fmt == OFMT) {
+ if ((vp->tval & CONVC) != 0
+ || ((vp->tval & CONVO) != 0 && vp->fmt != *fmt)) {
+ update_str_val(vp);
+ vp->tval &= ~CONVC;
+ vp->tval |= CONVO;
+ vp->fmt = *fmt;
+ }
+ } else {
+ /* CONVFMT */
+ if ((vp->tval & CONVO) != 0
+ || ((vp->tval & CONVC) != 0 && vp->fmt != *fmt)) {
+ update_str_val(vp);
+ vp->tval &= ~CONVO;
+ vp->tval |= CONVC;
+ vp->fmt = *fmt;
+ }
+ }
+ }
+done:
+ DPRINTF("getsval %p: %s = \"%s (%p)\", t=%o\n",
+ (void*)vp, NN(vp->nval), vp->sval, (void*)vp->sval, vp->tval);
+ return(vp->sval);
+}
+
+char *getsval(Cell *vp) /* get string val of a Cell */
+{
+ return get_str_val(vp, CONVFMT);
+}
+
+char *getpssval(Cell *vp) /* get string val of a Cell for print */
+{
+ return get_str_val(vp, OFMT);
+}
+
+
+char *tostring(const char *s) /* make a copy of string s */
+{
+ char *p = strdup(s);
+ if (p == NULL)
+ FATAL("out of space in tostring on %s", s);
+ return(p);
+}
+
+char *tostringN(const char *s, size_t n) /* make a copy of string s */
+{
+ char *p;
+
+ p = (char *) malloc(n);
+ if (p == NULL)
+ FATAL("out of space in tostring on %s", s);
+ strcpy(p, s);
+ return(p);
+}
+
+Cell *catstr(Cell *a, Cell *b) /* concatenate a and b */
+{
+ Cell *c;
+ char *p;
+ char *sa = getsval(a);
+ char *sb = getsval(b);
+ size_t l = strlen(sa) + strlen(sb) + 1;
+ p = (char *) malloc(l);
+ if (p == NULL)
+ FATAL("out of space concatenating %s and %s", sa, sb);
+ snprintf(p, l, "%s%s", sa, sb);
+
+ l++; // add room for ' '
+ char *newbuf = (char *) malloc(l);
+ if (newbuf == NULL)
+ FATAL("out of space concatenating %s and %s", sa, sb);
+ // See string() in lex.c; a string "xx" is stored in the symbol
+ // table as "xx ".
+ snprintf(newbuf, l, "%s ", p);
+ c = setsymtab(newbuf, p, 0.0, CON|STR|DONTFREE, symtab);
+ free(p);
+ free(newbuf);
+ return c;
+}
+
+char *qstring(const char *is, int delim) /* collect string up to next delim */
+{
+ int c, n;
+ const uschar *s = (const uschar *) is;
+ uschar *buf, *bp;
+
+ if ((buf = (uschar *) malloc(strlen(is)+3)) == NULL)
+ FATAL( "out of space in qstring(%s)", s);
+ for (bp = buf; (c = *s) != delim; s++) {
+ if (c == '\n')
+ SYNTAX( "newline in string %.20s...", is );
+ else if (c != '\\')
+ *bp++ = c;
+ else { /* \something */
+ c = *++s;
+ if (c == 0) { /* \ at end */
+ *bp++ = '\\';
+ break; /* for loop */
+ }
+ switch (c) {
+ case '\\': *bp++ = '\\'; break;
+ case 'n': *bp++ = '\n'; break;
+ case 't': *bp++ = '\t'; break;
+ case 'b': *bp++ = '\b'; break;
+ case 'f': *bp++ = '\f'; break;
+ case 'r': *bp++ = '\r'; break;
+ case 'v': *bp++ = '\v'; break;
+ case 'a': *bp++ = '\a'; break;
+ default:
+ if (!isdigit(c)) {
+ *bp++ = c;
+ break;
+ }
+ n = c - '0';
+ if (isdigit(s[1])) {
+ n = 8 * n + *++s - '0';
+ if (isdigit(s[1]))
+ n = 8 * n + *++s - '0';
+ }
+ *bp++ = n;
+ break;
+ }
+ }
+ }
+ *bp++ = 0;
+ return (char *) buf;
+}
+
+const char *flags2str(int flags)
+{
+ static const struct ftab {
+ const char *name;
+ int value;
+ } flagtab[] = {
+ { "NUM", NUM },
+ { "STR", STR },
+ { "DONTFREE", DONTFREE },
+ { "CON", CON },
+ { "ARR", ARR },
+ { "FCN", FCN },
+ { "FLD", FLD },
+ { "REC", REC },
+ { "CONVC", CONVC },
+ { "CONVO", CONVO },
+ { NULL, 0 }
+ };
+ static char buf[100];
+ int i;
+ char *cp = buf;
+
+ for (i = 0; flagtab[i].name != NULL; i++) {
+ if ((flags & flagtab[i].value) != 0) {
+ if (cp > buf)
+ *cp++ = '|';
+ strcpy(cp, flagtab[i].name);
+ cp += strlen(cp);
+ }
+ }
+
+ return buf;
+}
diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c
@@ -77,7 +77,7 @@ printgrid(size_t year, int month, int fday, int line)
if (trans && !(line == 2 && fday == 3))
dom += 11;
}
- if (ltime && year == ltime->tm_year + 1900 && month == ltime->tm_mon)
+ if (ltime && year == (size_t)(ltime->tm_year + 1900) && month == ltime->tm_mon)
today = ltime->tm_mday;
for (; d < 7 && dom <= monthlength(year, month, cal); ++d, ++dom) {
if (dom == today)
@@ -98,8 +98,8 @@ drawcal(size_t year, int month, size_t ncols, size_t nmons, int fday)
"May", "June", "July", "August",
"September", "October", "November", "December" };
char *days[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", };
- size_t m, n, col, cur_year, cur_month, dow;
- int line, pad;
+ size_t m, n, col, cur_year, cur_month;
+ int line, pad, dow;
char month_year[sizeof("Su Mo Tu We Th Fr Sa")];
for (m = 0; m < nmons; ) {
@@ -141,8 +141,12 @@ drawcal(size_t year, int month, size_t ncols, size_t nmons, int fday)
static void
usage(void)
{
+#ifdef FEATURE_CAL_EXT
eprintf("usage: %s [-1 | -3 | -y | -n num] "
"[-s | -m | -f num] [-c num] [[month] year]\n", argv0);
+#else
+ eprintf("usage: %s [-y] [[month] year]\n", argv0);
+#endif
}
int
@@ -161,10 +165,16 @@ main(int argc, char *argv[])
if (!isatty(STDOUT_FILENO))
ltime = NULL; /* don't highlight today's date */
+#ifdef FEATURE_CAL_EXT
ncols = 3;
nmons = 0;
+#else
+ ncols = 1;
+ nmons = 1;
+#endif
ARGBEGIN {
+#ifdef FEATURE_CAL_EXT
case '1':
nmons = 1;
break;
@@ -176,7 +186,7 @@ main(int argc, char *argv[])
}
break;
case 'c':
- ncols = estrtonum(EARGF(usage()), 0, MIN(SIZE_MAX, LLONG_MAX));
+ ncols = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
case 'f':
fday = estrtonum(EARGF(usage()), 0, 6);
@@ -185,11 +195,12 @@ main(int argc, char *argv[])
fday = 1;
break;
case 'n':
- nmons = estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
+ nmons = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
case 's': /* Sunday */
fday = 0;
break;
+#endif
case 'y':
month = 1;
nmons = 12;
@@ -198,6 +209,7 @@ main(int argc, char *argv[])
usage();
} ARGEND
+#ifdef FEATURE_CAL_EXT
if (nmons == 0) {
if (argc == 1) {
month = 1;
@@ -206,12 +218,14 @@ main(int argc, char *argv[])
nmons = 1;
}
}
+#endif
switch (argc) {
case 2:
month = estrtonum(argv[0], 1, 12);
argv++;
- case 1: /* fallthrough */
+ /* fallthrough */
+ case 1:
year = estrtonum(argv[0], 0, INT_MAX);
break;
case 0:
diff --git a/cmd/posix/chgrp.c b/cmd/posix/chgrp.c
@@ -18,6 +18,8 @@ chgrp(int dirfd, const char *name, struct stat *st, void *data, struct recursor
{
int flags = 0;
+ (void)data;
+
if ((r->maxdepth == 0 && r->follow == 'P') || (r->follow == 'H' && r->depth) || (hflag && !(r->depth)))
flags |= AT_SYMLINK_NOFOLLOW;
if (fchownat(dirfd, name, -1, gid, flags) < 0) {
diff --git a/cmd/posix/chmod.c b/cmd/posix/chmod.c
@@ -14,6 +14,8 @@ chmodr(int dirfd, const char *name, struct stat *st, void *data, struct recursor
{
mode_t m;
+ (void)data;
+
m = parsemode(modestr, st->st_mode, mask);
if (!S_ISLNK(st->st_mode) && fchmodat(dirfd, name, m, 0) < 0) {
weprintf("chmod %s:", r->path);
diff --git a/cmd/posix/chown.c b/cmd/posix/chown.c
@@ -21,6 +21,8 @@ chownpwgr(int dirfd, const char *name, struct stat *st, void *data, struct recur
{
int flags = 0;
+ (void)data;
+
if ((r->maxdepth == 0 && r->follow == 'P') || (r->follow == 'H' && r->depth) || (hflag && !(r->depth)))
flags |= AT_SYMLINK_NOFOLLOW;
diff --git a/cmd/posix/cksum.c b/cmd/posix/cksum.c
@@ -71,7 +71,7 @@ cksum(int fd, const char *s)
unsigned char buf[BUFSIZ];
while ((n = read(fd, buf, sizeof(buf))) > 0) {
- for (i = 0; i < n; i++)
+ for (i = 0; i < (size_t)n; i++)
ck = (ck << 8) ^ crctab[(ck >> 24) ^ buf[i]];
len += n;
}
diff --git a/cmd/posix/dd.c b/cmd/posix/dd.c
@@ -193,7 +193,7 @@ main(int argc, char *argv[])
continue;
ret = 0;
}
- if (ret < ibs) {
+ if ((size_t)ret < ibs) {
ipart++;
if (conv & SYNC) {
memset(buf + ipos + ret, 0, ibs - ret);
@@ -220,7 +220,7 @@ main(int argc, char *argv[])
eprintf("write:");
if (ret == 0)
eprintf("write returned 0\n");
- if (ret < obs)
+ if ((size_t)ret < obs)
opart++;
else
ofull++;
diff --git a/cmd/posix/df.c b/cmd/posix/df.c
@@ -112,6 +112,7 @@ main(int argc, char *argv[])
case 's':
case 'i':
eprintf("not implemented\n");
+ break;
default:
usage();
} ARGEND;
diff --git a/cmd/posix/du.c b/cmd/posix/du.c
@@ -98,7 +98,7 @@ du(int dirfd, const char *path, struct stat *st, void *data, struct recursor *r)
print:
if (!r->depth)
printpath(*total, r->path);
- else if (!sflag && r->depth <= maxdepth && (S_ISDIR(st->st_mode) || aflag))
+ else if (!sflag && (size_t)r->depth <= maxdepth && (S_ISDIR(st->st_mode) || aflag))
printpath(subtotal, r->path);
}
@@ -122,7 +122,7 @@ main(int argc, char *argv[])
break;
case 'd':
dflag = 1;
- maxdepth = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ maxdepth = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'h':
hflag = 1;
@@ -150,7 +150,7 @@ main(int argc, char *argv[])
bsize = getenv("BLOCKSIZE");
if (bsize)
- blksize = estrtonum(bsize, 1, MIN(LLONG_MAX, SIZE_MAX));
+ blksize = estrtonum(bsize, 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
if (kflag)
blksize = 1024;
diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c
@@ -244,7 +244,7 @@ gettxt(int line)
repeat:
chksignals();
- if (!csize || off < lasto || off - lasto >= csize) {
+ if (!csize || off < lasto || (size_t)(off - lasto) >= csize) {
block = off & ~(CACHESIZ-1);
if (lseek(scratch, block, SEEK_SET) < 0 ||
(n = read(scratch, buf, CACHESIZ)) < 0) {
@@ -405,7 +405,7 @@ compile(int delim)
bracket = lastre.siz = 0;
for (n = 0;; ++n) {
c = input();
- if (c == delim && !bracket || c == '\0') {
+ if ((c == delim && !bracket) || c == '\0') {
break;
} else if (c == '\\') {
addchar(c, &lastre);
@@ -450,6 +450,7 @@ match(int num)
static int
rematch(int num)
{
+ (void)num;
regoff_t off = matchs[0].rm_eo;
regmatch_t *m;
int r;
@@ -527,6 +528,7 @@ ensureblank(void)
case ' ':
case '\t':
skipblank();
+ /* fallthrough */
case '\0':
back(c);
break;
@@ -809,6 +811,7 @@ expandcmd(void)
back(c);
c = '\\';
}
+ /* fallthrough */
default:
addchar(c, &cmd);
}
@@ -901,7 +904,7 @@ doread(const char *fname)
for (cnt = 0; (len = getline(&s, &n, fp)) > 0; cnt += (size_t)len) {
chksignals();
if (s[len-1] != '\n') {
- if (len+1 >= n) {
+ if ((size_t)len + 1 >= n) {
if (n == SIZE_MAX || !(p = realloc(s, ++n)))
error("out of memory");
s = p;
@@ -1339,6 +1342,7 @@ repeat:
case 'v':
case 'V':
error("cannot nest global commands");
+ break;
case 'H':
if (nlines > 0)
goto unexpected;
@@ -1353,6 +1357,7 @@ repeat:
break;
case 'w':
trunc = 1;
+ /* fallthrough */
case 'W':
ensureblank();
deflines(nextln(0), lastln);
@@ -1468,6 +1473,7 @@ repeat:
break;
case 'x':
trunc = 1;
+ /* fallthrough */
case 'X':
ensureblank();
if (nlines > 0)
@@ -1475,6 +1481,7 @@ repeat:
exstatus = 0;
deflines(nextln(0), lastln);
dowrite(getfname(cmd), trunc);
+ /* fallthrough */
case 'Q':
case 'q':
if (nlines > 0)
@@ -1538,11 +1545,13 @@ chkglobal(void)
switch (c = input()) {
case 'g':
uflag = 0;
+ /* fallthrough */
case 'G':
dir = 1;
break;
case 'v':
uflag = 0;
+ /* fallthrough */
case 'V':
dir = 0;
break;
@@ -1643,12 +1652,14 @@ usage(void)
static void
sigintr(int n)
{
+ (void)n;
intr = 1;
}
static void
sighup(int dummy)
{
+ (void)dummy;
hup = 1;
}
diff --git a/cmd/posix/expand.c b/cmd/posix/expand.c
@@ -21,7 +21,7 @@ parselist(const char *s)
if (*p == '\0')
eprintf("empty field in tablist\n");
tablist = ereallocarray(tablist, i + 1, sizeof(*tablist));
- tablist[i] = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX));
+ tablist[i] = estrtonum(p, 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
if (i > 0 && tablist[i - 1] >= tablist[i])
eprintf("tablist must be ascending\n");
}
diff --git a/cmd/posix/expr.c b/cmd/posix/expr.c
@@ -103,6 +103,8 @@ doop(int *ophead, int *opp, struct val *valhead, struct val *valp)
struct val ret = { .str = NULL, .num = 0 }, *a, *b;
int op;
+ (void)ophead;
+
/* an operation "a op b" needs an operator and two values */
if (opp[-1] == '(')
enprintf(2, "syntax error: extra (\n");
@@ -153,6 +155,8 @@ lex(char *s, struct val *v)
int type = VAL;
char *ops = "|&=><+-*/%():";
+ (void)v;
+
if (s[0] && strchr(ops, s[0]) && !s[1]) {
/* one-char operand */
type = s[0];
diff --git a/cmd/posix/find.c b/cmd/posix/find.c
@@ -1,21 +1,22 @@
/* See LICENSE file for copyright and license details. */
+#include "config.h"
+#include "util.h"
+
#include <dirent.h>
#include <errno.h>
#include <fnmatch.h>
#include <grp.h>
#include <libgen.h>
#include <pwd.h>
+#include <regex.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <time.h>
-#include <unistd.h>
-
#include <sys/stat.h>
#include <sys/wait.h>
-
-#include "util.h"
+#include <time.h>
+#include <unistd.h>
/* because putting integers in pointers is undefined by the standard */
union extra {
@@ -116,6 +117,53 @@ static int do_stat(char *path, struct stat *sb, struct findhist *hist);
/* Primaries */
static int pri_name (struct arg *arg);
+#if FEATURE_FIND_INAME
+static int pri_iname(struct arg *arg);
+#endif
+#if FEATURE_FIND_IPATH
+static int pri_ipath(struct arg *arg);
+#endif
+#if FEATURE_FIND_REGEX
+static int pri_regex(struct arg *arg);
+static char **get_regex_arg(char *argv[], union extra *extra);
+static void free_regex_arg(union extra extra);
+#endif
+#if FEATURE_FIND_INUM
+static int pri_inum(struct arg *arg);
+static char **get_inum_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_SAMEFILE
+static int pri_samefile(struct arg *arg);
+static char **get_samefile_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_MAXDEPTH
+static int pri_maxdepth(struct arg *arg);
+static char **get_maxdepth_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_MINDEPTH
+static int pri_mindepth(struct arg *arg);
+static char **get_mindepth_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_DELETE
+static int pri_delete(struct arg *arg);
+static char **get_delete_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_QUIT
+static int pri_quit(struct arg *arg);
+static char **get_quit_arg(char *argv[], union extra *extra);
+#endif
+#if FEATURE_FIND_EMPTY
+static int pri_empty(struct arg *arg);
+#endif
+#if FEATURE_FIND_MMIN
+static int pri_mmin(struct arg *arg);
+#endif
+#if FEATURE_FIND_AMIN
+static int pri_amin(struct arg *arg);
+#endif
+#if FEATURE_FIND_CMIN
+static int pri_cmin(struct arg *arg);
+#endif
static int pri_path (struct arg *arg);
static int pri_nouser (struct arg *arg);
static int pri_nogroup(struct arg *arg);
@@ -133,7 +181,9 @@ static int pri_mtime (struct arg *arg);
static int pri_exec (struct arg *arg);
static int pri_ok (struct arg *arg);
static int pri_print (struct arg *arg);
+#if FEATURE_FIND_PRINT0
static int pri_print0 (struct arg *arg);
+#endif
static int pri_newer (struct arg *arg);
static int pri_depth (struct arg *arg);
@@ -174,6 +224,45 @@ static int cmp_lt(int a, int b) { return a < b; }
/* order from find(1p), may want to alphabetize */
static struct pri_info primaries[] = {
+#if FEATURE_FIND_INAME
+ { "-iname" , pri_iname , get_name_arg , NULL , 1 },
+#endif
+#if FEATURE_FIND_IPATH
+ { "-ipath" , pri_ipath , get_path_arg , NULL , 1 },
+#endif
+#if FEATURE_FIND_REGEX
+ { "-regex" , pri_regex , get_regex_arg, free_regex_arg, 1 },
+#endif
+#if FEATURE_FIND_INUM
+ { "-inum" , pri_inum , get_inum_arg , NULL , 1 },
+#endif
+#if FEATURE_FIND_SAMEFILE
+ { "-samefile", pri_samefile, get_samefile_arg, free_extra, 1 },
+#endif
+#if FEATURE_FIND_MAXDEPTH
+ { "-maxdepth", pri_maxdepth, get_maxdepth_arg, NULL , 1 },
+#endif
+#if FEATURE_FIND_MINDEPTH
+ { "-mindepth", pri_mindepth, get_mindepth_arg, NULL , 1 },
+#endif
+#if FEATURE_FIND_DELETE
+ { "-delete" , pri_delete , get_delete_arg, NULL , 0 },
+#endif
+#if FEATURE_FIND_QUIT
+ { "-quit" , pri_quit , get_quit_arg , NULL , 0 },
+#endif
+#if FEATURE_FIND_MMIN
+ { "-mmin" , pri_mmin , get_n_arg , free_extra , 1 },
+#endif
+#if FEATURE_FIND_AMIN
+ { "-amin" , pri_amin , get_n_arg , free_extra , 1 },
+#endif
+#if FEATURE_FIND_CMIN
+ { "-cmin" , pri_cmin , get_n_arg , free_extra , 1 },
+#endif
+#if FEATURE_FIND_EMPTY
+ { "-empty" , pri_empty , NULL , NULL , 1 },
+#endif
{ "-name" , pri_name , get_name_arg , NULL , 1 },
{ "-path" , pri_path , get_path_arg , NULL , 1 },
{ "-nouser" , pri_nouser , NULL , NULL , 1 },
@@ -192,7 +281,9 @@ static struct pri_info primaries[] = {
{ "-exec" , pri_exec , get_exec_arg , free_exec_arg, 1 },
{ "-ok" , pri_ok , get_ok_arg , free_ok_arg , 1 },
{ "-print" , pri_print , get_print_arg, NULL , 0 },
+#if FEATURE_FIND_PRINT0
{ "-print0" , pri_print0 , get_print_arg, NULL , 0 },
+#endif
{ "-newer" , pri_newer , get_newer_arg, NULL , 1 },
{ "-depth" , pri_depth , get_depth_arg, NULL , 0 },
@@ -227,6 +318,9 @@ static struct {
char prune; /* hit -prune */
char xdev ; /* -xdev, prune directories on different devices */
char print; /* whether we will need -print when parsing */
+ char quit ; /* quit execution immediately */
+ long maxdepth; /* max depth of recursion */
+ long mindepth; /* min depth of recursion */
} gflags;
/*
@@ -246,14 +340,19 @@ spawn(char *argv[])
switch((pid = fork())) {
case -1:
eprintf("fork:");
+ break;
case 0:
execvp(*argv, argv);
weprintf("exec %s failed:", *argv);
_exit(1);
}
- /* FIXME: proper course of action for waitpid() on EINTR? */
- waitpid(pid, &status, 0);
+ while (waitpid(pid, &status, 0) < 0) {
+ if (errno != EINTR) {
+ status = -1;
+ break;
+ }
+ }
return status;
}
@@ -310,12 +409,14 @@ pri_nogroup(struct arg *arg)
static int
pri_xdev(struct arg *arg)
{
+ (void)arg;
return 1;
}
static int
pri_prune(struct arg *arg)
{
+ (void)arg;
return gflags.prune = 1;
}
@@ -454,7 +555,7 @@ pri_ok(struct arg *arg)
* byte? */
;
- if (feof(stdin)) /* FIXME: ferror()? */
+ if (feof(stdin) || ferror(stdin))
clearerr(stdin);
if (reply != 'y' && reply != 'Y')
@@ -476,6 +577,7 @@ pri_print(struct arg *arg)
return 1;
}
+#if FEATURE_FIND_PRINT0
static int
pri_print0(struct arg *arg)
{
@@ -483,6 +585,7 @@ pri_print0(struct arg *arg)
eprintf("fwrite failed:");
return 1;
}
+#endif
/* FIXME: ignoring nanoseconds */
static int
@@ -494,6 +597,7 @@ pri_newer(struct arg *arg)
static int
pri_depth(struct arg *arg)
{
+ (void)arg;
return 1;
}
@@ -519,6 +623,7 @@ get_path_arg(char *argv[], union extra *extra)
static char **
get_xdev_arg(char *argv[], union extra *extra)
{
+ (void)extra;
gflags.xdev = 1;
return argv;
}
@@ -683,6 +788,7 @@ get_ok_arg(char *argv[], union extra *extra)
static char **
get_print_arg(char *argv[], union extra *extra)
{
+ (void)extra;
gflags.print = 0;
return argv;
}
@@ -703,6 +809,7 @@ get_newer_arg(char *argv[], union extra *extra)
static char **
get_depth_arg(char *argv[], union extra *extra)
{
+ (void)extra;
gflags.depth = 1;
return argv;
}
@@ -959,6 +1066,250 @@ eval(struct tok *tok, struct arg *arg)
/* evaluate path, if it's a directory iterate through directory entries and
* recurse
*/
+#if FEATURE_FIND_INAME
+static int
+pri_iname(struct arg *arg)
+{
+ int ret;
+ char *path;
+
+ path = estrdup(arg->path);
+ ret = !fnmatch((char *)arg->extra.p, basename(path), FNM_CASEFOLD);
+ free(path);
+
+ return ret;
+}
+#endif
+
+#if FEATURE_FIND_IPATH
+static int
+pri_ipath(struct arg *arg)
+{
+ return !fnmatch((char *)arg->extra.p, arg->path, FNM_CASEFOLD);
+}
+#endif
+
+#if FEATURE_FIND_REGEX
+static int
+pri_regex(struct arg *arg)
+{
+ regex_t *re = arg->extra.p;
+ regmatch_t match;
+ if (regexec(re, arg->path, 1, &match, 0) == 0) {
+ return match.rm_so == 0 && (size_t)match.rm_eo == strlen(arg->path);
+ }
+ return 0;
+}
+
+static char **
+get_regex_arg(char *argv[], union extra *extra)
+{
+ regex_t *re = emalloc(sizeof(*re));
+ eregcomp(re, *argv, 0);
+ extra->p = re;
+ return argv;
+}
+
+static void
+free_regex_arg(union extra extra)
+{
+ regex_t *re = extra.p;
+ regfree(re);
+ free(re);
+}
+#endif
+
+#if FEATURE_FIND_INUM
+static int
+pri_inum(struct arg *arg)
+{
+ ino_t ino = (ino_t)arg->extra.i;
+ return arg->st->st_ino == ino;
+}
+
+static char **
+get_inum_arg(char *argv[], union extra *extra)
+{
+ char *end;
+ extra->i = strtol(*argv, &end, 10);
+ if (end == *argv || *end)
+ eprintf("bad number '%s'\n", *argv);
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_SAMEFILE
+struct SameFileArg {
+ ino_t ino;
+ dev_t dev;
+};
+
+static int
+pri_samefile(struct arg *arg)
+{
+ struct SameFileArg *s = arg->extra.p;
+ return arg->st->st_ino == s->ino && arg->st->st_dev == s->dev;
+}
+
+static char **
+get_samefile_arg(char *argv[], union extra *extra)
+{
+ struct stat st;
+ struct SameFileArg *s = emalloc(sizeof(*s));
+ if (do_stat(*argv, &st, NULL))
+ eprintf("failed to stat '%s':", *argv);
+ s->ino = st.st_ino;
+ s->dev = st.st_dev;
+ extra->p = s;
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_MAXDEPTH
+static int
+pri_maxdepth(struct arg *arg)
+{
+ (void)arg;
+ return 1;
+}
+
+static char **
+get_maxdepth_arg(char *argv[], union extra *extra)
+{
+ (void)extra;
+ char *end;
+ gflags.maxdepth = strtol(*argv, &end, 10);
+ if (end == *argv || *end || gflags.maxdepth < 0)
+ eprintf("bad number '%s'\n", *argv);
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_MINDEPTH
+static int
+pri_mindepth(struct arg *arg)
+{
+ (void)arg;
+ return 1;
+}
+
+static char **
+get_mindepth_arg(char *argv[], union extra *extra)
+{
+ (void)extra;
+ char *end;
+ gflags.mindepth = strtol(*argv, &end, 10);
+ if (end == *argv || *end || gflags.mindepth < 0)
+ eprintf("bad number '%s'\n", *argv);
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_DELETE
+static int
+pri_delete(struct arg *arg)
+{
+ if (remove(arg->path) < 0) {
+ weprintf("remove %s failed:", arg->path);
+ gflags.ret = 1;
+ return 0;
+ }
+ return 1;
+}
+
+static char **
+get_delete_arg(char *argv[], union extra *extra)
+{
+ (void)extra;
+ gflags.depth = 1;
+ gflags.print = 0;
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_QUIT
+static int
+pri_quit(struct arg *arg)
+{
+ (void)arg;
+ gflags.quit = 1;
+ return 1;
+}
+
+static char **
+get_quit_arg(char *argv[], union extra *extra)
+{
+ (void)extra;
+ gflags.print = 0;
+ return argv;
+}
+#endif
+
+#if FEATURE_FIND_EMPTY
+static int
+pri_empty(struct arg *arg)
+{
+ DIR *dir;
+ struct dirent *de;
+ int empty = 1;
+
+ if (S_ISREG(arg->st->st_mode)) {
+ return arg->st->st_size == 0;
+ } else if (S_ISDIR(arg->st->st_mode)) {
+ dir = opendir(arg->path);
+ if (!dir)
+ return 0;
+ while ((de = readdir(dir))) {
+ if (strcmp(de->d_name, ".") && strcmp(de->d_name, "..")) {
+ empty = 0;
+ break;
+ }
+ }
+ closedir(dir);
+ return empty;
+ }
+ return 0;
+}
+#endif
+
+#if FEATURE_FIND_MMIN
+static int
+pri_mmin(struct arg *arg)
+{
+ struct narg *n = arg->extra.p;
+ return n->cmp((start.tv_sec - arg->st->st_mtime) / 60, n->n);
+}
+#endif
+
+#if FEATURE_FIND_AMIN
+static int
+pri_amin(struct arg *arg)
+{
+ struct narg *n = arg->extra.p;
+ return n->cmp((start.tv_sec - arg->st->st_atime) / 60, n->n);
+}
+#endif
+
+#if FEATURE_FIND_CMIN
+static int
+pri_cmin(struct arg *arg)
+{
+ struct narg *n = arg->extra.p;
+ return n->cmp((start.tv_sec - arg->st->st_ctime) / 60, n->n);
+}
+#endif
+
+static int
+get_depth(struct findhist *hist)
+{
+ int d = 0;
+ while (hist) {
+ d++;
+ hist = hist->next;
+ }
+ return d;
+}
+
static void
find(char *path, struct findhist *hist)
{
@@ -969,6 +1320,10 @@ find(char *path, struct findhist *hist)
size_t namelen, pathcap = 0, len;
struct arg arg = { path, &st, { NULL } };
char *p, *pathbuf = NULL;
+ int depth = get_depth(hist);
+
+ if (gflags.quit)
+ return;
len = strlen(path) + 2; /* \0 and '/' */
@@ -980,13 +1335,27 @@ find(char *path, struct findhist *hist)
gflags.prune = 0;
- /* don't eval now iff we will hit the eval at the bottom which means
- * 1. we are a directory 2. we have -depth 3. we don't have -xdev or we are
- * on same device (so most of the time we eval here) */
- if (!S_ISDIR(st.st_mode) ||
- !gflags.depth ||
- (gflags.xdev && hist && st.st_dev != hist->dev))
- eval(root, &arg);
+ if (gflags.maxdepth >= 0 && depth > gflags.maxdepth)
+ return;
+
+ if (gflags.mindepth < 0 || depth >= gflags.mindepth) {
+ /* don't eval now iff we will hit the eval at the bottom which means
+ * 1. we are a directory 2. we have -depth 3. we don't have -xdev or we are
+ * on same device (so most of the time we eval here) */
+ if (!S_ISDIR(st.st_mode) ||
+ !gflags.depth ||
+ (gflags.xdev && hist && st.st_dev != hist->dev))
+ eval(root, &arg);
+ }
+
+ if (gflags.maxdepth >= 0 && depth >= gflags.maxdepth) {
+ if (gflags.depth && (gflags.mindepth < 0 || depth >= gflags.mindepth)) {
+ if (S_ISDIR(st.st_mode) &&
+ (!gflags.xdev || !hist || st.st_dev == hist->dev))
+ eval(root, &arg);
+ }
+ return;
+ }
if (!S_ISDIR(st.st_mode) ||
gflags.prune ||
@@ -1009,12 +1378,14 @@ find(char *path, struct findhist *hist)
weprintf("failed to opendir %s:", path);
gflags.ret = 1;
/* should we just ignore this since we hit an error? */
- if (gflags.depth)
+ if (gflags.depth && (gflags.mindepth < 0 || depth >= gflags.mindepth))
eval(root, &arg);
return;
}
while (errno = 0, (de = readdir(dir))) {
+ if (gflags.quit)
+ break;
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
continue;
namelen = strlen(de->d_name);
@@ -1037,7 +1408,7 @@ find(char *path, struct findhist *hist)
}
closedir(dir);
- if (gflags.depth)
+ if (gflags.depth && (gflags.mindepth < 0 || depth >= gflags.mindepth))
eval(root, &arg);
}
@@ -1054,6 +1425,9 @@ main(int argc, char **argv)
int npaths;
struct tok *t;
+ gflags.maxdepth = -1;
+ gflags.mindepth = -1;
+
ARGBEGIN {
case 'H':
gflags.h = 1;
diff --git a/cmd/posix/fold.c b/cmd/posix/fold.c
@@ -96,7 +96,7 @@ main(int argc, char *argv[])
sflag = 1;
break;
case 'w':
- width = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
+ width = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
ARGNUM:
if (!(width = ARGNUMF()))
diff --git a/cmd/posix/getconf.c b/cmd/posix/getconf.c
@@ -25,7 +25,7 @@ main(int argc, char *argv[])
{
size_t len;
long res;
- int i;
+ size_t i;
char *str;
ARGBEGIN {
diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c
@@ -1,13 +1,13 @@
-/* See LICENSE file for copyright and license details. */
+#include "config.h"
+#include "queue.h"
+#include "util.h"
+
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
-#include "queue.h"
-#include "util.h"
-
enum { Match = 0, NoMatch = 1, Error = 2 };
static void addpattern(const char *);
@@ -27,6 +27,13 @@ static int wflag;
static int xflag;
static int many;
static int mode;
+#if FEATURE_GREP_CONTEXT
+static long Aflag = 0;
+static long Bflag = 0;
+#endif
+#if FEATURE_GREP_MAX_COUNT
+static long mval = -1;
+#endif
struct pattern {
regex_t preg;
@@ -75,6 +82,18 @@ addpatternfile(FILE *fp)
enprintf(Error, "read error:");
}
+#if FEATURE_GREP_CONTEXT
+static void
+print_line(const char *str, const char *line, long line_no, char sep)
+{
+ if (!hflag && (many || Hflag))
+ printf("%s%c", str, sep);
+ if (mode == 'n')
+ printf("%ld%c", line_no, sep);
+ puts(line);
+}
+#endif
+
static int
grep(FILE *fp, const char *str)
{
@@ -84,9 +103,24 @@ grep(FILE *fp, const char *str)
long c = 0, n;
struct pattern *pnode;
int match, result = NoMatch;
+#if FEATURE_GREP_MAX_COUNT
+ long matches = 0;
+#endif
+#if FEATURE_GREP_CONTEXT
+ struct context_line {
+ char *str;
+ long line_no;
+ } *before_buf = NULL;
+ size_t before_head = 0, before_count = 0, i = 0, idx = 0;
+ long after_left = 0;
+ long last_printed_line = 0;
+
+ if (Bflag > 0 && !(mode == 'c' || mode == 'l' || mode == 'q'))
+ before_buf = ecalloc(Bflag, sizeof(*before_buf));
+#endif
for (n = 1; (len = getline(&buf, &size, fp)) > 0; n++) {
- /* Remove the trailing newline if one is present. */
+ /* remove the trailing newline if one is present */
if (buf[len - 1] == '\n')
buf[len - 1] = '\0';
match = 0;
@@ -112,6 +146,9 @@ grep(FILE *fp, const char *str)
}
if (match != vflag) {
result = Match;
+#if FEATURE_GREP_MAX_COUNT
+ matches++;
+#endif
switch (mode) {
case 'c':
c++;
@@ -122,18 +159,69 @@ grep(FILE *fp, const char *str)
case 'q':
exit(Match);
default:
- if (!hflag && (many || Hflag))
- printf("%s:", str);
- if (mode == 'n')
- printf("%ld:", n);
- puts(buf);
+#if FEATURE_GREP_CONTEXT
+ if (Aflag > 0 || Bflag > 0) {
+ if (last_printed_line > 0 && n > last_printed_line + 1)
+ puts("--");
+ for (i = 0; i < before_count; i++) {
+ idx = (before_head - before_count + i + Bflag) % Bflag;
+ print_line(str, before_buf[idx].str, before_buf[idx].line_no, '-');
+ free(before_buf[idx].str);
+ before_buf[idx].str = NULL;
+ }
+ before_count = 0;
+ before_head = 0;
+ print_line(str, buf, n, ':');
+ after_left = Aflag;
+ last_printed_line = n;
+ } else {
+#endif
+ if (!hflag && (many || Hflag))
+ printf("%s:", str);
+ if (mode == 'n')
+ printf("%ld:", n);
+ puts(buf);
+#if FEATURE_GREP_CONTEXT
+ }
+#endif
break;
}
+#if FEATURE_GREP_MAX_COUNT
+ if (mval >= 0 && matches >= mval)
+ goto end;
+#endif
+ }
+#if FEATURE_GREP_CONTEXT
+ else if (Aflag > 0 || Bflag > 0) {
+ if (mode != 'c' && mode != 'l' && mode != 'q') {
+ if (after_left > 0) {
+ print_line(str, buf, n, '-');
+ after_left--;
+ last_printed_line = n;
+ }
+ if (Bflag > 0) {
+ if (before_count == (size_t)Bflag)
+ free(before_buf[before_head].str);
+ before_buf[before_head].str = estrdup(buf);
+ before_buf[before_head].line_no = n;
+ before_head = (before_head + 1) % Bflag;
+ if (before_count < (size_t)Bflag)
+ before_count++;
+ }
+ }
}
+#endif
}
if (mode == 'c')
printf("%ld\n", c);
end:
+#if FEATURE_GREP_CONTEXT
+ if (before_buf) {
+ for (i = 0; i < (size_t)Bflag; i++)
+ free(before_buf[i].str);
+ free(before_buf);
+ }
+#endif
if (ferror(fp)) {
weprintf("%s: read error:", str);
result = Error;
@@ -144,8 +232,14 @@ end:
static void
usage(void)
{
- enprintf(Error, "usage: %s [-EFHchilnqsvwx] [-e pattern] [-f file] "
- "[pattern] [file ...]\n", argv0);
+ enprintf(Error, "usage: %s [-EFHchilnqsvwx]"
+#if FEATURE_GREP_CONTEXT
+ " [-A num] [-B num] [-C num]"
+#endif
+#if FEATURE_GREP_MAX_COUNT
+ " [-m num]"
+#endif
+ " [-e pattern] [-f file] [pattern] [file ...]\n", argv0);
}
int
@@ -159,6 +253,25 @@ main(int argc, char *argv[])
SLIST_INIT(&phead);
ARGBEGIN {
+#if FEATURE_GREP_CONTEXT
+ case 'A':
+ Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
+ break;
+ case 'B':
+ Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
+ break;
+ case 'C':
+ Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX);
+ break;
+ ARGNUM:
+ Aflag = Bflag = ARGNUMF();
+ break;
+#endif
+#if FEATURE_GREP_MAX_COUNT
+ case 'm':
+ mval = estrtonum(EARGF(usage()), 0, LONG_MAX);
+ break;
+#endif
case 'E':
Eflag = 1;
Fflag = 0;
@@ -234,7 +347,7 @@ main(int argc, char *argv[])
}
if (!Fflag)
- /* Compile regex for all search patterns */
+ /* compile regex for all search patterns */
SLIST_FOREACH(pnode, &phead, entry)
enregcomp(Error, &pnode->preg, pnode->pattern, flags);
many = (argc > 1);
diff --git a/cmd/posix/head.c b/cmd/posix/head.c
@@ -37,7 +37,7 @@ main(int argc, char *argv[])
ARGBEGIN {
case 'n':
- n = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ n = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
ARGNUM:
n = ARGNUMF();
diff --git a/cmd/posix/join.c b/cmd/posix/join.c
@@ -322,7 +322,7 @@ makespec(char *s)
fldno = 0;
} else if ((s[0] == '1' || s[0] == '2') && s[1] == '.') {
fileno = s[0] - '0';
- fldno = estrtonum(&s[2], 1, MIN(LLONG_MAX, SIZE_MAX)) - 1;
+ fldno = estrtonum(&s[2], 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)) - 1;
} else {
eprintf("%s: invalid format\n", s);
}
@@ -459,10 +459,10 @@ main(int argc, char *argv[])
ARGBEGIN {
case '1':
- jf[0] = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
+ jf[0] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case '2':
- jf[1] = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
+ jf[1] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'a':
fno = EARGF(usage());
diff --git a/cmd/posix/kill.c b/cmd/posix/kill.c
@@ -1,4 +1,7 @@
/* See LICENSE file for copyright and license details. */
+#include "sig.h"
+#include "util.h"
+
#include <sys/wait.h>
#include <ctype.h>
@@ -8,45 +11,28 @@
#include <string.h>
#include <strings.h>
-#include "util.h"
-
-struct {
- const char *name;
- const int sig;
-} sigs[] = {
- { "0", 0 },
-#define SIG(n) { #n, SIG##n }
- SIG(ABRT), SIG(ALRM), SIG(BUS), SIG(CHLD), SIG(CONT), SIG(FPE), SIG(HUP),
- SIG(ILL), SIG(INT), SIG(KILL), SIG(PIPE), SIG(QUIT), SIG(SEGV), SIG(STOP),
- SIG(TERM), SIG(TRAP), SIG(TSTP), SIG(TTIN), SIG(TTOU), SIG(USR1), SIG(USR2),
- SIG(URG),
-#undef SIG
-};
-
-const char *
-sig2name(const int sig)
+static const char *
+sig2name(int sig)
{
- size_t i;
-
- for (i = 0; i < LEN(sigs); i++)
- if (sigs[i].sig == sig)
- return sigs[i].name;
- eprintf("%d: bad signal number\n", sig);
+ static char name[SIG2STR_MAX];
- return NULL; /* not reached */
+ if (sig == 0)
+ return "0";
+ if (sig2str(sig, name) < 0)
+ eprintf("%d: bad signal number\n", sig);
+ return name;
}
-int
+static int
name2sig(const char *name)
{
- size_t i;
-
- for (i = 0; i < LEN(sigs); i++)
- if (!strcasecmp(sigs[i].name, name))
- return sigs[i].sig;
- eprintf("%s: bad signal name\n", name);
+ int sig;
- return -1; /* not reached */
+ if (strcmp(name, "0") == 0)
+ return 0;
+ if (str2sig(name, &sig) < 0)
+ eprintf("%s: bad signal name\n", name);
+ return sig;
}
static void
@@ -75,8 +61,9 @@ main(int argc, char *argv[])
goto longopt;
argc--, argv++;
if (!argc) {
- for (i = 0; i < LEN(sigs); i++)
- puts(sigs[i].name);
+ for (i = 1; i < (size_t)sys_nsig; i++)
+ if (sys_signame[i])
+ puts(sys_signame[i]);
} else if (argc == 1) {
sig = estrtonum(*argv, 0, INT_MAX);
if (sig > 128)
diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c
@@ -448,8 +448,9 @@ main(int argc, char *argv[])
} ARGEND
switch (argc) {
- case 0: /* fallthrough */
+ case 0:
*--argv = ".", ++argc;
+ /* fallthrough */
case 1:
mkent(&ent, argv[0], 1, Hflag || Lflag);
ls("", &ent, (!dflag && S_ISDIR(ent.mode)) ||
@@ -458,7 +459,7 @@ main(int argc, char *argv[])
break;
default:
- for (i = ds = fs = 0, fents = dents = NULL; i < argc; ++i) {
+ for (i = ds = fs = 0, fents = dents = NULL; i < (size_t)argc; ++i) {
mkent(&ent, argv[i], 1, Hflag || Lflag);
if ((!dflag && S_ISDIR(ent.mode)) ||
diff --git a/cmd/posix/make/main.c b/cmd/posix/make/main.c
@@ -48,7 +48,7 @@ hash(char *name)
int c;
unsigned h = 5381;
- while (c = *name++)
+ while ((c = *name++))
h = h*33 ^ c;
return h;
@@ -253,7 +253,7 @@ parseargv(char **argv, char ***targets, int where, int export)
static void
parsemakeflags(void)
{
- int c, n;
+ int n;
char *s, *flags, **arr;
if ((flags = getenv("MAKEFLAGS")) == NULL)
@@ -293,7 +293,7 @@ parsemakefiles(char **argv)
hasmake = 0;
for ( ; *argv && **argv == '-'; ++argv) {
- for (s = *argv; c = *s; ++s) {
+ for (s = *argv; (c = *s); ++s) {
if (hasargs(c))
arg = getarg(&s, &argv);
@@ -328,7 +328,7 @@ enadebug(char *argv[])
for ( ; *argv && **argv == '-'; ++argv) {
p = *argv;
- for (++p; c = *p; ++p) {
+ for (++p; (c = *p); ++p) {
if (hasargs(c))
getarg(&p, &argv);
if (c == 'd')
@@ -342,6 +342,8 @@ main(int argc, char *argv[])
{
char *arg0, **targets;
+ (void)argc;
+
signal(SIGINT, sighandler);
signal(SIGHUP, sighandler);
signal(SIGTERM, sighandler);
diff --git a/cmd/posix/make/parser.c b/cmd/posix/make/parser.c
@@ -70,7 +70,7 @@ static Macro *
lookup(char *name)
{
Macro *mp;
- int h = hash(name) & TABSIZ-1;
+ int h = hash(name) & (TABSIZ-1);
for (mp = htab[h]; mp && strcmp(mp->name, name); mp = mp->next)
;
@@ -305,7 +305,6 @@ trim(char *s)
static void
include(char *s)
{
- int len;
FILE *fp;
char *fil, *t;
@@ -471,8 +470,8 @@ expandmacro(char *name)
static void
replace(char *line, char *repl, char *to)
{
- int siz, at, len, replsiz, tosiz, sep, pos;
- char *oline, *s, *cur, *buf;
+ int siz, at, len, replsiz, tosiz, pos;
+ char *oline, *cur, *buf;
debug("replacing '%s', with '%s' to '%s'", line, repl, to);
oline = line;
@@ -804,6 +803,7 @@ repeat:
case '#':
comment();
c = '\n';
+ /* fallthrough */
case ';':
case ':':
case '=':
diff --git a/cmd/posix/make/rules.c b/cmd/posix/make/rules.c
@@ -36,7 +36,7 @@ static Target *
lookup(char *name)
{
Target *tp;
- int h = hash(name) & TABSIZ-1;
+ int h = hash(name) & (TABSIZ-1);
for (tp = htab[h]; tp && strcmp(tp->name, name); tp = tp->next)
;
@@ -89,31 +89,16 @@ cleanup(Target *tp)
static int
depends(char *target, char *dep)
{
- int i;
Target **p, *tp = lookup(target);
for (p = tp->deps; p && *p; ++p) {
- if (strcmp((*p)->name, target) == 0)
+ if (strcmp((*p)->name, dep) == 0)
return 1;
}
return 0;
}
-static int
-is_suffix(char *s)
-{
- int n;
-
- if (s[0] != '.')
- return 0;
-
- for (n = 0; s = strchr(s, '.'); n++)
- s++;
-
- return n == 2;
-}
-
void
addtarget(char *target, int ndeps)
{
@@ -152,7 +137,6 @@ addtarget(char *target, int ndeps)
void
adddep(char *target, char *dep)
{
- int i;
size_t siz;
Target **p, *tp = lookup(target);
@@ -213,9 +197,10 @@ static int
execline(Target *tp, char *line, int ignore, int silence)
{
char *s, *t;
- Target *p, **q;
int r, at, plus, minus, l;
+ (void)tp;
+
debug("executing '%s'", line);
at = plus = minus = 0;
@@ -398,7 +383,7 @@ inference(Target *tp, int force)
to = strrchr(tp->name, '.');
if (to && !enabled(to))
return NULL;
- tolen = to ? to - tp->name : strlen(tp->name);
+ tolen = to ? (int)(to - tp->name) : (int)strlen(tp->name);
if (!to)
to = "";
@@ -413,7 +398,7 @@ inference(Target *tp, int force)
"%s%s",
from, to);
- if (r < 0 || r >= sizeof(buf))
+ if (r < 0 || (size_t)r >= sizeof(buf))
error("suffixes too long %s %s", from, to);
q = lookup(buf);
@@ -425,7 +410,7 @@ inference(Target *tp, int force)
"%*.*s%s",
tolen, tolen, tp->name, from);
- if (r < 0 || r >= sizeof(fname)) {
+ if (r < 0 || (size_t)r >= sizeof(fname)) {
error("prerequisite name too long %s %s",
tp->name, from);
}
@@ -492,7 +477,7 @@ update(Target *tp)
static int
rebuild(Target *tp, int *buildp)
{
- Target **p, *q;;
+ Target **p, *q;
int r, need, build, err, def;
debug("checking rebuild of %s", tp->name);
@@ -565,7 +550,7 @@ rebuild(Target *tp, int *buildp)
int
build(char *name)
{
- int build, r;
+ int build;
if (!name) {
if (!deftarget) {
diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c
@@ -128,6 +128,7 @@ main(int argc, char *argv[])
switch (utflen((d = EARGF(usage())))) {
case 0:
eprintf("empty logical page delimiter\n");
+ break;
case 1:
s = strlen(d);
delim = emalloc(s + 1 + 1);
@@ -151,10 +152,10 @@ main(int argc, char *argv[])
type[2] = getlinetype(EARGF(usage()), preg + 2);
break;
case 'i':
- incr = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ incr = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'l':
- blines = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ blines = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'n':
formattype = EARGF(usage());
@@ -181,7 +182,7 @@ main(int argc, char *argv[])
seplen = unescape(sep);
break;
case 'v':
- startnum = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX));
+ startnum = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
case 'w':
width = estrtonum(EARGF(usage()), 1, INT_MAX);
diff --git a/cmd/posix/od.c b/cmd/posix/od.c
@@ -1,4 +1,7 @@
/* See LICENSE file for copyright and license details. */
+#include "queue.h"
+#include "util.h"
+
#include <ctype.h>
#include <fcntl.h>
#include <stdint.h>
@@ -7,9 +10,6 @@
#include <string.h>
#include <unistd.h>
-#include "queue.h"
-#include "util.h"
-
struct type {
unsigned char format;
unsigned int len;
@@ -141,7 +141,7 @@ od(int fd, char *fname, int last)
ssize_t n;
while (skip - addr > 0) {
- n = read(fd, buf, MIN(skip - addr, sizeof(buf)));
+ n = read(fd, buf, MIN((size_t)(skip - addr), sizeof(buf)));
if (n < 0)
weprintf("read %s:", fname);
if (n <= 0)
@@ -153,10 +153,10 @@ od(int fd, char *fname, int last)
for (;;) {
if (max >= 0)
- size = MIN(max - (addr - skip), size);
+ size = MIN((size_t)(max - (addr - skip)), size);
if ((n = read(fd, buf, size)) <= 0)
break;
- for (i = 0; i < n; i++, addr++) {
+ for (i = 0; i < (size_t)n; i++, addr++) {
line[lineoff++] = buf[i];
if (lineoff == linelen) {
printline(line, lineoff, addr - lineoff + 1);
@@ -203,17 +203,19 @@ addtype(char format, int len)
static void
usage(void)
{
- eprintf("usage: %s [-bdosvx] [-A addressformat] [-E | -e] [-j skip] "
- "[-t outputformat] [file ...]\n", argv0);
+ eprintf("usage: %s [-bdosvx] [-A addressformat] "
+#if FEATURE_OD_ENDIAN
+ "[-E | -e] "
+#endif
+ "[-j skip] [-t outputformat] [file ...]\n", argv0);
}
int
main(int argc, char *argv[])
{
- int fd;
struct type *t;
- int ret = 0, len;
- char *s;
+ char *s, *end;
+ int fd, ret = 0, len, fmt_char;
big_endian = (*(uint16_t *)"\0\xff" == 0xff);
@@ -230,10 +232,12 @@ main(int argc, char *argv[])
case 'd':
addtype('u', 2);
break;
+#if FEATURE_OD_ENDIAN
case 'E':
case 'e':
big_endian = (ARGC() == 'E');
break;
+#endif
case 'j':
if ((skip = parseoffset(EARGF(usage()))) < 0)
usage();
@@ -260,28 +264,33 @@ main(int argc, char *argv[])
case 'o':
case 'u':
case 'x':
- /* todo: allow multiple digits */
- if (*(s+1) > '0' && *(s+1) <= '9') {
- len = *(s+1) - '0';
+ fmt_char = *s;
+ if (isdigit((unsigned char)*(s + 1))) {
+ len = strtol(s + 1, &end, 10);
+ s = end - 1;
} else {
- switch (*(s+1)) {
+ switch (*(s + 1)) {
case 'C':
len = sizeof(char);
+ s++;
break;
case 'S':
len = sizeof(short);
+ s++;
break;
case 'I':
len = sizeof(int);
+ s++;
break;
case 'L':
len = sizeof(long);
+ s++;
break;
default:
len = sizeof(int);
}
}
- addtype(*s, len);
+ addtype(fmt_char, len);
break;
default:
usage();
@@ -289,7 +298,7 @@ main(int argc, char *argv[])
}
break;
case 'v':
- /* always set - use uniq(1) to handle duplicate lines */
+ /* always set, use uniq(1) to handle duplicate lines */
break;
case 'x':
addtype('x', 2);
diff --git a/cmd/posix/paste.c b/cmd/posix/paste.c
@@ -14,7 +14,8 @@ static void
sequential(struct fdescr *dsc, int fdescrlen, Rune *delim, size_t delimlen)
{
Rune c, last;
- size_t i, d;
+ int i;
+ size_t d;
for (i = 0; i < fdescrlen; i++) {
d = 0;
@@ -41,20 +42,19 @@ static void
parallel(struct fdescr *dsc, int fdescrlen, Rune *delim, size_t delimlen)
{
Rune c, d;
- size_t i, m;
- ssize_t last;
+ int i, m, last;
nextline:
last = -1;
for (i = 0; i < fdescrlen; i++) {
- d = delim[i % delimlen];
+ d = delim[(size_t)i % delimlen];
c = 0;
while (efgetrune(&c, dsc[i].fp, dsc[i].name)) {
for (m = last + 1; m < i; m++) {
- if (delim[m % delimlen] != '\0')
- efputrune(&delim[m % delimlen], stdout, "<stdout>");
+ if (delim[(size_t)m % delimlen] != '\0')
+ efputrune(&delim[(size_t)m % delimlen], stdout, "<stdout>");
}
last = i;
if (c == '\n') {
@@ -89,8 +89,8 @@ main(int argc, char *argv[])
{
struct fdescr *dsc;
Rune *delim_rune = NULL;
- size_t delim_runelen, i, delim_bytelen = 1;
- int seq = 0, ret = 0;
+ size_t delim_runelen, delim_bytelen = 1;
+ int seq = 0, ret = 0, i;
char *delim = "\t";
ARGBEGIN {
diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c
@@ -0,0 +1,2535 @@
+/* taken from: https://github.com/michaelforney/pax */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE /* needed for major/minor (non-posix) */
+#endif
+
+#include "arg.h"
+
+#include <assert.h>
+#include <cpio.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fnmatch.h>
+#include <grp.h>
+#include <limits.h>
+#include <pwd.h>
+#include <regex.h>
+#include <spawn.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <sys/wait.h>
+#include <tar.h>
+#include <time.h>
+#include <unistd.h>
+
+#ifndef O_SEARCH /* not present on some bsds */
+#define O_SEARCH 0
+#endif
+
+#if __APPLE__ /* macos lacks st_*tim from posix.1-2008 */
+#define st_atim st_atimespec
+#define st_ctim st_ctimespec
+#define st_mtim st_mtimespec
+#endif
+
+#ifndef HAVE_REALLOCARRAY
+static void *
+pax_reallocarray(void *p, size_t n, size_t m)
+{
+ if (m && n > SIZE_MAX / m) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ return realloc(p, n * m);
+}
+#undef reallocarray
+#define reallocarray pax_reallocarray
+#endif
+
+#ifndef HAVE_PIPE2
+static int
+pax_pipe2(int fd[2], int flag)
+{
+ assert((flag | O_CLOEXEC) == O_CLOEXEC);
+ if (pipe(fd) != 0)
+ return -1;
+ if (flag & O_CLOEXEC && (fcntl(fd[0], F_SETFD, FD_CLOEXEC) != 0 || fcntl(fd[1], F_SETFD, FD_CLOEXEC) != 0))
+ return -1;
+ return 0;
+}
+#undef pipe2
+#define pipe2 pax_pipe2
+#endif
+
+#define LEN(a) (sizeof (a) / sizeof *(a))
+#define ROUNDUP(x, a) (((x) + ((a) - 1)) & ~((a) - 1))
+#define MAXTIME 077777777777
+#define MAXSIZE 077777777777
+#define MAXUGID 07777777
+
+enum mode {
+ LIST,
+ READ,
+ WRITE,
+ COPY,
+};
+
+enum format {
+ CPIO,
+ PAX,
+ USTAR,
+ GNUTAR,
+ V7,
+};
+
+enum field {
+ ATIME = 1<<0,
+ CTIME = 1<<1,
+ GID = 1<<2,
+ GNAME = 1<<3,
+ LINKPATH = 1<<4,
+ MODE = 1<<5,
+ MTIME = 1<<6,
+ PATH = 1<<7,
+ SIZE = 1<<8,
+ UID = 1<<9,
+ UNAME = 1<<10,
+};
+
+struct keyword {
+ const char *name;
+ enum field field;
+};
+
+struct strbuf {
+ char *str;
+ size_t len, cap;
+};
+
+struct header {
+ /* keywords present in this header */
+ enum field fields;
+ /* keywords ignored because they were overridden by an option */
+ enum field delete;
+
+ char type;
+
+ char *path;
+ size_t pathlen;
+ dev_t dev;
+ ino_t ino;
+ mode_t mode;
+ uid_t uid;
+ gid_t gid;
+ nlink_t nlink;
+ dev_t rdev;
+ off_t size;
+ struct timespec atime, mtime, ctime;
+ char *link;
+ size_t linklen;
+ char *uname;
+ char *gname;
+
+ struct strbuf pathbuf;
+ struct strbuf linkbuf;
+ struct strbuf unamebuf;
+ struct strbuf gnamebuf;
+
+ /* tar-specific, pre-calculated split point between name and prefix */
+ char *slash;
+ /* read this data instead of stdin */
+ char *data;
+ /* source file path and flags for hard link (-l flag) */
+ char *file;
+ struct timespec fileatime;
+ int flag;
+};
+
+struct account {
+ char *name;
+ enum field type;
+ uid_t uid;
+ gid_t gid;
+};
+
+struct bufio {
+ int fd, err;
+ off_t off;
+ char buf[64 * 1024];
+ char *pos, *end;
+};
+
+struct replstr {
+ regex_t old;
+ char *new;
+ int global;
+ int print;
+ int symlink;
+ struct replstr *next;
+};
+
+struct file {
+ size_t namelen;
+ size_t pathlen;
+ dev_t dev;
+ struct file *next;
+ char name[];
+};
+
+struct filelist {
+ FILE *input;
+ struct file *pending;
+};
+
+typedef int readfn(struct bufio *, struct header *);
+typedef void writefn(FILE *, struct header *);
+
+static int exitstatus;
+static int aflag;
+static int cflag;
+static int dflag;
+static int iflag;
+static int kflag;
+static int lflag;
+static int nflag;
+static int tflag;
+static int uflag;
+static int vflag;
+static int Xflag;
+static int follow;
+static int preserve = ATIME | MTIME;
+static const struct keyword keywords[] = {
+ {"atime", ATIME},
+ {"ctime", CTIME},
+ {"gid", GID},
+ {"gname", GNAME},
+ {"linkpath", LINKPATH},
+ {"mtime", MTIME},
+ {"path", PATH},
+ {"size", SIZE},
+ {"uid", UID},
+ {"uname", UNAME},
+};
+static struct {
+ enum field delete;
+ int linkdata;
+ const char *listopt;
+ const char *exthdrname;
+ const char *globexthdrname;
+ const char *invalid;
+ int times;
+} opt;
+static struct header exthdr, globexthdr;
+static struct replstr *replstr;
+static time_t curtime;
+static char **pats;
+static size_t patslen;
+static int *patsused;
+static struct filelist files;
+static struct bufio bioin;
+static char *dest = "";
+static int destfd = AT_FDCWD;
+
+static void
+fatal(const char *fmt, ...)
+{
+ va_list ap;
+
+ if (fmt) {
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
+ fputc(' ', stderr);
+ perror(NULL);
+ } else {
+ fputc('\n', stderr);
+ }
+ } else {
+ perror(NULL);
+ }
+ exit(1);
+}
+
+static char *
+sbufalloc(struct strbuf *b, size_t n, size_t a)
+{
+ char *s;
+
+ if (n > b->cap - b->len) {
+ if (n > SIZE_MAX - a || n + a > SIZE_MAX - b->len)
+ fatal("path is too long");
+ b->cap = ROUNDUP(n, a);
+ s = malloc(b->cap);
+ if (!s)
+ fatal(NULL);
+ if (b->len)
+ memcpy(s, b->str, b->len);
+ free(b->str);
+ b->str = s;
+ }
+ return b->str + b->len;
+}
+
+static int
+sbuffmtv(struct strbuf *b, size_t a, const char *fmt, va_list ap)
+{
+ va_list aptmp;
+ int n;
+
+ va_copy(aptmp, ap);
+ n = vsnprintf(b->str ? b->str + b->len : NULL, b->cap - b->len, fmt, aptmp);
+ va_end(aptmp);
+ if (n < 0)
+ fatal("vsnprintf:");
+ if ((size_t)n >= b->cap - b->len) {
+ sbufalloc(b, (size_t)n + 1, a);
+ n = vsnprintf(b->str + b->len, b->cap - b->len, fmt, ap);
+ if (n < 0)
+ fatal("vsnprintf:");
+ if ((size_t)n >= b->cap - b->len)
+ fatal("vsnprintf: formatted size changed");
+ }
+ b->len += n;
+ return n;
+}
+
+static int
+sbuffmt(struct strbuf *b, size_t a, const char *fmt, ...)
+{
+ va_list ap;
+ int n;
+
+ va_start(ap, fmt);
+ n = sbuffmtv(b, a, fmt, ap);
+ va_end(ap);
+ return n;
+}
+
+static void
+sbufcat(struct strbuf *b, const char *s, size_t n, size_t a)
+{
+ char *d;
+
+ d = sbufalloc(b, n + 1, a);
+ memcpy(d, s, n);
+ d[n] = 0;
+ b->len += n;
+}
+
+static void
+bioinit(struct bufio *f, int fd)
+{
+ f->fd = fd;
+ f->pos = f->end = f->buf;
+ f->off = 0;
+}
+
+static size_t
+bioread(struct bufio *f, void *p, size_t n)
+{
+ size_t l;
+ unsigned char *d;
+ struct iovec iov[2];
+ ssize_t r;
+
+ d = p;
+ if (f->pos != f->end) {
+ l = f->end - f->pos;
+ if (n < l)
+ l = n;
+ memcpy(d, f->pos, l);
+ f->pos += l;
+ n -= l;
+ d += l;
+ }
+ iov[1].iov_base = f->buf;
+ iov[1].iov_len = sizeof f->buf;
+ for (; n > 0; n -= r, d += r) {
+ iov[0].iov_base = d;
+ iov[0].iov_len = n;
+ r = readv(f->fd, iov, 2);
+ if (r < 0)
+ f->err = errno;
+ if (r <= 0)
+ break;
+ if ((size_t)r >= n) {
+ f->pos = f->buf;
+ f->end = f->buf + (r - n);
+ r = n;
+ }
+ }
+ l = d - (unsigned char *)p;
+ f->off += l;
+ return l;
+}
+
+static int
+bioskip(struct bufio *f, off_t n)
+{
+ static int seekfail;
+ size_t l;
+ ssize_t r;
+
+ if (f->pos != f->end) {
+ l = f->end - f->pos;
+ if (n < (off_t)l) {
+ f->pos += n;
+ return 0;
+ }
+ n -= l;
+ f->pos = f->end = f->buf;
+ }
+ if (!seekfail) {
+ if (n == 0 || lseek(f->fd, n, SEEK_CUR) >= 0)
+ return 0;
+ seekfail = 1;
+ }
+ for (; n > 0; n -= r) {
+ l = sizeof f->buf;
+ if (n < (off_t)l)
+ l = n;
+ r = read(f->fd, f->buf, l);
+ if (r <= 0)
+ return -1;
+ }
+ return 0;
+}
+
+static void
+copyblock(char *b, struct bufio *r, size_t nr, FILE *w, size_t nw)
+{
+ if (bioread(r, b, nr) != nr) {
+ if (r->err)
+ fatal("read: %s", strerror(r->err));
+ fatal("archive truncated");
+ }
+ if (nw > nr)
+ memset(b + nr, 0, nw - nr);
+ if (nw && fwrite(b, 1, nw, w) != nw)
+ fatal("write:");
+}
+
+/* nr and nw must differ by at most 8192 */
+static void
+copy(struct bufio *r, off_t nr, FILE *w, off_t nw)
+{
+ char b[8192];
+
+ assert(nr - nw <= (off_t)sizeof b || nw - nr <= (off_t)sizeof b);
+ for (; nr > (off_t)sizeof b && nw > (off_t)sizeof b; nr -= (off_t)sizeof b, nw -= (off_t)sizeof b)
+ copyblock(b, r, sizeof b, w, sizeof b);
+ copyblock(b, r, nr, w, nw);
+}
+
+static struct account *
+findaccount(const char *name, uid_t uid, gid_t gid)
+{
+ static struct account *accts;
+ static size_t acctslen;
+ struct account *a;
+
+ for (a = accts; a < accts + acctslen; ++a) {
+ if ((uid == (uid_t)-1 || uid == a->uid) && (gid == (gid_t)-1 || gid == a->gid)
+ && (!name || (a->name && strcmp(a->name, name) == 0)))
+ return a;
+ }
+ if ((acctslen & (acctslen - 1)) == 0) {
+ accts = reallocarray(accts, acctslen ? acctslen * 2 : 16, sizeof *accts);
+ if (!accts)
+ fatal(NULL);
+ }
+ a = &accts[acctslen++];
+ a->name = NULL;
+ a->type = 0;
+ a->uid = -1;
+ a->gid = -1;
+ if (name) {
+ a->name = strdup(name);
+ if (!a->name)
+ fatal(NULL);
+ }
+ return a;
+}
+
+static uid_t
+unametouid(const char *uname, uid_t fallback)
+{
+ struct account *a;
+ struct passwd *pw;
+
+ if (!*uname)
+ return fallback;
+ a = findaccount(uname, (uid_t)-1, (gid_t)-1);
+ if (~a->type & UID) {
+ a->type |= UID;
+ pw = getpwnam(uname);
+ a->uid = pw ? pw->pw_uid : (uid_t)-1;
+ }
+ return a->uid != (uid_t)-1 ? a->uid : fallback;
+}
+
+static gid_t
+gnametogid(const char *gname, gid_t fallback)
+{
+ struct account *a;
+ struct group *gr;
+
+ if (!*gname)
+ return fallback;
+ a = findaccount(gname, (uid_t)-1, (gid_t)-1);
+ if (~a->type & GID) {
+ a->type |= GID;
+ gr = getgrnam(gname);
+ a->gid = gr ? gr->gr_gid : (gid_t)-1;
+ }
+ return a->gid != (gid_t)-1 ? a->gid : fallback;
+}
+
+static char *
+uidtouname(uid_t uid, char *fallback)
+{
+ struct account *a;
+ struct passwd *pw;
+
+ a = findaccount(NULL, uid, (gid_t)-1);
+ if (~a->type & UID) {
+ a->type |= UID;
+ a->uid = uid;
+ assert(!a->name);
+ pw = getpwuid(uid);
+ if (pw) {
+ a->name = strdup(pw->pw_name);
+ if (!a->name)
+ fatal(NULL);
+ }
+ }
+ return a->name ? a->name : fallback;
+}
+
+static char *
+gidtogname(gid_t gid, char *fallback)
+{
+ struct account *a;
+ struct group *gr;
+
+ a = findaccount(NULL, (uid_t)-1, gid);
+ if (~a->type & GID) {
+ a->type |= GID;
+ a->gid = gid;
+ assert(!a->name);
+ gr = getgrgid(gid);
+ if (gr) {
+ a->name = strdup(gr->gr_name);
+ if (!a->name)
+ fatal(NULL);
+ }
+ }
+ return a->name ? a->name : fallback;
+}
+
+static unsigned long long
+octnum(const char *str, size_t len)
+{
+ const char *end;
+ unsigned c;
+ unsigned long long n;
+
+ n = 0;
+ end = str + len;
+ /* some archives have leading spaces, so skip them */
+ for (; str != end && *str == ' '; ++str)
+ ;
+ for (; str != end; ++str) {
+ c = *str;
+ if (c == ' ' || c == '\0')
+ break;
+ c -= '0';
+ if (c > 7)
+ fatal("invalid number field");
+ n = n * 8 + c;
+ }
+ return n;
+}
+
+static unsigned long long
+decnum(const char *str, size_t len, char **pos)
+{
+ const char *end;
+ unsigned c;
+ unsigned long long n;
+
+ n = 0;
+ end = str + len;
+ for (; str != end; ++str) {
+ c = *str - '0';
+ if (c > 9)
+ break;
+ n = n * 10 + c;
+ }
+ if (pos)
+ *pos = (char *)str;
+ return n;
+}
+
+static int
+readustar(struct bufio *f, struct header *h)
+{
+ static char buf[512];
+ static off_t end;
+ size_t namelen, prefixlen, linklen;
+ unsigned long sum;
+ int i;
+ enum format format;
+
+ assert(bioin.off <= end);
+ if (bioskip(f, end - bioin.off) != 0 || bioread(f, buf, sizeof buf) != sizeof buf) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ sum = 0;
+ for (i = 0; i < 512; ++i)
+ sum += ((unsigned char *)buf)[i];
+ if (sum == 0)
+ return 0;
+ for (i = 148; i < 156; ++i)
+ sum += ' ' - ((unsigned char *)buf)[i];
+ if (sum != octnum(buf + 148, 8))
+ fatal("invalid tar header: bad checksum");
+ if (memcmp(buf + 257, "ustar\0" "00", 8) == 0)
+ format = USTAR;
+ else if (memcmp(buf + 257, "ustar ", 8) == 0)
+ format = GNUTAR;
+ else
+ format = V7;
+ h->fields = PATH | UID | GID | SIZE;
+ namelen = strnlen(buf, 100);
+ prefixlen = format == USTAR ? strnlen(buf + 345, 155) : 0;
+ if (namelen == 100 || prefixlen > 0) {
+ h->pathbuf.len = 0;
+ if (prefixlen > 0) {
+ sbufcat(&h->pathbuf, buf + 345, prefixlen, 1024);
+ sbufcat(&h->pathbuf, "/", 1, 1024);
+ }
+ sbufcat(&h->pathbuf, buf, namelen, 1024);
+ h->path = h->pathbuf.str;
+ h->pathlen = h->pathbuf.len;
+ } else {
+ h->path = buf;
+ h->pathlen = namelen;
+ }
+ h->dev = 0;
+ h->ino = 0;
+ h->mode = octnum(buf + 100, 8);
+ h->uid = octnum(buf + 108, 8);
+ h->gid = octnum(buf + 116, 8);
+ h->nlink = 1;
+ h->size = octnum(buf + 124, 12);
+ end = bioin.off + ROUNDUP(h->size, 512);
+ h->mtime = (struct timespec){.tv_sec = octnum(buf + 136, 12)};
+ if (format == GNUTAR) {
+ h->fields |= ATIME | CTIME;
+ h->atime = (struct timespec){.tv_sec = octnum(buf + 345, 12)};
+ h->ctime = (struct timespec){.tv_sec = octnum(buf + 357, 12)};
+ }
+ h->type = buf[156];
+ if (h->type == AREGTYPE)
+ h->type = REGTYPE;
+
+ linklen = strnlen(buf + 157, 100);
+ if (linklen > 0)
+ h->fields |= LINKPATH;
+ if (linklen == 100) {
+ h->linkbuf.len = 0;
+ sbufcat(&h->linkbuf, buf + 157, 100, 1024);
+ h->link = h->linkbuf.str;
+ h->linklen = h->linkbuf.len;
+ } else {
+ h->link = buf + 157;
+ }
+ h->linklen = linklen;
+ if (format == V7) {
+ h->uname = "";
+ h->gname = "";
+ } else {
+ h->fields |= UNAME | GNAME;
+ h->uname = buf + 265;
+ if (!memchr(h->uname, '\0', 32))
+ fatal("uname is not NUL-terminated");
+ h->gname = buf + 297;
+ if (!memchr(h->gname, '\0', 32))
+ fatal("gname is not NUL-terminated");
+ if (h->type == CHRTYPE || h->type == BLKTYPE) {
+ unsigned major, minor;
+
+ major = octnum(buf + 329, 8);
+ minor = octnum(buf + 337, 8);
+ h->rdev = makedev(major, minor);
+ }
+ }
+ return 1;
+}
+
+static void
+parsetime(struct timespec *ts, const char *field, const char *str, size_t len)
+{
+ const char *end = str + len;
+ char *pos;
+ unsigned long long subsec;
+ size_t sublen;
+
+ ts->tv_sec = decnum(str, len, &pos);
+ if (*pos == '.') {
+ str = ++pos;
+ subsec = decnum(str, end - str, &pos);
+ for (sublen = pos - str; sublen < 9; ++sublen)
+ subsec *= 10;
+ ts->tv_nsec = subsec % 1000000000;
+ }
+ if (pos != end)
+ fatal("invalid extended header: bad %s", field);
+}
+
+static void
+extkeyval(struct header *h, const char *key, const char *val, size_t vallen)
+{
+ enum field field;
+ char *end;
+ const struct keyword *kw;
+
+ field = 0;
+ for (kw = keywords; kw != keywords + LEN(keywords); ++kw) {
+ if (strcmp(key, kw->name) == 0) {
+ field = kw->field;
+ break;
+ }
+ }
+ if (!field) {
+ if (strcmp(key, "charset") == 0) {
+ } else if (strcmp(key, "comment") == 0) {
+ /* ignore */
+ } else if (strcmp(key, "hdrcharset") == 0) {
+ } else if (strncmp(key, "realtime.", 9) == 0) {
+ } else if (strncmp(key, "security.", 9) == 0) {
+ } else {
+ fprintf(stderr, "ignoring unknown keyword '%s'\n", key);
+ }
+ return;
+ }
+ if ((h->delete | opt.delete) & field)
+ return;
+
+ switch (field) {
+ case ATIME:
+ parsetime(&h->atime, "atime", val, vallen);
+ break;
+ case CTIME:
+ parsetime(&h->ctime, "ctime", val, vallen);
+ break;
+ case GID:
+ h->gid = decnum(val, vallen, &end);
+ if (end != val + vallen)
+ fatal("invalid extended header: bad gid");
+ break;
+ case GNAME:
+ h->gnamebuf.len = 0;
+ sbufcat(&h->gnamebuf, val, vallen, 256);
+ h->gname = h->gnamebuf.str;
+ break;
+ case LINKPATH:
+ h->linkbuf.len = 0;
+ sbufcat(&h->linkbuf, val, vallen, 1024);
+ h->link = h->linkbuf.str;
+ h->linklen = h->linkbuf.len;
+ break;
+ case MTIME:
+ parsetime(&h->mtime, "mtime", val, vallen);
+ break;
+ case PATH:
+ h->pathbuf.len = 0;
+ sbufcat(&h->pathbuf, val, vallen, 1024);
+ h->path = h->pathbuf.str;
+ h->pathlen = h->pathbuf.len;
+ break;
+ case SIZE:
+ h->size = decnum(val, vallen, &end);
+ if (end != val + vallen)
+ fatal("invalid extended header: bad size");
+ break;
+ case UID:
+ h->uid = decnum(val, vallen, &end);
+ if (end != val + vallen)
+ fatal("invalid extended header: bad uid");
+ break;
+ case UNAME:
+ h->unamebuf.len = 0;
+ sbufcat(&h->unamebuf, val, vallen, 256);
+ h->uname = h->unamebuf.str;
+ break;
+ default:
+ return;
+ }
+ h->fields |= field;
+}
+
+static void
+readexthdr(struct bufio *f, struct header *h, off_t len)
+{
+ static struct strbuf buf;
+ size_t reclen, vallen;
+ char *rec, *end, *key, *val;
+
+ if (len > (off_t)SIZE_MAX)
+ fatal("extended header is too large");
+ buf.len = 0;
+ sbufalloc(&buf, (size_t)len, 8192);
+ if (bioread(f, buf.str, (size_t)len) != (size_t)len) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ rec = buf.str;
+ while (len > 0) {
+ end = memchr(rec, '\n', len);
+ if (!end)
+ fatal("invalid extended header: record is missing newline");
+ *end = '\0';
+ reclen = decnum(rec, (size_t)(end - rec), &key);
+ if (*key != ' ' || reclen != (unsigned long long)(end - rec + 1))
+ fatal("invalid extended header: invalid record");
+ ++key;
+ val = strchr(key, '=');
+ if (!val)
+ fatal("invalid extended header: record has no '='");
+ *val++ = '\0';
+ vallen = end - val;
+ extkeyval(h, key, val, vallen);
+ len -= reclen;
+ rec += reclen;
+ }
+}
+
+static void
+readgnuhdr(struct bufio *f, struct strbuf *b, off_t len)
+{
+ if (len > (off_t)(SIZE_MAX - 1))
+ fatal("GNU header is too large");
+ b->len = 0;
+ sbufalloc(b, (size_t)(len + 1), 1024);
+ if (bioread(f, b->str, (size_t)len) != (size_t)len) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ b->str[len] = '\0';
+ b->len = len;
+}
+
+static int
+readpax(struct bufio *f, struct header *h)
+{
+ exthdr.fields = exthdr.delete;
+ while (readustar(f, h)) {
+ switch (h->type) {
+ case 'g':
+ readexthdr(f, &globexthdr, h->size);
+ break;
+ case 'x':
+ readexthdr(f, &exthdr, h->size);
+ break;
+ case 'L':
+ if ((exthdr.delete | opt.delete) & PATH)
+ break;
+ readgnuhdr(f, &exthdr.pathbuf, h->size);
+ exthdr.path = exthdr.pathbuf.str;
+ exthdr.pathlen = exthdr.pathbuf.len;
+ exthdr.fields |= PATH;
+ break;
+ case 'K':
+ if ((exthdr.delete | opt.delete) & LINKPATH)
+ break;
+ readgnuhdr(f, &exthdr.linkbuf, h->size);
+ exthdr.link = exthdr.linkbuf.str;
+ exthdr.linklen = exthdr.linkbuf.len;
+ exthdr.fields |= LINKPATH;
+ break;
+ default:
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static int
+readcpio(struct bufio *f, struct header *h)
+{
+ static off_t end;
+ unsigned long type;
+ char buf[76];
+
+ if (bioskip(f, end - bioin.off) != 0 || bioread(f, buf, sizeof buf) != sizeof buf) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ if (memcmp(buf, "070707", 6) != 0)
+ fatal("invalid cpio header: bad magic");
+ h->pathlen = octnum(buf + 59, 6);
+ if (h->pathlen == 0)
+ fatal("invalid cpio header: c_namesize is 0");
+ h->pathbuf.len = 0;
+ sbufalloc(&h->pathbuf, h->pathlen, 1024);
+ h->path = h->pathbuf.str;
+ if (bioread(f, h->path, h->pathlen) != h->pathlen) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ if (h->path[--h->pathlen] != '\0')
+ fatal("invalid cpio header: name is not NUL-terminated");
+ if (strcmp(h->path, "TRAILER!!!") == 0)
+ return 0;
+
+ h->fields = PATH | MODE | UID | GID | MTIME | SIZE;
+ h->dev = octnum(buf + 6, 6);
+ h->ino = octnum(buf + 12, 6);
+ type = octnum(buf + 18, 6);
+ h->mode = type & 07777;
+ type &= ~07777;
+ switch (type) {
+ case C_ISDIR: h->type = DIRTYPE; break;
+ case C_ISFIFO: h->type = FIFOTYPE; break;
+ case C_ISREG: h->type = REGTYPE; break;
+ case C_ISLNK: h->type = SYMTYPE; break;
+ case C_ISBLK: h->type = BLKTYPE; break;
+ case C_ISCHR: h->type = CHRTYPE; break;
+ default: fatal("invalid cpio header: invalid or unsupported file type: %#o", type);
+ }
+ h->uid = octnum(buf + 24, 6);
+ h->gid = octnum(buf + 30, 6);
+ h->nlink = octnum(buf + 36, 6);
+ h->rdev = octnum(buf + 42, 6);
+ h->mtime = (struct timespec){.tv_sec = octnum(buf + 48, 11)};
+ h->size = octnum(buf + 65, 11);
+ h->uname = "";
+ h->gname = "";
+ if (h->type == SYMTYPE) {
+ if (h->size > (off_t)(SIZE_MAX - 1))
+ fatal("symlink target is too long");
+ h->linklen = h->size;
+ h->linkbuf.len = 0;
+ h->link = sbufalloc(&h->linkbuf, h->linklen + 1, 1024);
+ if (bioread(f, h->link, h->linklen) != h->linklen) {
+ if (f->err)
+ fatal("read: %s", strerror(f->err));
+ fatal("archive truncated");
+ }
+ h->link[h->linklen] = '\0';
+ h->size = 0;
+ h->fields |= LINKPATH;
+ } else {
+ h->link = "";
+ h->linklen = 0;
+ }
+ end = bioin.off + h->size;
+ return 1;
+}
+
+static int
+decompress(const char *algo, int fd, pid_t *pid)
+{
+ extern char **environ;
+ posix_spawn_file_actions_t fa;
+ int p[2], err;
+ char *argv[3];
+
+ if (!algo)
+ return fd;
+ argv[0] = (char *)algo;
+ argv[1] = "-dc";
+ argv[2] = NULL;
+ if (pipe2(p, O_CLOEXEC) != 0)
+ fatal("pipe2:");
+ err = posix_spawn_file_actions_init(&fa);
+ if (err)
+ fatal("posix_spawn_file_actions_init: %s", strerror(errno));
+ err = posix_spawn_file_actions_adddup2(&fa, fd, 0);
+ if (err)
+ fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
+ err = posix_spawn_file_actions_adddup2(&fa, p[1], 1);
+ if (err)
+ fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
+ err = posix_spawnp(pid, algo, &fa, NULL, argv, environ);
+ if (err)
+ fatal("posix_spawnp %s: %s", algo, strerror(errno));
+ close(p[1]);
+ return p[0];
+}
+
+static readfn *
+detectformat(struct bufio *f, const char *algo, pid_t *pid)
+{
+ size_t l, i;
+ ssize_t n;
+ unsigned char *b;
+
+again:
+ f->fd = decompress(algo, f->fd, pid);
+ b = (unsigned char *)f->buf;
+ for (l = 0; l < 512; l += n) {
+ n = read(f->fd, b + l, 512 - l);
+ if (n < 0)
+ fatal("read:");
+ if (n == 0)
+ break;
+ }
+ f->pos = f->buf;
+ f->end = f->buf + l;
+ if (l == 512) {
+ unsigned long sum, hdrsum;
+
+ sum = 0;
+ for (i = 0; i < 512; ++i)
+ sum += b[i];
+ if (sum == 0)
+ return readpax;
+ hdrsum = 0;
+ for (i = 148; i < 156; ++i) {
+ sum += ' ' - b[i];
+ if (b[i] >= '0' && b[i] <= '9')
+ hdrsum = hdrsum * 8 + (b[i] - '0');
+ }
+ if (sum == hdrsum)
+ return readpax;
+ }
+ if (l >= 76) {
+ if (memcmp(b, "070707", 6) == 0)
+ return readcpio;
+ }
+ if (!algo) {
+ static const struct command {
+ char algo[6];
+ unsigned char magiclen;
+ unsigned char magic[6];
+ } cmds[] = {
+ {"gzip", 2, {0x1F, 0x8B}},
+ {"bzip2", 2, {'B', 'Z'}},
+ {"xz", 6, {0xFD, '7', 'z', 'X', 'Z', 0x00}},
+ {"zstd", 4, {0x28, 0xB5, 0x2F, 0xFD}},
+ {"lzip", 4, {'L', 'Z', 'I', 'P'}},
+ };
+ const struct command *c;
+
+ for (c = cmds; c < cmds + LEN(cmds); ++c) {
+ if (l >= c->magiclen && memcmp(b, c->magic, c->magiclen) == 0) {
+ if (lseek(f->fd, 0, SEEK_SET) != 0)
+ fatal("compression detection requires seekable input");
+ algo = c->algo;
+ goto again;
+ }
+ }
+ }
+ return NULL;
+}
+
+static FILE *
+compress(const char *algo, const char *name, pid_t *pid)
+{
+ extern char **environ;
+ FILE *f;
+ int fd, p[2], err;
+ posix_spawn_file_actions_t fa;
+ char *argv[3];
+
+ if (!algo) {
+ if (name && !freopen(name, aflag ? "r+" : "w", stdout))
+ fatal("open %s:");
+ if (aflag && name) {
+ if (fseek(stdout, 0, SEEK_END) != 0)
+ fatal("fseek %s:");
+ }
+ return stdout;
+ }
+ argv[0] = (char *)algo;
+ argv[1] = "-c";
+ argv[2] = NULL;
+ if (name) {
+ fd = open(name, O_WRONLY | O_CREAT, 0666);
+ if (fd < 0)
+ fatal("open %s:");
+ } else {
+ fd = 1;
+ }
+ if (pipe2(p, O_CLOEXEC) != 0)
+ fatal("pipe2:");
+ f = fdopen(p[1], "w");
+ if (!f)
+ fatal("fdopen:");
+ err = posix_spawn_file_actions_init(&fa);
+ if (err)
+ fatal("posix_spawn_file_actions_init: %s", strerror(errno));
+ err = posix_spawn_file_actions_adddup2(&fa, p[0], 0);
+ if (err)
+ fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
+ err = posix_spawn_file_actions_adddup2(&fa, fd, 1);
+ if (err)
+ fatal("posix_spawn_file_actions_adddup2: %s", strerror(errno));
+ err = posix_spawnp(pid, algo, &fa, NULL, argv, environ);
+ if (err)
+ fatal("posix_spawnp %s: %s", algo, strerror(errno));
+ close(fd);
+ close(p[0]);
+ return f;
+}
+
+static char *
+splitname(char *name, size_t namelen)
+{
+ char *slash;
+
+ if (namelen > 256)
+ return NULL;
+ slash = memchr(name + namelen - 100, '/', 100);
+ if (!slash || slash - name > 155)
+ return NULL;
+ return slash;
+}
+
+static void
+openfile(struct header *h)
+{
+ int fd;
+
+ if (h->file) {
+ fd = open(h->file, O_RDONLY);
+ if (fd < 0)
+ fatal("open %s:", h->file);
+ bioinit(&bioin, fd);
+ }
+}
+
+static void
+closefile(struct header *h)
+{
+ if (h->file) {
+ if (tflag)
+ futimens(bioin.fd, (struct timespec[2]){h->fileatime, {.tv_nsec = UTIME_OMIT}});
+ close(bioin.fd);
+ }
+}
+
+static void
+closeustar(FILE *f)
+{
+ char pad[512];
+
+ memset(pad, 0, 512);
+ if (fwrite(pad, 512, 1, f) != 1)
+ fatal("write:");
+ if (fwrite(pad, 512, 1, f) != 1)
+ fatal("write:");
+}
+
+static void
+writeustar(FILE *f, struct header *h)
+{
+ char buf[512], *slash, tmp[32];
+ unsigned long sum;
+ int i;
+
+ if (!h) {
+ closeustar(f);
+ return;
+ }
+ slash = h->slash;
+ if (!slash && h->pathlen > 100) {
+ slash = splitname(h->path, h->pathlen);
+ if (!slash)
+ fatal("path is too long: %s\n", h->path);
+ }
+ if (slash) {
+ size_t len;
+
+ strncpy(buf, slash + 1, 100);
+ len = slash - h->path;
+ memcpy(buf + 345, h->path, len);
+ memset(buf + 345 + len, 0, 155 - len);
+ } else {
+ strncpy(buf, h->path, 100);
+ memset(buf + 345, 0, 155);
+ }
+ if (h->mode > 07777777)
+ fatal("mode is too large: %ju", (uintmax_t)h->mode);
+ snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->mode & 07777777);
+ memcpy(buf + 100, tmp, 8);
+ if (h->uid > MAXUGID)
+ fatal("uid is too large: %ju", (uintmax_t)h->uid);
+ snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->uid & 07777777);
+ memcpy(buf + 108, tmp, 8);
+ if (h->gid > MAXUGID)
+ fatal("gid is too large: %ju", (uintmax_t)h->gid);
+ snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)h->gid & 07777777);
+ memcpy(buf + 116, tmp, 8);
+ if (h->size < 0 || h->size > MAXSIZE)
+ fatal("size is too large: %ju", (uintmax_t)h->size);
+ snprintf(buf + 124, 12, "%.11llo", (unsigned long long)h->size);
+ if (h->mtime.tv_sec < 0 || h->mtime.tv_sec > MAXTIME)
+ fatal("mtime is too large: %ju", (uintmax_t)h->mtime.tv_sec);
+ snprintf(buf + 136, 12, "%.11llo", (unsigned long long)h->mtime.tv_sec);
+ memset(buf + 148, ' ', 8);
+ buf[156] = h->type;
+ if (h->linklen > 100)
+ fatal("link name is too long: %s\n", h->link);
+ strncpy(buf + 157, h->link, 100);
+ memcpy(buf + 257, "ustar", 6);
+ memcpy(buf + 263, "00", 2);
+ if (strlen(h->uname) > 31)
+ fatal("user name is too long: %s\n", h->uname);
+ strncpy(buf + 265, h->uname, 32);
+ if (strlen(h->gname) > 31)
+ fatal("group name is too long: %s\n", h->gname);
+ strncpy(buf + 297, h->gname, 32);
+ if (major(h->rdev) > 07777777)
+ fatal("device major is too large: %ju\n", (uintmax_t)major(h->rdev));
+ snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)major(h->rdev) & 07777777);
+ memcpy(buf + 329, tmp, 8);
+ if (minor(h->rdev) > 07777777)
+ fatal("device minor is too large: %ju\n", (uintmax_t)minor(h->rdev));
+ snprintf(tmp, sizeof(tmp), "%.7lo", (unsigned long)minor(h->rdev) & 07777777);
+ memcpy(buf + 337, tmp, 8);
+ memset(buf + 500, 0, 12);
+ sum = 0;
+ for (i = 0; i < 512; ++i)
+ sum += ((unsigned char *)buf)[i];
+ snprintf(tmp, sizeof(tmp), "%.7lo", sum & 07777777);
+ memcpy(buf + 148, tmp, 8);
+ if (fwrite(buf, 512, 1, f) != 1)
+ fatal("write:");
+ if (h->data) {
+ size_t pad;
+
+ if (fwrite(h->data, 1, (size_t)h->size, f) != (size_t)h->size)
+ fatal("write:");
+ pad = (size_t)(ROUNDUP(h->size, 512) - h->size);
+ memset(bioin.buf, 0, pad);
+ if (fwrite(bioin.buf, 1, pad, f) != pad)
+ fatal("write:");
+ } else if (h->size > 0) {
+ openfile(h);
+ copy(&bioin, h->size, f, ROUNDUP(h->size, 512));
+ closefile(h);
+ }
+}
+
+static void
+writerec(struct strbuf *ext, const char *fmt, ...)
+{
+ static struct strbuf buf;
+ va_list ap;
+ int d, n, m, l;
+
+ buf.len = 0;
+ va_start(ap, fmt);
+ l = sbuffmtv(&buf, 256, fmt, ap);
+ va_end(ap);
+
+ d = 0;
+ m = 1;
+ for (n = l; n > 0; n /= 10) {
+ m *= 10;
+ ++d;
+ }
+ n = d + 1 + l + 1;
+ if (n >= m)
+ ++n;
+ sbuffmt(ext, 256, "%d %.*s\n", n, l, buf.str);
+}
+
+static void
+writetimerec(struct strbuf *ext, char *kw, struct timespec *ts)
+{
+ if (ts->tv_nsec != 0)
+ writerec(ext, "%s=%ju.%.9ld", kw, (uintmax_t)ts->tv_sec, ts->tv_nsec % 1000000000);
+ else
+ writerec(ext, "%s=%ju", kw, (uintmax_t)ts->tv_sec);
+}
+
+static void
+writeexthdr(FILE *f, int type, struct header *h)
+{
+ static struct strbuf ext;
+ struct header exthdr;
+
+ ext.len = 0;
+ if (h->fields & PATH)
+ writerec(&ext, "path=%s", h->path);
+ if (h->fields & UID)
+ writerec(&ext, "uid=%ju", (uintmax_t)h->uid);
+ if (h->fields & GID)
+ writerec(&ext, "gid=%ju", (uintmax_t)h->gid);
+ if (h->fields & SIZE)
+ writerec(&ext, "size=%ju", (uintmax_t)h->size);
+ if (h->fields & MTIME)
+ writetimerec(&ext, "mtime", &h->mtime);
+ if (h->fields & ATIME)
+ writetimerec(&ext, "atime", &h->atime);
+ if (h->fields & CTIME)
+ writetimerec(&ext, "ctime", &h->ctime);
+ if (h->fields & UNAME)
+ writerec(&ext, "uname=%s", h->uname);
+ if (h->fields & GNAME)
+ writerec(&ext, "gname=%s", h->gname);
+ if (ext.len > 0) {
+ memset(&exthdr, 0, sizeof exthdr);
+ exthdr.path = "pax_extended_header";
+ exthdr.pathlen = 20;
+ exthdr.mode = 0600;
+ exthdr.link = "";
+ exthdr.uname = "";
+ exthdr.gname = "";
+ exthdr.size = ext.len;
+ exthdr.type = type;
+ exthdr.data = ext.str;
+ writeustar(f, &exthdr);
+ }
+}
+
+static void
+mergehdr(struct header *dst, struct header *src, enum field fields)
+{
+ fields &= src->fields;
+ if (fields & PATH) {
+ dst->path = src->path;
+ dst->pathlen = src->pathlen;
+ }
+ if (fields & UID)
+ dst->uid = src->uid;
+ if (fields & GID)
+ dst->gid = src->gid;
+ if (fields & SIZE)
+ dst->size = src->size;
+ if (fields & MTIME)
+ dst->mtime = src->mtime;
+ if (fields & ATIME)
+ dst->atime = src->atime;
+ if (fields & CTIME)
+ dst->ctime = src->ctime;
+ if (fields & UNAME)
+ dst->uname = src->uname;
+ if (fields & GNAME)
+ dst->gname = src->gname;
+ if (fields & LINKPATH) {
+ dst->link = src->link;
+ dst->linklen = src->linklen;
+ }
+ dst->fields |= fields;
+}
+
+static void
+writepax(FILE *f, struct header *h)
+{
+ enum field fields;
+
+ if (!h) {
+ closeustar(f);
+ return;
+ }
+ if (vflag)
+ fprintf(stderr, "%s\n", h->path);
+ fields = 0;
+ if (h->pathlen > 100) {
+ h->slash = splitname(h->path, h->pathlen);
+ if (!h->slash)
+ fields |= PATH;
+ }
+ if (h->uid > MAXUGID)
+ fields |= UID;
+ if (h->gid > MAXUGID)
+ fields |= GID;
+ if (h->size > MAXSIZE)
+ fields |= SIZE;
+ if (h->mtime.tv_sec > MAXTIME || h->mtime.tv_nsec != 0)
+ fields |= MTIME;
+ if (opt.times)
+ fields |= ATIME | CTIME;
+ if (strlen(h->uname) > 31)
+ fields |= UNAME;
+ if (strlen(h->gname) > 31)
+ fields |= GNAME;
+ if (h->linklen > 100)
+ fields |= LINKPATH;
+ fields &= ~(exthdr.fields | opt.delete);
+ mergehdr(&exthdr, h, fields);
+ writeexthdr(f, 'x', &exthdr);
+
+ /* reset fields merged into extended header */
+ if (fields & PATH)
+ h->path = "", h->pathlen = 0;
+ if (fields & UID)
+ h->uid = 0;
+ if (fields & GID)
+ h->gid = 0;
+ if (fields & SIZE)
+ h->size = 0;
+ if (fields & MTIME) {
+ if (h->mtime.tv_sec > MAXTIME)
+ h->mtime.tv_sec = MAXTIME;
+ h->mtime.tv_nsec = 0;
+ }
+ if (fields & ATIME) {
+ if (h->atime.tv_sec > MAXTIME)
+ h->atime.tv_sec = MAXTIME;
+ h->atime.tv_nsec = 0;
+ }
+ if (fields & CTIME) {
+ if (h->ctime.tv_sec > MAXTIME)
+ h->ctime.tv_sec = MAXTIME;
+ h->ctime.tv_nsec = 0;
+ }
+ if (fields & UNAME)
+ h->uname = "";
+ if (fields & GNAME)
+ h->gname = "";
+ if (fields & LINKPATH)
+ h->link = "", h->linklen = 0;
+ h->fields &= ~fields;
+ writeustar(f, h);
+}
+
+static void
+writecpio(FILE *f, struct header *h)
+{
+ static unsigned long ino;
+ char buf[77];
+ unsigned long mode;
+ uintmax_t size;
+ size_t namesize;
+ int len;
+
+ if (!h) {
+ memcpy(buf, "070707", 6);
+ memset(buf + 6, '0', 70);
+ memcpy(buf + 59, "000013", 6);
+ if (fwrite(buf, 1, 76, f) != 76)
+ fatal("write:");
+ if (fwrite("TRAILER!!!", 1, 11, f) != 11)
+ fatal("write:");
+ return;
+ }
+ if (vflag)
+ fprintf(stderr, "%s\n", h->path);
+ mode = h->mode;
+ switch (h->type) {
+ case DIRTYPE: mode |= S_IFDIR; break;
+ case FIFOTYPE: mode |= S_IFIFO; break;
+ case REGTYPE: mode |= S_IFREG; break;
+ case SYMTYPE: mode |= S_IFLNK; break;
+ case BLKTYPE: mode |= S_IFBLK; break;
+ case CHRTYPE: mode |= S_IFCHR; break;
+ default: fatal("unknown or unsupported header type");
+ }
+ if (h->dev > 0777777)
+ fatal("device is too large: %ju", (uintmax_t)h->dev);
+ if (++ino > 0777777)
+ fatal("inode is too large: %lu", ino);
+ if (mode > 0777777)
+ fatal("mode is too large: %lu", mode);
+ if (h->uid > MAXUGID)
+ fatal("uid is too large: %ju", (uintmax_t)h->uid);
+ if (h->gid > MAXUGID)
+ fatal("gid is too large: %ju", (uintmax_t)h->gid);
+ if (h->nlink > 0777777)
+ fatal("nlink is too large: %ju", (uintmax_t)h->nlink);
+ if (h->rdev > 0777777)
+ fatal("device is too large: %ju", (uintmax_t)h->rdev);
+ if (h->mtime.tv_sec > MAXTIME)
+ fatal("mtime is too large: %ju", (uintmax_t)h->mtime.tv_sec);
+ namesize = h->pathlen;
+ if (namesize > 0 && h->path[namesize - 1] == '/')
+ --namesize;
+ if (namesize > 077777777777 - 1)
+ fatal("path is too large: %ju", (uintmax_t)h->pathlen + 1);
+ size = h->type == SYMTYPE ? (uintmax_t)h->linklen : (uintmax_t)h->size;
+ if (size > MAXSIZE)
+ fatal("size is too large: %ju", h->size);
+ len = snprintf(buf, sizeof buf, "070707%.6lo%.6lo%.6lo%.6lo%.6lo%.6lo%.6lo%.11llo%.6lo%.11jo",
+ (unsigned long)h->dev, ino, mode,
+ (unsigned long)h->uid, (unsigned long)h->gid,
+ (unsigned long)h->nlink, (unsigned long)h->rdev,
+ (unsigned long long)h->mtime.tv_sec, (unsigned long)namesize + 1, size);
+ assert(len == 76);
+ if (fwrite(buf, 1, 76, f) != 76)
+ fatal("write:");
+ if (fwrite(h->path, 1, namesize, f) != namesize || fputc('\0', f) == EOF)
+ fatal("write:");
+ switch (h->type) {
+ case SYMTYPE:
+ if (fwrite(h->link, 1, h->linklen, f) != h->linklen)
+ fatal("write:");
+ break;
+ case REGTYPE:
+ openfile(h);
+ copy(&bioin, h->size, f, h->size);
+ closefile(h);
+ break;
+ default:
+ break;
+ }
+}
+
+static void
+filepush(struct filelist *files, const char *name, size_t pathlen, dev_t dev)
+{
+ struct file *f;
+ size_t namelen;
+
+ namelen = strlen(name);
+ f = malloc(sizeof *f + namelen + 1);
+ if (!f)
+ fatal(NULL);
+ memcpy(f->name, name, namelen + 1);
+ f->namelen = namelen;
+ f->pathlen = pathlen;
+ f->dev = dev;
+ f->next = files->pending;
+ files->pending = f;
+}
+
+static int
+readfile(struct bufio *f, struct header *h)
+{
+ /* use our own path buffer, since we use it for traversal */
+ static struct strbuf path;
+ struct stat st;
+ int flag;
+ DIR *dir;
+ struct dirent *d;
+ ssize_t ret;
+ dev_t dev;
+
+ (void)f;
+
+next:
+ flag = follow == 'L' ? 0 : AT_SYMLINK_NOFOLLOW;
+ if (files.pending) {
+ struct file *f;
+
+ f = files.pending;
+ files.pending = f->next;
+ assert(f->pathlen <= path.len);
+ path.len = f->pathlen;
+ sbufcat(&path, f->name, f->namelen, 1024);
+ if (follow == 'H' && f->pathlen > 0)
+ flag &= ~AT_SYMLINK_NOFOLLOW;
+ dev = f->dev;
+ free(f);
+ } else {
+ if (!files.input)
+ return 0;
+ ret = getline(&path.str, &path.cap, files.input);
+ if (ret < 0) {
+ if (ferror(files.input))
+ fatal("getline:");
+ return 0;
+ }
+ if (ret > 0 && path.str[ret - 1] == '\n')
+ path.str[--ret] = '\0';
+ path.len = ret;
+ dev = 0;
+ }
+
+ if (fstatat(AT_FDCWD, path.str, &st, flag) != 0)
+ fatal("stat %s:", path.str);
+ if (Xflag && dev && st.st_dev != dev)
+ goto next;
+ if (S_ISDIR(st.st_mode) && path.str[path.len - 1] != '/')
+ sbufcat(&path, "/", 1, 1024);
+ h->fields = PATH | UID | GID | ATIME | MTIME | CTIME;
+ h->path = path.str;
+ h->pathlen = path.len;
+ h->dev = st.st_dev;
+ h->ino = st.st_ino;
+ h->mode = st.st_mode & ~S_IFMT;
+ h->uid = st.st_uid;
+ h->gid = st.st_gid;
+ h->nlink = st.st_nlink;
+ h->rdev = 0;
+ h->size = 0;
+ h->atime = st.st_atim;
+ h->mtime = st.st_mtim;
+ h->ctime = st.st_ctim;
+ h->uname = uidtouname(st.st_uid, "");
+ h->gname = gidtogname(st.st_gid, "");
+ h->link = "";
+ h->linklen = 0;
+ h->slash = NULL;
+ h->data = NULL;
+ h->file = h->path;
+ h->fileatime = st.st_atim;
+ h->flag = flag;
+ switch (st.st_mode & S_IFMT) {
+ case S_IFREG:
+ h->type = REGTYPE;
+ h->size = st.st_size;
+ break;
+ case S_IFLNK:
+ h->type = SYMTYPE;
+ h->linkbuf.len = 0;
+ sbufalloc(&h->linkbuf, 1024, 1024);
+ for (;;) {
+ ret = readlink(h->path, h->linkbuf.str, h->linkbuf.cap - 1);
+ if (ret < 0)
+ fatal("readlink %s:", h->path);
+ if ((size_t)ret < h->linkbuf.cap)
+ break;
+ if (h->linkbuf.cap > (size_t)SSIZE_MAX / 2)
+ fatal("symlink target is too long");
+ sbufalloc(&h->linkbuf, h->linkbuf.cap * 2, 1024);
+ }
+ h->linkbuf.str[ret] = '\0';
+ h->linkbuf.len = ret;
+ h->link = h->linkbuf.str;
+ h->linklen = h->linkbuf.len;
+ break;
+ case S_IFCHR:
+ h->type = CHRTYPE;
+ h->rdev = st.st_rdev;
+ break;
+ case S_IFBLK:
+ h->type = BLKTYPE;
+ h->rdev = st.st_rdev;
+ break;
+ case S_IFDIR:
+ h->type = DIRTYPE;
+ dir = opendir(h->path);
+ if (!dir)
+ fatal("opendir %s:", h->path);
+ for (;;) {
+ errno = 0;
+ d = readdir(dir);
+ if (!d)
+ break;
+ if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
+ continue;
+ filepush(&files, d->d_name, path.len, st.st_dev);
+ }
+ if (errno != 0)
+ fatal("readdir %s:", h->path);
+ closedir(dir);
+ break;
+ case S_IFIFO:
+ h->type = FIFOTYPE;
+ break;
+ }
+ return 1;
+}
+
+static void
+usage(void)
+{
+ fprintf(stderr, "usage: pax\n");
+ exit(2);
+}
+
+static void
+print_listopt(struct header *h)
+{
+ const char *s;
+ size_t len;
+
+ s = opt.listopt;
+ while (*s) {
+ if (*s == '%') {
+ s++;
+ if (*s == '%') {
+ putchar('%');
+ s++;
+ } else {
+ len = 0;
+ while (s[len] && isalnum((unsigned char)s[len]))
+ len++;
+ if (len > 0) {
+ if (strncmp(s, "path", len) == 0 && len == 4)
+ printf("%s", h->path);
+ else if (strncmp(s, "size", len) == 0 && len == 4)
+ printf("%ju", (uintmax_t)h->size);
+ else if (strncmp(s, "uid", len) == 0 && len == 3)
+ printf("%ju", (uintmax_t)h->uid);
+ else if (strncmp(s, "gid", len) == 0 && len == 3)
+ printf("%ju", (uintmax_t)h->gid);
+ else if (strncmp(s, "uname", len) == 0 && len == 5)
+ printf("%s", h->uname);
+ else if (strncmp(s, "gname", len) == 0 && len == 5)
+ printf("%s", h->gname);
+ else if (strncmp(s, "mode", len) == 0 && len == 4)
+ printf("%04o", (unsigned int)(h->mode & 07777));
+ else if (strncmp(s, "mtime", len) == 0 && len == 5)
+ printf("%ju", (uintmax_t)h->mtime.tv_sec);
+ else if (strncmp(s, "atime", len) == 0 && len == 5)
+ printf("%ju", (uintmax_t)h->atime.tv_sec);
+ else if (strncmp(s, "ctime", len) == 0 && len == 5)
+ printf("%ju", (uintmax_t)h->ctime.tv_sec);
+ else if (strncmp(s, "linkpath", len) == 0 && len == 8)
+ printf("%s", h->link);
+ else {
+ putchar('%');
+ fwrite(s, 1, len, stdout);
+ }
+ s += len;
+ } else {
+ putchar('%');
+ }
+ }
+ } else if (*s == '\\') {
+ s++;
+ if (*s == 'n') {
+ putchar('\n');
+ s++;
+ } else if (*s == 't') {
+ putchar('\t');
+ s++;
+ } else if (*s == '\\') {
+ putchar('\\');
+ s++;
+ } else if (*s) {
+ putchar(*s);
+ s++;
+ }
+ } else {
+ putchar(*s);
+ s++;
+ }
+ }
+ putchar('\n');
+}
+
+static void
+parseopts(char *s)
+{
+ char *key, *val, *end, *d;
+ int ext;
+
+ for (;;) {
+ s += strspn(s, " \t\n\v\f\r");
+ if (!*s)
+ break;
+ key = s;
+ while (*s && *s != ',' && *s != '=')
+ ++s;
+ val = NULL;
+ end = NULL, ext = 0; /* silence gcc uninitialized warning */
+ if (*s == '=') {
+ ext = s > key && s[-1] == ':';
+ s[-ext] = '\0';
+ val = ++s;
+ for (d = s; *s && *s != ','; ++s, ++d) {
+ if (*s == '\\')
+ ++s;
+ if (d < s)
+ *d = *s;
+ }
+ end = d;
+ }
+ if (*s == ',')
+ *s++ = '\0';
+ if (strcmp(key, "linkdata") == 0) {
+ if (val)
+ fatal("option 'linkdata' must not have a value");
+ opt.linkdata = 1;
+ } else if (strcmp(key, "times") == 0) {
+ if (val)
+ fatal("option 'times' must not have a value");
+ opt.times = 1;
+ } else if (!val) {
+ fatal("option '%s' must have a value", key);
+ } else if (strcmp(key, "delete") == 0) {
+ const struct keyword *kw;
+
+ for (kw = keywords; kw != keywords + LEN(keywords); ++kw) {
+ switch (fnmatch(val, kw->name, 0)) {
+ case 0: opt.delete |= kw->field; break;
+ case FNM_NOMATCH: break;
+ default: fatal("fnmatch error");
+ }
+ }
+ } else if (strcmp(key, "exthdr.name") == 0) {
+ opt.exthdrname = val;
+ } else if (strcmp(key, "globexthdr.name") == 0) {
+ opt.globexthdrname = val;
+ } else if (strcmp(key, "invalid") == 0) {
+ if (strcmp(val, "bypass") != 0 && strcmp(val, "rename") != 0 &&
+ strcmp(val, "UTF-8") != 0 && strcmp(val, "write") != 0) {
+ fatal("invalid action '%s' for option 'invalid'", val);
+ }
+ opt.invalid = val;
+ } else if (strcmp(key, "listopt") == 0) {
+ opt.listopt = val;
+ } else {
+ extkeyval(ext ? &exthdr : &globexthdr, key, val, end - val);
+ }
+ }
+}
+
+static void
+listhdr(FILE *f, struct header *h)
+{
+ char mode[11], time[13], info[23];
+ char unamebuf[(sizeof(uid_t) * CHAR_BIT + 2) / 3 + 1];
+ char gnamebuf[(sizeof(gid_t) * CHAR_BIT + 2) / 3 + 1];
+ const char *uname, *gname, *timefmt;
+ struct tm *tm;
+
+ if (!h)
+ return;
+ (void)f;
+ if (opt.listopt) {
+ print_listopt(h);
+ return;
+ }
+ if (!vflag) {
+ printf("%s\n", h->path);
+ return;
+ }
+ memset(mode, '-', sizeof mode - 1);
+ mode[10] = '\0';
+ switch (h->type) {
+ case SYMTYPE: mode[0] = 'l'; break;
+ case CHRTYPE: mode[0] = 'c'; break;
+ case BLKTYPE: mode[0] = 'b'; break;
+ case DIRTYPE: mode[0] = 'd'; break;
+ case FIFOTYPE: mode[0] = 'p'; break;
+ }
+ if (h->mode & S_IRUSR) mode[1] = 'r';
+ if (h->mode & S_IWUSR) mode[2] = 'w';
+ if (h->mode & S_IXUSR) mode[3] = 'x';
+ if (h->mode & S_IRGRP) mode[4] = 'r';
+ if (h->mode & S_IWGRP) mode[5] = 'w';
+ if (h->mode & S_IXGRP) mode[6] = 'x';
+ if (h->mode & S_IROTH) mode[7] = 'r';
+ if (h->mode & S_IWOTH) mode[8] = 'w';
+ if (h->mode & S_IXOTH) mode[9] = 'x';
+ if (h->mode & S_ISUID) mode[3] = mode[3] == 'x' ? 's' : 'S';
+ if (h->mode & S_ISGID) mode[3] = mode[6] == 'x' ? 's' : 'S';
+ if (h->mode & S_ISVTX) mode[9] = mode[9] == 'x' ? 't' : 'T';
+ uname = h->uname;
+ if (!uname[0]) {
+ snprintf(unamebuf, sizeof unamebuf, "%ju", (uintmax_t)h->uid);
+ uname = unamebuf;
+ }
+ gname = h->gname;
+ if (!gname[0]) {
+ snprintf(gnamebuf, sizeof gnamebuf, "%ju", (uintmax_t)h->gid);
+ gname = gnamebuf;
+ }
+ timefmt = h->mtime.tv_sec + 15780000 < curtime || h->mtime.tv_sec > curtime
+ ? "%b %e %Y" : "%b %e %H:%M";
+ tm = localtime(&h->mtime.tv_sec);
+ if (!tm)
+ fatal("localtime:");
+ strftime(time, sizeof time, timefmt, tm);
+ if (h->type == CHRTYPE || h->type == BLKTYPE)
+ snprintf(info, sizeof info, "%u, %u", major(h->rdev), minor(h->rdev));
+ else
+ snprintf(info, sizeof info, "%ju", (uintmax_t)h->size);
+ printf("%s %2ju %-8s %-8s %9s %s %s", mode, (uintmax_t)h->nlink, uname, gname, info, time, h->path);
+ switch (h->type) {
+ case LNKTYPE: printf(" == %s", h->link); break;
+ case SYMTYPE: printf(" -> %s", h->link); break;
+ }
+ putchar('\n');
+}
+
+static void
+mkdirp(int fd, char *name, size_t len)
+{
+ char *p;
+
+ if (len == 0)
+ return;
+ for (p = name + 1; p < name + len - 1; ++p) {
+ if (*p != '/')
+ continue;
+ *p = 0;
+ if (mkdirat(fd, name, 0777) != 0 && errno != EEXIST)
+ fatal("mkdir %s:", name);
+ *p = '/';
+ }
+}
+
+static void
+writefile(FILE *unused, struct header *h)
+{
+ FILE *f;
+ int fd, retry, flags;
+ struct stat st;
+ mode_t mode;
+
+ (void)unused;
+ if (!h)
+ return;
+ if (uflag && fstatat(destfd, h->path, &st, 0) == 0) {
+ if (h->mtime.tv_sec < st.st_mtime || (h->mtime.tv_sec == st.st_mtime
+ && h->mtime.tv_nsec < st.st_mtim.tv_nsec))
+ return;
+ }
+ if (vflag)
+ fprintf(stderr, "%s\n", h->path);
+ if (lflag && h->file && h->type != DIRTYPE) {
+ if (linkat(AT_FDCWD, h->file, destfd, h->path, h->flag) == 0)
+ return;
+ }
+ retry = 1;
+ if (0) {
+ retry:
+ retry = 0;
+ mkdirp(destfd, h->path, h->pathlen);
+ }
+ mode = h->mode & ~(S_ISUID | S_ISGID);
+ switch (h->type) {
+ case REGTYPE:
+ flags = O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC;
+ if (kflag)
+ flags |= O_EXCL;
+ fd = openat(destfd, h->path, flags, mode);
+ if (fd < 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ fatal("open %s%s:", dest, h->path);
+ }
+ f = fdopen(fd, "w");
+ if (!f)
+ fatal("open %s:", h->path);
+ openfile(h);
+ copy(&bioin, h->size, f, h->size);
+ closefile(h);
+ fclose(f);
+ break;
+ case LNKTYPE:
+ if (linkat(destfd, h->link, destfd, h->path, 0) != 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ fatal("link %s%s:", dest, h->path);
+ }
+ break;
+ case SYMTYPE:
+ if (symlinkat(h->link, destfd, h->path) != 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ fatal("symlink %s%s:", dest, h->path);
+ }
+ break;
+ case CHRTYPE:
+ case BLKTYPE:
+ mode |= h->type == CHRTYPE ? S_IFCHR : S_IFBLK;
+ if (mknodat(destfd, h->path, mode, h->rdev) != 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ fatal("mknod %s%s:", dest, h->path);
+ }
+ break;
+ case DIRTYPE:
+ if (mkdirat(destfd, h->path, mode) != 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ if (errno == EEXIST) {
+ if (fstatat(destfd, h->path, &st, 0) == 0 && S_ISDIR(st.st_mode))
+ break;
+ errno = EEXIST;
+ }
+ fatal("mkdir %s%s:", dest, h->path);
+ }
+ break;
+ case FIFOTYPE:
+ if (mkfifoat(destfd, h->path, mode) != 0) {
+ if (retry && errno == ENOENT)
+ goto retry;
+ if (errno == EEXIST) {
+ if (fstatat(destfd, h->path, &st, 0) == 0 && S_ISFIFO(st.st_mode))
+ break;
+ errno = EEXIST;
+ }
+ fatal("mkfifo %s%s:", dest, h->path);
+ }
+ break;
+ }
+ if (preserve & (ATIME | MTIME)) {
+ struct timespec ts[2];
+
+ ts[0] = preserve & ATIME ? h->atime : (struct timespec){.tv_nsec = UTIME_OMIT};
+ ts[1] = preserve & MTIME ? h->mtime : (struct timespec){.tv_nsec = UTIME_OMIT};
+ if (utimensat(destfd, h->path, ts, AT_SYMLINK_NOFOLLOW) != 0) {
+ fprintf(stderr, "utimens %s%s: %s\n", dest, h->path, strerror(errno));
+ exitstatus = 1;
+ }
+ }
+ if (preserve & (UID | GID)) {
+ uid_t uid;
+ gid_t gid;
+
+ uid = preserve & UID ? unametouid(h->uname, h->uid) : (uid_t)-1;
+ gid = preserve & GID ? gnametogid(h->gname, h->gid) : (gid_t)-1;
+ if (fchownat(destfd, h->path, uid, gid, 0) != 0) {
+ fprintf(stderr, "chown %s%s: %s\n", dest, h->path, strerror(errno));
+ exitstatus = 1;
+ } else {
+ /* add back setuid/setgid bits if we preserved the uid/gid */
+ mode = h->mode;
+ }
+ }
+ if (preserve & MODE && h->type != SYMTYPE) {
+ if (fchmodat(destfd, h->path, mode, 0) != 0) {
+ fprintf(stderr, "chmod %s%s: %s\n", dest, h->path, strerror(errno));
+ exitstatus = 1;
+ }
+ }
+}
+
+static int
+match(struct header *h)
+{
+ static struct dir {
+ char *path;
+ size_t pathlen;
+ } *dirs;
+ static size_t dirslen;
+ size_t i;
+
+ if (patslen == 0)
+ return 1;
+ if (!dflag) {
+ struct dir *d;
+
+ for (d = dirs; d < dirs + dirslen; ++d) {
+ if (h->pathlen >= d->pathlen && memcmp(h->path, d->path, d->pathlen) == 0)
+ return !cflag;
+ }
+ }
+ for (i = 0; i < patslen; ++i) {
+ if (nflag && patsused[i])
+ continue;
+ switch (fnmatch(pats[i], h->path, FNM_PATHNAME | FNM_PERIOD)) {
+ case 0:
+ patsused[i] = 1;
+ if (!dflag && h->type == DIRTYPE) {
+ struct dir *d;
+
+ if ((dirslen & (dirslen - 1)) == 0) {
+ dirs = reallocarray(dirs, dirslen ? dirslen * 2 : 32, sizeof *dirs);
+ if (!dirs)
+ fatal(NULL);
+ }
+ d = &dirs[dirslen++];
+ d->pathlen = h->pathlen;
+ d->path = malloc(d->pathlen + 1);
+ if (!d->path)
+ fatal(NULL);
+ memcpy(d->path, h->path, h->pathlen);
+ /* add trailing slash if not already present */
+ if (d->path[d->pathlen - 1] != '/')
+ d->path[d->pathlen++] = '/';
+ }
+ return !cflag;
+ case FNM_NOMATCH:
+ break;
+ default:
+ fatal("fnmatch error");
+ }
+ }
+ return cflag;
+}
+
+static void
+parsereplstr(char *str)
+{
+ static struct replstr **end = &replstr;
+ struct replstr *r;
+ char *old, *new, delim;
+ int err;
+
+ delim = str[0];
+ if (!delim)
+ usage();
+ old = str + 1;
+ str = strchr(old, delim);
+ if (!str)
+ usage();
+ *str = 0;
+ new = str + 1;
+ str = strchr(new, delim);
+ if (!str)
+ usage();
+ *str = 0;
+
+ r = malloc(sizeof *r);
+ if (!r)
+ fatal(NULL);
+ r->next = NULL;
+ r->global = 0;
+ r->print = 0;
+ r->symlink = 0;
+ for (;;) {
+ switch (*++str) {
+ case 'g': r->global = 1; break;
+ case 'p': r->print = 1; break;
+ case 's': r->symlink = 0; break;
+ case 'S': r->symlink = 1; break;
+ case 0: goto done;
+ }
+ }
+done:
+ err = regcomp(&r->old, old, REG_NEWLINE);
+ if (err != 0) {
+ char errbuf[256];
+
+ regerror(err, &r->old, errbuf, sizeof errbuf);
+ fatal("invalid regular expression: %s", errbuf);
+ }
+ r->new = new;
+ *end = r;
+ end = &r->next;
+}
+
+static int
+applyrepl(struct replstr *r, struct strbuf *b, const char *old, size_t oldlen)
+{
+ regmatch_t match[10];
+ size_t i, n, l;
+ const char *s, *p;
+ char *d;
+ int flags;
+
+ flags = 0;
+ b->len = 0;
+ p = old;
+ while (regexec(&r->old, p, LEN(match), match, flags) == 0) {
+ n = match[0].rm_so;
+ for (s = r->new; *s; ++s) {
+ switch (*s) {
+ case '&': i = 0; break;
+ case '\\': i = *++s - '0'; break;
+ default: i = -1; break;
+ }
+ n += i <= 9 ? match[i].rm_eo - match[i].rm_so : 1;
+ }
+ d = sbufalloc(b, n + 1, 1024);
+ b->len += n;
+ memcpy(d, p, match[0].rm_so);
+ d += match[0].rm_so;
+ for (s = r->new; *s; ++s) {
+ switch (*s) {
+ case '&': i = 0; break;
+ case '\\': i = *++s - '0'; break;
+ default: i = -1; break;
+ }
+ if (i <= 9) {
+ l = match[i].rm_eo - match[i].rm_so;
+ memcpy(d, p + match[i].rm_so, l);
+ d += l;
+ } else {
+ *d++ = *s;
+ }
+ }
+ flags |= REG_NOTBOL;
+ p += match[0].rm_eo;
+ if (!r->global)
+ break;
+ }
+ if (flags == 0)
+ return 0;
+ sbufcat(b, p, oldlen - (p - old), 1024);
+ if (r->print)
+ fprintf(stderr, "%s >> %s\n", old, b->str);
+ return 1;
+}
+
+static void
+replace(struct header *h)
+{
+ static struct strbuf path, link;
+ struct replstr *r;
+
+ for (r = replstr; r; r = r->next) {
+ if (applyrepl(r, &path, h->path, h->pathlen)) {
+ h->path = path.str;
+ h->pathlen = path.len;
+ break;
+ }
+ }
+ if (h->type != LNKTYPE && h->type != SYMTYPE)
+ return;
+ for (r = replstr; r; r = r->next) {
+ if (h->type == SYMTYPE && !r->symlink)
+ continue;
+ if (applyrepl(r, &link, h->link, h->linklen)) {
+ h->link = link.str;
+ h->linklen = link.len;
+ break;
+ }
+ }
+}
+
+static int
+is_invalid_name(const char *name)
+{
+ unsigned char c;
+
+ if (!name || !*name)
+ return 1;
+ for (; *name; name++) {
+ c = (unsigned char)*name;
+ if (c < 32 || c >= 127)
+ return 1;
+ }
+ return 0;
+}
+
+static void
+interactiverename(struct header *h)
+{
+ static FILE *ttyfp = NULL;
+ static char ttybuf[1024];
+ char *res;
+
+ if (!iflag)
+ return;
+
+ if (!ttyfp) {
+ ttyfp = fopen("/dev/tty", "r+");
+ if (!ttyfp)
+ ttyfp = stdin;
+ }
+
+ fprintf(stderr, "rename %s? ", h->path);
+ fflush(stderr);
+
+ if (ttyfp == stdin)
+ res = fgets(ttybuf, sizeof(ttybuf), stdin);
+ else
+ res = fgets(ttybuf, sizeof(ttybuf), ttyfp);
+
+ if (!res) {
+ h->path = "";
+ h->pathlen = 0;
+ return;
+ }
+
+ ttybuf[strcspn(ttybuf, "\n")] = '\0';
+
+ if (ttybuf[0] == '\0')
+ return;
+
+ if (strcmp(ttybuf, ".") == 0) {
+ h->path = "";
+ h->pathlen = 0;
+ return;
+ }
+
+ h->pathbuf.len = 0;
+ sbufcat(&h->pathbuf, ttybuf, strlen(ttybuf), 1024);
+ h->path = h->pathbuf.str;
+ h->pathlen = h->pathbuf.len;
+}
+
+static void
+checkinvalid(struct header *h)
+{
+ int saved_iflag;
+
+ if (!opt.invalid)
+ return;
+ if (is_invalid_name(h->path)) {
+ if (strcmp(opt.invalid, "bypass") == 0) {
+ h->path = "";
+ h->pathlen = 0;
+ } else if (strcmp(opt.invalid, "rename") == 0) {
+ saved_iflag = iflag;
+ iflag = 1;
+ interactiverename(h);
+ iflag = saved_iflag;
+ }
+ }
+}
+
+static off_t
+locate_tar_end(const char *filename)
+{
+ char buf[512];
+ off_t offset = 0;
+ int zero_blocks = 0;
+ int fd, i, is_zero;
+ ssize_t r;
+
+ fd = open(filename, O_RDONLY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ return 0;
+ fatal("open %s for append check:", filename);
+ }
+
+ while ((r = read(fd, buf, 512)) == 512) {
+ is_zero = 1;
+ for (i = 0; i < 512; i++) {
+ if (buf[i] != 0) {
+ is_zero = 0;
+ break;
+ }
+ }
+ if (is_zero) {
+ zero_blocks++;
+ if (zero_blocks == 2) {
+ close(fd);
+ return offset;
+ }
+ } else {
+ zero_blocks = 0;
+ }
+ offset += 512;
+ }
+
+ close(fd);
+ return offset;
+}
+
+static void
+handle_append(const char *filename, const char *algo, const char *format)
+{
+ off_t offset;
+ int fd;
+
+ if (!aflag)
+ return;
+ if (algo)
+ fatal("cannot append to compressed archives");
+ if (strcmp(format, "ustar") != 0 && strcmp(format, "pax") != 0)
+ fatal("append is only supported for ustar and pax formats");
+
+ if (filename) {
+ offset = locate_tar_end(filename);
+ if (offset > 0) {
+ fd = open(filename, O_RDWR);
+ if (fd >= 0) {
+ if (ftruncate(fd, offset) != 0)
+ fatal("ftruncate %s for append:", filename);
+ close(fd);
+ }
+ }
+ }
+}
+
+int
+main(int argc, char *argv[])
+{
+ const char *name = NULL, *arg, *format = "pax";
+ const char *algo = NULL;
+ enum mode mode = LIST;
+ struct header hdr;
+ readfn *readhdr = NULL;
+ writefn *writehdr = listhdr;
+ FILE *out = NULL;
+ pid_t pid = -1;
+ int i;
+ size_t l;
+
+ ARGBEGIN {
+ case 'a':
+ aflag = 1;
+ break;
+ case 'b':
+ EARGF(usage());
+ break;
+ case 'c':
+ cflag = 1;
+ break;
+ case 'd':
+ dflag = 1;
+ break;
+ case 'f':
+ name = EARGF(usage());
+ break;
+ case 'H':
+ follow = 'H';
+ break;
+ case 'i':
+ iflag = 1;
+ break;
+ case 'j':
+ algo = "bzip2";
+ break;
+ case 'J':
+ algo = "xz";
+ break;
+ case 'k':
+ kflag = 1;
+ break;
+ case 'l':
+ lflag = 1;
+ break;
+ case 'L':
+ follow = 'L';
+ break;
+ case 'n':
+ nflag = 1;
+ break;
+ case 'o':
+ parseopts(EARGF(usage()));
+ break;
+ case 'p':
+ for (arg = EARGF(usage()); *arg; ++arg) {
+ switch (*arg) {
+ case 'a': preserve &= ~ATIME; break;
+ case 'e': preserve = ~0; break;
+ case 'm': preserve &= ~MTIME; break;
+ case 'o': preserve |= UID | GID; break;
+ case 'p': preserve |= MODE; break;
+ default: fatal("unknown -p option");
+ }
+ }
+ break;
+ case 'r':
+ mode |= READ;
+ break;
+ case 's':
+ parsereplstr(EARGF(usage()));
+ break;
+ case 't':
+ tflag = 1;
+ break;
+ case 'u':
+ uflag = 1;
+ break;
+ case 'v':
+ vflag = 1;
+ break;
+ case 'w':
+ mode |= WRITE;
+ break;
+ case 'x':
+ format = EARGF(usage());
+ break;
+ case 'X':
+ Xflag = 1;
+ break;
+ case 'z':
+ algo = "gzip";
+ break;
+ default:
+ usage();
+ } ARGEND;
+
+ curtime = time(NULL);
+ if (curtime == (time_t)-1)
+ fatal("time:");
+ exthdr.fields &= ~opt.delete;
+ exthdr.delete = exthdr.fields;
+ globexthdr.fields &= ~opt.delete;
+ globexthdr.delete = globexthdr.fields;
+ if ((exthdr.fields | globexthdr.fields | opt.delete) & SIZE)
+ fatal("field 'size' cannot be overridden or deleted");
+
+ switch (mode) {
+ case READ:
+ writehdr = writefile;
+ /* fallthrough */
+ case LIST:
+ if (name && strcmp(name, "-") != 0) {
+ bioin.fd = open(name, O_RDONLY);
+ if (bioin.fd < 0)
+ fatal("open %s:", name);
+ }
+ readhdr = detectformat(&bioin, algo, &pid);
+ if (!readhdr)
+ fatal("could not detect archive format");
+ if (argc) {
+ pats = argv;
+ patslen = argc;
+ patsused = calloc(1, argc);
+ if (!patsused)
+ fatal(NULL);
+ }
+ break;
+ case WRITE:
+ if (name && strcmp(name, "-") == 0)
+ name = NULL;
+ handle_append(name, algo, format);
+ out = compress(algo, name, &pid);
+ if (strcmp(format, "ustar") == 0) {
+ writehdr = writeustar;
+ } else if (strcmp(format, "pax") == 0) {
+ writehdr = writepax;
+ if (globexthdr.fields)
+ writeexthdr(stdout, 'g', &globexthdr);
+ } else if (strcmp(format, "cpio") == 0) {
+ writehdr = writecpio;
+ } else {
+ fatal("unsupported archive format '%s'", format);
+ }
+ break;
+ case COPY:
+ if (name || argc == 0)
+ usage();
+ l = strlen(argv[--argc]);
+ dest = malloc(l + 2);
+ if (!dest)
+ fatal(NULL);
+ memcpy(dest, argv[argc], l);
+ memcpy(dest + l, "/", 2);
+ destfd = open(dest, O_SEARCH|O_DIRECTORY);
+ if (destfd < 0)
+ fatal("open %s:", dest);
+ writehdr = writefile;
+ break;
+ }
+ if (mode & WRITE) {
+ readhdr = readfile;
+ bioin.fd = -1;
+ for (i = 0; i < argc; ++i)
+ filepush(&files, argv[i], 0, 0);
+ if (argc == 0)
+ files.input = stdin;
+ }
+
+ memset(&hdr, 0, sizeof hdr);
+ while (readhdr(&bioin, &hdr)) {
+ mergehdr(&hdr, &exthdr, ~0);
+ mergehdr(&hdr, &globexthdr, ~exthdr.fields);
+ if (match(&hdr)) {
+ replace(&hdr);
+ checkinvalid(&hdr);
+ interactiverename(&hdr);
+ if (*hdr.path)
+ writehdr(out, &hdr);
+ }
+ }
+ writehdr(out, NULL);
+ if (out) {
+ if (fflush(out) != 0)
+ fatal("write:");
+ fclose(out);
+ }
+ for (i = 0; i < (int)patslen; ++i) {
+ if (!patsused[i])
+ fatal("pattern not matched: %s", pats[i]);
+ }
+
+ if (pid != -1) {
+ int st;
+
+ if (waitpid(pid, &st, 0) == -1)
+ fatal("waitpid:");
+ if (WIFEXITED(st) && WEXITSTATUS(st) != 0)
+ fatal("child exited with status %d", WEXITSTATUS(st));
+ if (WIFSIGNALED(st))
+ fatal("child terminated by signal %d", WTERMSIG(st));
+ }
+ return exitstatus;
+}
diff --git a/cmd/posix/printf.c b/cmd/posix/printf.c
@@ -47,7 +47,7 @@ unescape_pct(char *s, char *is_pct)
for (q = 0, m = 3; m && is_odigit(*r); m--, r++)
q = q * 8 + (*r - '0');
is_pct[w - s] = 0;
- *w++ = MIN(q, 255);
+ *w++ = MIN(q, (size_t)255);
} else if (*r == 'x' && isxdigit(r[1])) {
r++;
for (q = 0, m = 2; m && isxdigit(*r); m--, r++)
diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c
@@ -32,7 +32,7 @@ psout(struct procstat *ps)
{
struct procstatus pstatus;
char cmdline[BUFSIZ], *cmd;
- char buf[BUFSIZ];
+ char buf[sizeof(cmdline) + sizeof(ps->comm) + 1024];
char ttystr[TTY_NAME_MAX], *myttystr;
int tty_maj, tty_min;
uid_t myeuid;
diff --git a/cmd/posix/rm.c b/cmd/posix/rm.c
@@ -25,7 +25,7 @@ forbidden(char *path, struct stat *root)
for (s = t; s > path && s[-1] != '/'; --s)
;
n = t - s;
- if (n == 1 && *s == '.' || n == 2 && s[0] == '.' && s[1] == '.') {
+ if ((n == 1 && *s == '.') || (n == 2 && s[0] == '.' && s[1] == '.')) {
if (!w1)
weprintf("\".\" and \"..\" may not be removed\n");
w1 = 1;
@@ -47,7 +47,6 @@ forbidden(char *path, struct stat *root)
int
main(int argc, char *argv[])
{
- char *s;
struct stat st;
struct recursor r = { .fn = rm, .maxdepth = 1, .follow = 'P' };
diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c
@@ -7,14 +7,18 @@
* POSIX says don't flush on N when out of input, but GNU and busybox do.
*/
+#include "config.h"
+#include "utf.h"
+#include "util.h"
+
#include <ctype.h>
#include <errno.h>
+#include <libgen.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
-
-#include "utf.h"
-#include "util.h"
+#include <sys/stat.h>
+#include <unistd.h>
/* Types */
@@ -353,6 +357,32 @@ leprintf(char *s)
}
/* FIXME: write usage message */
+#if FEATURE_SED_INPLACE
+static int iflag = 0;
+static char *backup_suffix = NULL;
+
+static int
+create_temp_file(const char *orig_path, char **temp_path)
+{
+ char *dir, *dircopy, *tmpl;
+ int fd;
+
+ dircopy = estrdup(orig_path);
+ dir = dirname(dircopy);
+ tmpl = emalloc(strlen(dir) + 16);
+ sprintf(tmpl, "%s/sedtmpXXXXXX", dir);
+ free(dircopy);
+
+ fd = mkstemp(tmpl);
+ if (fd < 0) {
+ free(tmpl);
+ return -1;
+ }
+ *temp_path = tmpl;
+ return fd;
+}
+#endif
+
static void
usage(void)
{
@@ -1463,7 +1493,9 @@ cmd_s(Cmd *c)
strnacat(&genbuf, p, len);
p += len;
switch (*p) {
- default: leprintf("this shouldn't be possible");
+ default:
+ leprintf("this shouldn't be possible");
+ break;
case '\0':
/* we're at the end, back up one so the ++p will put us on
* the null byte to break out of the loop */
@@ -1594,6 +1626,7 @@ cmd_y(Cmd *c)
static void
cmd_colon(Cmd *c)
{
+ (void)c;
}
static void
@@ -1620,12 +1653,14 @@ cmd_lbrace(Cmd *c)
static void
cmd_rbrace(Cmd *c)
{
+ (void)c;
}
/* not actually a sed function, but acts like one, put in last spot of script */
static void
cmd_last(Cmd *c)
{
+ (void)c;
if (!gflags.n)
check_puts(patt.str, stdout);
do_writes();
@@ -1713,6 +1748,17 @@ main(int argc, char *argv[])
compile(arg, 1);
script = 1;
break;
+#if FEATURE_SED_INPLACE
+ case 'i':
+ iflag = 1;
+ if (argv[0][1] != '\0') {
+ backup_suffix = &argv[0][1];
+ brk_ = 1;
+ } else {
+ backup_suffix = "";
+ }
+ break;
+#endif
default : usage();
} ARGEND
@@ -1729,8 +1775,113 @@ main(int argc, char *argv[])
pc = prog + pcap - 1;
pc->fninfo = &(Fninfo){ cmd_last, NULL, NULL, 0 };
- files = argv;
- run();
+#if FEATURE_SED_INPLACE
+ if (iflag) {
+ char *single_file[2] = { NULL, NULL };
+ char **orig_files = argv;
+ int i;
+
+ if (!*orig_files)
+ eprintf("no input files\n");
+
+ for (i = 0; orig_files[i]; i++) {
+ char *temp_path = NULL;
+ int temp_fd;
+ int real_stdout;
+ struct stat st;
+ Cmd *c;
+
+ if (strcmp(orig_files[i], "-") == 0) {
+ weprintf("cannot edit stdin in-place\n");
+ ret = 1;
+ continue;
+ }
+
+ if (stat(orig_files[i], &st) < 0) {
+ weprintf("stat %s:", orig_files[i]);
+ ret = 1;
+ continue;
+ }
+
+ temp_fd = create_temp_file(orig_files[i], &temp_path);
+ if (temp_fd < 0) {
+ weprintf("create_temp_file:");
+ ret = 1;
+ continue;
+ }
+
+ real_stdout = dup(1);
+ if (real_stdout < 0) {
+ weprintf("dup stdout:");
+ close(temp_fd);
+ free(temp_path);
+ ret = 1;
+ continue;
+ }
+ if (dup2(temp_fd, 1) < 0) {
+ weprintf("dup2 stdout:");
+ close(temp_fd);
+ close(real_stdout);
+ free(temp_path);
+ ret = 1;
+ continue;
+ }
+ close(temp_fd);
+
+ single_file[0] = orig_files[i];
+ files = single_file;
+
+ /* reset state for next file */
+ lineno = 0;
+ gflags.halt = 0;
+ stracpy(&hold, "");
+ stracpy(&patt, "");
+ writes.size = 0;
+ for (c = prog; c->fninfo->fn != cmd_last; c++) {
+ c->in_match = 0;
+ }
+
+ run();
+
+ fflush(stdout);
+ dup2(real_stdout, 1);
+ close(real_stdout);
+
+ if (backup_suffix && *backup_suffix) {
+ char *backup_path = emalloc(strlen(orig_files[i]) + strlen(backup_suffix) + 1);
+ sprintf(backup_path, "%s%s", orig_files[i], backup_suffix);
+ if (rename(orig_files[i], backup_path) < 0) {
+ weprintf("rename %s to %s:", orig_files[i], backup_path);
+ unlink(temp_path);
+ free(backup_path);
+ free(temp_path);
+ ret = 1;
+ continue;
+ }
+ free(backup_path);
+ } else {
+ unlink(orig_files[i]);
+ }
+
+ if (rename(temp_path, orig_files[i]) < 0) {
+ weprintf("rename %s to %s:", temp_path, orig_files[i]);
+ unlink(temp_path);
+ free(temp_path);
+ ret = 1;
+ continue;
+ }
+
+ chmod(orig_files[i], st.st_mode);
+ chown(orig_files[i], st.st_uid, st.st_gid);
+
+ free(temp_path);
+ }
+ } else
+#endif
+ {
+ files = argv;
+ run();
+ }
ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>");
diff --git a/cmd/posix/sh/alias.c b/cmd/posix/sh/alias.c
@@ -0,0 +1,272 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdlib.h>
+#include "shell.h"
+#include "output.h"
+#include "error.h"
+#include "memalloc.h"
+#include "mystring.h"
+#include "alias.h"
+#include "options.h"
+#include "builtins.h"
+
+#define ATABSIZE 39
+
+static struct alias *atab[ATABSIZE];
+static int aliases;
+
+static void setalias(const char *, const char *);
+static int unalias(const char *);
+static size_t hashalias(const char *);
+
+static
+void
+setalias(const char *name, const char *val)
+{
+ struct alias *ap, **app;
+
+ unalias(name);
+ app = &atab[hashalias(name)];
+ INTOFF;
+ ap = ckmalloc(sizeof (struct alias));
+ ap->name = savestr(name);
+ ap->val = savestr(val);
+ ap->flag = 0;
+ ap->next = *app;
+ *app = ap;
+ aliases++;
+ INTON;
+}
+
+static void
+freealias(struct alias *ap)
+{
+ ckfree(ap->name);
+ ckfree(ap->val);
+ ckfree(ap);
+}
+
+static int
+unalias(const char *name)
+{
+ struct alias *ap, **app;
+
+ app = &atab[hashalias(name)];
+
+ for (ap = *app; ap; app = &(ap->next), ap = ap->next) {
+ if (equal(name, ap->name)) {
+ /*
+ * if the alias is currently in use (i.e. its
+ * buffer is being used by the input routine) we
+ * just null out the name instead of freeing it.
+ * We could clear it out later, but this situation
+ * is so rare that it hardly seems worth it.
+ */
+ if (ap->flag & ALIASINUSE)
+ *ap->name = '\0';
+ else {
+ INTOFF;
+ *app = ap->next;
+ freealias(ap);
+ INTON;
+ }
+ aliases--;
+ return (0);
+ }
+ }
+
+ return (1);
+}
+
+static void
+rmaliases(void)
+{
+ struct alias *ap, **app;
+ int i;
+
+ INTOFF;
+ for (i = 0; i < ATABSIZE; i++) {
+ app = &atab[i];
+ while (*app) {
+ ap = *app;
+ if (ap->flag & ALIASINUSE) {
+ *ap->name = '\0';
+ app = &(*app)->next;
+ } else {
+ *app = ap->next;
+ freealias(ap);
+ }
+ }
+ }
+ aliases = 0;
+ INTON;
+}
+
+struct alias *
+lookupalias(const char *name, int check)
+{
+ struct alias *ap;
+
+ if (aliases == 0)
+ return (NULL);
+ for (ap = atab[hashalias(name)]; ap; ap = ap->next) {
+ if (equal(name, ap->name)) {
+ if (check && (ap->flag & ALIASINUSE))
+ return (NULL);
+ return (ap);
+ }
+ }
+
+ return (NULL);
+}
+
+static int
+comparealiases(const void *p1, const void *p2)
+{
+ const struct alias *const *a1 = p1;
+ const struct alias *const *a2 = p2;
+
+ return strcmp((*a1)->name, (*a2)->name);
+}
+
+static void
+printalias(const struct alias *a)
+{
+ out1fmt("%s=", a->name);
+ out1qstr(a->val);
+ out1c('\n');
+}
+
+static void
+printaliases(void)
+{
+ int i, j;
+ struct alias **sorted, *ap;
+
+ INTOFF;
+ sorted = ckmalloc(aliases * sizeof(*sorted));
+ j = 0;
+ for (i = 0; i < ATABSIZE; i++)
+ for (ap = atab[i]; ap; ap = ap->next)
+ if (*ap->name != '\0')
+ sorted[j++] = ap;
+ qsort(sorted, aliases, sizeof(*sorted), comparealiases);
+ for (i = 0; i < aliases; i++) {
+ printalias(sorted[i]);
+ if (int_pending())
+ break;
+ }
+ ckfree(sorted);
+ INTON;
+}
+
+int
+aliascmd(int argc __unused, char **argv __unused)
+{
+ char *n, *v;
+ int ret = 0;
+ struct alias *ap;
+
+ nextopt("");
+
+ if (*argptr == NULL) {
+ printaliases();
+ return (0);
+ }
+ while ((n = *argptr++) != NULL) {
+ if (n[0] == '\0') {
+ warning("'': not found");
+ ret = 1;
+ continue;
+ }
+ if ((v = strchr(n+1, '=')) == NULL) /* n+1: funny ksh stuff */
+ if ((ap = lookupalias(n, 0)) == NULL) {
+ warning("%s: not found", n);
+ ret = 1;
+ } else
+ printalias(ap);
+ else {
+ *v++ = '\0';
+ setalias(n, v);
+ }
+ }
+
+ return (ret);
+}
+
+int
+unaliascmd(int argc __unused, char **argv __unused)
+{
+ int i;
+
+ while ((i = nextopt("a")) != '\0') {
+ if (i == 'a') {
+ rmaliases();
+ return (0);
+ }
+ }
+ for (i = 0; *argptr; argptr++)
+ i |= unalias(*argptr);
+
+ return (i);
+}
+
+static size_t
+hashalias(const char *p)
+{
+ unsigned int hashval;
+
+ hashval = (unsigned char)*p << 4;
+ while (*p)
+ hashval+= *p++;
+ return (hashval % ATABSIZE);
+}
+
+const struct alias *
+iteralias(const struct alias *index)
+{
+ size_t i = 0;
+
+ if (index != NULL) {
+ if (index->next != NULL)
+ return (index->next);
+ i = hashalias(index->name) + 1;
+ }
+ for (; i < ATABSIZE; i++)
+ if (atab[i] != NULL)
+ return (atab[i]);
+
+ return (NULL);
+}
diff --git a/cmd/posix/sh/alias.h b/cmd/posix/sh/alias.h
@@ -0,0 +1,45 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define ALIASINUSE 1
+
+struct alias {
+ struct alias *next;
+ char *name;
+ char *val;
+ int flag;
+};
+
+struct alias *lookupalias(const char *, int);
+const struct alias *iteralias(const struct alias *);
diff --git a/cmd/posix/sh/arith.h b/cmd/posix/sh/arith.h
@@ -0,0 +1,36 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1995
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "shell.h"
+
+#define DIGITS(var) (3 + (2 + CHAR_BIT * sizeof((var))) / 3)
+
+arith_t arith(const char *);
diff --git a/cmd/posix/sh/arith_yacc.c b/cmd/posix/sh/arith_yacc.c
@@ -0,0 +1,387 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ * Copyright (c) 2007
+ * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(__has_include)
+#if __has_include(<sys/cdefs.h>)
+#include <sys/cdefs.h>
+#endif
+#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
+#include <sys/cdefs.h>
+#endif
+#include <limits.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include "arith.h"
+#include "arith_yacc.h"
+#include "expand.h"
+#include "shell.h"
+#include "error.h"
+#include "memalloc.h"
+#include "output.h"
+#include "options.h"
+#include "var.h"
+
+#if ARITH_BOR + 11 != ARITH_BORASS || ARITH_ASS + 11 != ARITH_EQ
+#error Arithmetic tokens are out of order.
+#endif
+
+static const char *arith_startbuf;
+
+const char *arith_buf;
+union yystype yylval;
+
+static int last_token;
+
+#define ARITH_PRECEDENCE(op, prec) [op - ARITH_BINOP_MIN] = prec
+
+static const char prec[ARITH_BINOP_MAX - ARITH_BINOP_MIN] = {
+ ARITH_PRECEDENCE(ARITH_MUL, 0),
+ ARITH_PRECEDENCE(ARITH_DIV, 0),
+ ARITH_PRECEDENCE(ARITH_REM, 0),
+ ARITH_PRECEDENCE(ARITH_ADD, 1),
+ ARITH_PRECEDENCE(ARITH_SUB, 1),
+ ARITH_PRECEDENCE(ARITH_LSHIFT, 2),
+ ARITH_PRECEDENCE(ARITH_RSHIFT, 2),
+ ARITH_PRECEDENCE(ARITH_LT, 3),
+ ARITH_PRECEDENCE(ARITH_LE, 3),
+ ARITH_PRECEDENCE(ARITH_GT, 3),
+ ARITH_PRECEDENCE(ARITH_GE, 3),
+ ARITH_PRECEDENCE(ARITH_EQ, 4),
+ ARITH_PRECEDENCE(ARITH_NE, 4),
+ ARITH_PRECEDENCE(ARITH_BAND, 5),
+ ARITH_PRECEDENCE(ARITH_BXOR, 6),
+ ARITH_PRECEDENCE(ARITH_BOR, 7),
+};
+
+#define ARITH_MAX_PREC 8
+
+int letcmd(int, char **);
+
+static __dead2 void yyerror(const char *s)
+{
+ error("arithmetic expression: %s: \"%s\"", s, arith_startbuf);
+ /* NOTREACHED */
+}
+
+static arith_t arith_lookupvarint(char *varname)
+{
+ const char *str;
+ char *p;
+ arith_t result;
+
+ str = lookupvar(varname);
+ if (uflag && str == NULL)
+ yyerror("variable not set");
+ if (str == NULL || *str == '\0')
+ str = "0";
+ errno = 0;
+ result = strtoarith_t(str, &p);
+ if (errno != 0 || *p != '\0')
+ yyerror("variable conversion error");
+ return result;
+}
+
+static inline int arith_prec(int op)
+{
+ return prec[op - ARITH_BINOP_MIN];
+}
+
+static inline int higher_prec(int op1, int op2)
+{
+ return arith_prec(op1) < arith_prec(op2);
+}
+
+static arith_t do_binop(int op, arith_t a, arith_t b)
+{
+
+ switch (op) {
+ default:
+ case ARITH_REM:
+ case ARITH_DIV:
+ if (!b)
+ yyerror("division by zero");
+ if (a == ARITH_MIN && b == -1)
+ yyerror("divide error");
+ return op == ARITH_REM ? a % b : a / b;
+ case ARITH_MUL:
+ return (uintmax_t)a * (uintmax_t)b;
+ case ARITH_ADD:
+ return (uintmax_t)a + (uintmax_t)b;
+ case ARITH_SUB:
+ return (uintmax_t)a - (uintmax_t)b;
+ case ARITH_LSHIFT:
+ return (uintmax_t)a << (b & (sizeof(uintmax_t) * CHAR_BIT - 1));
+ case ARITH_RSHIFT:
+ return a >> (b & (sizeof(uintmax_t) * CHAR_BIT - 1));
+ case ARITH_LT:
+ return a < b;
+ case ARITH_LE:
+ return a <= b;
+ case ARITH_GT:
+ return a > b;
+ case ARITH_GE:
+ return a >= b;
+ case ARITH_EQ:
+ return a == b;
+ case ARITH_NE:
+ return a != b;
+ case ARITH_BAND:
+ return a & b;
+ case ARITH_BXOR:
+ return a ^ b;
+ case ARITH_BOR:
+ return a | b;
+ }
+}
+
+static arith_t assignment(int var, int noeval);
+
+static arith_t primary(int token, union yystype *val, int op, int noeval)
+{
+ arith_t result;
+
+again:
+ switch (token) {
+ case ARITH_LPAREN:
+ result = assignment(op, noeval);
+ if (last_token != ARITH_RPAREN)
+ yyerror("expecting ')'");
+ last_token = yylex();
+ return result;
+ case ARITH_NUM:
+ last_token = op;
+ return val->val;
+ case ARITH_VAR:
+ last_token = op;
+ return noeval ? val->val : arith_lookupvarint(val->name);
+ case ARITH_ADD:
+ token = op;
+ *val = yylval;
+ op = yylex();
+ goto again;
+ case ARITH_SUB:
+ *val = yylval;
+ return -primary(op, val, yylex(), noeval);
+ case ARITH_NOT:
+ *val = yylval;
+ return !primary(op, val, yylex(), noeval);
+ case ARITH_BNOT:
+ *val = yylval;
+ return ~primary(op, val, yylex(), noeval);
+ default:
+ yyerror("expecting primary");
+ }
+}
+
+static arith_t binop2(arith_t a, int op, int precedence, int noeval)
+{
+ for (;;) {
+ union yystype val;
+ arith_t b;
+ int op2;
+ int token;
+
+ token = yylex();
+ val = yylval;
+
+ b = primary(token, &val, yylex(), noeval);
+
+ op2 = last_token;
+ if (op2 >= ARITH_BINOP_MIN && op2 < ARITH_BINOP_MAX &&
+ higher_prec(op2, op)) {
+ b = binop2(b, op2, arith_prec(op), noeval);
+ op2 = last_token;
+ }
+
+ a = noeval ? b : do_binop(op, a, b);
+
+ if (op2 < ARITH_BINOP_MIN || op2 >= ARITH_BINOP_MAX ||
+ arith_prec(op2) >= precedence)
+ return a;
+
+ op = op2;
+ }
+}
+
+static arith_t binop(int token, union yystype *val, int op, int noeval)
+{
+ arith_t a = primary(token, val, op, noeval);
+
+ op = last_token;
+ if (op < ARITH_BINOP_MIN || op >= ARITH_BINOP_MAX)
+ return a;
+
+ return binop2(a, op, ARITH_MAX_PREC, noeval);
+}
+
+static arith_t and(int token, union yystype *val, int op, int noeval)
+{
+ arith_t a = binop(token, val, op, noeval);
+ arith_t b;
+
+ op = last_token;
+ if (op != ARITH_AND)
+ return a;
+
+ token = yylex();
+ *val = yylval;
+
+ b = and(token, val, yylex(), noeval | !a);
+
+ return a && b;
+}
+
+static arith_t or(int token, union yystype *val, int op, int noeval)
+{
+ arith_t a = and(token, val, op, noeval);
+ arith_t b;
+
+ op = last_token;
+ if (op != ARITH_OR)
+ return a;
+
+ token = yylex();
+ *val = yylval;
+
+ b = or(token, val, yylex(), noeval | !!a);
+
+ return a || b;
+}
+
+static arith_t cond(int token, union yystype *val, int op, int noeval)
+{
+ arith_t a = or(token, val, op, noeval);
+ arith_t b;
+ arith_t c;
+
+ if (last_token != ARITH_QMARK)
+ return a;
+
+ b = assignment(yylex(), noeval | !a);
+
+ if (last_token != ARITH_COLON)
+ yyerror("expecting ':'");
+
+ token = yylex();
+ *val = yylval;
+
+ c = cond(token, val, yylex(), noeval | !!a);
+
+ return a ? b : c;
+}
+
+static arith_t assignment(int var, int noeval)
+{
+ union yystype val = yylval;
+ int op = yylex();
+ arith_t result;
+ char sresult[DIGITS(result) + 1];
+
+ if (var != ARITH_VAR)
+ return cond(var, &val, op, noeval);
+
+ if (op != ARITH_ASS && (op < ARITH_ASS_MIN || op >= ARITH_ASS_MAX))
+ return cond(var, &val, op, noeval);
+
+ result = assignment(yylex(), noeval);
+ if (noeval)
+ return result;
+
+ if (op != ARITH_ASS)
+ result = do_binop(op - 11, arith_lookupvarint(val.name), result);
+ snprintf(sresult, sizeof(sresult), ARITH_FORMAT_STR, result);
+ setvar(val.name, sresult, 0);
+ return result;
+}
+
+arith_t arith(const char *s)
+{
+ struct stackmark smark;
+ arith_t result;
+
+ setstackmark(&smark);
+
+ arith_buf = arith_startbuf = s;
+
+ result = assignment(yylex(), 0);
+
+ if (last_token)
+ yyerror("expecting EOF");
+
+ popstackmark(&smark);
+
+ return result;
+}
+
+/*
+ * The exp(1) builtin.
+ */
+int
+letcmd(int argc, char **argv)
+{
+ const char *p;
+ char *concat;
+ char **ap;
+ arith_t i;
+
+ if (argc > 1) {
+ p = argv[1];
+ if (argc > 2) {
+ /*
+ * Concatenate arguments.
+ */
+ STARTSTACKSTR(concat);
+ ap = argv + 2;
+ for (;;) {
+ while (*p)
+ STPUTC(*p++, concat);
+ if ((p = *ap++) == NULL)
+ break;
+ STPUTC(' ', concat);
+ }
+ STPUTC('\0', concat);
+ p = grabstackstr(concat);
+ }
+ } else
+ p = "";
+
+ i = arith(p);
+
+ out1fmt(ARITH_FORMAT_STR "\n", i);
+ return !i;
+}
diff --git a/cmd/posix/sh/arith_yacc.h b/cmd/posix/sh/arith_yacc.h
@@ -0,0 +1,94 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ * Copyright (c) 2007
+ * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#define ARITH_ASS 1
+
+#define ARITH_OR 2
+#define ARITH_AND 3
+#define ARITH_BAD 4
+#define ARITH_NUM 5
+#define ARITH_VAR 6
+#define ARITH_NOT 7
+
+#define ARITH_BINOP_MIN 8
+#define ARITH_LE 8
+#define ARITH_GE 9
+#define ARITH_LT 10
+#define ARITH_GT 11
+#define ARITH_EQ 12
+#define ARITH_REM 13
+#define ARITH_BAND 14
+#define ARITH_LSHIFT 15
+#define ARITH_RSHIFT 16
+#define ARITH_MUL 17
+#define ARITH_ADD 18
+#define ARITH_BOR 19
+#define ARITH_SUB 20
+#define ARITH_BXOR 21
+#define ARITH_DIV 22
+#define ARITH_NE 23
+#define ARITH_BINOP_MAX 24
+
+#define ARITH_ASS_MIN 24
+#define ARITH_REMASS 24
+#define ARITH_BANDASS 25
+#define ARITH_LSHIFTASS 26
+#define ARITH_RSHIFTASS 27
+#define ARITH_MULASS 28
+#define ARITH_ADDASS 29
+#define ARITH_BORASS 30
+#define ARITH_SUBASS 31
+#define ARITH_BXORASS 32
+#define ARITH_DIVASS 33
+#define ARITH_ASS_MAX 34
+
+#define ARITH_LPAREN 34
+#define ARITH_RPAREN 35
+#define ARITH_BNOT 36
+#define ARITH_QMARK 37
+#define ARITH_COLON 38
+
+extern const char *arith_buf;
+
+union yystype {
+ arith_t val;
+ char *name;
+};
+
+extern union yystype yylval;
+
+arith_t strtoarith_t(const char *restrict nptr, char **restrict endptr);
+int yylex(void);
diff --git a/cmd/posix/sh/arith_yylex.c b/cmd/posix/sh/arith_yylex.c
@@ -0,0 +1,282 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 2002
+ * Herbert Xu.
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if defined(__has_include)
+#if __has_include(<sys/cdefs.h>)
+#include <sys/cdefs.h>
+#endif
+#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
+#include <sys/cdefs.h>
+#endif
+#include <ctype.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include "shell.h"
+#include "arith_yacc.h"
+#include "expand.h"
+#include "error.h"
+#include "memalloc.h"
+#include "parser.h"
+#include "syntax.h"
+
+#if ARITH_BOR + 11 != ARITH_BORASS || ARITH_ASS + 11 != ARITH_EQ
+#error Arithmetic tokens are out of order.
+#endif
+
+arith_t
+strtoarith_t(const char *restrict nptr, char **restrict endptr)
+{
+ arith_t val;
+
+ while (isspace((unsigned char)*nptr))
+ nptr++;
+ switch (*nptr) {
+ case '-':
+ return strtoimax(nptr, endptr, 0);
+ case '0':
+ return (arith_t)strtoumax(nptr, endptr, 0);
+ default:
+ val = (arith_t)strtoumax(nptr, endptr, 0);
+ if (val >= 0)
+ return val;
+ else if (val == ARITH_MIN) {
+ errno = ERANGE;
+ return ARITH_MIN;
+ } else {
+ errno = ERANGE;
+ return ARITH_MAX;
+ }
+ }
+}
+
+int
+yylex(void)
+{
+ int value;
+ const char *buf = arith_buf;
+ char *end;
+ const char *p;
+
+ for (;;) {
+ value = *buf;
+ switch (value) {
+ case ' ':
+ case '\t':
+ case '\n':
+ buf++;
+ continue;
+ default:
+ return ARITH_BAD;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ yylval.val = strtoarith_t(buf, &end);
+ arith_buf = end;
+ return ARITH_NUM;
+ case 'A':
+ case 'B':
+ case 'C':
+ case 'D':
+ case 'E':
+ case 'F':
+ case 'G':
+ case 'H':
+ case 'I':
+ case 'J':
+ case 'K':
+ case 'L':
+ case 'M':
+ case 'N':
+ case 'O':
+ case 'P':
+ case 'Q':
+ case 'R':
+ case 'S':
+ case 'T':
+ case 'U':
+ case 'V':
+ case 'W':
+ case 'X':
+ case 'Y':
+ case 'Z':
+ case '_':
+ case 'a':
+ case 'b':
+ case 'c':
+ case 'd':
+ case 'e':
+ case 'f':
+ case 'g':
+ case 'h':
+ case 'i':
+ case 'j':
+ case 'k':
+ case 'l':
+ case 'm':
+ case 'n':
+ case 'o':
+ case 'p':
+ case 'q':
+ case 'r':
+ case 's':
+ case 't':
+ case 'u':
+ case 'v':
+ case 'w':
+ case 'x':
+ case 'y':
+ case 'z':
+ p = buf;
+ while (buf++, is_in_name(*buf))
+ ;
+ yylval.name = stalloc(buf - p + 1);
+ memcpy(yylval.name, p, buf - p);
+ yylval.name[buf - p] = '\0';
+ value = ARITH_VAR;
+ goto out;
+ case '=':
+ value += ARITH_ASS - '=';
+checkeq:
+ buf++;
+checkeqcur:
+ if (*buf != '=')
+ goto out;
+ value += 11;
+ break;
+ case '>':
+ switch (*++buf) {
+ case '=':
+ value += ARITH_GE - '>';
+ break;
+ case '>':
+ value += ARITH_RSHIFT - '>';
+ goto checkeq;
+ default:
+ value += ARITH_GT - '>';
+ goto out;
+ }
+ break;
+ case '<':
+ switch (*++buf) {
+ case '=':
+ value += ARITH_LE - '<';
+ break;
+ case '<':
+ value += ARITH_LSHIFT - '<';
+ goto checkeq;
+ default:
+ value += ARITH_LT - '<';
+ goto out;
+ }
+ break;
+ case '|':
+ if (*++buf != '|') {
+ value += ARITH_BOR - '|';
+ goto checkeqcur;
+ }
+ value += ARITH_OR - '|';
+ break;
+ case '&':
+ if (*++buf != '&') {
+ value += ARITH_BAND - '&';
+ goto checkeqcur;
+ }
+ value += ARITH_AND - '&';
+ break;
+ case '!':
+ if (*++buf != '=') {
+ value += ARITH_NOT - '!';
+ goto out;
+ }
+ value += ARITH_NE - '!';
+ break;
+ case 0:
+ goto out;
+ case '(':
+ value += ARITH_LPAREN - '(';
+ break;
+ case ')':
+ value += ARITH_RPAREN - ')';
+ break;
+ case '*':
+ value += ARITH_MUL - '*';
+ goto checkeq;
+ case '/':
+ value += ARITH_DIV - '/';
+ goto checkeq;
+ case '%':
+ value += ARITH_REM - '%';
+ goto checkeq;
+ case '+':
+ if (buf[1] == '+')
+ return ARITH_BAD;
+ value += ARITH_ADD - '+';
+ goto checkeq;
+ case '-':
+ if (buf[1] == '-')
+ return ARITH_BAD;
+ value += ARITH_SUB - '-';
+ goto checkeq;
+ case '~':
+ value += ARITH_BNOT - '~';
+ break;
+ case '^':
+ value += ARITH_BXOR - '^';
+ goto checkeq;
+ case '?':
+ value += ARITH_QMARK - '?';
+ break;
+ case ':':
+ value += ARITH_COLON - ':';
+ break;
+ }
+ break;
+ }
+
+ buf++;
+out:
+ arith_buf = buf;
+ return value;
+}
diff --git a/cmd/posix/sh/bltin.h b/cmd/posix/sh/bltin.h
@@ -0,0 +1,78 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This file is included by programs which are optionally built into the
+ * shell. If SHELL is defined, we try to map the standard UNIX library
+ * routines to ash routines using defines.
+ */
+
+#include "shell.h"
+#include "mystring.h"
+#ifdef SHELL
+#include "error.h"
+#include "output.h"
+#include "builtins.h"
+#define FILE struct output
+#undef stdout
+#define stdout out1
+#undef stderr
+#define stderr out2
+#define printf out1fmt
+#undef putc
+#define putc(c, file) outc(c, file)
+#undef putchar
+#define putchar(c) out1c(c)
+#define fprintf outfmt
+#define fputs outstr
+#define fwrite(ptr, size, nmemb, file) outbin(ptr, (size) * (nmemb), file)
+#define fflush flushout
+#define INITARGS(argv)
+#define warnx warning
+#define warn(fmt, ...) warning(fmt ": %s", __VA_ARGS__, strerror(errno))
+#define errx(exitstatus, ...) error(__VA_ARGS__)
+
+#else
+#undef NULL
+#include <stdio.h>
+#undef main
+#define INITARGS(argv) if ((commandname = argv[0]) == NULL) {fputs("Argc is zero\n", stderr); exit(2);} else
+#endif
+
+#include <unistd.h>
+
+pointer stalloc(int);
+int killjob(const char *, int);
+
+extern char *commandname;
diff --git a/cmd/posix/sh/builtins.def b/cmd/posix/sh/builtins.def
@@ -0,0 +1,91 @@
+#!/bin/sh -
+
+#-
+# Copyright (c) 1991, 1993
+# The Regents of the University of California. All rights reserved.
+#
+# This code is derived from software contributed to Berkeley by
+# Kenneth Almquist.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the University nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+#
+# This file lists all the builtin commands. The first column is the name
+# of a C routine.
+# The -j flag specifies that this command is to be excluded from systems
+# without job control.
+# The -n flag specifies that this command can safely be run in the same
+# process when it is the only command in a command substitution. Some
+# commands have special logic defined in safe_builtin().
+# The -s flag specifies that this is a POSIX 'special built-in' command.
+# The rest of the line specifies the command name or names used to run the
+# command. The entry for bltincmd, which is run when the user does not specify
+# a command, must come first.
+#
+# NOTE: bltincmd must come first!
+
+bltincmd -n builtin
+aliascmd alias
+bgcmd -j bg
+bindcmd bind #FEATURE_SH_HISTEDIT
+breakcmd -s break -s continue
+cdcmd cd chdir
+commandcmd -n command
+dotcmd -s .
+echocmd -n echo
+evalcmd -s eval
+execcmd -s exec
+exitcmd -s exit
+letcmd let #FEATURE_SH_LET
+exportcmd -s export -s readonly
+#exprcmd expr
+falsecmd -n false
+fgcmd -j fg
+freebsd_wordexpcmd freebsd_wordexp #FEATURE_SH_WORDEXP
+getoptscmd getopts
+hashcmd hash
+histcmd fc #FEATURE_SH_HISTEDIT
+jobidcmd -n jobid
+jobscmd -n jobs
+killcmd -n kill
+localcmd local #FEATURE_SH_LOCAL
+printfcmd -n printf
+pwdcmd -n pwd
+readcmd read
+returncmd -s return
+setcmd -s set
+setvarcmd setvar #FEATURE_SH_SETVAR
+shiftcmd -s shift
+testcmd -n test [
+timescmd -n -s times
+trapcmd -s trap
+truecmd -n -s : true
+typecmd -n type
+ulimitcmd ulimit #FEATURE_SH_ULIMIT
+umaskcmd umask
+unaliascmd unalias
+unsetcmd -s unset
+waitcmd wait
+wordexpcmd wordexp #FEATURE_SH_WORDEXP
diff --git a/cmd/posix/sh/cd.c b/cmd/posix/sh/cd.c
@@ -0,0 +1,423 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <limits.h>
+
+/*
+ * The cd and pwd commands.
+ */
+
+#include "shell.h"
+#include "var.h"
+#include "nodes.h" /* for jobs.h */
+#include "jobs.h"
+#include "options.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "exec.h"
+#include "redir.h"
+#include "mystring.h"
+#include "show.h"
+#include "cd.h"
+#include "builtins.h"
+
+static int cdlogical(char *);
+static int cdphysical(char *);
+static int docd(char *, int, int);
+static char *getcomponent(char **);
+static char *findcwd(char *);
+static void updatepwd(char *);
+static char *getpwd(void);
+static char *getpwd2(void);
+
+static char *curdir = NULL; /* current working directory */
+
+int
+cdcmd(int argc __unused, char **argv __unused)
+{
+ const char *dest;
+ const char *path;
+ char *p;
+ struct stat statb;
+ int ch, phys, print = 0, getcwderr = 0;
+ int rc;
+ int errno1 = ENOENT;
+
+ phys = Pflag;
+ while ((ch = nextopt("eLP")) != '\0') {
+ switch (ch) {
+ case 'e':
+ getcwderr = 1;
+ break;
+ case 'L':
+ phys = 0;
+ break;
+ case 'P':
+ phys = 1;
+ break;
+ }
+ }
+
+ if (*argptr != NULL && argptr[1] != NULL)
+ error("too many arguments");
+
+ if ((dest = *argptr) == NULL && (dest = bltinlookup("HOME", 1)) == NULL)
+ error("HOME not set");
+ if (dest[0] == '-' && dest[1] == '\0') {
+ dest = bltinlookup("OLDPWD", 1);
+ if (dest == NULL)
+ error("OLDPWD not set");
+ print = 1;
+ }
+ if (dest[0] == '/' ||
+ (dest[0] == '.' && (dest[1] == '/' || dest[1] == '\0')) ||
+ (dest[0] == '.' && dest[1] == '.' && (dest[2] == '/' || dest[2] == '\0')) ||
+ (path = bltinlookup("CDPATH", 1)) == NULL)
+ path = "";
+ while ((p = padvance(&path, NULL, dest)) != NULL) {
+ if (stat(p, &statb) < 0) {
+ if (errno != ENOENT)
+ errno1 = errno;
+ } else if (!S_ISDIR(statb.st_mode))
+ errno1 = ENOTDIR;
+ else {
+ if (!print) {
+ /*
+ * XXX - rethink
+ */
+ if (p[0] == '.' && p[1] == '/' && p[2] != '\0')
+ print = strcmp(p + 2, dest);
+ else
+ print = strcmp(p, dest);
+ }
+ rc = docd(p, print, phys);
+ if (rc >= 0)
+ return getcwderr ? rc : 0;
+ if (errno != ENOENT)
+ errno1 = errno;
+ }
+ }
+ error("%s: %s", dest, strerror(errno1));
+ /*NOTREACHED*/
+ return 0;
+}
+
+
+/*
+ * Actually change the directory. In an interactive shell, print the
+ * directory name if "print" is nonzero.
+ */
+static int
+docd(char *dest, int print, int phys)
+{
+ int rc;
+
+ TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
+
+ /* If logical cd fails, fall back to physical. */
+ if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0)
+ return (-1);
+
+ if (print && iflag && curdir) {
+ out1fmt("%s\n", curdir);
+ /*
+ * Ignore write errors to preserve the invariant that the
+ * current directory is changed iff the exit status is 0
+ * (or 1 if -e was given and the full pathname could not be
+ * determined).
+ */
+ flushout(out1);
+ outclearerror(out1);
+ }
+
+ return (rc);
+}
+
+static int
+cdlogical(char *dest)
+{
+ char *p;
+ char *q;
+ char *component;
+ char *path;
+ struct stat statb;
+ int first;
+ int badstat;
+
+ /*
+ * Check each component of the path. If we find a symlink or
+ * something we can't stat, clear curdir to force a getcwd()
+ * next time we get the value of the current directory.
+ */
+ badstat = 0;
+ path = stsavestr(dest);
+ STARTSTACKSTR(p);
+ if (*dest == '/') {
+ STPUTC('/', p);
+ path++;
+ }
+ first = 1;
+ while ((q = getcomponent(&path)) != NULL) {
+ if (q[0] == '\0' || (q[0] == '.' && q[1] == '\0'))
+ continue;
+ if (! first)
+ STPUTC('/', p);
+ first = 0;
+ component = q;
+ STPUTS(q, p);
+ if (equal(component, ".."))
+ continue;
+ STACKSTRNUL(p);
+ if (lstat(stackblock(), &statb) < 0) {
+ badstat = 1;
+ break;
+ }
+ }
+
+ INTOFF;
+ if ((p = findcwd(badstat ? NULL : dest)) == NULL || chdir(p) < 0) {
+ INTON;
+ return (-1);
+ }
+ updatepwd(p);
+ INTON;
+ return (0);
+}
+
+static int
+cdphysical(char *dest)
+{
+ char *p;
+ int rc = 0;
+
+ INTOFF;
+ if (chdir(dest) < 0) {
+ INTON;
+ return (-1);
+ }
+ p = findcwd(NULL);
+ if (p == NULL) {
+ warning("warning: failed to get name of current directory");
+ rc = 1;
+ }
+ updatepwd(p);
+ INTON;
+ return (rc);
+}
+
+/*
+ * Get the next component of the path name pointed to by *path.
+ * This routine overwrites *path and the string pointed to by it.
+ */
+static char *
+getcomponent(char **path)
+{
+ char *p;
+ char *start;
+
+ if ((p = *path) == NULL)
+ return NULL;
+ start = *path;
+ while (*p != '/' && *p != '\0')
+ p++;
+ if (*p == '\0') {
+ *path = NULL;
+ } else {
+ *p++ = '\0';
+ *path = p;
+ }
+ return start;
+}
+
+
+static char *
+findcwd(char *dir)
+{
+ char *new;
+ char *p;
+ char *path;
+
+ /*
+ * If our argument is NULL, we don't know the current directory
+ * any more because we traversed a symbolic link or something
+ * we couldn't stat().
+ */
+ if (dir == NULL || curdir == NULL)
+ return getpwd2();
+ path = stsavestr(dir);
+ STARTSTACKSTR(new);
+ if (*dir != '/') {
+ STPUTS(curdir, new);
+ if (STTOPC(new) == '/')
+ STUNPUTC(new);
+ }
+ while ((p = getcomponent(&path)) != NULL) {
+ if (equal(p, "..")) {
+ while (new > stackblock() && (STUNPUTC(new), *new) != '/');
+ } else if (*p != '\0' && ! equal(p, ".")) {
+ STPUTC('/', new);
+ STPUTS(p, new);
+ }
+ }
+ if (new == stackblock())
+ STPUTC('/', new);
+ STACKSTRNUL(new);
+ return stackblock();
+}
+
+/*
+ * Update curdir (the name of the current directory) in response to a
+ * cd command. We also call hashcd to let the routines in exec.c know
+ * that the current directory has changed.
+ */
+static void
+updatepwd(char *dir)
+{
+ char *prevdir;
+
+ hashcd(); /* update command hash table */
+
+ setvar("PWD", dir, VEXPORT);
+ setvar("OLDPWD", curdir, VEXPORT);
+ prevdir = curdir;
+ curdir = dir ? savestr(dir) : NULL;
+ ckfree(prevdir);
+}
+
+int
+pwdcmd(int argc __unused, char **argv __unused)
+{
+ char *p;
+ int ch, phys;
+
+ phys = Pflag;
+ while ((ch = nextopt("LP")) != '\0') {
+ switch (ch) {
+ case 'L':
+ phys = 0;
+ break;
+ case 'P':
+ phys = 1;
+ break;
+ }
+ }
+
+ if (*argptr != NULL)
+ error("too many arguments");
+
+ if (!phys && getpwd()) {
+ out1fmt("%s\n", curdir);
+ } else {
+ if ((p = getpwd2()) == NULL)
+ error(".: %s", strerror(errno));
+ out1fmt("%s\n", p);
+ }
+
+ return 0;
+}
+
+/*
+ * Get the current directory and cache the result in curdir.
+ */
+static char *
+getpwd(void)
+{
+ char *p;
+
+ if (curdir)
+ return curdir;
+
+ p = getpwd2();
+ if (p != NULL) {
+ INTOFF;
+ curdir = savestr(p);
+ INTON;
+ }
+
+ return curdir;
+}
+
+#define MAXPWD 256
+
+/*
+ * Return the current directory.
+ */
+static char *
+getpwd2(void)
+{
+ char *pwd;
+ int i;
+
+ for (i = MAXPWD;; i *= 2) {
+ pwd = stalloc(i);
+ if (getcwd(pwd, i) != NULL)
+ return pwd;
+ stunalloc(pwd);
+ if (errno != ERANGE)
+ break;
+ }
+
+ return NULL;
+}
+
+/*
+ * Initialize PWD in a new shell.
+ * If the shell is interactive, we need to warn if this fails.
+ */
+void
+pwd_init(int warn)
+{
+ char *pwd;
+ struct stat stdot, stpwd;
+
+ pwd = lookupvar("PWD");
+ if (pwd && *pwd == '/' && stat(".", &stdot) != -1 &&
+ stat(pwd, &stpwd) != -1 &&
+ stdot.st_dev == stpwd.st_dev &&
+ stdot.st_ino == stpwd.st_ino) {
+ if (curdir)
+ ckfree(curdir);
+ curdir = savestr(pwd);
+ }
+ if (getpwd() == NULL && warn)
+ out2fmt_flush("sh: cannot determine working directory\n");
+ setvar("PWD", curdir, VEXPORT);
+}
diff --git a/cmd/posix/sh/cd.h b/cmd/posix/sh/cd.h
@@ -0,0 +1,32 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1995
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+void pwd_init(int);
diff --git a/cmd/posix/sh/echo.c b/cmd/posix/sh/echo.c
@@ -0,0 +1,104 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "bltin.h"
+
+/*
+ * Echo command.
+ */
+
+#define main echocmd
+
+/* #define eflag 1 */
+
+int
+main(int argc, char *argv[])
+{
+ char **ap;
+ char *p;
+ char c;
+ int count;
+ int nflag = 0;
+#ifndef eflag
+ int eflag = 0;
+#endif
+
+ ap = argv;
+ if (argc)
+ ap++;
+ if ((p = *ap) != NULL) {
+ if (equal(p, "-n")) {
+ nflag++;
+ ap++;
+ } else if (equal(p, "-e")) {
+#ifndef eflag
+ eflag++;
+#endif
+ ap++;
+ }
+ }
+ while ((p = *ap++) != NULL) {
+ while ((c = *p++) != '\0') {
+ if (c == '\\' && eflag) {
+ switch (*p++) {
+ case 'a': c = '\a'; break;
+ case 'b': c = '\b'; break;
+ case 'c': return 0; /* exit */
+ case 'e': c = '\033'; break;
+ case 'f': c = '\f'; break;
+ case 'n': c = '\n'; break;
+ case 'r': c = '\r'; break;
+ case 't': c = '\t'; break;
+ case 'v': c = '\v'; break;
+ case '\\': break; /* c = '\\' */
+ case '0':
+ c = 0;
+ count = 3;
+ while (--count >= 0 && (unsigned)(*p - '0') < 8)
+ c = (c << 3) + (*p++ - '0');
+ break;
+ default:
+ p--;
+ break;
+ }
+ }
+ putchar(c);
+ }
+ if (*ap)
+ putchar(' ');
+ }
+ if (! nflag)
+ putchar('\n');
+ return 0;
+}
diff --git a/cmd/posix/sh/error.c b/cmd/posix/sh/error.c
@@ -0,0 +1,196 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Errors and exceptions.
+ */
+
+#include "shell.h"
+#include "eval.h"
+#include "main.h"
+#include "options.h"
+#include "output.h"
+#include "error.h"
+#include "nodes.h" /* show.h needs nodes.h */
+#include "show.h"
+#include "trap.h"
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <errno.h>
+
+
+/*
+ * Code to handle exceptions in C.
+ */
+
+struct jmploc *handler;
+volatile sig_atomic_t exception;
+volatile sig_atomic_t suppressint;
+volatile sig_atomic_t intpending;
+
+
+static void verrorwithstatus(int, const char *, va_list) __printf0like(2, 0) __dead2;
+
+/*
+ * Called to raise an exception. Since C doesn't include exceptions, we
+ * just do a longjmp to the exception handler. The type of exception is
+ * stored in the global variable "exception".
+ *
+ * Interrupts are disabled; they should be re-enabled when the exception is
+ * caught.
+ */
+
+void
+exraise(int e)
+{
+ INTOFF;
+ if (handler == NULL)
+ abort();
+ exception = e;
+ longjmp(handler->loc, 1);
+}
+
+
+/*
+ * Called from trap.c when a SIGINT is received and not suppressed, or when
+ * an interrupt is pending and interrupts are re-enabled using INTON.
+ * (If the user specifies that SIGINT is to be trapped or ignored using the
+ * trap builtin, then this routine is not called.) Suppressint is nonzero
+ * when interrupts are held using the INTOFF macro. If SIGINTs are not
+ * suppressed and the shell is not a root shell, then we want to be
+ * terminated if we get here, as if we were terminated directly by a SIGINT.
+ * Arrange for this here.
+ */
+
+void
+onint(void)
+{
+ sigset_t sigs;
+
+ intpending = 0;
+ sigemptyset(&sigs);
+ sigprocmask(SIG_SETMASK, &sigs, NULL);
+
+ /*
+ * This doesn't seem to be needed, since main() emits a newline.
+ */
+#if 0
+ if (tcgetpgrp(0) == getpid())
+ write(STDERR_FILENO, "\n", 1);
+#endif
+ if (rootshell && iflag)
+ exraise(EXINT);
+ else {
+ signal(SIGINT, SIG_DFL);
+ kill(getpid(), SIGINT);
+ _exit(128 + SIGINT);
+ }
+}
+
+
+static void
+vwarning(const char *msg, va_list ap)
+{
+ if (commandname)
+ outfmt(out2, "%s: ", commandname);
+ else if (arg0)
+ outfmt(out2, "%s: ", arg0);
+ doformat(out2, msg, ap);
+ out2fmt_flush("\n");
+}
+
+
+void
+warning(const char *msg, ...)
+{
+ va_list ap;
+ va_start(ap, msg);
+ vwarning(msg, ap);
+ va_end(ap);
+}
+
+
+/*
+ * Exverror is called to raise the error exception. If the first argument
+ * is not NULL then error prints an error message using printf style
+ * formatting. It then raises the error exception.
+ */
+static void
+verrorwithstatus(int status, const char *msg, va_list ap)
+{
+ /*
+ * An interrupt trumps an error. Certain places catch error
+ * exceptions or transform them to a plain nonzero exit code
+ * in child processes, and if an error exception can be handled,
+ * an interrupt can be handled as well.
+ *
+ * exraise() will disable interrupts for the exception handler.
+ */
+ FORCEINTON;
+
+#ifdef DEBUG
+ if (msg)
+ TRACE(("verrorwithstatus(%d, \"%s\") pid=%d\n",
+ status, msg, getpid()));
+ else
+ TRACE(("verrorwithstatus(%d, NULL) pid=%d\n",
+ status, getpid()));
+#endif
+ if (msg)
+ vwarning(msg, ap);
+ flushall();
+ exitstatus = status;
+ exraise(EXERROR);
+}
+
+
+void
+error(const char *msg, ...)
+{
+ va_list ap;
+ va_start(ap, msg);
+ verrorwithstatus(2, msg, ap);
+ va_end(ap);
+}
+
+
+void
+errorwithstatus(int status, const char *msg, ...)
+{
+ va_list ap;
+ va_start(ap, msg);
+ verrorwithstatus(status, msg, ap);
+ va_end(ap);
+}
diff --git a/cmd/posix/sh/error.h b/cmd/posix/sh/error.h
@@ -0,0 +1,95 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * We enclose jmp_buf in a structure so that we can declare pointers to
+ * jump locations. The global variable handler contains the location to
+ * jump to when an exception occurs, and the global variable exception
+ * contains a code identifying the exception. To implement nested
+ * exception handlers, the user should save the value of handler on entry
+ * to an inner scope, set handler to point to a jmploc structure for the
+ * inner scope, and restore handler on exit from the scope.
+ */
+
+#include <setjmp.h>
+#include <signal.h>
+
+struct jmploc {
+ jmp_buf loc;
+};
+
+extern struct jmploc *handler;
+extern volatile sig_atomic_t exception;
+
+/* exceptions */
+#define EXINT 0 /* SIGINT received */
+#define EXERROR 1 /* a generic error with exitstatus */
+#define EXEXIT 2 /* call exitshell(exitstatus) */
+
+
+/*
+ * These macros allow the user to suspend the handling of interrupt signals
+ * over a period of time. This is similar to SIGHOLD to or sigblock, but
+ * much more efficient and portable. (But hacking the kernel is so much
+ * more fun than worrying about efficiency and portability. :-))
+ */
+
+extern volatile sig_atomic_t suppressint;
+extern volatile sig_atomic_t intpending;
+
+#define INTOFF suppressint++
+#define INTON { if (--suppressint == 0 && intpending) onint(); }
+#define is_int_on() suppressint
+#define SETINTON(s) do { suppressint = (s); if (suppressint == 0 && intpending) onint(); } while (0)
+#define FORCEINTON {suppressint = 0; if (intpending) onint();}
+#define SET_PENDING_INT intpending = 1
+#define CLEAR_PENDING_INT intpending = 0
+#define int_pending() intpending
+
+void exraise(int) __dead2;
+void onint(void) __dead2;
+void warning(const char *, ...) __printflike(1, 2);
+void error(const char *, ...) __printf0like(1, 2) __dead2;
+void errorwithstatus(int, const char *, ...) __printf0like(2, 3) __dead2;
+
+
+/*
+ * BSD setjmp saves the signal mask, which violates ANSI C and takes time,
+ * so we use _setjmp instead.
+ */
+
+#undef setjmp
+#define setjmp(jmploc) _setjmp(jmploc)
+#undef longjmp
+#define longjmp(jmploc, val) _longjmp(jmploc, val)
diff --git a/cmd/posix/sh/eval.c b/cmd/posix/sh/eval.c
@@ -0,0 +1,1423 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <paths.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/resource.h>
+#include <errno.h>
+
+/*
+ * Evaluate a command.
+ */
+
+#include "shell.h"
+#include "nodes.h"
+#include "syntax.h"
+#include "expand.h"
+#include "parser.h"
+#include "jobs.h"
+#include "eval.h"
+#include "builtins.h"
+#include "options.h"
+#include "exec.h"
+#include "redir.h"
+#include "input.h"
+#include "output.h"
+#include "trap.h"
+#include "var.h"
+#include "memalloc.h"
+#include "error.h"
+#include "show.h"
+#include "mystring.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+
+int evalskip; /* set if we are skipping commands */
+int skipcount; /* number of levels to skip */
+static int loopnest; /* current loop nesting level */
+int funcnest; /* depth of function calls */
+static int builtin_flags; /* evalcommand flags for builtins */
+
+
+char *commandname;
+struct arglist *cmdenviron;
+int exitstatus; /* exit status of last command */
+int oexitstatus; /* saved exit status */
+
+
+static void evalloop(union node *, int);
+static void evalfor(union node *, int);
+static union node *evalcase(union node *);
+static void evalsubshell(union node *, int);
+static void evalredir(union node *, int);
+static void exphere(union node *, struct arglist *);
+static void expredir(union node *);
+static void evalpipe(union node *);
+static int is_valid_fast_cmdsubst(union node *n);
+static void evalcommand(union node *, int, struct backcmd *);
+static void prehash(union node *);
+
+
+/*
+ * Called to reset things after an exception.
+ */
+
+void
+reseteval(void)
+{
+ evalskip = 0;
+ loopnest = 0;
+}
+
+
+/*
+ * The eval command.
+ */
+
+int
+evalcmd(int argc, char **argv)
+{
+ char *p;
+ char *concat;
+ char **ap;
+
+ if (argc > 1) {
+ p = argv[1];
+ if (argc > 2) {
+ STARTSTACKSTR(concat);
+ ap = argv + 2;
+ for (;;) {
+ STPUTS(p, concat);
+ if ((p = *ap++) == NULL)
+ break;
+ STPUTC(' ', concat);
+ }
+ STPUTC('\0', concat);
+ p = grabstackstr(concat);
+ }
+ evalstring(p, builtin_flags);
+ } else
+ exitstatus = 0;
+ return exitstatus;
+}
+
+
+/*
+ * Execute a command or commands contained in a string.
+ */
+
+void
+evalstring(const char *s, int flags)
+{
+ union node *n;
+ struct stackmark smark;
+ int flags_exit;
+ int any;
+
+ flags_exit = flags & EV_EXIT;
+ flags &= ~EV_EXIT;
+ any = 0;
+ setstackmark(&smark);
+ setinputstring(s);
+ while ((n = parsecmd(0)) != NEOF) {
+ if (n != NULL && !nflag) {
+ if (flags_exit && preadateof())
+ evaltree(n, flags | EV_EXIT);
+ else
+ evaltree(n, flags);
+ any = 1;
+ if (evalskip)
+ break;
+ }
+ popstackmark(&smark);
+ setstackmark(&smark);
+ }
+ popfile();
+ popstackmark(&smark);
+ if (!any)
+ exitstatus = 0;
+ if (flags_exit)
+ exraise(EXEXIT);
+}
+
+
+/*
+ * Evaluate a parse tree. The value is left in the global variable
+ * exitstatus.
+ */
+
+void
+evaltree(union node *n, int flags)
+{
+ int do_etest;
+ union node *next;
+ struct stackmark smark;
+
+ setstackmark(&smark);
+ do_etest = 0;
+ if (n == NULL) {
+ TRACE(("evaltree(NULL) called\n"));
+ exitstatus = 0;
+ goto out;
+ }
+ do {
+ next = NULL;
+#ifndef NO_HISTORY
+ displayhist = 1; /* show history substitutions done with fc */
+#endif
+ TRACE(("evaltree(%p: %d) called\n", (void *)n, n->type));
+ switch (n->type) {
+ case NSEMI:
+ evaltree(n->nbinary.ch1, flags & ~EV_EXIT);
+ if (evalskip)
+ goto out;
+ next = n->nbinary.ch2;
+ break;
+ case NAND:
+ evaltree(n->nbinary.ch1, EV_TESTED);
+ if (evalskip || exitstatus != 0) {
+ goto out;
+ }
+ next = n->nbinary.ch2;
+ break;
+ case NOR:
+ evaltree(n->nbinary.ch1, EV_TESTED);
+ if (evalskip || exitstatus == 0)
+ goto out;
+ next = n->nbinary.ch2;
+ break;
+ case NREDIR:
+ evalredir(n, flags);
+ break;
+ case NSUBSHELL:
+ evalsubshell(n, flags);
+ do_etest = !(flags & EV_TESTED);
+ break;
+ case NBACKGND:
+ evalsubshell(n, flags);
+ break;
+ case NIF: {
+ evaltree(n->nif.test, EV_TESTED);
+ if (evalskip)
+ goto out;
+ if (exitstatus == 0)
+ next = n->nif.ifpart;
+ else if (n->nif.elsepart)
+ next = n->nif.elsepart;
+ else
+ exitstatus = 0;
+ break;
+ }
+ case NWHILE:
+ case NUNTIL:
+ evalloop(n, flags & ~EV_EXIT);
+ break;
+ case NFOR:
+ evalfor(n, flags & ~EV_EXIT);
+ break;
+ case NCASE:
+ next = evalcase(n);
+ break;
+ case NCLIST:
+ next = n->nclist.body;
+ break;
+ case NCLISTFALLTHRU:
+ if (n->nclist.body) {
+ evaltree(n->nclist.body, flags & ~EV_EXIT);
+ if (evalskip)
+ goto out;
+ }
+ next = n->nclist.next;
+ break;
+ case NDEFUN:
+ defun(n->narg.text, n->narg.next);
+ exitstatus = 0;
+ break;
+ case NNOT:
+ evaltree(n->nnot.com, EV_TESTED);
+ if (evalskip)
+ goto out;
+ exitstatus = !exitstatus;
+ break;
+
+ case NPIPE:
+ evalpipe(n);
+ do_etest = !(flags & EV_TESTED);
+ break;
+ case NCMD:
+ evalcommand(n, flags, (struct backcmd *)NULL);
+ do_etest = !(flags & EV_TESTED);
+ break;
+ default:
+ out1fmt("Node type = %d\n", n->type);
+ flushout(&output);
+ break;
+ }
+ n = next;
+ popstackmark(&smark);
+ setstackmark(&smark);
+ } while (n != NULL);
+out:
+ popstackmark(&smark);
+ if (pendingsig)
+ dotrap();
+ if (eflag && exitstatus != 0 && do_etest)
+ exitshell(exitstatus);
+ if (flags & EV_EXIT)
+ exraise(EXEXIT);
+}
+
+
+static void
+evalloop(union node *n, int flags)
+{
+ int status;
+
+ loopnest++;
+ status = 0;
+ for (;;) {
+ if (!evalskip)
+ evaltree(n->nbinary.ch1, EV_TESTED);
+ if (evalskip) {
+ if (evalskip == SKIPCONT && --skipcount <= 0) {
+ evalskip = 0;
+ continue;
+ }
+ if (evalskip == SKIPBREAK && --skipcount <= 0)
+ evalskip = 0;
+ if (evalskip == SKIPRETURN)
+ status = exitstatus;
+ break;
+ }
+ if (n->type == NWHILE) {
+ if (exitstatus != 0)
+ break;
+ } else {
+ if (exitstatus == 0)
+ break;
+ }
+ evaltree(n->nbinary.ch2, flags);
+ status = exitstatus;
+ }
+ loopnest--;
+ exitstatus = status;
+}
+
+
+
+static void
+evalfor(union node *n, int flags)
+{
+ struct arglist arglist;
+ union node *argp;
+ int i;
+ int status;
+
+ emptyarglist(&arglist);
+ for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
+ oexitstatus = exitstatus;
+ expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
+ }
+
+ loopnest++;
+ status = 0;
+ for (i = 0; i < arglist.count; i++) {
+ setvar(n->nfor.var, arglist.args[i], 0);
+ evaltree(n->nfor.body, flags);
+ status = exitstatus;
+ if (evalskip) {
+ if (evalskip == SKIPCONT && --skipcount <= 0) {
+ evalskip = 0;
+ continue;
+ }
+ if (evalskip == SKIPBREAK && --skipcount <= 0)
+ evalskip = 0;
+ break;
+ }
+ }
+ loopnest--;
+ exitstatus = status;
+}
+
+
+/*
+ * Evaluate a case statement, returning the selected tree.
+ *
+ * The exit status needs care to get right.
+ */
+
+static union node *
+evalcase(union node *n)
+{
+ union node *cp;
+ union node *patp;
+ struct arglist arglist;
+
+ emptyarglist(&arglist);
+ oexitstatus = exitstatus;
+ expandarg(n->ncase.expr, &arglist, EXP_TILDE);
+ for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
+ for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
+ if (casematch(patp, arglist.args[0])) {
+ while (cp->nclist.next &&
+ cp->type == NCLISTFALLTHRU &&
+ cp->nclist.body == NULL)
+ cp = cp->nclist.next;
+ if (cp->nclist.next &&
+ cp->type == NCLISTFALLTHRU)
+ return (cp);
+ if (cp->nclist.body == NULL)
+ exitstatus = 0;
+ return (cp->nclist.body);
+ }
+ }
+ }
+ exitstatus = 0;
+ return (NULL);
+}
+
+
+
+/*
+ * Kick off a subshell to evaluate a tree.
+ */
+
+static void
+evalsubshell(union node *n, int flags)
+{
+ struct job *jp;
+ int backgnd = (n->type == NBACKGND);
+
+ oexitstatus = exitstatus;
+ expredir(n->nredir.redirect);
+ if ((!backgnd && flags & EV_EXIT && !have_traps()) ||
+ forkshell(jp = makejob(n, 1), n, backgnd) == 0) {
+ if (backgnd)
+ flags &=~ EV_TESTED;
+ redirect(n->nredir.redirect, 0);
+ evaltree(n->nredir.n, flags | EV_EXIT); /* never returns */
+ } else if (! backgnd) {
+ INTOFF;
+ exitstatus = waitforjob(jp, (int *)NULL);
+ INTON;
+ } else
+ exitstatus = 0;
+}
+
+
+/*
+ * Evaluate a redirected compound command.
+ */
+
+static void
+evalredir(union node *n, int flags)
+{
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ volatile int in_redirect = 1;
+
+ oexitstatus = exitstatus;
+ expredir(n->nredir.redirect);
+ savehandler = handler;
+ if (setjmp(jmploc.loc)) {
+ int e;
+
+ handler = savehandler;
+ e = exception;
+ popredir();
+ if (e == EXERROR && in_redirect) {
+ FORCEINTON;
+ return;
+ }
+ longjmp(handler->loc, 1);
+ } else {
+ INTOFF;
+ handler = &jmploc;
+ redirect(n->nredir.redirect, REDIR_PUSH);
+ in_redirect = 0;
+ INTON;
+ evaltree(n->nredir.n, flags);
+ }
+ INTOFF;
+ handler = savehandler;
+ popredir();
+ INTON;
+}
+
+
+static void
+exphere(union node *redir, struct arglist *fn)
+{
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ struct localvar *savelocalvars;
+ int need_longjmp = 0;
+ unsigned char saveoptreset;
+
+ redir->nhere.expdoc = "";
+ savelocalvars = localvars;
+ localvars = NULL;
+ saveoptreset = shellparam.reset;
+ forcelocal++;
+ savehandler = handler;
+ if (setjmp(jmploc.loc))
+ need_longjmp = exception != EXERROR;
+ else {
+ handler = &jmploc;
+ expandarg(redir->nhere.doc, fn, 0);
+ redir->nhere.expdoc = fn->args[0];
+ INTOFF;
+ }
+ handler = savehandler;
+ forcelocal--;
+ poplocalvars();
+ localvars = savelocalvars;
+ shellparam.reset = saveoptreset;
+ if (need_longjmp)
+ longjmp(handler->loc, 1);
+ INTON;
+}
+
+
+/*
+ * Compute the names of the files in a redirection list.
+ */
+
+static void
+expredir(union node *n)
+{
+ union node *redir;
+
+ for (redir = n ; redir ; redir = redir->nfile.next) {
+ struct arglist fn;
+ emptyarglist(&fn);
+ switch (redir->type) {
+ case NFROM:
+ case NTO:
+ case NFROMTO:
+ case NAPPEND:
+ case NCLOBBER:
+ expandarg(redir->nfile.fname, &fn, EXP_TILDE);
+ redir->nfile.expfname = fn.args[0];
+ break;
+ case NFROMFD:
+ case NTOFD:
+ if (redir->ndup.vname) {
+ expandarg(redir->ndup.vname, &fn, EXP_TILDE);
+ fixredir(redir, fn.args[0], 1);
+ }
+ break;
+ case NXHERE:
+ exphere(redir, &fn);
+ break;
+ }
+ }
+}
+
+
+
+/*
+ * Evaluate a pipeline. All the processes in the pipeline are children
+ * of the process creating the pipeline. (This differs from some versions
+ * of the shell, which make the last process in a pipeline the parent
+ * of all the rest.)
+ */
+
+static void
+evalpipe(union node *n)
+{
+ struct job *jp;
+ struct nodelist *lp;
+ int pipelen;
+ int prevfd;
+ int pip[2];
+
+ TRACE(("evalpipe(%p) called\n", (void *)n));
+ pipelen = 0;
+ for (lp = n->npipe.cmdlist ; lp ; lp = lp->next)
+ pipelen++;
+ INTOFF;
+ jp = makejob(n, pipelen);
+ prevfd = -1;
+ for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
+ prehash(lp->n);
+ pip[1] = -1;
+ if (lp->next) {
+ if (pipe(pip) < 0) {
+ if (prevfd >= 0)
+ close(prevfd);
+ error("Pipe call failed: %s", strerror(errno));
+ }
+ }
+ if (forkshell(jp, lp->n, n->npipe.backgnd) == 0) {
+ INTON;
+ if (prevfd > 0) {
+ dup2(prevfd, 0);
+ close(prevfd);
+ }
+ if (pip[1] >= 0) {
+ if (!(prevfd >= 0 && pip[0] == 0))
+ close(pip[0]);
+ if (pip[1] != 1) {
+ dup2(pip[1], 1);
+ close(pip[1]);
+ }
+ }
+ evaltree(lp->n, EV_EXIT);
+ }
+ if (prevfd >= 0)
+ close(prevfd);
+ prevfd = pip[0];
+ if (pip[1] != -1)
+ close(pip[1]);
+ }
+ INTON;
+ if (n->npipe.backgnd == 0) {
+ INTOFF;
+ exitstatus = waitforjob(jp, (int *)NULL);
+ TRACE(("evalpipe: job done exit status %d\n", exitstatus));
+ INTON;
+ } else
+ exitstatus = 0;
+}
+
+
+
+static int
+is_valid_fast_cmdsubst(union node *n)
+{
+
+ return (n->type == NCMD);
+}
+
+/*
+ * Execute a command inside back quotes. If it's a builtin command, we
+ * want to save its output in a block obtained from malloc. Otherwise
+ * we fork off a subprocess and get the output of the command via a pipe.
+ * Should be called with interrupts off.
+ */
+
+void
+evalbackcmd(union node *n, struct backcmd *result)
+{
+ int pip[2];
+ struct job *jp;
+ struct stackmark smark;
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ struct localvar *savelocalvars;
+ unsigned char saveoptreset;
+
+ result->fd = -1;
+ result->buf = NULL;
+ result->nleft = 0;
+ result->jp = NULL;
+ if (n == NULL) {
+ exitstatus = 0;
+ return;
+ }
+ setstackmark(&smark);
+ exitstatus = oexitstatus;
+ if (is_valid_fast_cmdsubst(n)) {
+ savelocalvars = localvars;
+ localvars = NULL;
+ saveoptreset = shellparam.reset;
+ forcelocal++;
+ savehandler = handler;
+ if (setjmp(jmploc.loc)) {
+ if (exception == EXERROR)
+ /* nothing */;
+ else if (exception != 0) {
+ handler = savehandler;
+ forcelocal--;
+ poplocalvars();
+ localvars = savelocalvars;
+ shellparam.reset = saveoptreset;
+ longjmp(handler->loc, 1);
+ }
+ } else {
+ handler = &jmploc;
+ evalcommand(n, EV_BACKCMD, result);
+ }
+ handler = savehandler;
+ forcelocal--;
+ poplocalvars();
+ localvars = savelocalvars;
+ shellparam.reset = saveoptreset;
+ } else {
+ if (pipe(pip) < 0)
+ error("Pipe call failed: %s", strerror(errno));
+ jp = makejob(n, 1);
+ if (forkshell(jp, n, FORK_NOJOB) == 0) {
+ FORCEINTON;
+ close(pip[0]);
+ if (pip[1] != 1) {
+ dup2(pip[1], 1);
+ close(pip[1]);
+ }
+ evaltree(n, EV_EXIT);
+ }
+ close(pip[1]);
+ result->fd = pip[0];
+ result->jp = jp;
+ }
+ popstackmark(&smark);
+ TRACE(("evalbackcmd done: fd=%d buf=%p nleft=%d jp=%p\n",
+ result->fd, result->buf, result->nleft, result->jp));
+}
+
+static int
+mustexpandto(const char *argtext, const char *mask)
+{
+ for (;;) {
+ if (*argtext == CTLQUOTEMARK || *argtext == CTLQUOTEEND) {
+ argtext++;
+ continue;
+ }
+ if (*argtext == CTLESC)
+ argtext++;
+ else if (BASESYNTAX[(int)*argtext] == CCTL)
+ return (0);
+ if (*argtext != *mask)
+ return (0);
+ if (*argtext == '\0')
+ return (1);
+ argtext++;
+ mask++;
+ }
+}
+
+static int
+isdeclarationcmd(struct narg *arg)
+{
+ int have_command = 0;
+
+ if (arg == NULL)
+ return (0);
+ while (mustexpandto(arg->text, "command")) {
+ have_command = 1;
+ arg = &arg->next->narg;
+ if (arg == NULL)
+ return (0);
+ /*
+ * To also allow "command -p" and "command --" as part of
+ * a declaration command, add code here.
+ * We do not do this, as ksh does not do it either and it
+ * is not required by POSIX.
+ */
+ }
+ return (mustexpandto(arg->text, "export") ||
+ mustexpandto(arg->text, "readonly") ||
+ (mustexpandto(arg->text, "local") &&
+ (have_command || !isfunc("local"))));
+}
+
+static void
+xtracecommand(struct arglist *varlist, int argc, char **argv)
+{
+ char sep = 0;
+ const char *text, *p, *ps4;
+ int i;
+
+ ps4 = expandstr(ps4val());
+ out2str(ps4 != NULL ? ps4 : ps4val());
+ for (i = 0; i < varlist->count; i++) {
+ text = varlist->args[i];
+ if (sep != 0)
+ out2c(' ');
+ p = strchr(text, '=');
+ if (p != NULL) {
+ p++;
+ outbin(text, p - text, out2);
+ out2qstr(p);
+ } else
+ out2qstr(text);
+ sep = ' ';
+ }
+ for (i = 0; i < argc; i++) {
+ text = argv[i];
+ if (sep != 0)
+ out2c(' ');
+ out2qstr(text);
+ sep = ' ';
+ }
+ out2c('\n');
+ flushout(&errout);
+}
+
+/*
+ * Check if a builtin can safely be executed in the same process,
+ * even though it should be in a subshell (command substitution).
+ * Note that jobid, jobs, times and trap can show information not
+ * available in a child process; this is deliberate.
+ * The arguments should already have been expanded.
+ */
+static int
+safe_builtin(int idx, int argc, char **argv)
+{
+ /* Generated from builtins.def. */
+ if (safe_builtin_always(idx))
+ return (1);
+ if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD ||
+ idx == UMASKCMD)
+ return (argc <= 1 || (argc == 2 && argv[1][0] == '-'));
+ if (idx == SETCMD)
+ return (argc <= 1 || (argc == 2 && (argv[1][0] == '-' ||
+ argv[1][0] == '+') && argv[1][1] == 'o' &&
+ argv[1][2] == '\0'));
+ return (0);
+}
+
+/*
+ * Perform redirections, then execute a simple command with vfork.
+ * This cannot be used for command substitutions for two reasons:
+ * - Redirections might cause the error message for later redirections or for
+ * an unknown command to be sent to the pipe (to be substituted), and this
+ * might cause a deadlock if the message is too long.
+ * - The assignment of the pipe needs to come before instead of after the
+ * redirections.
+ */
+static int
+redirected_vforkexecshell(struct job *jp, union node *redir, char **argv,
+ char **envp, const char *path, int idx)
+{
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ volatile int in_redirect = 1;
+
+ savehandler = handler;
+ if (setjmp(jmploc.loc)) {
+ int e;
+
+ handler = savehandler;
+ e = exception;
+ popredir();
+ if (e == EXERROR && in_redirect) {
+ FORCEINTON;
+ return 0;
+ }
+ longjmp(handler->loc, 1);
+ } else {
+ INTOFF;
+ handler = &jmploc;
+ redirect(redir, REDIR_PUSH);
+ in_redirect = 0;
+ INTON;
+ vforkexecshell(jp, argv, envp, path, idx, NULL);
+ }
+ INTOFF;
+ handler = savehandler;
+ popredir();
+ INTON;
+ return 1;
+}
+
+/*
+ * Execute a simple command.
+ * Note: This may or may not return if (flags & EV_EXIT).
+ */
+
+static void
+evalcommand(union node *cmd, int flags, struct backcmd *backcmd)
+{
+ union node *argp;
+ struct arglist arglist;
+ struct arglist varlist;
+ char **argv;
+ int argc;
+ char **envp;
+ int varflag;
+ int mode;
+ int pip[2];
+ struct cmdentry cmdentry;
+ struct job *jp;
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ char *savecmdname;
+ struct shparam saveparam;
+ struct localvar *savelocalvars;
+ struct parsefile *savetopfile;
+ volatile int e;
+ char *lastarg;
+ int signaled;
+ int do_clearcmdentry;
+ const char *path = pathval();
+ int i;
+
+ /* First expand the arguments. */
+ TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags));
+ emptyarglist(&arglist);
+ emptyarglist(&varlist);
+ varflag = 1;
+ jp = NULL;
+ do_clearcmdentry = 0;
+ oexitstatus = exitstatus;
+ exitstatus = 0;
+ /* Add one slot at the beginning for tryexec(). */
+ appendarglist(&arglist, nullstr);
+ for (argp = cmd->ncmd.args ; argp ; argp = argp->narg.next) {
+ if (varflag && isassignment(argp->narg.text)) {
+ expandarg(argp, varflag == 1 ? &varlist : &arglist,
+ EXP_VARTILDE);
+ continue;
+ } else if (varflag == 1)
+ varflag = isdeclarationcmd(&argp->narg) ? 2 : 0;
+ expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
+ }
+ appendarglist(&arglist, nullstr);
+ expredir(cmd->ncmd.redirect);
+ argc = arglist.count - 2;
+ argv = &arglist.args[1];
+
+ argv[argc] = NULL;
+ lastarg = NULL;
+ if (iflag && funcnest == 0 && argc > 0)
+ lastarg = argv[argc - 1];
+
+ /* Print the command if xflag is set. */
+ if (xflag)
+ xtracecommand(&varlist, argc, argv);
+
+ /* Now locate the command. */
+ if (argc == 0) {
+ /* Variable assignment(s) without command */
+ cmdentry.cmdtype = CMDBUILTIN;
+ cmdentry.u.index = BLTINCMD;
+ cmdentry.special = 0;
+ } else {
+ static const char PATH[] = "PATH=";
+ int cmd_flags = 0, bltinonly = 0;
+
+ /*
+ * Modify the command lookup path, if a PATH= assignment
+ * is present
+ */
+ for (i = 0; i < varlist.count; i++)
+ if (strncmp(varlist.args[i], PATH, sizeof(PATH) - 1) == 0) {
+ path = varlist.args[i] + sizeof(PATH) - 1;
+ /*
+ * On `PATH=... command`, we need to make
+ * sure that the command isn't using the
+ * non-updated hash table of the outer PATH
+ * setting and we need to make sure that
+ * the hash table isn't filled with items
+ * from the temporary setting.
+ *
+ * It would be better to forbid using and
+ * updating the table while this command
+ * runs, by the command finding mechanism
+ * is heavily integrated with hash handling,
+ * so we just delete the hash before and after
+ * the command runs. Partly deleting like
+ * changepatch() does doesn't seem worth the
+ * booking effort, since most such runs add
+ * directories in front of the new PATH.
+ */
+ clearcmdentry();
+ do_clearcmdentry = 1;
+ }
+
+ for (;;) {
+ if (bltinonly) {
+ cmdentry.u.index = find_builtin(*argv, &cmdentry.special);
+ if (cmdentry.u.index < 0) {
+ cmdentry.u.index = BLTINCMD;
+ argv--;
+ argc++;
+ break;
+ }
+ } else
+ find_command(argv[0], &cmdentry, cmd_flags, path);
+ /* implement the bltin and command builtins here */
+ if (cmdentry.cmdtype != CMDBUILTIN)
+ break;
+ if (cmdentry.u.index == BLTINCMD) {
+ if (argc == 1)
+ break;
+ argv++;
+ argc--;
+ bltinonly = 1;
+ } else if (cmdentry.u.index == COMMANDCMD) {
+ if (argc == 1)
+ break;
+ if (!strcmp(argv[1], "-p")) {
+ if (argc == 2)
+ break;
+ if (argv[2][0] == '-') {
+ if (strcmp(argv[2], "--"))
+ break;
+ if (argc == 3)
+ break;
+ argv += 3;
+ argc -= 3;
+ } else {
+ argv += 2;
+ argc -= 2;
+ }
+ path = _PATH_STDPATH;
+ clearcmdentry();
+ do_clearcmdentry = 1;
+ } else if (!strcmp(argv[1], "--")) {
+ if (argc == 2)
+ break;
+ argv += 2;
+ argc -= 2;
+ } else if (argv[1][0] == '-')
+ break;
+ else {
+ argv++;
+ argc--;
+ }
+ cmd_flags |= DO_NOFUNC;
+ bltinonly = 0;
+ } else
+ break;
+ }
+ /*
+ * Special builtins lose their special properties when
+ * called via 'command'.
+ */
+ if (cmd_flags & DO_NOFUNC)
+ cmdentry.special = 0;
+ }
+
+ /* Fork off a child process if necessary. */
+ if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN)
+ && ((flags & EV_EXIT) == 0 || have_traps()))
+ || ((flags & EV_BACKCMD) != 0
+ && (cmdentry.cmdtype != CMDBUILTIN ||
+ !safe_builtin(cmdentry.u.index, argc, argv)))) {
+ jp = makejob(cmd, 1);
+ mode = FORK_FG;
+ if (flags & EV_BACKCMD) {
+ mode = FORK_NOJOB;
+ if (pipe(pip) < 0)
+ error("Pipe call failed: %s", strerror(errno));
+ }
+ if (cmdentry.cmdtype == CMDNORMAL &&
+ (cmd->ncmd.redirect == NULL || (flags & EV_BACKCMD) == 0) &&
+ varlist.count == 0 &&
+ (mode == FORK_FG || mode == FORK_NOJOB) &&
+ !disvforkset() && !iflag && !mflag) {
+ if (cmd->ncmd.redirect != NULL) {
+ if (redirected_vforkexecshell(jp,
+ cmd->ncmd.redirect,
+ argv, environment(), path,
+ cmdentry.u.index))
+ goto parent;
+ else
+ goto out;
+ } else
+ vforkexecshell(jp, argv, environment(), path,
+ cmdentry.u.index,
+ flags & EV_BACKCMD ? pip : NULL);
+ goto parent;
+ }
+ if (forkshell(jp, cmd, mode) != 0)
+ goto parent; /* at end of routine */
+ if (flags & EV_BACKCMD) {
+ FORCEINTON;
+ close(pip[0]);
+ if (pip[1] != 1) {
+ dup2(pip[1], 1);
+ close(pip[1]);
+ }
+ flags &= ~EV_BACKCMD;
+ }
+ flags |= EV_EXIT;
+ }
+
+ /* This is the child process if a fork occurred. */
+ /* Execute the command. */
+ if (cmdentry.cmdtype == CMDFUNCTION) {
+#ifdef DEBUG
+ trputs("Shell function: "); trargs(argv);
+#endif
+ saveparam = shellparam;
+ shellparam.malloc = 0;
+ shellparam.reset = 1;
+ shellparam.nparam = argc - 1;
+ shellparam.p = argv + 1;
+ shellparam.optp = NULL;
+ shellparam.optnext = NULL;
+ INTOFF;
+ savelocalvars = localvars;
+ localvars = NULL;
+ reffunc(cmdentry.u.func);
+ savehandler = handler;
+ if (setjmp(jmploc.loc)) {
+ popredir();
+ unreffunc(cmdentry.u.func);
+ poplocalvars();
+ localvars = savelocalvars;
+ freeparam(&shellparam);
+ shellparam = saveparam;
+ funcnest--;
+ handler = savehandler;
+ longjmp(handler->loc, 1);
+ }
+ handler = &jmploc;
+ funcnest++;
+ redirect(cmd->ncmd.redirect, REDIR_PUSH);
+ INTON;
+ for (i = 0; i < varlist.count; i++)
+ mklocal(varlist.args[i]);
+ exitstatus = oexitstatus;
+ evaltree(getfuncnode(cmdentry.u.func),
+ flags & (EV_TESTED | EV_EXIT));
+ INTOFF;
+ unreffunc(cmdentry.u.func);
+ poplocalvars();
+ localvars = savelocalvars;
+ freeparam(&shellparam);
+ shellparam = saveparam;
+ handler = savehandler;
+ funcnest--;
+ popredir();
+ INTON;
+ if (evalskip == SKIPRETURN) {
+ evalskip = 0;
+ skipcount = 0;
+ }
+ if (jp)
+ exitshell(exitstatus);
+ } else if (cmdentry.cmdtype == CMDBUILTIN) {
+#ifdef DEBUG
+ trputs("builtin command: "); trargs(argv);
+#endif
+ mode = (cmdentry.u.index == EXECCMD)? 0 : REDIR_PUSH;
+ if (flags == EV_BACKCMD) {
+ memout.nextc = memout.buf;
+ mode |= REDIR_BACKQ;
+ }
+ savecmdname = commandname;
+ savetopfile = getcurrentfile();
+ cmdenviron = &varlist;
+ e = -1;
+ savehandler = handler;
+ if (setjmp(jmploc.loc)) {
+ e = exception;
+ if (e == EXINT)
+ exitstatus = SIGINT+128;
+ goto cmddone;
+ }
+ handler = &jmploc;
+ redirect(cmd->ncmd.redirect, mode);
+ outclearerror(out1);
+ /*
+ * If there is no command word, redirection errors should
+ * not be fatal but assignment errors should.
+ */
+ if (argc == 0)
+ cmdentry.special = 1;
+ listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET);
+ if (argc > 0)
+ bltinsetlocale();
+ commandname = argv[0];
+ argptr = argv + 1;
+ nextopt_optptr = NULL; /* initialize nextopt */
+ builtin_flags = flags;
+ exitstatus = (*builtinfunc[cmdentry.u.index])(argc, argv);
+ flushall();
+ if (outiserror(out1)) {
+ warning("write error on stdout");
+ if (exitstatus == 0 || exitstatus == 1)
+ exitstatus = 2;
+ }
+cmddone:
+ if (argc > 0)
+ bltinunsetlocale();
+ cmdenviron = NULL;
+ out1 = &output;
+ out2 = &errout;
+ freestdout();
+ handler = savehandler;
+ commandname = savecmdname;
+ if (jp)
+ exitshell(exitstatus);
+ if (flags == EV_BACKCMD) {
+ backcmd->buf = memout.buf;
+ backcmd->nleft = memout.buf != NULL ?
+ memout.nextc - memout.buf : 0;
+ memout.buf = NULL;
+ memout.nextc = NULL;
+ memout.bufend = NULL;
+ memout.bufsize = 64;
+ }
+ if (cmdentry.u.index != EXECCMD)
+ popredir();
+ if (e != -1) {
+ if (e != EXERROR || cmdentry.special)
+ exraise(e);
+ popfilesupto(savetopfile);
+ if (flags != EV_BACKCMD)
+ FORCEINTON;
+ }
+ } else {
+#ifdef DEBUG
+ trputs("normal command: "); trargs(argv);
+#endif
+ redirect(cmd->ncmd.redirect, 0);
+ for (i = 0; i < varlist.count; i++)
+ setvareq(varlist.args[i], VEXPORT|VSTACK);
+ envp = environment();
+ shellexec(argv, envp, path, cmdentry.u.index);
+ /*NOTREACHED*/
+ }
+ goto out;
+
+parent: /* parent process gets here (if we forked) */
+ if (mode == FORK_FG) { /* argument to fork */
+ INTOFF;
+ exitstatus = waitforjob(jp, &signaled);
+ INTON;
+ if (iflag && loopnest > 0 && signaled) {
+ evalskip = SKIPBREAK;
+ skipcount = loopnest;
+ }
+ } else if (mode == FORK_NOJOB) {
+ backcmd->fd = pip[0];
+ close(pip[1]);
+ backcmd->jp = jp;
+ }
+
+out:
+ if (lastarg)
+ setvar("_", lastarg, 0);
+ if (do_clearcmdentry)
+ clearcmdentry();
+}
+
+
+
+/*
+ * Search for a command. This is called before we fork so that the
+ * location of the command will be available in the parent as well as
+ * the child. The check for "goodname" is an overly conservative
+ * check that the name will not be subject to expansion.
+ */
+
+static void
+prehash(union node *n)
+{
+ struct cmdentry entry;
+
+ if (n && n->type == NCMD && n->ncmd.args)
+ if (goodname(n->ncmd.args->narg.text))
+ find_command(n->ncmd.args->narg.text, &entry, 0,
+ pathval());
+}
+
+
+
+/*
+ * Builtin commands. Builtin commands whose functions are closely
+ * tied to evaluation are implemented here.
+ */
+
+/*
+ * No command given, a bltin command with no arguments, or a bltin command
+ * with an invalid name.
+ */
+
+int
+bltincmd(int argc, char **argv)
+{
+ if (argc > 1) {
+ out2fmt_flush("%s: not found\n", argv[1]);
+ return 127;
+ }
+ /*
+ * Preserve exitstatus of a previous possible command substitution
+ * as POSIX mandates
+ */
+ return exitstatus;
+}
+
+
+/*
+ * Handle break and continue commands. Break, continue, and return are
+ * all handled by setting the evalskip flag. The evaluation routines
+ * above all check this flag, and if it is set they start skipping
+ * commands rather than executing them. The variable skipcount is
+ * the number of loops to break/continue, or the number of function
+ * levels to return. (The latter is always 1.) It should probably
+ * be an error to break out of more loops than exist, but it isn't
+ * in the standard shell so we don't make it one here.
+ */
+
+int
+breakcmd(int argc, char **argv)
+{
+ long n;
+ char *end;
+
+ if (argc > 1) {
+ /* Allow arbitrarily large numbers. */
+ n = strtol(argv[1], &end, 10);
+ if (!is_digit(argv[1][0]) || *end != '\0')
+ error("Illegal number: %s", argv[1]);
+ } else
+ n = 1;
+ if (n > loopnest)
+ n = loopnest;
+ if (n > 0) {
+ evalskip = (**argv == 'c')? SKIPCONT : SKIPBREAK;
+ skipcount = n;
+ }
+ return 0;
+}
+
+/*
+ * The `command' command.
+ */
+int
+commandcmd(int argc __unused, char **argv __unused)
+{
+ const char *path;
+ int ch;
+ int cmd = -1;
+
+ path = bltinlookup("PATH", 1);
+
+ while ((ch = nextopt("pvV")) != '\0') {
+ switch (ch) {
+ case 'p':
+ path = _PATH_STDPATH;
+ break;
+ case 'v':
+ cmd = TYPECMD_SMALLV;
+ break;
+ case 'V':
+ cmd = TYPECMD_BIGV;
+ break;
+ }
+ }
+
+ if (cmd != -1) {
+ if (*argptr == NULL || argptr[1] != NULL)
+ error("wrong number of arguments");
+ return typecmd_impl(2, argptr - 1, cmd, path);
+ }
+ if (*argptr != NULL)
+ error("commandcmd bad call");
+
+ /*
+ * Do nothing successfully if no command was specified;
+ * ksh also does this.
+ */
+ return 0;
+}
+
+
+/*
+ * The return command.
+ */
+
+int
+returncmd(int argc, char **argv)
+{
+ int ret = argc > 1 ? number(argv[1]) : oexitstatus;
+
+ evalskip = SKIPRETURN;
+ skipcount = 1;
+ return ret;
+}
+
+
+int
+falsecmd(int argc __unused, char **argv __unused)
+{
+ return 1;
+}
+
+
+int
+truecmd(int argc __unused, char **argv __unused)
+{
+ return 0;
+}
+
+
+int
+execcmd(int argc, char **argv)
+{
+ int i;
+
+ /*
+ * Because we have historically not supported any options,
+ * only treat "--" specially.
+ */
+ if (argc > 1 && strcmp(argv[1], "--") == 0)
+ argc--, argv++;
+ if (argc > 1) {
+ iflag = 0; /* exit on error */
+ mflag = 0;
+ optschanged();
+ for (i = 0; i < cmdenviron->count; i++)
+ setvareq(cmdenviron->args[i], VEXPORT|VSTACK);
+ shellexec(argv + 1, environment(), pathval(), 0);
+
+ }
+ return 0;
+}
+
+
+int
+timescmd(int argc __unused, char **argv __unused)
+{
+ struct rusage ru;
+ long shumins, shsmins, chumins, chsmins;
+ double shusecs, shssecs, chusecs, chssecs;
+
+ if (getrusage(RUSAGE_SELF, &ru) < 0)
+ return 1;
+ shumins = ru.ru_utime.tv_sec / 60;
+ shusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
+ shsmins = ru.ru_stime.tv_sec / 60;
+ shssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
+ if (getrusage(RUSAGE_CHILDREN, &ru) < 0)
+ return 1;
+ chumins = ru.ru_utime.tv_sec / 60;
+ chusecs = ru.ru_utime.tv_sec % 60 + ru.ru_utime.tv_usec / 1000000.;
+ chsmins = ru.ru_stime.tv_sec / 60;
+ chssecs = ru.ru_stime.tv_sec % 60 + ru.ru_stime.tv_usec / 1000000.;
+ out1fmt("%ldm%.3fs %ldm%.3fs\n%ldm%.3fs %ldm%.3fs\n", shumins,
+ shusecs, shsmins, shssecs, chumins, chusecs, chsmins, chssecs);
+ return 0;
+}
diff --git a/cmd/posix/sh/eval.h b/cmd/posix/sh/eval.h
@@ -0,0 +1,69 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+extern char *commandname; /* currently executing command */
+extern int exitstatus; /* exit status of last command */
+extern int oexitstatus; /* saved exit status */
+extern struct arglist *cmdenviron; /* environment for builtin command */
+
+
+struct backcmd { /* result of evalbackcmd */
+ int fd; /* file descriptor to read from */
+ char *buf; /* buffer */
+ int nleft; /* number of chars in buffer */
+ struct job *jp; /* job structure for command */
+};
+
+void reseteval(void);
+
+/* flags in argument to evaltree/evalstring */
+#define EV_EXIT 01 /* exit after evaluating tree */
+#define EV_TESTED 02 /* exit status is checked; ignore -e flag */
+#define EV_BACKCMD 04 /* command executing within back quotes */
+
+void evalstring(const char *, int);
+union node; /* BLETCH for ansi C */
+void evaltree(union node *, int);
+void evalbackcmd(union node *, struct backcmd *);
+
+/* in_function returns nonzero if we are currently evaluating a function */
+#define in_function() funcnest
+extern int funcnest;
+extern int evalskip;
+extern int skipcount;
+
+/* reasons for skipping commands (see comment on breakcmd routine) */
+#define SKIPBREAK 1
+#define SKIPCONT 2
+#define SKIPRETURN 3
diff --git a/cmd/posix/sh/exec.c b/cmd/posix/sh/exec.c
@@ -0,0 +1,848 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <paths.h>
+#include <stdlib.h>
+
+/*
+ * When commands are first encountered, they are entered in a hash table.
+ * This ensures that a full path search will not have to be done for them
+ * on each invocation.
+ *
+ * We should investigate converting to a linear search, even though that
+ * would make the command name "hash" a misnomer.
+ */
+
+#include "shell.h"
+#include "main.h"
+#include "nodes.h"
+#include "parser.h"
+#include "redir.h"
+#include "eval.h"
+#include "exec.h"
+#include "builtins.h"
+#include "var.h"
+#include "options.h"
+#include "input.h"
+#include "output.h"
+#include "syntax.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "show.h"
+#include "jobs.h"
+#include "alias.h"
+
+
+#define CMDTABLESIZE 31 /* should be prime */
+
+
+
+struct tblentry {
+ struct tblentry *next; /* next entry in hash chain */
+ union param param; /* definition of builtin function */
+ int special; /* flag for special builtin commands */
+ signed char cmdtype; /* index identifying command */
+ char cmdname[]; /* name of command */
+};
+
+
+static struct tblentry *cmdtable[CMDTABLESIZE];
+static int cmdtable_cd = 0; /* cmdtable contains cd-dependent entries */
+
+
+static void tryexec(char *, char **, char **);
+static void printentry(struct tblentry *, int);
+static struct tblentry *cmdlookup(const char *, int);
+static void delete_cmd_entry(void);
+static void addcmdentry(const char *, struct cmdentry *);
+
+
+
+/*
+ * Exec a program. Never returns. If you change this routine, you may
+ * have to change the find_command routine as well.
+ *
+ * The argv array may be changed and element argv[-1] should be writable.
+ */
+
+void
+shellexec(char **argv, char **envp, const char *path, int idx)
+{
+ char *cmdname;
+ const char *opt;
+ int e;
+
+ if (strchr(argv[0], '/') != NULL) {
+ tryexec(argv[0], argv, envp);
+ e = errno;
+ } else {
+ e = ENOENT;
+ while ((cmdname = padvance(&path, &opt, argv[0])) != NULL) {
+ if (--idx < 0 && opt == NULL) {
+ tryexec(cmdname, argv, envp);
+ if (errno != ENOENT && errno != ENOTDIR)
+ e = errno;
+ if (e == ENOEXEC)
+ break;
+ }
+ stunalloc(cmdname);
+ }
+ }
+
+ /* Map to POSIX errors */
+ if (e == ENOENT || e == ENOTDIR)
+ errorwithstatus(127, "%s: not found", argv[0]);
+ else
+ errorwithstatus(126, "%s: %s", argv[0], strerror(e));
+}
+
+
+static int
+isbinary(const char *data, size_t len)
+{
+ const char *nul, *p;
+ int hasletter;
+
+ nul = memchr(data, '\0', len);
+ if (nul == NULL)
+ return 0;
+ /*
+ * POSIX says we shall allow execution if the initial part intended
+ * to be parsed by the shell consists of characters and does not
+ * contain the NUL character. This allows concatenating a shell
+ * script (ending with exec or exit) and a binary payload.
+ *
+ * In order to reject common binary files such as PNG images, check
+ * that there is a lowercase letter or expansion before the last
+ * newline before the NUL character, in addition to the check for
+ * the newline character suggested by POSIX.
+ */
+ hasletter = 0;
+ for (p = data; *p != '\0'; p++) {
+ if ((*p >= 'a' && *p <= 'z') || *p == '$' || *p == '`')
+ hasletter = 1;
+ if (hasletter && *p == '\n')
+ return 0;
+ }
+ return 1;
+}
+
+
+static void
+tryexec(char *cmd, char **argv, char **envp)
+{
+ int e, in;
+ ssize_t n;
+ char buf[256];
+
+ execve(cmd, argv, envp);
+ e = errno;
+ if (e == ENOEXEC) {
+ INTOFF;
+ in = open(cmd, O_RDONLY | O_NONBLOCK);
+ if (in != -1) {
+ n = pread(in, buf, sizeof buf, 0);
+ close(in);
+ if (n > 0 && isbinary(buf, n)) {
+ errno = ENOEXEC;
+ return;
+ }
+ }
+ *argv = cmd;
+ *--argv = __DECONST(char *, _PATH_BSHELL);
+ execve(_PATH_BSHELL, argv, envp);
+ }
+ errno = e;
+}
+
+/*
+ * Do a path search. The variable path (passed by reference) should be
+ * set to the start of the path before the first call; padvance will update
+ * this value as it proceeds. Successive calls to padvance will return
+ * the possible path expansions in sequence. If popt is not NULL, options
+ * are processed: if an option (indicated by a percent sign) appears in
+ * the path entry then *popt will be set to point to it; else *popt will be
+ * set to NULL. If popt is NULL, percent signs are not special.
+ */
+
+char *
+padvance(const char **path, const char **popt, const char *name)
+{
+ const char *p, *start;
+ char *q;
+ size_t len, namelen;
+
+ if (*path == NULL)
+ return NULL;
+ start = *path;
+ if (popt != NULL)
+ for (p = start; *p && *p != ':' && *p != '%'; p++)
+ ; /* nothing */
+ else
+ for (p = start; *p && *p != ':'; p++)
+ ; /* nothing */
+ namelen = strlen(name);
+ len = p - start + namelen + 2; /* "2" is for '/' and '\0' */
+ STARTSTACKSTR(q);
+ CHECKSTRSPACE(len, q);
+ if (p != start) {
+ memcpy(q, start, p - start);
+ q += p - start;
+ *q++ = '/';
+ }
+ memcpy(q, name, namelen + 1);
+ if (popt != NULL) {
+ if (*p == '%') {
+ *popt = ++p;
+ while (*p && *p != ':') p++;
+ } else
+ *popt = NULL;
+ }
+ if (*p == ':')
+ *path = p + 1;
+ else
+ *path = NULL;
+ return stalloc(len);
+}
+
+
+
+/*** Command hashing code ***/
+
+
+int
+hashcmd(int argc __unused, char **argv __unused)
+{
+ struct tblentry **pp;
+ struct tblentry *cmdp;
+ int c;
+ int verbose;
+ struct cmdentry entry;
+ char *name;
+ int errors;
+
+ errors = 0;
+ verbose = 0;
+ while ((c = nextopt("rv")) != '\0') {
+ if (c == 'r') {
+ clearcmdentry();
+ } else if (c == 'v') {
+ verbose++;
+ }
+ }
+ if (*argptr == NULL) {
+ for (pp = cmdtable ; pp < &cmdtable[CMDTABLESIZE] ; pp++) {
+ for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
+ if (cmdp->cmdtype == CMDNORMAL)
+ printentry(cmdp, verbose);
+ }
+ }
+ return 0;
+ }
+ while ((name = *argptr) != NULL) {
+ if ((cmdp = cmdlookup(name, 0)) != NULL
+ && cmdp->cmdtype == CMDNORMAL)
+ delete_cmd_entry();
+ find_command(name, &entry, DO_ERR, pathval());
+ if (entry.cmdtype == CMDUNKNOWN)
+ errors = 1;
+ else if (verbose) {
+ cmdp = cmdlookup(name, 0);
+ if (cmdp != NULL)
+ printentry(cmdp, verbose);
+ else {
+ outfmt(out2, "%s: not found\n", name);
+ errors = 1;
+ }
+ flushall();
+ }
+ argptr++;
+ }
+ return errors;
+}
+
+
+static void
+printentry(struct tblentry *cmdp, int verbose)
+{
+ int idx;
+ const char *path, *opt;
+ char *name;
+
+ if (cmdp->cmdtype == CMDNORMAL) {
+ idx = cmdp->param.index;
+ path = pathval();
+ do {
+ name = padvance(&path, &opt, cmdp->cmdname);
+ stunalloc(name);
+ } while (--idx >= 0);
+ out1str(name);
+ } else if (cmdp->cmdtype == CMDBUILTIN) {
+ out1fmt("builtin %s", cmdp->cmdname);
+ } else if (cmdp->cmdtype == CMDFUNCTION) {
+ out1fmt("function %s", cmdp->cmdname);
+ if (verbose) {
+ INTOFF;
+ name = commandtext(getfuncnode(cmdp->param.func));
+ out1c(' ');
+ out1str(name);
+ ckfree(name);
+ INTON;
+ }
+#ifdef DEBUG
+ } else {
+ error("internal error: cmdtype %d", cmdp->cmdtype);
+#endif
+ }
+ out1c('\n');
+}
+
+
+
+/*
+ * Resolve a command name. If you change this routine, you may have to
+ * change the shellexec routine as well.
+ */
+
+void
+find_command(const char *name, struct cmdentry *entry, int act,
+ const char *path)
+{
+ struct tblentry *cmdp, loc_cmd;
+ int idx;
+ const char *opt;
+ char *fullname;
+ struct stat statb;
+ int e;
+ int i;
+ int spec;
+ int cd;
+
+ /* If name contains a slash, don't use the hash table */
+ if (strchr(name, '/') != NULL) {
+ entry->cmdtype = CMDNORMAL;
+ entry->u.index = 0;
+ entry->special = 0;
+ return;
+ }
+
+ cd = 0;
+
+ /* If name is in the table, we're done */
+ if ((cmdp = cmdlookup(name, 0)) != NULL) {
+ if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC)
+ cmdp = NULL;
+ else
+ goto success;
+ }
+
+ /* Check for builtin next */
+ if ((i = find_builtin(name, &spec)) >= 0) {
+ INTOFF;
+ cmdp = cmdlookup(name, 1);
+ if (cmdp->cmdtype == CMDFUNCTION)
+ cmdp = &loc_cmd;
+ cmdp->cmdtype = CMDBUILTIN;
+ cmdp->param.index = i;
+ cmdp->special = spec;
+ INTON;
+ goto success;
+ }
+
+ /* We have to search path. */
+
+ e = ENOENT;
+ idx = -1;
+ for (;(fullname = padvance(&path, &opt, name)) != NULL;
+ stunalloc(fullname)) {
+ idx++;
+ if (opt) {
+ if (strncmp(opt, "func", 4) == 0) {
+ /* handled below */
+ } else {
+ continue; /* ignore unimplemented options */
+ }
+ }
+ if (fullname[0] != '/')
+ cd = 1;
+ if (stat(fullname, &statb) < 0) {
+ if (errno != ENOENT && errno != ENOTDIR)
+ e = errno;
+ continue;
+ }
+ e = EACCES; /* if we fail, this will be the error */
+ if (!S_ISREG(statb.st_mode))
+ continue;
+ if (opt) { /* this is a %func directory */
+ readcmdfile(fullname, -1 /* verify */);
+ if ((cmdp = cmdlookup(name, 0)) == NULL || cmdp->cmdtype != CMDFUNCTION)
+ error("%s not defined in %s", name, fullname);
+ stunalloc(fullname);
+ goto success;
+ }
+#ifdef notdef
+ if (statb.st_uid == geteuid()) {
+ if ((statb.st_mode & 0100) == 0)
+ goto loop;
+ } else if (statb.st_gid == getegid()) {
+ if ((statb.st_mode & 010) == 0)
+ goto loop;
+ } else {
+ if ((statb.st_mode & 01) == 0)
+ goto loop;
+ }
+#endif
+ TRACE(("searchexec \"%s\" returns \"%s\"\n", name, fullname));
+ INTOFF;
+ stunalloc(fullname);
+ cmdp = cmdlookup(name, 1);
+ if (cmdp->cmdtype == CMDFUNCTION)
+ cmdp = &loc_cmd;
+ cmdp->cmdtype = CMDNORMAL;
+ cmdp->param.index = idx;
+ cmdp->special = 0;
+ INTON;
+ goto success;
+ }
+
+ if (act & DO_ERR) {
+ if (e == ENOENT || e == ENOTDIR)
+ outfmt(out2, "%s: not found\n", name);
+ else
+ outfmt(out2, "%s: %s\n", name, strerror(e));
+ }
+ entry->cmdtype = CMDUNKNOWN;
+ entry->u.index = 0;
+ entry->special = 0;
+ return;
+
+success:
+ if (cd)
+ cmdtable_cd = 1;
+ entry->cmdtype = cmdp->cmdtype;
+ entry->u = cmdp->param;
+ entry->special = cmdp->special;
+}
+
+
+
+/*
+ * Search the table of builtin commands.
+ */
+
+int
+find_builtin(const char *name, int *special)
+{
+ const unsigned char *bp;
+ size_t len;
+
+ len = strlen(name);
+ for (bp = builtincmd ; *bp ; bp += 2 + bp[0]) {
+ if (bp[0] == len && memcmp(bp + 2, name, len) == 0) {
+ *special = (bp[1] & BUILTIN_SPECIAL) != 0;
+ return bp[1] & ~BUILTIN_SPECIAL;
+ }
+ }
+ return -1;
+}
+
+
+
+/*
+ * Called when a cd is done. If any entry in cmdtable depends on the current
+ * directory, simply clear cmdtable completely.
+ */
+
+void
+hashcd(void)
+{
+ if (cmdtable_cd)
+ clearcmdentry();
+}
+
+
+
+/*
+ * Called before PATH is changed. The argument is the new value of PATH;
+ * pathval() still returns the old value at this point. Called with
+ * interrupts off.
+ */
+
+void
+changepath(const char *newval __unused)
+{
+ clearcmdentry();
+}
+
+
+/*
+ * Clear out cached utility locations.
+ */
+
+void
+clearcmdentry(void)
+{
+ struct tblentry **tblp;
+ struct tblentry **pp;
+ struct tblentry *cmdp;
+
+ INTOFF;
+ for (tblp = cmdtable ; tblp < &cmdtable[CMDTABLESIZE] ; tblp++) {
+ pp = tblp;
+ while ((cmdp = *pp) != NULL) {
+ if (cmdp->cmdtype == CMDNORMAL) {
+ *pp = cmdp->next;
+ ckfree(cmdp);
+ } else {
+ pp = &cmdp->next;
+ }
+ }
+ }
+ cmdtable_cd = 0;
+ INTON;
+}
+
+
+static unsigned int
+hashname(const char *p)
+{
+ unsigned int hashval;
+
+ hashval = (unsigned char)*p << 4;
+ while (*p)
+ hashval += *p++;
+
+ return (hashval % CMDTABLESIZE);
+}
+
+
+/*
+ * Locate a command in the command hash table. If "add" is nonzero,
+ * add the command to the table if it is not already present. The
+ * variable "lastcmdentry" is set to point to the address of the link
+ * pointing to the entry, so that delete_cmd_entry can delete the
+ * entry.
+ */
+
+static struct tblentry **lastcmdentry;
+
+
+static struct tblentry *
+cmdlookup(const char *name, int add)
+{
+ struct tblentry *cmdp;
+ struct tblentry **pp;
+ size_t len;
+
+ pp = &cmdtable[hashname(name)];
+ for (cmdp = *pp ; cmdp ; cmdp = cmdp->next) {
+ if (equal(cmdp->cmdname, name))
+ break;
+ pp = &cmdp->next;
+ }
+ if (add && cmdp == NULL) {
+ INTOFF;
+ len = strlen(name);
+ cmdp = *pp = ckmalloc(sizeof (struct tblentry) + len + 1);
+ cmdp->next = NULL;
+ cmdp->cmdtype = CMDUNKNOWN;
+ memcpy(cmdp->cmdname, name, len + 1);
+ INTON;
+ }
+ lastcmdentry = pp;
+ return cmdp;
+}
+
+const void *
+itercmd(const void *entry, struct cmdentry *result)
+{
+ const struct tblentry *e = entry;
+ size_t i = 0;
+
+ if (e != NULL) {
+ if (e->next != NULL) {
+ e = e->next;
+ goto success;
+ }
+ i = hashname(e->cmdname) + 1;
+ }
+ for (; i < CMDTABLESIZE; i++)
+ if ((e = cmdtable[i]) != NULL)
+ goto success;
+
+ return (NULL);
+success:
+ result->cmdtype = e->cmdtype;
+ result->cmdname = e->cmdname;
+
+ return (e);
+}
+
+/*
+ * Delete the command entry returned on the last lookup.
+ */
+
+static void
+delete_cmd_entry(void)
+{
+ struct tblentry *cmdp;
+
+ INTOFF;
+ cmdp = *lastcmdentry;
+ *lastcmdentry = cmdp->next;
+ ckfree(cmdp);
+ INTON;
+}
+
+
+
+/*
+ * Add a new command entry, replacing any existing command entry for
+ * the same name.
+ */
+
+static void
+addcmdentry(const char *name, struct cmdentry *entry)
+{
+ struct tblentry *cmdp;
+
+ INTOFF;
+ cmdp = cmdlookup(name, 1);
+ if (cmdp->cmdtype == CMDFUNCTION) {
+ unreffunc(cmdp->param.func);
+ }
+ cmdp->cmdtype = entry->cmdtype;
+ cmdp->param = entry->u;
+ cmdp->special = entry->special;
+ INTON;
+}
+
+
+/*
+ * Define a shell function.
+ */
+
+void
+defun(const char *name, union node *func)
+{
+ struct cmdentry entry;
+
+ INTOFF;
+ entry.cmdtype = CMDFUNCTION;
+ entry.u.func = copyfunc(func);
+ entry.special = 0;
+ addcmdentry(name, &entry);
+ INTON;
+}
+
+
+/*
+ * Delete a function if it exists.
+ * Called with interrupts off.
+ */
+
+int
+unsetfunc(const char *name)
+{
+ struct tblentry *cmdp;
+
+ if ((cmdp = cmdlookup(name, 0)) != NULL && cmdp->cmdtype == CMDFUNCTION) {
+ unreffunc(cmdp->param.func);
+ delete_cmd_entry();
+ return (0);
+ }
+ return (0);
+}
+
+
+/*
+ * Check if a function by a certain name exists.
+ */
+int
+isfunc(const char *name)
+{
+ struct tblentry *cmdp;
+ cmdp = cmdlookup(name, 0);
+ return (cmdp != NULL && cmdp->cmdtype == CMDFUNCTION);
+}
+
+
+static void
+print_absolute_path(const char *name)
+{
+ const char *pwd;
+
+ if (*name != '/' && (pwd = lookupvar("PWD")) != NULL && *pwd != '\0') {
+ out1str(pwd);
+ if (strcmp(pwd, "/") != 0)
+ outcslow('/', out1);
+ }
+ out1str(name);
+ outcslow('\n', out1);
+}
+
+
+/*
+ * Shared code for the following builtin commands:
+ * type, command -v, command -V
+ */
+
+int
+typecmd_impl(int argc, char **argv, int cmd, const char *path)
+{
+ struct cmdentry entry;
+ struct tblentry *cmdp;
+ const char *const *pp;
+ struct alias *ap;
+ int i;
+ int error1 = 0;
+
+ if (path != pathval())
+ clearcmdentry();
+
+ for (i = 1; i < argc; i++) {
+ /* First look at the keywords */
+ for (pp = parsekwd; *pp; pp++)
+ if (**pp == *argv[i] && equal(*pp, argv[i]))
+ break;
+
+ if (*pp) {
+ if (cmd == TYPECMD_SMALLV)
+ out1fmt("%s\n", argv[i]);
+ else
+ out1fmt("%s is a shell keyword\n", argv[i]);
+ continue;
+ }
+
+ /* Then look at the aliases */
+ if ((ap = lookupalias(argv[i], 1)) != NULL) {
+ if (cmd == TYPECMD_SMALLV) {
+ out1fmt("alias %s=", argv[i]);
+ out1qstr(ap->val);
+ outcslow('\n', out1);
+ } else
+ out1fmt("%s is an alias for %s\n", argv[i],
+ ap->val);
+ continue;
+ }
+
+ /* Then check if it is a tracked alias */
+ if ((cmdp = cmdlookup(argv[i], 0)) != NULL) {
+ entry.cmdtype = cmdp->cmdtype;
+ entry.u = cmdp->param;
+ entry.special = cmdp->special;
+ }
+ else {
+ /* Finally use brute force */
+ find_command(argv[i], &entry, 0, path);
+ }
+
+ switch (entry.cmdtype) {
+ case CMDNORMAL: {
+ if (strchr(argv[i], '/') == NULL) {
+ const char *path2 = path;
+ const char *opt2;
+ char *name;
+ int j = entry.u.index;
+ do {
+ name = padvance(&path2, &opt2, argv[i]);
+ stunalloc(name);
+ } while (--j >= 0);
+ if (cmd != TYPECMD_SMALLV)
+ out1fmt("%s is%s ", argv[i],
+ (cmdp && cmd == TYPECMD_TYPE) ?
+ " a tracked alias for" : "");
+ print_absolute_path(name);
+ } else {
+ if (eaccess(argv[i], X_OK) == 0) {
+ if (cmd != TYPECMD_SMALLV)
+ out1fmt("%s is ", argv[i]);
+ print_absolute_path(argv[i]);
+ } else {
+ if (cmd != TYPECMD_SMALLV)
+ outfmt(out2, "%s: %s\n",
+ argv[i], strerror(errno));
+ error1 |= 127;
+ }
+ }
+ break;
+ }
+ case CMDFUNCTION:
+ if (cmd == TYPECMD_SMALLV)
+ out1fmt("%s\n", argv[i]);
+ else
+ out1fmt("%s is a shell function\n", argv[i]);
+ break;
+
+ case CMDBUILTIN:
+ if (cmd == TYPECMD_SMALLV)
+ out1fmt("%s\n", argv[i]);
+ else if (entry.special)
+ out1fmt("%s is a special shell builtin\n",
+ argv[i]);
+ else
+ out1fmt("%s is a shell builtin\n", argv[i]);
+ break;
+
+ default:
+ if (cmd != TYPECMD_SMALLV)
+ outfmt(out2, "%s: not found\n", argv[i]);
+ error1 |= 127;
+ break;
+ }
+ }
+
+ if (path != pathval())
+ clearcmdentry();
+
+ return error1;
+}
+
+/*
+ * Locate and print what a word is...
+ */
+
+int
+typecmd(int argc, char **argv)
+{
+ if (argc > 2 && strcmp(argv[1], "--") == 0)
+ argc--, argv++;
+ return typecmd_impl(argc, argv, TYPECMD_TYPE, bltinlookup("PATH", 1));
+}
diff --git a/cmd/posix/sh/exec.h b/cmd/posix/sh/exec.h
@@ -0,0 +1,75 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* values of cmdtype */
+#define CMDUNKNOWN -1 /* no entry in table for command */
+#define CMDNORMAL 0 /* command is an executable program */
+#define CMDBUILTIN 1 /* command is a shell builtin */
+#define CMDFUNCTION 2 /* command is a shell function */
+
+/* values for typecmd_impl's third parameter */
+enum {
+ TYPECMD_SMALLV, /* command -v */
+ TYPECMD_BIGV, /* command -V */
+ TYPECMD_TYPE /* type */
+};
+
+union node;
+struct cmdentry {
+ int cmdtype;
+ union param {
+ int index;
+ struct funcdef *func;
+ } u;
+ int special;
+ const char *cmdname;
+};
+
+
+/* action to find_command() */
+#define DO_ERR 0x01 /* prints errors */
+#define DO_NOFUNC 0x02 /* don't return shell functions, for command */
+
+void shellexec(char **, char **, const char *, int) __dead2;
+char *padvance(const char **, const char **, const char *);
+void find_command(const char *, struct cmdentry *, int, const char *);
+int find_builtin(const char *, int *);
+void hashcd(void);
+void changepath(const char *);
+void defun(const char *, union node *);
+int unsetfunc(const char *);
+int isfunc(const char *);
+int typecmd_impl(int, char **, int, const char *);
+void clearcmdentry(void);
+const void *itercmd(const void *, struct cmdentry *);
diff --git a/cmd/posix/sh/expand.c b/cmd/posix/sh/expand.c
@@ -0,0 +1,1547 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ * Copyright (c) 1997-2005
+ * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved.
+ * Copyright (c) 2010-2015
+ * Jilles Tjoelker <jilles@stack.nl>. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/stat.h>
+#include <dirent.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <wchar.h>
+#include <wctype.h>
+
+/*
+ * Routines to expand arguments to commands. We have to deal with
+ * backquotes, shell variables, and file metacharacters.
+ */
+
+#include "shell.h"
+#include "main.h"
+#include "nodes.h"
+#include "eval.h"
+#include "expand.h"
+#include "syntax.h"
+#include "parser.h"
+#include "jobs.h"
+#include "options.h"
+#include "var.h"
+#include "input.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "arith.h"
+#include "show.h"
+#include "builtins.h"
+
+enum wordstate { WORD_IDLE, WORD_WS_DELIMITED, WORD_QUOTEMARK };
+
+struct worddest {
+ struct arglist *list;
+ enum wordstate state;
+};
+
+static char *expdest; /* output of current string */
+
+static const char *argstr(const char *, struct nodelist **restrict, int,
+ struct worddest *);
+static const char *exptilde(const char *, int);
+static const char *expari(const char *, struct nodelist **restrict, int,
+ struct worddest *);
+static void expbackq(union node *, int, int, struct worddest *);
+static const char *subevalvar_trim(const char *, struct nodelist **restrict,
+ int, int, int);
+static const char *subevalvar_misc(const char *, struct nodelist **restrict,
+ const char *, int, int, int);
+static const char *evalvar(const char *, struct nodelist **restrict, int,
+ struct worddest *);
+static int varisset(const char *, int);
+static void strtodest(const char *, int, int, int, struct worddest *);
+static void reprocess(int, int, int, int, struct worddest *);
+static void varvalue(const char *, int, int, int, struct worddest *);
+static void expandmeta(char *, struct arglist *);
+static void expmeta(char *, char *, struct arglist *);
+static int expsortcmp(const void *, const void *);
+static int patmatch(const char *, const char *);
+static void cvtnum(int, char *);
+static int collate_range_cmp(wchar_t, wchar_t);
+
+void
+emptyarglist(struct arglist *list)
+{
+
+ list->args = list->smallarg;
+ list->count = 0;
+ list->capacity = sizeof(list->smallarg) / sizeof(list->smallarg[0]);
+}
+
+void
+appendarglist(struct arglist *list, char *str)
+{
+ char **newargs;
+ int newcapacity;
+
+ if (list->count >= list->capacity) {
+ newcapacity = list->capacity * 2;
+ if (newcapacity < 16)
+ newcapacity = 16;
+ if (newcapacity > INT_MAX / (int)sizeof(newargs[0]))
+ error("Too many entries in arglist");
+ newargs = stalloc(newcapacity * sizeof(newargs[0]));
+ memcpy(newargs, list->args, list->count * sizeof(newargs[0]));
+ list->args = newargs;
+ list->capacity = newcapacity;
+ }
+ list->args[list->count++] = str;
+}
+
+static int
+collate_range_cmp(wchar_t c1, wchar_t c2)
+{
+ wchar_t s1[2], s2[2];
+
+ s1[0] = c1;
+ s1[1] = L'\0';
+ s2[0] = c2;
+ s2[1] = L'\0';
+ return (wcscoll(s1, s2));
+}
+
+static char *
+stputs_quotes(const char *data, const char *syntax, char *p)
+{
+ while (*data) {
+ CHECKSTRSPACE(2, p);
+ if (syntax[(int)*data] == CCTL)
+ USTPUTC(CTLESC, p);
+ USTPUTC(*data++, p);
+ }
+ return (p);
+}
+#define STPUTS_QUOTES(data, syntax, p) p = stputs_quotes((data), syntax, p)
+
+static char *
+nextword(char c, int flag, char *p, struct worddest *dst)
+{
+ int is_ws;
+
+ is_ws = c == '\t' || c == '\n' || c == ' ';
+ if (p != stackblock() || (is_ws ? dst->state == WORD_QUOTEMARK :
+ dst->state != WORD_WS_DELIMITED) || c == '\0') {
+ STPUTC('\0', p);
+ if (flag & EXP_GLOB)
+ expandmeta(grabstackstr(p), dst->list);
+ else
+ appendarglist(dst->list, grabstackstr(p));
+ dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE;
+ } else if (!is_ws && dst->state == WORD_WS_DELIMITED)
+ dst->state = WORD_IDLE;
+ /* Reserve space while the stack string is empty. */
+ appendarglist(dst->list, NULL);
+ dst->list->count--;
+ STARTSTACKSTR(p);
+ return p;
+}
+#define NEXTWORD(c, flag, p, dstlist) p = nextword(c, flag, p, dstlist)
+
+static char *
+stputs_split(const char *data, const char *syntax, int flag, char *p,
+ struct worddest *dst)
+{
+ const char *ifs;
+ char c;
+
+ ifs = ifsset() ? ifsval() : " \t\n";
+ while (*data) {
+ CHECKSTRSPACE(2, p);
+ c = *data++;
+ if (strchr(ifs, c) != NULL) {
+ NEXTWORD(c, flag, p, dst);
+ continue;
+ }
+ if (flag & EXP_GLOB && syntax[(int)c] == CCTL)
+ USTPUTC(CTLESC, p);
+ USTPUTC(c, p);
+ }
+ return (p);
+}
+#define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst)
+
+/*
+ * Perform expansions on an argument, placing the resulting list of arguments
+ * in arglist. Parameter expansion, command substitution and arithmetic
+ * expansion are always performed; additional expansions can be requested
+ * via flag (EXP_*).
+ * The result is left in the stack string.
+ * When arglist is NULL, perform here document expansion.
+ *
+ * When doing something that may cause this to be re-entered, make sure
+ * the stack string is empty via grabstackstr() and do not assume expdest
+ * remains valid.
+ */
+void
+expandarg(union node *arg, struct arglist *arglist, int flag)
+{
+ struct worddest exparg;
+ struct nodelist *argbackq;
+
+ if (fflag)
+ flag &= ~EXP_GLOB;
+ argbackq = arg->narg.backquote;
+ exparg.list = arglist;
+ exparg.state = WORD_IDLE;
+ STARTSTACKSTR(expdest);
+ argstr(arg->narg.text, &argbackq, flag, &exparg);
+ if (arglist == NULL) {
+ STACKSTRNUL(expdest);
+ return; /* here document expanded */
+ }
+ if ((flag & EXP_SPLIT) == 0 || expdest != stackblock() ||
+ exparg.state == WORD_QUOTEMARK) {
+ STPUTC('\0', expdest);
+ if (flag & EXP_SPLIT) {
+ if (flag & EXP_GLOB)
+ expandmeta(grabstackstr(expdest), exparg.list);
+ else
+ appendarglist(exparg.list, grabstackstr(expdest));
+ }
+ }
+ if ((flag & EXP_SPLIT) == 0)
+ appendarglist(arglist, grabstackstr(expdest));
+}
+
+
+
+/*
+ * Perform parameter expansion, command substitution and arithmetic
+ * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE.
+ * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'.
+ * This is used to expand word in ${var+word} etc.
+ * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC
+ * characters to allow for further processing.
+ *
+ * If EXP_SPLIT is set, dst receives any complete words produced.
+ */
+static const char *
+argstr(const char *p, struct nodelist **restrict argbackq, int flag,
+ struct worddest *dst)
+{
+ char c;
+ int quotes = flag & (EXP_GLOB | EXP_CASE); /* do CTLESC */
+ int firsteq = 1;
+ int split_lit;
+ int lit_quoted;
+
+ split_lit = flag & EXP_SPLIT_LIT;
+ lit_quoted = flag & EXP_LIT_QUOTED;
+ flag &= ~(EXP_SPLIT_LIT | EXP_LIT_QUOTED);
+ if (*p == '~' && (flag & (EXP_TILDE | EXP_VARTILDE)))
+ p = exptilde(p, flag);
+ for (;;) {
+ CHECKSTRSPACE(2, expdest);
+ switch (c = *p++) {
+ case '\0':
+ return (p - 1);
+ case CTLENDVAR:
+ case CTLENDARI:
+ return (p);
+ case CTLQUOTEMARK:
+ lit_quoted = 1;
+ /* "$@" syntax adherence hack */
+ if (p[0] == CTLVAR && (p[1] & VSQUOTE) != 0 &&
+ p[2] == '@' && p[3] == '=')
+ break;
+ if ((flag & EXP_SPLIT) != 0 && expdest == stackblock())
+ dst->state = WORD_QUOTEMARK;
+ break;
+ case CTLQUOTEEND:
+ lit_quoted = 0;
+ break;
+ case CTLESC:
+ c = *p++;
+ if (split_lit && !lit_quoted &&
+ strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
+ NEXTWORD(c, flag, expdest, dst);
+ break;
+ }
+ if (quotes)
+ USTPUTC(CTLESC, expdest);
+ USTPUTC(c, expdest);
+ break;
+ case CTLVAR:
+ p = evalvar(p, argbackq, flag, dst);
+ break;
+ case CTLBACKQ:
+ case CTLBACKQ|CTLQUOTE:
+ expbackq((*argbackq)->n, c & CTLQUOTE, flag, dst);
+ *argbackq = (*argbackq)->next;
+ break;
+ case CTLARI:
+ p = expari(p, argbackq, flag, dst);
+ break;
+ case ':':
+ case '=':
+ /*
+ * sort of a hack - expand tildes in variable
+ * assignments (after the first '=' and after ':'s).
+ */
+ if (split_lit && !lit_quoted &&
+ strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
+ NEXTWORD(c, flag, expdest, dst);
+ break;
+ }
+ USTPUTC(c, expdest);
+ if (flag & EXP_VARTILDE && *p == '~' &&
+ (c != '=' || firsteq)) {
+ if (c == '=')
+ firsteq = 0;
+ p = exptilde(p, flag);
+ }
+ break;
+ default:
+ if (split_lit && !lit_quoted &&
+ strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) {
+ NEXTWORD(c, flag, expdest, dst);
+ break;
+ }
+ USTPUTC(c, expdest);
+ }
+ }
+}
+
+/*
+ * Perform tilde expansion, placing the result in the stack string and
+ * returning the next position in the input string to process.
+ */
+static const char *
+exptilde(const char *p, int flag)
+{
+ char c;
+ const char *startp = p;
+ const char *user;
+ struct passwd *pw;
+ char *home;
+ int len;
+
+ for (;;) {
+ c = *p;
+ switch(c) {
+ case CTLESC: /* This means CTL* are always considered quoted. */
+ case CTLVAR:
+ case CTLBACKQ:
+ case CTLBACKQ | CTLQUOTE:
+ case CTLARI:
+ case CTLENDARI:
+ case CTLQUOTEMARK:
+ return (startp);
+ case ':':
+ if ((flag & EXP_VARTILDE) == 0)
+ break;
+ /* FALLTHROUGH */
+ case '\0':
+ case '/':
+ case CTLENDVAR:
+ len = p - startp - 1;
+ STPUTBIN(startp + 1, len, expdest);
+ STACKSTRNUL(expdest);
+ user = expdest - len;
+ if (*user == '\0') {
+ home = lookupvar("HOME");
+ } else {
+ pw = getpwnam(user);
+ home = pw != NULL ? pw->pw_dir : NULL;
+ }
+ STADJUST(-len, expdest);
+ if (home == NULL || *home == '\0')
+ return (startp);
+ strtodest(home, flag, VSNORMAL, 1, NULL);
+ return (p);
+ }
+ p++;
+ }
+}
+
+
+/*
+ * Expand arithmetic expression.
+ */
+static const char *
+expari(const char *p, struct nodelist **restrict argbackq, int flag,
+ struct worddest *dst)
+{
+ char *q, *start;
+ arith_t result;
+ int begoff;
+ int quoted;
+ int adj;
+
+ quoted = *p++ == '"';
+ begoff = expdest - stackblock();
+ p = argstr(p, argbackq, 0, NULL);
+ STPUTC('\0', expdest);
+ start = stackblock() + begoff;
+
+ q = grabstackstr(expdest);
+ result = arith(start);
+ ungrabstackstr(q, expdest);
+
+ start = stackblock() + begoff;
+ adj = start - expdest;
+ STADJUST(adj, expdest);
+
+ CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
+ fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
+ adj = strlen(expdest);
+ STADJUST(adj, expdest);
+ /*
+ * If this is quoted, a '-' must not indicate a range in [...].
+ * If this is not quoted, splitting may occur.
+ */
+ if (quoted ?
+ result < 0 && begoff > 1 && flag & (EXP_GLOB | EXP_CASE) :
+ flag & EXP_SPLIT)
+ reprocess(expdest - adj - stackblock(), flag, VSNORMAL, quoted,
+ dst);
+ return p;
+}
+
+
+/*
+ * Perform command substitution.
+ */
+static void
+expbackq(union node *cmd, int quoted, int flag, struct worddest *dst)
+{
+ struct backcmd in;
+ int i;
+ char buf[128];
+ char *p;
+ char *dest = expdest;
+ char lastc;
+ char const *syntax = quoted? DQSYNTAX : BASESYNTAX;
+ int quotes = flag & (EXP_GLOB | EXP_CASE);
+ size_t nnl;
+ const char *ifs;
+ int startloc;
+
+ INTOFF;
+ p = grabstackstr(dest);
+ evalbackcmd(cmd, &in);
+ ungrabstackstr(p, dest);
+
+ p = in.buf;
+ startloc = dest - stackblock();
+ nnl = 0;
+ if (!quoted && flag & EXP_SPLIT)
+ ifs = ifsset() ? ifsval() : " \t\n";
+ else
+ ifs = "";
+ /* Remove trailing newlines */
+ for (;;) {
+ if (--in.nleft < 0) {
+ if (in.fd < 0)
+ break;
+ while ((i = read(in.fd, buf, sizeof buf)) < 0 && errno == EINTR)
+ ;
+ TRACE(("expbackq: read returns %d\n", i));
+ if (i <= 0)
+ break;
+ p = buf;
+ in.nleft = i - 1;
+ }
+ lastc = *p++;
+ if (lastc == '\0')
+ continue;
+ if (nnl > 0 && lastc != '\n') {
+ NEXTWORD('\n', flag, dest, dst);
+ nnl = 0;
+ }
+ if (strchr(ifs, lastc) != NULL) {
+ if (lastc == '\n')
+ nnl++;
+ else
+ NEXTWORD(lastc, flag, dest, dst);
+ } else {
+ CHECKSTRSPACE(2, dest);
+ if (quotes && syntax[(int)lastc] == CCTL)
+ USTPUTC(CTLESC, dest);
+ USTPUTC(lastc, dest);
+ }
+ }
+ while (dest > stackblock() + startloc && STTOPC(dest) == '\n')
+ STUNPUTC(dest);
+
+ if (in.fd >= 0)
+ close(in.fd);
+ if (in.buf)
+ ckfree(in.buf);
+ if (in.jp) {
+ p = grabstackstr(dest);
+ exitstatus = waitforjob(in.jp, (int *)NULL);
+ ungrabstackstr(p, dest);
+ }
+ TRACE(("expbackq: done\n"));
+ expdest = dest;
+ INTON;
+}
+
+
+
+static void
+recordleft(const char *str, const char *loc, char *startp)
+{
+ int amount;
+
+ amount = ((str - 1) - (loc - startp)) - expdest;
+ STADJUST(amount, expdest);
+ while (loc != str - 1)
+ *startp++ = *loc++;
+}
+
+static const char *
+subevalvar_trim(const char *p, struct nodelist **restrict argbackq, int strloc,
+ int subtype, int startloc)
+{
+ char *startp;
+ char *loc = NULL;
+ char *str;
+ int c = 0;
+ int amount;
+
+ p = argstr(p, argbackq, EXP_CASE | EXP_TILDE, NULL);
+ STACKSTRNUL(expdest);
+ startp = stackblock() + startloc;
+ str = stackblock() + strloc;
+
+ switch (subtype) {
+ case VSTRIMLEFT:
+ for (loc = startp; loc < str; loc++) {
+ c = *loc;
+ *loc = '\0';
+ if (patmatch(str, startp)) {
+ *loc = c;
+ recordleft(str, loc, startp);
+ return p;
+ }
+ *loc = c;
+ }
+ break;
+
+ case VSTRIMLEFTMAX:
+ for (loc = str - 1; loc >= startp;) {
+ c = *loc;
+ *loc = '\0';
+ if (patmatch(str, startp)) {
+ *loc = c;
+ recordleft(str, loc, startp);
+ return p;
+ }
+ *loc = c;
+ loc--;
+ }
+ break;
+
+ case VSTRIMRIGHT:
+ for (loc = str - 1; loc >= startp;) {
+ if (patmatch(str, loc)) {
+ amount = loc - expdest;
+ STADJUST(amount, expdest);
+ return p;
+ }
+ loc--;
+ }
+ break;
+
+ case VSTRIMRIGHTMAX:
+ for (loc = startp; loc < str - 1; loc++) {
+ if (patmatch(str, loc)) {
+ amount = loc - expdest;
+ STADJUST(amount, expdest);
+ return p;
+ }
+ }
+ break;
+
+
+ default:
+ abort();
+ }
+ amount = (expdest - stackblock() - strloc) + 1;
+ STADJUST(-amount, expdest);
+ return p;
+}
+
+
+static const char *
+subevalvar_misc(const char *p, struct nodelist **restrict argbackq,
+ const char *var, int subtype, int startloc, int varflags)
+{
+ const char *end;
+ char *startp;
+ int amount;
+
+ end = argstr(p, argbackq, EXP_TILDE, NULL);
+ STACKSTRNUL(expdest);
+ startp = stackblock() + startloc;
+
+ switch (subtype) {
+ case VSASSIGN:
+ setvar(var, startp, 0);
+ amount = startp - expdest;
+ STADJUST(amount, expdest);
+ return end;
+
+ case VSQUESTION:
+ if (*p != CTLENDVAR) {
+ outfmt(out2, "%s\n", startp);
+ error((char *)NULL);
+ }
+ error("%.*s: parameter %snot set", (int)(p - var - 1),
+ var, (varflags & VSNUL) ? "null or " : "");
+
+ default:
+ abort();
+ }
+}
+
+
+/*
+ * Expand a variable, and return a pointer to the next character in the
+ * input string.
+ */
+
+static const char *
+evalvar(const char *p, struct nodelist **restrict argbackq, int flag,
+ struct worddest *dst)
+{
+ int subtype;
+ int varflags;
+ const char *var;
+ const char *val;
+ int patloc;
+ int c;
+ int set;
+ int special;
+ int startloc;
+ int varlen;
+ int varlenb;
+ char buf[21];
+
+ varflags = (unsigned char)*p++;
+ subtype = varflags & VSTYPE;
+ var = p;
+ special = 0;
+ if (! is_name(*p))
+ special = 1;
+ p = strchr(p, '=') + 1;
+ if (varflags & VSLINENO) {
+ set = 1;
+ special = 1;
+ val = NULL;
+ } else if (special) {
+ set = varisset(var, varflags & VSNUL);
+ val = NULL;
+ } else {
+ val = bltinlookup(var, 1);
+ if (val == NULL || ((varflags & VSNUL) && val[0] == '\0')) {
+ val = NULL;
+ set = 0;
+ } else
+ set = 1;
+ }
+ varlen = 0;
+ startloc = expdest - stackblock();
+ if (!set && uflag && *var != '@' && *var != '*') {
+ switch (subtype) {
+ case VSNORMAL:
+ case VSTRIMLEFT:
+ case VSTRIMLEFTMAX:
+ case VSTRIMRIGHT:
+ case VSTRIMRIGHTMAX:
+ case VSLENGTH:
+ error("%.*s: parameter not set", (int)(p - var - 1),
+ var);
+ }
+ }
+ if (set && subtype != VSPLUS) {
+ /* insert the value of the variable */
+ if (special) {
+ if (varflags & VSLINENO) {
+ if (p - var > (ptrdiff_t)sizeof(buf))
+ abort();
+ memcpy(buf, var, p - var - 1);
+ buf[p - var - 1] = '\0';
+ strtodest(buf, flag, subtype,
+ varflags & VSQUOTE, dst);
+ } else
+ varvalue(var, varflags & VSQUOTE, subtype, flag,
+ dst);
+ if (subtype == VSLENGTH) {
+ varlenb = expdest - stackblock() - startloc;
+ varlen = varlenb;
+ if (localeisutf8) {
+ val = stackblock() + startloc;
+ for (;val != expdest; val++)
+ if ((*val & 0xC0) == 0x80)
+ varlen--;
+ }
+ STADJUST(-varlenb, expdest);
+ }
+ } else {
+ if (subtype == VSLENGTH) {
+ for (;*val; val++)
+ if (!localeisutf8 ||
+ (*val & 0xC0) != 0x80)
+ varlen++;
+ }
+ else
+ strtodest(val, flag, subtype,
+ varflags & VSQUOTE, dst);
+ }
+ }
+
+ if (subtype == VSPLUS)
+ set = ! set;
+
+ switch (subtype) {
+ case VSLENGTH:
+ cvtnum(varlen, buf);
+ strtodest(buf, flag, VSNORMAL, varflags & VSQUOTE, dst);
+ break;
+
+ case VSNORMAL:
+ return p;
+
+ case VSPLUS:
+ case VSMINUS:
+ if (!set) {
+ return argstr(p, argbackq,
+ flag | (flag & EXP_SPLIT ? EXP_SPLIT_LIT : 0) |
+ (varflags & VSQUOTE ? EXP_LIT_QUOTED : 0), dst);
+ }
+ break;
+
+ case VSTRIMLEFT:
+ case VSTRIMLEFTMAX:
+ case VSTRIMRIGHT:
+ case VSTRIMRIGHTMAX:
+ if (!set)
+ break;
+ /*
+ * Terminate the string and start recording the pattern
+ * right after it
+ */
+ STPUTC('\0', expdest);
+ patloc = expdest - stackblock();
+ p = subevalvar_trim(p, argbackq, patloc, subtype, startloc);
+ reprocess(startloc, flag, VSNORMAL, varflags & VSQUOTE, dst);
+ if (flag & EXP_SPLIT && *var == '@' && varflags & VSQUOTE)
+ dst->state = WORD_QUOTEMARK;
+ return p;
+
+ case VSASSIGN:
+ case VSQUESTION:
+ if (!set) {
+ p = subevalvar_misc(p, argbackq, var, subtype,
+ startloc, varflags);
+ /* assert(subtype == VSASSIGN); */
+ val = lookupvar(var);
+ strtodest(val, flag, subtype, varflags & VSQUOTE, dst);
+ return p;
+ }
+ break;
+
+ case VSERROR:
+ c = p - var - 1;
+ error("${%.*s%s}: Bad substitution", c, var,
+ (c > 0 && *p != CTLENDVAR) ? "..." : "");
+
+ default:
+ abort();
+ }
+
+ { /* skip to end of alternative */
+ int nesting = 1;
+ for (;;) {
+ if ((c = *p++) == CTLESC)
+ p++;
+ else if (c == CTLBACKQ || c == (CTLBACKQ|CTLQUOTE))
+ *argbackq = (*argbackq)->next;
+ else if (c == CTLVAR) {
+ if ((*p++ & VSTYPE) != VSNORMAL)
+ nesting++;
+ } else if (c == CTLENDVAR) {
+ if (--nesting == 0)
+ break;
+ }
+ }
+ }
+ return p;
+}
+
+
+
+/*
+ * Test whether a special or positional parameter is set.
+ */
+
+static int
+varisset(const char *name, int nulok)
+{
+
+ if (*name == '!')
+ return backgndpidset();
+ else if (*name == '@' || *name == '*') {
+ if (*shellparam.p == NULL)
+ return 0;
+
+ if (nulok) {
+ char **av;
+
+ for (av = shellparam.p; *av; av++)
+ if (**av != '\0')
+ return 1;
+ return 0;
+ }
+ } else if (is_digit(*name)) {
+ char *ap;
+ long num;
+
+ errno = 0;
+ num = strtol(name, NULL, 10);
+ if (errno != 0 || num > shellparam.nparam)
+ return 0;
+
+ if (num == 0)
+ ap = arg0;
+ else
+ ap = shellparam.p[num - 1];
+
+ if (nulok && (ap == NULL || *ap == '\0'))
+ return 0;
+ }
+ return 1;
+}
+
+static void
+strtodest(const char *p, int flag, int subtype, int quoted,
+ struct worddest *dst)
+{
+ if (subtype == VSLENGTH || subtype == VSTRIMLEFT ||
+ subtype == VSTRIMLEFTMAX || subtype == VSTRIMRIGHT ||
+ subtype == VSTRIMRIGHTMAX)
+ STPUTS(p, expdest);
+ else if (flag & EXP_SPLIT && !quoted && dst != NULL)
+ STPUTS_SPLIT(p, BASESYNTAX, flag, expdest, dst);
+ else if (flag & (EXP_GLOB | EXP_CASE))
+ STPUTS_QUOTES(p, quoted ? DQSYNTAX : BASESYNTAX, expdest);
+ else
+ STPUTS(p, expdest);
+}
+
+static void
+reprocess(int startloc, int flag, int subtype, int quoted,
+ struct worddest *dst)
+{
+ static char *buf = NULL;
+ static size_t buflen = 0;
+ char *startp;
+ size_t len, zpos, zlen;
+
+ startp = stackblock() + startloc;
+ len = expdest - startp;
+ if (len >= SIZE_MAX / 2 || len > PTRDIFF_MAX)
+ abort();
+ INTOFF;
+ if (len >= buflen) {
+ ckfree(buf);
+ buf = NULL;
+ }
+ if (buflen < 128)
+ buflen = 128;
+ while (len >= buflen)
+ buflen <<= 1;
+ if (buf == NULL)
+ buf = ckmalloc(buflen);
+ INTON;
+ memcpy(buf, startp, len);
+ buf[len] = '\0';
+ STADJUST(-(ptrdiff_t)len, expdest);
+ for (zpos = 0;;) {
+ zlen = strlen(buf + zpos);
+ strtodest(buf + zpos, flag, subtype, quoted, dst);
+ zpos += zlen + 1;
+ if (zpos == len + 1)
+ break;
+ if (flag & EXP_SPLIT && (quoted || (zlen > 0 && zpos < len)))
+ NEXTWORD('\0', flag, expdest, dst);
+ }
+}
+
+/*
+ * Add the value of a special or positional parameter to the stack string.
+ */
+
+static void
+varvalue(const char *name, int quoted, int subtype, int flag,
+ struct worddest *dst)
+{
+ int num;
+ char *p;
+ int i;
+ int splitlater;
+ char sep[2];
+ char **ap;
+ char buf[(NSHORTOPTS > 10 ? NSHORTOPTS : 10) + 1];
+
+ if (subtype == VSLENGTH)
+ flag &= ~EXP_FULL;
+ splitlater = subtype == VSTRIMLEFT || subtype == VSTRIMLEFTMAX ||
+ subtype == VSTRIMRIGHT || subtype == VSTRIMRIGHTMAX;
+
+ switch (*name) {
+ case '$':
+ num = rootpid;
+ break;
+ case '?':
+ num = oexitstatus;
+ break;
+ case '#':
+ num = shellparam.nparam;
+ break;
+ case '!':
+ num = backgndpidval();
+ break;
+ case '-':
+ p = buf;
+ for (i = 0 ; i < NSHORTOPTS ; i++) {
+ if (optval[i])
+ *p++ = optletter[i];
+ }
+ *p = '\0';
+ strtodest(buf, flag, subtype, quoted, dst);
+ return;
+ case '@':
+ if (flag & EXP_SPLIT && quoted) {
+ for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
+ strtodest(p, flag, subtype, quoted, dst);
+ if (*ap) {
+ if (splitlater)
+ STPUTC('\0', expdest);
+ else
+ NEXTWORD('\0', flag, expdest,
+ dst);
+ }
+ }
+ if (shellparam.nparam > 0)
+ dst->state = WORD_QUOTEMARK;
+ return;
+ }
+ /* FALLTHROUGH */
+ case '*':
+ if (ifsset())
+ sep[0] = ifsval()[0];
+ else
+ sep[0] = ' ';
+ sep[1] = '\0';
+ for (ap = shellparam.p ; (p = *ap++) != NULL ; ) {
+ strtodest(p, flag, subtype, quoted, dst);
+ if (!*ap)
+ break;
+ if (sep[0])
+ strtodest(sep, flag, subtype, quoted, dst);
+ else if (flag & EXP_SPLIT && !quoted && **ap != '\0') {
+ if (splitlater)
+ STPUTC('\0', expdest);
+ else
+ NEXTWORD('\0', flag, expdest, dst);
+ }
+ }
+ return;
+ default:
+ if (is_digit(*name)) {
+ num = atoi(name);
+ if (num == 0)
+ p = arg0;
+ else if (num > 0 && num <= shellparam.nparam)
+ p = shellparam.p[num - 1];
+ else
+ return;
+ strtodest(p, flag, subtype, quoted, dst);
+ }
+ return;
+ }
+ cvtnum(num, buf);
+ strtodest(buf, flag, subtype, quoted, dst);
+}
+
+
+
+static char expdir[PATH_MAX];
+#define expdir_end (expdir + sizeof(expdir))
+
+/*
+ * Perform pathname generation and remove control characters.
+ * At this point, the only control characters should be CTLESC.
+ * The results are stored in the list dstlist.
+ */
+static void
+expandmeta(char *pattern, struct arglist *dstlist)
+{
+ char *p;
+ int firstmatch;
+ char c;
+
+ firstmatch = dstlist->count;
+ p = pattern;
+ for (; (c = *p) != '\0'; p++) {
+ /* fast check for meta chars */
+ if (c == '*' || c == '?' || c == '[') {
+ INTOFF;
+ expmeta(expdir, pattern, dstlist);
+ INTON;
+ break;
+ }
+ }
+ if (dstlist->count == firstmatch) {
+ /*
+ * no matches
+ */
+ rmescapes(pattern);
+ appendarglist(dstlist, pattern);
+ } else {
+ qsort(&dstlist->args[firstmatch],
+ dstlist->count - firstmatch,
+ sizeof(dstlist->args[0]), expsortcmp);
+ }
+}
+
+
+/*
+ * Do metacharacter (i.e. *, ?, [...]) expansion.
+ */
+
+static void
+expmeta(char *enddir, char *name, struct arglist *arglist)
+{
+ const char *p;
+ const char *q;
+ const char *start;
+ char *endname;
+ int metaflag;
+ struct stat statb;
+ DIR *dirp;
+ struct dirent *dp;
+ int atend;
+ int matchdot;
+ int esc;
+ int namlen;
+
+ metaflag = 0;
+ start = name;
+ for (p = name; esc = 0, *p; p += esc + 1) {
+ if (*p == '*' || *p == '?')
+ metaflag = 1;
+ else if (*p == '[') {
+ q = p + 1;
+ if (*q == '!' || *q == '^')
+ q++;
+ for (;;) {
+ if (*q == CTLESC)
+ q++;
+ if (*q == '/' || *q == '\0')
+ break;
+ if (*++q == ']') {
+ metaflag = 1;
+ break;
+ }
+ }
+ } else if (*p == '\0')
+ break;
+ else {
+ if (*p == CTLESC)
+ esc++;
+ if (p[esc] == '/') {
+ if (metaflag)
+ break;
+ start = p + esc + 1;
+ }
+ }
+ }
+ if (metaflag == 0) { /* we've reached the end of the file name */
+ if (enddir != expdir)
+ metaflag++;
+ for (p = name ; ; p++) {
+ if (*p == CTLESC)
+ p++;
+ *enddir++ = *p;
+ if (*p == '\0')
+ break;
+ if (enddir == expdir_end)
+ return;
+ }
+ if (metaflag == 0 || lstat(expdir, &statb) >= 0)
+ appendarglist(arglist, stsavestr(expdir));
+ return;
+ }
+ endname = name + (p - name);
+ if (start != name) {
+ p = name;
+ while (p < start) {
+ if (*p == CTLESC)
+ p++;
+ *enddir++ = *p++;
+ if (enddir == expdir_end)
+ return;
+ }
+ }
+ if (enddir == expdir) {
+ p = ".";
+ } else if (enddir == expdir + 1 && *expdir == '/') {
+ p = "/";
+ } else {
+ p = expdir;
+ enddir[-1] = '\0';
+ }
+ if ((dirp = opendir(p)) == NULL)
+ return;
+ if (enddir != expdir)
+ enddir[-1] = '/';
+ if (*endname == 0) {
+ atend = 1;
+ } else {
+ atend = 0;
+ *endname = '\0';
+ endname += esc + 1;
+ }
+ matchdot = 0;
+ p = start;
+ if (*p == CTLESC)
+ p++;
+ if (*p == '.')
+ matchdot++;
+ while (! int_pending() && (dp = readdir(dirp)) != NULL) {
+ if (dp->d_name[0] == '.' && ! matchdot)
+ continue;
+ if (patmatch(start, dp->d_name)) {
+ namlen = strlen(dp->d_name);
+ if (enddir + namlen + 1 > expdir_end)
+ continue;
+ memcpy(enddir, dp->d_name, namlen + 1);
+ if (atend)
+ appendarglist(arglist, stsavestr(expdir));
+ else {
+ if (dp->d_type != DT_UNKNOWN &&
+ dp->d_type != DT_DIR &&
+ dp->d_type != DT_LNK)
+ continue;
+ if (enddir + namlen + 2 > expdir_end)
+ continue;
+ enddir[namlen] = '/';
+ enddir[namlen + 1] = '\0';
+ expmeta(enddir + namlen + 1, endname, arglist);
+ }
+ }
+ }
+ closedir(dirp);
+ if (! atend)
+ endname[-esc - 1] = esc ? CTLESC : '/';
+}
+
+
+static int
+expsortcmp(const void *p1, const void *p2)
+{
+ const char *s1 = *(const char * const *)p1;
+ const char *s2 = *(const char * const *)p2;
+
+ return (strcoll(s1, s2));
+}
+
+
+
+static wchar_t
+get_wc(const char **p)
+{
+ wchar_t c;
+ int chrlen;
+
+ chrlen = mbtowc(&c, *p, 4);
+ if (chrlen == 0)
+ return 0;
+ else if (chrlen == -1)
+ c = 0;
+ else
+ *p += chrlen;
+ return c;
+}
+
+
+/*
+ * See if a character matches a character class, starting at the first colon
+ * of "[:class:]".
+ * If a valid character class is recognized, a pointer to the next character
+ * after the final closing bracket is stored into *end, otherwise a null
+ * pointer is stored into *end.
+ */
+static int
+match_charclass(const char *p, wchar_t chr, const char **end)
+{
+ char name[20];
+ const char *nameend;
+ wctype_t cclass;
+
+ *end = NULL;
+ p++;
+ nameend = strstr(p, ":]");
+ if (nameend == NULL || (size_t)(nameend - p) >= sizeof(name) ||
+ nameend == p)
+ return 0;
+ memcpy(name, p, nameend - p);
+ name[nameend - p] = '\0';
+ *end = nameend + 2;
+ cclass = wctype(name);
+ /* An unknown class matches nothing but is valid nevertheless. */
+ if (cclass == 0)
+ return 0;
+ return iswctype(chr, cclass);
+}
+
+
+/*
+ * Returns true if the pattern matches the string.
+ */
+
+static int
+patmatch(const char *pattern, const char *string)
+{
+ const char *p, *q, *end;
+ const char *bt_p, *bt_q;
+ char c;
+ wchar_t wc, wc2;
+
+ p = pattern;
+ q = string;
+ bt_p = NULL;
+ bt_q = NULL;
+ for (;;) {
+ switch (c = *p++) {
+ case '\0':
+ if (*q != '\0')
+ goto backtrack;
+ return 1;
+ case CTLESC:
+ if (*q++ != *p++)
+ goto backtrack;
+ break;
+ case '?':
+ if (*q == '\0')
+ return 0;
+ if (localeisutf8) {
+ wc = get_wc(&q);
+ /*
+ * A '?' does not match invalid UTF-8 but a
+ * '*' does, so backtrack.
+ */
+ if (wc == 0)
+ goto backtrack;
+ } else
+ q++;
+ break;
+ case '*':
+ c = *p;
+ while (c == '*')
+ c = *++p;
+ /*
+ * If the pattern ends here, we know the string
+ * matches without needing to look at the rest of it.
+ */
+ if (c == '\0')
+ return 1;
+ /*
+ * First try the shortest match for the '*' that
+ * could work. We can forget any earlier '*' since
+ * there is no way having it match more characters
+ * can help us, given that we are already here.
+ */
+ bt_p = p;
+ bt_q = q;
+ break;
+ case '[': {
+ const char *savep, *saveq;
+ int invert, found;
+ wchar_t chr;
+
+ savep = p, saveq = q;
+ invert = 0;
+ if (*p == '!' || *p == '^') {
+ invert++;
+ p++;
+ }
+ found = 0;
+ if (*q == '\0')
+ return 0;
+ if (localeisutf8) {
+ chr = get_wc(&q);
+ if (chr == 0)
+ goto backtrack;
+ } else
+ chr = (unsigned char)*q++;
+ c = *p++;
+ do {
+ if (c == '\0') {
+ p = savep, q = saveq;
+ c = '[';
+ goto dft;
+ }
+ if (c == '[' && *p == ':') {
+ found |= match_charclass(p, chr, &end);
+ if (end != NULL) {
+ p = end;
+ continue;
+ }
+ }
+ if (c == CTLESC)
+ c = *p++;
+ if (localeisutf8 && c & 0x80) {
+ p--;
+ wc = get_wc(&p);
+ if (wc == 0) /* bad utf-8 */
+ return 0;
+ } else
+ wc = (unsigned char)c;
+ if (*p == '-' && p[1] != ']') {
+ p++;
+ if (*p == CTLESC)
+ p++;
+ if (localeisutf8) {
+ wc2 = get_wc(&p);
+ if (wc2 == 0) /* bad utf-8 */
+ return 0;
+ } else
+ wc2 = (unsigned char)*p++;
+ if ( collate_range_cmp(chr, wc) >= 0
+ && collate_range_cmp(chr, wc2) <= 0
+ )
+ found = 1;
+ } else {
+ if (chr == wc)
+ found = 1;
+ }
+ } while ((c = *p++) != ']');
+ if (found == invert)
+ goto backtrack;
+ break;
+ }
+dft: default:
+ if (*q == '\0')
+ return 0;
+ if (*q++ == c)
+ break;
+backtrack:
+ /*
+ * If we have a mismatch (other than hitting the end
+ * of the string), go back to the last '*' seen and
+ * have it match one additional character.
+ */
+ if (bt_p == NULL)
+ return 0;
+ if (*bt_q == '\0')
+ return 0;
+ bt_q++;
+ p = bt_p;
+ q = bt_q;
+ break;
+ }
+ }
+}
+
+
+
+/*
+ * Remove any CTLESC and CTLQUOTEMARK characters from a string.
+ */
+
+void
+rmescapes(char *str)
+{
+ char *p, *q;
+
+ p = str;
+ while (*p != CTLESC && *p != CTLQUOTEMARK && *p != CTLQUOTEEND) {
+ if (*p++ == '\0')
+ return;
+ }
+ q = p;
+ while (*p) {
+ if (*p == CTLQUOTEMARK || *p == CTLQUOTEEND) {
+ p++;
+ continue;
+ }
+ if (*p == CTLESC)
+ p++;
+ *q++ = *p++;
+ }
+ *q = '\0';
+}
+
+
+
+/*
+ * See if a pattern matches in a case statement.
+ */
+
+int
+casematch(union node *pattern, const char *val)
+{
+ struct stackmark smark;
+ struct nodelist *argbackq;
+ int result;
+ char *p;
+
+ setstackmark(&smark);
+ argbackq = pattern->narg.backquote;
+ STARTSTACKSTR(expdest);
+ argstr(pattern->narg.text, &argbackq, EXP_TILDE | EXP_CASE, NULL);
+ STPUTC('\0', expdest);
+ p = grabstackstr(expdest);
+ result = patmatch(p, val);
+ popstackmark(&smark);
+ return result;
+}
+
+/*
+ * Our own itoa().
+ */
+
+static void
+cvtnum(int num, char *buf)
+{
+ char temp[32];
+ int neg = num < 0;
+ char *p = temp + 31;
+
+ temp[31] = '\0';
+
+ do {
+ *--p = num % 10 + '0';
+ } while ((num /= 10) != 0);
+
+ if (neg)
+ *--p = '-';
+
+ memcpy(buf, p, temp + 32 - p);
+}
+
+/*
+ * Do most of the work for wordexp(3).
+ */
+
+int
+wordexpcmd(int argc, char **argv)
+{
+ size_t len;
+ int i;
+
+ out1fmt("%08x", argc - 1);
+ for (i = 1, len = 0; i < argc; i++)
+ len += strlen(argv[i]);
+ out1fmt("%08x", (int)len);
+ for (i = 1; i < argc; i++)
+ outbin(argv[i], strlen(argv[i]) + 1, out1);
+ return (0);
+}
+
+/*
+ * Do most of the work for wordexp(3), new version.
+ */
+
+int
+freebsd_wordexpcmd(int argc __unused, char **argv __unused)
+{
+ struct arglist arglist;
+ union node *args, *n;
+ size_t len;
+ int ch;
+ int protected = 0;
+ int fd = -1;
+ int i;
+
+ while ((ch = nextopt("f:p")) != '\0') {
+ switch (ch) {
+ case 'f':
+ fd = number(shoptarg);
+ break;
+ case 'p':
+ protected = 1;
+ break;
+ }
+ }
+ if (*argptr != NULL)
+ error("wrong number of arguments");
+ if (fd < 0)
+ error("missing fd");
+ INTOFF;
+ setinputfd(fd, 1);
+ INTON;
+ args = parsewordexp();
+ popfile(); /* will also close fd */
+ if (protected)
+ for (n = args; n != NULL; n = n->narg.next) {
+ if (n->narg.backquote != NULL) {
+ outcslow('C', out1);
+ error("command substitution disabled");
+ }
+ }
+ outcslow(' ', out1);
+ emptyarglist(&arglist);
+ for (n = args; n != NULL; n = n->narg.next)
+ expandarg(n, &arglist, EXP_FULL | EXP_TILDE);
+ for (i = 0, len = 0; i < arglist.count; i++)
+ len += strlen(arglist.args[i]);
+ out1fmt("%016x %016zx", arglist.count, len);
+ for (i = 0; i < arglist.count; i++)
+ outbin(arglist.args[i], strlen(arglist.args[i]) + 1, out1);
+ return (0);
+}
diff --git a/cmd/posix/sh/expand.h b/cmd/posix/sh/expand.h
@@ -0,0 +1,61 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+struct arglist {
+ char **args;
+ int count;
+ int capacity;
+ char *smallarg[1];
+};
+
+/*
+ * expandarg() flags
+ */
+#define EXP_SPLIT 0x1 /* perform word splitting */
+#define EXP_TILDE 0x2 /* do normal tilde expansion */
+#define EXP_VARTILDE 0x4 /* expand tildes in an assignment */
+#define EXP_CASE 0x10 /* keeps quotes around for CASE pattern */
+#define EXP_SPLIT_LIT 0x20 /* IFS split literal text ${v+-a b c} */
+#define EXP_LIT_QUOTED 0x40 /* for EXP_SPLIT_LIT, start off quoted */
+#define EXP_GLOB 0x80 /* perform file globbing */
+
+#define EXP_FULL (EXP_SPLIT | EXP_GLOB)
+
+
+void emptyarglist(struct arglist *);
+void appendarglist(struct arglist *, char *);
+union node;
+void expandarg(union node *, struct arglist *, int);
+void rmescapes(char *);
+int casematch(union node *, const char *);
diff --git a/cmd/posix/sh/histedit.c b/cmd/posix/sh/histedit.c
@@ -0,0 +1,802 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#if !FEATURE_SH_HISTEDIT
+#ifndef NO_HISTORY
+#define NO_HISTORY
+#endif
+#endif
+
+#include "shell.h"
+#include "alias.h"
+#include "builtins.h"
+#include "error.h"
+#include "eval.h"
+#include "exec.h"
+#include "main.h"
+#include "memalloc.h"
+#include "mystring.h"
+#include "options.h"
+#include "output.h"
+#include "parser.h"
+#include "var.h"
+
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+
+#include <sys/param.h>
+#include <sys/stat.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#define MAXHISTLOOPS 4 /* max recursions through fc */
+#define DEFEDITOR "ed" /* default editor *should* be $EDITOR */
+
+History *hist; /* history cookie */
+EditLine *el; /* editline cookie */
+int displayhist;
+static int savehist;
+static FILE *el_in, *el_out;
+static int in_command_completion;
+
+static char *fc_replace(const char *, char *, char *);
+static int not_fcnumber(const char *);
+static int str_to_event(const char *, int);
+static int comparator(const void *, const void *, void *);
+static char **sh_matches(const char *, int, int);
+static const char *append_char_function(const char *);
+static unsigned char sh_complete(EditLine *, int);
+
+static const char *
+get_histfile(void)
+{
+ const char *histfile;
+
+ /* don't try to save if the history size is 0 */
+ if (hist == NULL || !strcmp(histsizeval(), "0"))
+ return (NULL);
+ histfile = expandstr("${HISTFILE-${HOME-}/.sh_history}");
+
+ if (histfile[0] == '\0')
+ return (NULL);
+ return (histfile);
+}
+
+void
+histsave(void)
+{
+ HistEvent he;
+ char *histtmpname = NULL;
+ const char *histfile;
+ int fd;
+ FILE *f;
+
+ if (!savehist || (histfile = get_histfile()) == NULL)
+ return;
+ INTOFF;
+ asprintf(&histtmpname, "%s.XXXXXXXXXX", histfile);
+ if (histtmpname == NULL) {
+ INTON;
+ return;
+ }
+ fd = mkstemp(histtmpname);
+ if (fd == -1 || (f = fdopen(fd, "w")) == NULL) {
+ free(histtmpname);
+ INTON;
+ return;
+ }
+ if (history(hist, &he, H_SAVE_FP, f) < 1 ||
+ rename(histtmpname, histfile) == -1)
+ unlink(histtmpname);
+ fclose(f);
+ free(histtmpname);
+ INTON;
+
+}
+
+void
+histload(void)
+{
+ const char *histfile;
+ HistEvent he;
+
+ if ((histfile = get_histfile()) == NULL)
+ return;
+ errno = 0;
+ if (history(hist, &he, H_LOAD, histfile) != -1 || errno == ENOENT)
+ savehist = 1;
+}
+
+/*
+ * Set history and editing status. Called whenever the status may
+ * have changed (figures out what to do).
+ */
+void
+histedit(void)
+{
+
+#define editing (Eflag || Vflag)
+
+ if (iflag) {
+ if (!hist) {
+ /*
+ * turn history on
+ */
+ INTOFF;
+ hist = history_init();
+ INTON;
+
+ if (hist != NULL)
+ sethistsize(histsizeval());
+ else
+ out2fmt_flush("sh: can't initialize history\n");
+ }
+ if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
+ /*
+ * turn editing on
+ */
+ char *term;
+
+ INTOFF;
+ if (el_in == NULL)
+ el_in = fdopen(0, "r");
+ if (el_out == NULL)
+ el_out = fdopen(2, "w");
+ if (el_in == NULL || el_out == NULL)
+ goto bad;
+ term = lookupvar("TERM");
+ if (term)
+ setenv("TERM", term, 1);
+ else
+ unsetenv("TERM");
+ el = el_init(arg0, el_in, el_out, el_out);
+ if (el != NULL) {
+ if (hist)
+ el_set(el, EL_HIST, history, hist);
+ el_set(el, EL_PROMPT_ESC, getprompt, '\001');
+ el_set(el, EL_ADDFN, "sh-complete",
+ "Filename completion",
+ sh_complete);
+ } else {
+bad:
+ out2fmt_flush("sh: can't initialize editing\n");
+ }
+ INTON;
+ } else if (!editing && el) {
+ INTOFF;
+ el_end(el);
+ el = NULL;
+ INTON;
+ }
+ if (el) {
+ if (Vflag)
+ el_set(el, EL_EDITOR, "vi");
+ else if (Eflag) {
+ el_set(el, EL_EDITOR, "emacs");
+ }
+ el_set(el, EL_BIND, "^I", "sh-complete", NULL);
+ el_source(el, NULL);
+ }
+ } else {
+ INTOFF;
+ if (el) { /* no editing if not interactive */
+ el_end(el);
+ el = NULL;
+ }
+ if (hist) {
+ history_end(hist);
+ hist = NULL;
+ }
+ INTON;
+ }
+}
+
+
+void
+sethistsize(const char *hs)
+{
+ int histsize;
+ HistEvent he;
+
+ if (hist != NULL) {
+ if (hs == NULL || !is_number(hs))
+ histsize = 128;
+ else
+ histsize = atoi(hs);
+ history(hist, &he, H_SETSIZE, histsize);
+ history(hist, &he, H_SETUNIQUE, 1);
+ }
+}
+
+void
+setterm(const char *term)
+{
+ if (rootshell && el != NULL && term != NULL)
+ el_set(el, EL_TERMINAL, term);
+}
+
+int
+histcmd(int argc, char **argv __unused)
+{
+ const char *editor = NULL;
+ HistEvent he;
+ int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
+ int i, retval;
+ const char *firststr, *laststr;
+ int first, last, direction;
+ char *pat = NULL, *repl = NULL;
+ static int active = 0;
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ char editfilestr[PATH_MAX];
+ char *volatile editfile;
+ FILE *efp = NULL;
+ int oldhistnum;
+
+ if (hist == NULL)
+ error("history not active");
+
+ if (argc == 1)
+ error("missing history argument");
+
+ while (not_fcnumber(*argptr))
+ do {
+ switch (nextopt("e:lnrs")) {
+ case 'e':
+ editor = shoptarg;
+ break;
+ case 'l':
+ lflg = 1;
+ break;
+ case 'n':
+ nflg = 1;
+ break;
+ case 'r':
+ rflg = 1;
+ break;
+ case 's':
+ sflg = 1;
+ break;
+ case '\0':
+ goto operands;
+ }
+ } while (nextopt_optptr != NULL);
+operands:
+ savehandler = handler;
+ /*
+ * If executing...
+ */
+ if (lflg == 0 || editor || sflg) {
+ lflg = 0; /* ignore */
+ editfile = NULL;
+ /*
+ * Catch interrupts to reset active counter and
+ * cleanup temp files.
+ */
+ if (setjmp(jmploc.loc)) {
+ active = 0;
+ if (editfile)
+ unlink(editfile);
+ handler = savehandler;
+ longjmp(handler->loc, 1);
+ }
+ handler = &jmploc;
+ if (++active > MAXHISTLOOPS) {
+ active = 0;
+ displayhist = 0;
+ error("called recursively too many times");
+ }
+ /*
+ * Set editor.
+ */
+ if (sflg == 0) {
+ if (editor == NULL &&
+ (editor = bltinlookup("FCEDIT", 1)) == NULL &&
+ (editor = bltinlookup("EDITOR", 1)) == NULL)
+ editor = DEFEDITOR;
+ if (editor[0] == '-' && editor[1] == '\0') {
+ sflg = 1; /* no edit */
+ editor = NULL;
+ }
+ }
+ }
+
+ /*
+ * If executing, parse [old=new] now
+ */
+ if (lflg == 0 && *argptr != NULL &&
+ ((repl = strchr(*argptr, '=')) != NULL)) {
+ pat = *argptr;
+ *repl++ = '\0';
+ argptr++;
+ }
+ /*
+ * determine [first] and [last]
+ */
+ if (*argptr == NULL) {
+ firststr = lflg ? "-16" : "-1";
+ laststr = "-1";
+ } else if (argptr[1] == NULL) {
+ firststr = argptr[0];
+ laststr = lflg ? "-1" : argptr[0];
+ } else if (argptr[2] == NULL) {
+ firststr = argptr[0];
+ laststr = argptr[1];
+ } else
+ error("too many arguments");
+ /*
+ * Turn into event numbers.
+ */
+ first = str_to_event(firststr, 0);
+ last = str_to_event(laststr, 1);
+
+ if (rflg) {
+ i = last;
+ last = first;
+ first = i;
+ }
+ /*
+ * XXX - this should not depend on the event numbers
+ * always increasing. Add sequence numbers or offset
+ * to the history element in next (diskbased) release.
+ */
+ direction = first < last ? H_PREV : H_NEXT;
+
+ /*
+ * If editing, grab a temp file.
+ */
+ if (editor) {
+ int fd;
+ INTOFF; /* easier */
+ sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP);
+ if ((fd = mkstemp(editfilestr)) < 0)
+ error("can't create temporary file %s", editfile);
+ editfile = editfilestr;
+ if ((efp = fdopen(fd, "w")) == NULL) {
+ close(fd);
+ error("Out of space");
+ }
+ }
+
+ /*
+ * Loop through selected history events. If listing or executing,
+ * do it now. Otherwise, put into temp file and call the editor
+ * after.
+ *
+ * The history interface needs rethinking, as the following
+ * convolutions will demonstrate.
+ */
+ history(hist, &he, H_FIRST);
+ retval = history(hist, &he, H_NEXT_EVENT, first);
+ for (;retval != -1; retval = history(hist, &he, direction)) {
+ if (lflg) {
+ if (!nflg)
+ out1fmt("%5d ", he.num);
+ out1str(he.str);
+ } else {
+ const char *s = pat ?
+ fc_replace(he.str, pat, repl) : he.str;
+
+ if (sflg) {
+ if (displayhist) {
+ out2str(s);
+ flushout(out2);
+ }
+ evalstring(s, 0);
+ if (displayhist && hist) {
+ /*
+ * XXX what about recursive and
+ * relative histnums.
+ */
+ oldhistnum = he.num;
+ history(hist, &he, H_ENTER, s);
+ /*
+ * XXX H_ENTER moves the internal
+ * cursor, set it back to the current
+ * entry.
+ */
+ history(hist, &he,
+ H_NEXT_EVENT, oldhistnum);
+ }
+ } else
+ fputs(s, efp);
+ }
+ /*
+ * At end? (if we were to lose last, we'd sure be
+ * messed up).
+ */
+ if (he.num == last)
+ break;
+ }
+ if (editor) {
+ char *editcmd;
+
+ fclose(efp);
+ INTON;
+ editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
+ sprintf(editcmd, "%s %s", editor, editfile);
+ evalstring(editcmd, 0); /* XXX - should use no JC command */
+ readcmdfile(editfile, 0 /* verify */); /* XXX - should read back - quick tst */
+ unlink(editfile);
+ }
+
+ if (lflg == 0 && active > 0)
+ --active;
+ if (displayhist)
+ displayhist = 0;
+ handler = savehandler;
+ return 0;
+}
+
+static char *
+fc_replace(const char *s, char *p, char *r)
+{
+ char *dest;
+ int plen = strlen(p);
+
+ STARTSTACKSTR(dest);
+ while (*s) {
+ if (*s == *p && strncmp(s, p, plen) == 0) {
+ STPUTS(r, dest);
+ s += plen;
+ *p = '\0'; /* so no more matches */
+ } else
+ STPUTC(*s++, dest);
+ }
+ STPUTC('\0', dest);
+ dest = grabstackstr(dest);
+
+ return (dest);
+}
+
+static int
+not_fcnumber(const char *s)
+{
+ if (s == NULL)
+ return (0);
+ if (*s == '-')
+ s++;
+ return (!is_number(s));
+}
+
+static int
+str_to_event(const char *str, int last)
+{
+ HistEvent he;
+ const char *s = str;
+ int relative = 0;
+ int i, retval;
+
+ retval = history(hist, &he, H_FIRST);
+ switch (*s) {
+ case '-':
+ relative = 1;
+ /*FALLTHROUGH*/
+ case '+':
+ s++;
+ }
+ if (is_number(s)) {
+ i = atoi(s);
+ if (relative) {
+ while (retval != -1 && i--) {
+ retval = history(hist, &he, H_NEXT);
+ }
+ if (retval == -1)
+ retval = history(hist, &he, H_LAST);
+ } else {
+ retval = history(hist, &he, H_NEXT_EVENT, i);
+ if (retval == -1) {
+ /*
+ * the notion of first and last is
+ * backwards to that of the history package
+ */
+ retval = history(hist, &he, last ? H_FIRST : H_LAST);
+ }
+ }
+ if (retval == -1)
+ error("history number %s not found (internal error)",
+ str);
+ } else {
+ /*
+ * pattern
+ */
+ retval = history(hist, &he, H_PREV_STR, str);
+ if (retval == -1)
+ error("history pattern not found: %s", str);
+ }
+ return (he.num);
+}
+
+int
+bindcmd(int argc, char **argv)
+{
+ int ret;
+ FILE *old;
+ FILE *out;
+
+ if (el == NULL)
+ error("line editing is disabled");
+
+ INTOFF;
+
+ out = out1fp();
+ if (out == NULL)
+ error("Out of space");
+
+ el_get(el, EL_GETFP, 1, &old);
+ el_set(el, EL_SETFP, 1, out);
+
+ ret = el_parse(el, argc, __DECONST(const char **, argv));
+
+ el_set(el, EL_SETFP, 1, old);
+
+ fclose(out);
+
+ if (argc > 1 && argv[1][0] == '-' &&
+ memchr("ve", argv[1][1], 2) != NULL) {
+ Vflag = argv[1][1] == 'v';
+ Eflag = !Vflag;
+ histedit();
+ }
+
+ INTON;
+
+ return ret;
+}
+
+/*
+ * Comparator function for qsort(). The use of curpos here is to skip
+ * characters that we already know to compare equal (common prefix).
+ */
+static int
+comparator(const void *a, const void *b, void *thunk)
+{
+ size_t curpos = (intptr_t)thunk;
+
+ return (strcmp(*(char *const *)a + curpos,
+ *(char *const *)b + curpos));
+}
+
+static char
+**add_match(char **matches, size_t i, size_t *size, char *match_copy)
+{
+ if (match_copy == NULL)
+ return (NULL);
+ matches[i] = match_copy;
+ if (i >= *size - 1) {
+ *size *= 2;
+ matches = reallocarray(matches, *size, sizeof(matches[0]));
+ }
+
+ return (matches);
+}
+
+/*
+ * This function is passed to libedit's fn_complete2(). The library will use
+ * it instead of its standard function that finds matching files in current
+ * directory. If we're at the start of the line, we want to look for
+ * available commands from all paths in $PATH.
+ */
+static char
+**sh_matches(const char *text, int start, int end)
+{
+ char *free_path = NULL, *path;
+ const char *dirname;
+ char **matches = NULL, **rmatches;
+ size_t i = 0, size = 16, uniq;
+ size_t curpos = end - start, lcstring = -1;
+ struct cmdentry e;
+
+ in_command_completion = 0;
+ if (start > 0 || memchr("/.~", text[0], 3) != NULL)
+ return (NULL);
+ in_command_completion = 1;
+ if ((free_path = path = strdup(pathval())) == NULL)
+ goto out;
+ if ((matches = malloc(size * sizeof(matches[0]))) == NULL)
+ goto out;
+ while ((dirname = strsep(&path, ":")) != NULL) {
+ struct dirent *entry;
+ DIR *dir;
+ int dfd;
+
+ dir = opendir(dirname[0] == '\0' ? "." : dirname);
+ if (dir == NULL)
+ continue;
+ if ((dfd = dirfd(dir)) == -1) {
+ closedir(dir);
+ continue;
+ }
+ while ((entry = readdir(dir)) != NULL) {
+ struct stat statb;
+
+ if (strncmp(entry->d_name, text, curpos) != 0)
+ continue;
+ if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK) {
+ if (fstatat(dfd, entry->d_name, &statb, 0) == -1)
+ continue;
+ if (!S_ISREG(statb.st_mode))
+ continue;
+ } else if (entry->d_type != DT_REG)
+ continue;
+ rmatches = add_match(matches, ++i, &size,
+ strdup(entry->d_name));
+ if (rmatches == NULL) {
+ closedir(dir);
+ goto out;
+ }
+ matches = rmatches;
+ }
+ closedir(dir);
+ }
+ for (const unsigned char *bp = builtincmd; *bp != 0; bp += 2 + bp[0]) {
+ if (curpos > bp[0] || memcmp(bp + 2, text, curpos) != 0)
+ continue;
+ rmatches = add_match(matches, ++i, &size, strndup(bp + 2, bp[0]));
+ if (rmatches == NULL)
+ goto out;
+ matches = rmatches;
+ }
+ for (const struct alias *ap = NULL; (ap = iteralias(ap)) != NULL;) {
+ if (strncmp(ap->name, text, curpos) != 0)
+ continue;
+ rmatches = add_match(matches, ++i, &size, strdup(ap->name));
+ if (rmatches == NULL)
+ goto out;
+ matches = rmatches;
+ }
+ for (const void *a = NULL; (a = itercmd(a, &e)) != NULL;) {
+ if (e.cmdtype != CMDFUNCTION)
+ continue;
+ if (strncmp(e.cmdname, text, curpos) != 0)
+ continue;
+ rmatches = add_match(matches, ++i, &size, strdup(e.cmdname));
+ if (rmatches == NULL)
+ goto out;
+ matches = rmatches;
+ }
+out:
+ free(free_path);
+ if (i == 0) {
+ free(matches);
+ return (NULL);
+ }
+ uniq = 1;
+ if (i > 1) {
+ qsort_s(matches + 1, i, sizeof(matches[0]), comparator,
+ (void *)(intptr_t)curpos);
+ for (size_t k = 2; k <= i; k++) {
+ const char *l = matches[uniq] + curpos;
+ const char *r = matches[k] + curpos;
+ size_t common = 0;
+
+ while (*l != '\0' && *r != '\0' && *l == *r)
+ (void)l++, r++, common++;
+ if (common < lcstring)
+ lcstring = common;
+ if (*l == *r)
+ free(matches[k]);
+ else
+ matches[++uniq] = matches[k];
+ }
+ }
+ matches[uniq + 1] = NULL;
+ /*
+ * matches[0] is special: it's not a real matching file name but
+ * a common prefix for all matching names. It can't be null, unlike
+ * any other element of the array. When strings matches[0] and
+ * matches[1] compare equal and matches[2] is null that means to
+ * libedit that there is only a single match. It will then replace
+ * user input with possibly escaped string in matches[0] which is the
+ * reason to copy the full name of the only match.
+ */
+ if (uniq == 1)
+ matches[0] = strdup(matches[1]);
+ else if (lcstring != (size_t)-1)
+ matches[0] = strndup(matches[1], curpos + lcstring);
+ else
+ matches[0] = strdup(text);
+ if (matches[0] == NULL) {
+ for (size_t k = 1; k <= uniq; k++)
+ free(matches[k]);
+ free(matches);
+ return (NULL);
+ }
+ return (matches);
+}
+
+/*
+ * If we don't specify this function as app_func in the call to fn_complete2,
+ * libedit will use the default one, which adds a " " to plain files and
+ * a "/" to directories regardless of whether it's a command name or a plain
+ * path (relative or absolute). We never want to add "/" to commands.
+ *
+ * For example, after I did "mkdir rmdir", "rmdi" would be autocompleted to
+ * "rmdir/" instead of "rmdir ".
+ */
+static const char *
+append_char_function(const char *name)
+{
+ struct stat stbuf;
+ char *expname = name[0] == '~' ? fn_tilde_expand(name) : NULL;
+ const char *rs;
+
+ if (!in_command_completion &&
+ stat(expname ? expname : name, &stbuf) == 0 &&
+ S_ISDIR(stbuf.st_mode))
+ rs = "/";
+ else
+ rs = " ";
+ free(expname);
+ return (rs);
+}
+
+/*
+ * This is passed to el_set(el, EL_ADDFN, ...) so that it's possible to
+ * bind a key (tab by default) to execute the function.
+ */
+unsigned char
+sh_complete(EditLine *sel, int ch __unused)
+{
+ return (unsigned char)fn_complete2(sel, NULL, sh_matches,
+ L" \t\n\"\\'`@$><=;|&{(", NULL, append_char_function,
+ (size_t)100, NULL, &((int) {0}), NULL, NULL, FN_QUOTE_MATCH);
+}
+
+#else
+
+int
+histcmd(int argc __unused, char **argv __unused)
+{
+
+ error("not compiled with history support");
+ /*NOTREACHED*/
+ return (0);
+}
+
+int
+bindcmd(int argc __unused, char **argv __unused)
+{
+
+ error("not compiled with line editing support");
+ return (0);
+}
+#endif
diff --git a/cmd/posix/sh/input.c b/cmd/posix/sh/input.c
@@ -0,0 +1,522 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdio.h> /* defines BUFSIZ */
+#include <fcntl.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+
+/*
+ * This file implements the input routines used by the parser.
+ */
+
+#include "shell.h"
+#include "redir.h"
+#include "syntax.h"
+#include "input.h"
+#include "output.h"
+#include "options.h"
+#include "memalloc.h"
+#include "error.h"
+#include "alias.h"
+#include "parser.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+#include "trap.h"
+
+#define EOF_NLEFT -99 /* value of parsenleft when EOF pushed back */
+
+struct strpush {
+ struct strpush *prev; /* preceding string on stack */
+ const char *prevstring;
+ int prevnleft;
+ int prevlleft;
+ struct alias *ap; /* if push was associated with an alias */
+};
+
+/*
+ * The parsefile structure pointed to by the global variable parsefile
+ * contains information about the current file being read.
+ */
+
+struct parsefile {
+ struct parsefile *prev; /* preceding file on stack */
+ int linno; /* current line */
+ int fd; /* file descriptor (or -1 if string) */
+ int nleft; /* number of chars left in this line */
+ int lleft; /* number of lines left in this buffer */
+ const char *nextc; /* next char in buffer */
+ char *buf; /* input buffer */
+ size_t bufsize; /* input buffer size */
+ struct strpush *strpush; /* for pushing strings at this level */
+ struct strpush basestrpush; /* so pushing one is fast */
+};
+
+
+int plinno = 1; /* input line number */
+int parsenleft; /* copy of parsefile->nleft */
+static int parselleft; /* copy of parsefile->lleft */
+const char *parsenextc; /* copy of parsefile->nextc */
+static char basebuf[BUFSIZ + 1];/* buffer for top level input file */
+static struct parsefile basepf = { /* top level input file */
+ .nextc = basebuf,
+ .buf = basebuf,
+ .bufsize = sizeof(basebuf),
+};
+static struct parsefile *parsefile = &basepf; /* current input file */
+int whichprompt; /* 1 == PS1, 2 == PS2 */
+
+static void pushfile(void);
+static int preadfd(void);
+static void popstring(void);
+
+void
+resetinput(void)
+{
+ popallfiles();
+ parselleft = parsenleft = 0; /* clear input buffer */
+}
+
+
+
+/*
+ * Read a character from the script, returning PEOF on end of file.
+ * Nul characters in the input are silently discarded.
+ */
+
+int
+pgetc(void)
+{
+ return pgetc_macro();
+}
+
+
+static int
+preadfd(void)
+{
+ int nr;
+
+ retry:
+#ifndef NO_HISTORY
+ if (parsefile->fd == 0 && el) {
+ const char *line;
+
+ el_resize(el);
+ line = el_gets(el, &nr);
+ if (nr > 0 && parsefile->bufsize < (size_t)nr + 1) {
+ size_t bufsize;
+
+ INTOFF;
+ if (parsefile->buf != basebuf) {
+ ckfree(parsefile->buf);
+ parsefile->buf = NULL;
+ parsefile->bufsize = 0;
+ }
+ bufsize = (size_t)nr + BUFSIZ + 1;
+ bufsize -= bufsize % BUFSIZ;
+ parsefile->buf = ckmalloc(bufsize);
+ parsefile->bufsize = bufsize;
+ INTON;
+ }
+ if (nr > 0 && line != NULL)
+ memcpy(parsefile->buf, line, nr);
+ else
+ nr = nr ? -1 : 0;
+ } else
+#endif
+ nr = read(parsefile->fd, parsefile->buf, parsefile->bufsize - 1);
+
+ if (nr < 0)
+ switch (errno) {
+ int flags;
+
+ case EINTR:
+ goto retry;
+ case EWOULDBLOCK:
+ if (parsefile->fd != 0)
+ break;
+ if ((flags = fcntl(0, F_GETFL, 0)) < 0)
+ break;
+ if (!(flags & O_NONBLOCK))
+ break;
+ if (fcntl(0, F_SETFL, flags & ~O_NONBLOCK) < 0)
+ break;
+ out2fmt_flush("sh: turning off NDELAY mode\n");
+ goto retry;
+ }
+ else if (nr > 0)
+ parsefile->buf[nr] = '\0';
+ else
+ nr = -1;
+
+ parsenextc = parsefile->buf;
+ return nr;
+}
+
+/*
+ * Refill the input buffer and return the next input character:
+ *
+ * 1) If a string was pushed back on the input, pop it;
+ * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading
+ * from a string so we can't refill the buffer, return EOF.
+ * 3) If there is more in this buffer, use it else call read to fill it.
+ * 4) Process input up to the next newline, deleting nul characters.
+ */
+
+int
+preadbuffer(void)
+{
+ const char *end;
+ char *q, *r;
+ char savec;
+
+ while (parsefile->strpush) {
+ /*
+ * Add a space to the end of an alias to ensure that the
+ * alias remains in use while parsing its last word.
+ * This avoids alias recursions.
+ */
+ if (parsenleft == -1 && parsefile->strpush->ap != NULL)
+ return ' ';
+ popstring();
+ if (--parsenleft >= 0)
+ return (*parsenextc++);
+ }
+ if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
+ return PEOF;
+
+ again:
+ if (parselleft <= 0 && (parselleft = preadfd()) == -1) {
+ parselleft = parsenleft = EOF_NLEFT;
+ return (PEOF);
+ }
+ end = parsenextc + parselleft;
+ q = strchrnul(parsenextc, '\n');
+ if (*q == '\0' && q != end) {
+ /* delete nul characters */
+ for (r = q++; q != end; q++)
+ if (*q != '\0')
+ *r++ = *q;
+ *r = '\0';
+ parselleft = r - parsenextc;
+ goto again;
+ }
+ if (*q == '\0') {
+ parsenleft = parselleft;
+ parselleft = 0;
+ } else /* *q == '\n' */ {
+ q++;
+ parsenleft = q - parsenextc;
+ parselleft -= parsenleft;
+ }
+ parsenleft--;
+
+ savec = *q;
+ *q = '\0';
+
+#ifndef NO_HISTORY
+ if (parsefile->fd == 0 && hist &&
+ parsenextc[strspn(parsenextc, " \t\n")] != '\0') {
+ HistEvent he;
+ INTOFF;
+ history(hist, &he, whichprompt == 1 ? H_ENTER : H_ADD,
+ parsenextc);
+ INTON;
+ }
+#endif
+
+ if (vflag) {
+ out2str(parsenextc);
+ flushout(out2);
+ }
+
+ *q = savec;
+
+ return *parsenextc++;
+}
+
+/*
+ * Returns if we are certain we are at EOF. Does not cause any more input
+ * to be read from the outside world.
+ */
+
+int
+preadateof(void)
+{
+ if (parsenleft > 0)
+ return 0;
+ if (parsefile->strpush)
+ return 0;
+ if (parsenleft == EOF_NLEFT || parsefile->buf == NULL)
+ return 1;
+ return 0;
+}
+
+/*
+ * Undo the last call to pgetc. Only one character may be pushed back.
+ * PEOF may be pushed back.
+ */
+
+void
+pungetc(void)
+{
+ parsenleft++;
+ parsenextc--;
+}
+
+/*
+ * Push a string back onto the input at this current parsefile level.
+ * We handle aliases this way.
+ */
+void
+pushstring(const char *s, int len, struct alias *ap)
+{
+ struct strpush *sp;
+
+ INTOFF;
+/*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/
+ if (parsefile->strpush) {
+ sp = ckmalloc(sizeof(struct strpush));
+ sp->prev = parsefile->strpush;
+ parsefile->strpush = sp;
+ } else
+ sp = parsefile->strpush = &(parsefile->basestrpush);
+ sp->prevstring = parsenextc;
+ sp->prevnleft = parsenleft;
+ sp->prevlleft = parselleft;
+ sp->ap = ap;
+ if (ap)
+ ap->flag |= ALIASINUSE;
+ parsenextc = s;
+ parsenleft = len;
+ INTON;
+}
+
+static void
+popstring(void)
+{
+ struct strpush *sp = parsefile->strpush;
+
+ INTOFF;
+ if (sp->ap) {
+ if (parsenextc != sp->ap->val &&
+ (parsenextc[-1] == ' ' || parsenextc[-1] == '\t'))
+ forcealias();
+ sp->ap->flag &= ~ALIASINUSE;
+ }
+ parsenextc = sp->prevstring;
+ parsenleft = sp->prevnleft;
+ parselleft = sp->prevlleft;
+/*out2fmt_flush("*** calling popstring: restoring to '%s'\n", parsenextc);*/
+ parsefile->strpush = sp->prev;
+ if (sp != &(parsefile->basestrpush))
+ ckfree(sp);
+ INTON;
+}
+
+/*
+ * Set the input to take input from a file. If push is set, push the
+ * old input onto the stack first.
+ * About verify:
+ * -1: Obey verifyflag
+ * 0: Do not verify
+ * 1: Do verify
+ */
+
+void
+setinputfile(const char *fname, int push, int verify)
+{
+ int e;
+ int fd;
+ int fd2;
+ int oflags = O_RDONLY | O_CLOEXEC;
+
+ if (verify == 1 || (verify == -1 && verifyflag))
+ oflags |= O_VERIFY;
+
+ INTOFF;
+ if ((fd = open(fname, oflags)) < 0) {
+ e = errno;
+ errorwithstatus(e == ENOENT || e == ENOTDIR ? 127 : 126,
+ "cannot open %s: %s", fname, strerror(e));
+ }
+ if (fd < 10) {
+ fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 10);
+ close(fd);
+ if (fd2 < 0)
+ error("Out of file descriptors");
+ fd = fd2;
+ }
+ setinputfd(fd, push);
+ INTON;
+}
+
+
+/*
+ * Like setinputfile, but takes an open file descriptor (which should have
+ * its FD_CLOEXEC flag already set). Call this with interrupts off.
+ */
+
+void
+setinputfd(int fd, int push)
+{
+ if (push)
+ pushfile();
+ if (parsefile->fd > 0)
+ close(parsefile->fd);
+ parsefile->fd = fd;
+ if (parsefile->buf == NULL) {
+ parsefile->buf = ckmalloc(BUFSIZ + 1);
+ parsefile->bufsize = BUFSIZ + 1;
+ }
+ parselleft = parsenleft = 0;
+ plinno = 1;
+}
+
+
+/*
+ * Like setinputfile, but takes input from a string.
+ */
+
+void
+setinputstring(const char *string)
+{
+ INTOFF;
+ pushfile();
+ parsenextc = string;
+ parselleft = parsenleft = strlen(string);
+ plinno = 1;
+ INTON;
+}
+
+
+
+/*
+ * To handle the "." command, a stack of input files is used. Pushfile
+ * adds a new entry to the stack and popfile restores the previous level.
+ */
+
+static void
+pushfile(void)
+{
+ struct parsefile *pf;
+
+ pf = (struct parsefile *)ckmalloc(sizeof(struct parsefile));
+ *pf = (struct parsefile){ .prev = parsefile, .fd = -1 };
+ parsefile->nleft = parsenleft;
+ parsefile->lleft = parselleft;
+ parsefile->nextc = parsenextc;
+ parsefile->linno = plinno;
+ parsefile = pf;
+}
+
+
+void
+popfile(void)
+{
+ struct parsefile *pf = parsefile;
+
+ INTOFF;
+ if (pf->fd >= 0)
+ close(pf->fd);
+ if (pf->buf)
+ ckfree(pf->buf);
+ while (pf->strpush)
+ popstring();
+ parsefile = pf->prev;
+ ckfree(pf);
+ parsenleft = parsefile->nleft;
+ parselleft = parsefile->lleft;
+ parsenextc = parsefile->nextc;
+ plinno = parsefile->linno;
+ INTON;
+}
+
+
+/*
+ * Return current file (to go back to it later using popfilesupto()).
+ */
+
+struct parsefile *
+getcurrentfile(void)
+{
+ return parsefile;
+}
+
+
+/*
+ * Pop files until the given file is on top again. Useful for regular
+ * builtins that read shell commands from files or strings.
+ * If the given file is not an active file, an error is raised.
+ */
+
+void
+popfilesupto(struct parsefile *file)
+{
+ while (parsefile != file && parsefile != &basepf)
+ popfile();
+ if (parsefile != file)
+ error("popfilesupto() misused");
+}
+
+/*
+ * Return to top level.
+ */
+
+void
+popallfiles(void)
+{
+ while (parsefile != &basepf)
+ popfile();
+}
+
+
+
+/*
+ * Close the file(s) that the shell is reading commands from. Called
+ * after a fork is done.
+ */
+
+void
+closescript(void)
+{
+ popallfiles();
+ if (parsefile->fd > 0) {
+ close(parsefile->fd);
+ parsefile->fd = 0;
+ }
+}
diff --git a/cmd/posix/sh/input.h b/cmd/posix/sh/input.h
@@ -0,0 +1,64 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* PEOF (the end of file marker) is defined in syntax.h */
+
+/*
+ * The input line number. Input.c just defines this variable, and saves
+ * and restores it when files are pushed and popped. The user of this
+ * package must set its value.
+ */
+extern int plinno;
+extern int parsenleft; /* number of characters left in input buffer */
+extern const char *parsenextc; /* next character in input buffer */
+
+struct alias;
+struct parsefile;
+
+void resetinput(void);
+int pgetc(void);
+int preadbuffer(void);
+int preadateof(void);
+void pungetc(void);
+void pushstring(const char *, int, struct alias *);
+void setinputfile(const char *, int, int);
+void setinputfd(int, int);
+void setinputstring(const char *);
+void popfile(void);
+struct parsefile *getcurrentfile(void);
+void popfilesupto(struct parsefile *);
+void popallfiles(void);
+void closescript(void);
+
+#define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
diff --git a/cmd/posix/sh/jobs.c b/cmd/posix/sh/jobs.c
@@ -0,0 +1,1578 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/ioctl.h>
+#include <sys/param.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <paths.h>
+#include <signal.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "shell.h"
+#if JOBS
+#include <termios.h>
+#undef CEOF /* syntax.h redefines this */
+#endif
+#include "redir.h"
+#include "exec.h"
+#include "show.h"
+#include "main.h"
+#include "parser.h"
+#include "nodes.h"
+#include "jobs.h"
+#include "options.h"
+#include "trap.h"
+#include "syntax.h"
+#include "input.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "var.h"
+#include "builtins.h"
+#include "eval.h"
+
+
+/*
+ * A job structure contains information about a job. A job is either a
+ * single process or a set of processes contained in a pipeline. In the
+ * latter case, pidlist will be non-NULL, and will point to a -1 terminated
+ * array of pids.
+ */
+
+struct procstat {
+ pid_t pid; /* process id */
+ int status; /* status flags (defined above) */
+ char *cmd; /* text of command being run */
+};
+
+
+/* states */
+#define JOBSTOPPED 1 /* all procs are stopped */
+#define JOBDONE 2 /* all procs are completed */
+
+
+struct job {
+ struct procstat ps0; /* status of process */
+ struct procstat *ps; /* status or processes when more than one */
+ short nprocs; /* number of processes */
+ pid_t pgrp; /* process group of this job */
+ char state; /* true if job is finished */
+ char used; /* true if this entry is in use */
+ char changed; /* true if status has changed */
+ char foreground; /* true if running in the foreground */
+ char remembered; /* true if $! referenced */
+ char pipefail; /* pass any non-zero status */
+#if JOBS
+ char jobctl; /* job running under job control */
+ struct job *next; /* job used after this one */
+#endif
+};
+
+
+static struct job *jobtab; /* array of jobs */
+static int njobs; /* size of array */
+static pid_t backgndpid = -1; /* pid of last background process */
+static struct job *bgjob = NULL; /* last background process */
+#if JOBS
+static struct job *jobmru; /* most recently used job list */
+static pid_t initialpgrp; /* pgrp of shell on invocation */
+#endif
+static int ttyfd = -1;
+
+/* mode flags for dowait */
+#define DOWAIT_BLOCK 0x1 /* wait until a child exits */
+#define DOWAIT_SIG 0x2 /* if DOWAIT_BLOCK, abort on signal */
+#define DOWAIT_SIG_TRAP 0x4 /* if DOWAIT_SIG, abort on trapped signal only */
+
+#if JOBS
+static void restartjob(struct job *);
+#endif
+static void freejob(struct job *);
+static int waitcmdloop(struct job *);
+static struct job *getjob_nonotfound(const char *);
+static struct job *getjob(const char *);
+pid_t killjob(const char *, int);
+static pid_t dowait(int, struct job *);
+static void checkzombies(void);
+static void cmdtxt(union node *);
+static void cmdputs(const char *);
+#if JOBS
+static void setcurjob(struct job *);
+static void deljob(struct job *);
+static struct job *getcurjob(struct job *);
+#endif
+static int getjobstatus(const struct job *);
+static void printjobcmd(struct job *);
+static void showjob(struct job *, int);
+
+
+/*
+ * Turn job control on and off.
+ */
+
+static int jobctl;
+
+#if JOBS
+static void
+jobctl_notty(void)
+{
+ if (ttyfd >= 0) {
+ close(ttyfd);
+ ttyfd = -1;
+ }
+ if (!iflag) {
+ setsignal(SIGTSTP);
+ setsignal(SIGTTOU);
+ setsignal(SIGTTIN);
+ jobctl = 1;
+ return;
+ }
+ out2fmt_flush("sh: can't access tty; job control turned off\n");
+ mflag = 0;
+}
+
+void
+setjobctl(int on)
+{
+ int i;
+
+ if (on == jobctl || rootshell == 0)
+ return;
+ if (on) {
+ if (ttyfd != -1)
+ close(ttyfd);
+ if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) {
+ i = 0;
+ while (i <= 2 && !isatty(i))
+ i++;
+ if (i > 2 ||
+ (ttyfd = fcntl(i, F_DUPFD_CLOEXEC, 10)) < 0) {
+ jobctl_notty();
+ return;
+ }
+ }
+ if (ttyfd < 10) {
+ /*
+ * Keep our TTY file descriptor out of the way of
+ * the user's redirections.
+ */
+ if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) {
+ jobctl_notty();
+ return;
+ }
+ close(ttyfd);
+ ttyfd = i;
+ }
+ do { /* while we are in the background */
+ initialpgrp = tcgetpgrp(ttyfd);
+ if (initialpgrp < 0) {
+ jobctl_notty();
+ return;
+ }
+ if (initialpgrp != getpgrp()) {
+ if (!iflag) {
+ initialpgrp = -1;
+ jobctl_notty();
+ return;
+ }
+ kill(0, SIGTTIN);
+ continue;
+ }
+ } while (0);
+ setsignal(SIGTSTP);
+ setsignal(SIGTTOU);
+ setsignal(SIGTTIN);
+ setpgid(0, rootpid);
+ tcsetpgrp(ttyfd, rootpid);
+ } else { /* turning job control off */
+ setpgid(0, initialpgrp);
+ if (ttyfd >= 0) {
+ tcsetpgrp(ttyfd, initialpgrp);
+ close(ttyfd);
+ ttyfd = -1;
+ }
+ setsignal(SIGTSTP);
+ setsignal(SIGTTOU);
+ setsignal(SIGTTIN);
+ }
+ jobctl = on;
+}
+#endif
+
+
+#if JOBS
+int
+fgcmd(int argc __unused, char **argv __unused)
+{
+ struct job *jp;
+ pid_t pgrp;
+ int status;
+
+ nextopt("");
+ jp = getjob(*argptr);
+ if (jp->jobctl == 0)
+ error("job not created under job control");
+ printjobcmd(jp);
+ flushout(&output);
+ pgrp = jp->ps[0].pid;
+ if (ttyfd >= 0)
+ tcsetpgrp(ttyfd, pgrp);
+ restartjob(jp);
+ jp->foreground = 1;
+ INTOFF;
+ status = waitforjob(jp, (int *)NULL);
+ INTON;
+ return status;
+}
+
+
+int
+bgcmd(int argc __unused, char **argv __unused)
+{
+ struct job *jp;
+
+ nextopt("");
+ do {
+ jp = getjob(*argptr);
+ if (jp->jobctl == 0)
+ error("job not created under job control");
+ if (jp->state == JOBDONE)
+ continue;
+ restartjob(jp);
+ jp->foreground = 0;
+ out1fmt("[%td] ", jp - jobtab + 1);
+ printjobcmd(jp);
+ } while (*argptr != NULL && *++argptr != NULL);
+ return 0;
+}
+
+
+static void
+restartjob(struct job *jp)
+{
+ struct procstat *ps;
+ int i;
+
+ if (jp->state == JOBDONE)
+ return;
+ setcurjob(jp);
+ INTOFF;
+ kill(-jp->ps[0].pid, SIGCONT);
+ for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
+ if (WIFSTOPPED(ps->status)) {
+ ps->status = -1;
+ jp->state = 0;
+ }
+ }
+ INTON;
+}
+#endif
+
+
+int
+jobscmd(int argc __unused, char *argv[] __unused)
+{
+ char *id;
+ int ch, mode;
+
+ mode = SHOWJOBS_DEFAULT;
+ while ((ch = nextopt("lps")) != '\0') {
+ switch (ch) {
+ case 'l':
+ mode = SHOWJOBS_VERBOSE;
+ break;
+ case 'p':
+ mode = SHOWJOBS_PGIDS;
+ break;
+ case 's':
+ mode = SHOWJOBS_PIDS;
+ break;
+ }
+ }
+
+ if (*argptr == NULL)
+ showjobs(0, mode);
+ else
+ while ((id = *argptr++) != NULL)
+ showjob(getjob(id), mode);
+
+ return (0);
+}
+
+static int getjobstatus(const struct job *jp)
+{
+ int i, status;
+
+ if (!jp->pipefail)
+ return (jp->ps[jp->nprocs - 1].status);
+ for (i = jp->nprocs - 1; i >= 0; i--) {
+ status = jp->ps[i].status;
+ if (status != 0)
+ return (status);
+ }
+ return (0);
+}
+
+static void
+printjobcmd(struct job *jp)
+{
+ struct procstat *ps;
+ int i;
+
+ for (ps = jp->ps, i = jp->nprocs ; --i >= 0 ; ps++) {
+ out1str(ps->cmd);
+ if (i > 0)
+ out1str(" | ");
+ }
+ out1c('\n');
+}
+
+static void
+showjob(struct job *jp, int mode)
+{
+ char s[64];
+ char statebuf[16];
+ const char *statestr, *coredump;
+ struct procstat *ps;
+ struct job *j;
+ int col, curr, i, jobno, prev, procno, status;
+ char c;
+
+ procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
+ jobno = jp - jobtab + 1;
+ curr = prev = 0;
+#if JOBS
+ if ((j = getcurjob(NULL)) != NULL) {
+ curr = j - jobtab + 1;
+ if ((j = getcurjob(j)) != NULL)
+ prev = j - jobtab + 1;
+ }
+#endif
+ coredump = "";
+ status = getjobstatus(jp);
+ if (jp->state == 0) {
+ statestr = "Running";
+#if JOBS
+ } else if (jp->state == JOBSTOPPED) {
+ ps = jp->ps + jp->nprocs - 1;
+ while (!WIFSTOPPED(ps->status) && ps > jp->ps)
+ ps--;
+ if (WIFSTOPPED(ps->status))
+ i = WSTOPSIG(ps->status);
+ else
+ i = -1;
+ statestr = strsignal(i);
+ if (statestr == NULL)
+ statestr = "Suspended";
+#endif
+ } else if (WIFEXITED(status)) {
+ if (WEXITSTATUS(status) == 0)
+ statestr = "Done";
+ else {
+ fmtstr(statebuf, sizeof(statebuf), "Done(%d)",
+ WEXITSTATUS(status));
+ statestr = statebuf;
+ }
+ } else {
+ i = WTERMSIG(status);
+ statestr = strsignal(i);
+ if (statestr == NULL)
+ statestr = "Unknown signal";
+ if (WCOREDUMP(status))
+ coredump = " (core dumped)";
+ }
+
+ for (ps = jp->ps ; procno > 0 ; ps++, procno--) { /* for each process */
+ if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
+ out1fmt("%d\n", (int)ps->pid);
+ continue;
+ }
+ if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
+ continue;
+ if (jobno == curr && ps == jp->ps)
+ c = '+';
+ else if (jobno == prev && ps == jp->ps)
+ c = '-';
+ else
+ c = ' ';
+ if (ps == jp->ps)
+ fmtstr(s, 64, "[%d] %c ", jobno, c);
+ else
+ fmtstr(s, 64, " %c ", c);
+ out1str(s);
+ col = strlen(s);
+ if (mode == SHOWJOBS_VERBOSE) {
+ fmtstr(s, 64, "%d ", (int)ps->pid);
+ out1str(s);
+ col += strlen(s);
+ }
+ if (ps == jp->ps) {
+ out1str(statestr);
+ out1str(coredump);
+ col += strlen(statestr) + strlen(coredump);
+ }
+ do {
+ out1c(' ');
+ col++;
+ } while (col < 30);
+ if (mode == SHOWJOBS_VERBOSE) {
+ out1str(ps->cmd);
+ out1c('\n');
+ } else
+ printjobcmd(jp);
+ }
+}
+
+/*
+ * Print a list of jobs. If "change" is nonzero, only print jobs whose
+ * statuses have changed since the last call to showjobs.
+ *
+ * If the shell is interrupted in the process of creating a job, the
+ * result may be a job structure containing zero processes. Such structures
+ * will be freed here.
+ */
+
+void
+showjobs(int change, int mode)
+{
+ int jobno;
+ struct job *jp;
+
+ TRACE(("showjobs(%d) called\n", change));
+ checkzombies();
+ for (jobno = 1, jp = jobtab ; jobno <= njobs ; jobno++, jp++) {
+ if (! jp->used)
+ continue;
+ if (jp->nprocs == 0) {
+ freejob(jp);
+ continue;
+ }
+ if (change && ! jp->changed)
+ continue;
+ showjob(jp, mode);
+ if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) {
+ jp->changed = 0;
+ /* Hack: discard jobs for which $! has not been
+ * referenced in interactive mode when they terminate.
+ */
+ if (jp->state == JOBDONE && !jp->remembered &&
+ (iflag || jp != bgjob)) {
+ freejob(jp);
+ }
+ }
+ }
+}
+
+
+/*
+ * Mark a job structure as unused.
+ */
+
+static void
+freejob(struct job *jp)
+{
+ struct procstat *ps;
+ int i;
+
+ INTOFF;
+ if (bgjob == jp)
+ bgjob = NULL;
+ for (i = jp->nprocs, ps = jp->ps ; --i >= 0 ; ps++) {
+ if (ps->cmd != nullstr)
+ ckfree(ps->cmd);
+ }
+ if (jp->ps != &jp->ps0)
+ ckfree(jp->ps);
+ jp->used = 0;
+#if JOBS
+ deljob(jp);
+#endif
+ INTON;
+}
+
+
+
+int
+waitcmd(int argc __unused, char **argv __unused)
+{
+ struct job *job;
+ int retval;
+
+ nextopt("");
+ if (*argptr == NULL)
+ return (waitcmdloop(NULL));
+
+ do {
+ job = getjob_nonotfound(*argptr);
+ if (job == NULL)
+ retval = 127;
+ else
+ retval = waitcmdloop(job);
+ argptr++;
+ } while (*argptr != NULL);
+
+ return (retval);
+}
+
+static int
+waitcmdloop(struct job *job)
+{
+ int status, retval, sig;
+ struct job *jp;
+
+ /*
+ * Loop until a process is terminated or stopped, or a SIGINT is
+ * received.
+ */
+
+ do {
+ if (job != NULL) {
+ if (job->state == JOBDONE) {
+ status = getjobstatus(job);
+ if (WIFEXITED(status))
+ retval = WEXITSTATUS(status);
+ else
+ retval = WTERMSIG(status) + 128;
+ if (! iflag || ! job->changed)
+ freejob(job);
+ else {
+ job->remembered = 0;
+ deljob(job);
+ if (job == bgjob)
+ bgjob = NULL;
+ }
+ return retval;
+ }
+ } else {
+ if (njobs == 0)
+ return 0;
+ for (jp = jobtab ; jp < jobtab + njobs; jp++)
+ if (jp->used && jp->state == JOBDONE) {
+ if (! iflag || ! jp->changed)
+ freejob(jp);
+ else {
+ jp->remembered = 0;
+ if (jp == bgjob)
+ bgjob = NULL;
+ }
+ }
+ for (jp = jobtab ; ; jp++) {
+ if (jp >= jobtab + njobs) { /* no running procs */
+ return 0;
+ }
+ if (jp->used && jp->state == 0)
+ break;
+ }
+ }
+ } while (dowait(DOWAIT_BLOCK | DOWAIT_SIG, job) != -1);
+
+ sig = pendingsig_waitcmd;
+ pendingsig_waitcmd = 0;
+ return sig + 128;
+}
+
+
+
+int
+jobidcmd(int argc __unused, char **argv __unused)
+{
+ struct job *jp;
+ int i;
+
+ nextopt("");
+ jp = getjob(*argptr);
+ for (i = 0 ; i < jp->nprocs ; ) {
+ out1fmt("%d", (int)jp->ps[i].pid);
+ out1c(++i < jp->nprocs? ' ' : '\n');
+ }
+ return 0;
+}
+
+
+
+/*
+ * Convert a job name to a job structure.
+ */
+
+static struct job *
+getjob_nonotfound(const char *name)
+{
+ int jobno;
+ struct job *found, *jp;
+ size_t namelen;
+ pid_t pid;
+ int i;
+
+ if (name == NULL) {
+#if JOBS
+ name = "%+";
+#else
+ error("No current job");
+#endif
+ }
+ if (name[0] == '%') {
+ if (is_digit(name[1])) {
+ jobno = number(name + 1);
+ if (jobno > 0 && jobno <= njobs
+ && jobtab[jobno - 1].used != 0)
+ return &jobtab[jobno - 1];
+#if JOBS
+ } else if ((name[1] == '%' || name[1] == '+') &&
+ name[2] == '\0') {
+ if ((jp = getcurjob(NULL)) == NULL)
+ error("No current job");
+ return (jp);
+ } else if (name[1] == '-' && name[2] == '\0') {
+ if ((jp = getcurjob(NULL)) == NULL ||
+ (jp = getcurjob(jp)) == NULL)
+ error("No previous job");
+ return (jp);
+#endif
+ } else if (name[1] == '?') {
+ found = NULL;
+ for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
+ if (jp->used && jp->nprocs > 0
+ && strstr(jp->ps[0].cmd, name + 2) != NULL) {
+ if (found)
+ error("%s: ambiguous", name);
+ found = jp;
+ }
+ }
+ if (found != NULL)
+ return (found);
+ } else {
+ namelen = strlen(name);
+ found = NULL;
+ for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
+ if (jp->used && jp->nprocs > 0
+ && strncmp(jp->ps[0].cmd, name + 1,
+ namelen - 1) == 0) {
+ if (found)
+ error("%s: ambiguous", name);
+ found = jp;
+ }
+ }
+ if (found)
+ return found;
+ }
+ } else if (is_number(name)) {
+ pid = (pid_t)number(name);
+ for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) {
+ if (jp->used && jp->nprocs > 0
+ && jp->ps[jp->nprocs - 1].pid == pid)
+ return jp;
+ }
+ }
+ return NULL;
+}
+
+
+static struct job *
+getjob(const char *name)
+{
+ struct job *jp;
+
+ jp = getjob_nonotfound(name);
+ if (jp == NULL)
+ error("No such job: %s", name);
+ return (jp);
+}
+
+
+int
+killjob(const char *name, int sig)
+{
+ struct job *jp;
+ int i, ret;
+
+ jp = getjob(name);
+ if (jp->state == JOBDONE)
+ return 0;
+ if (jp->jobctl)
+ return kill(-jp->ps[0].pid, sig);
+ ret = -1;
+ errno = ESRCH;
+ for (i = 0; i < jp->nprocs; i++)
+ if (jp->ps[i].status == -1 || WIFSTOPPED(jp->ps[i].status)) {
+ if (kill(jp->ps[i].pid, sig) == 0)
+ ret = 0;
+ } else
+ ret = 0;
+ return ret;
+}
+
+/*
+ * Return a new job structure,
+ */
+
+struct job *
+makejob(union node *node __unused, int nprocs)
+{
+ int i;
+ struct job *jp;
+
+ for (i = njobs, jp = jobtab ; ; jp++) {
+ if (--i < 0) {
+ INTOFF;
+ if (njobs == 0) {
+ jobtab = ckmalloc(4 * sizeof jobtab[0]);
+#if JOBS
+ jobmru = NULL;
+#endif
+ } else {
+ jp = ckmalloc((njobs + 4) * sizeof jobtab[0]);
+ memcpy(jp, jobtab, njobs * sizeof jp[0]);
+#if JOBS
+ /* Relocate `next' pointers and list head */
+ if (jobmru != NULL)
+ jobmru = &jp[jobmru - jobtab];
+ for (i = 0; i < njobs; i++)
+ if (jp[i].next != NULL)
+ jp[i].next = &jp[jp[i].next -
+ jobtab];
+#endif
+ if (bgjob != NULL)
+ bgjob = &jp[bgjob - jobtab];
+ /* Relocate `ps' pointers */
+ for (i = 0; i < njobs; i++)
+ if (jp[i].ps == &jobtab[i].ps0)
+ jp[i].ps = &jp[i].ps0;
+ ckfree(jobtab);
+ jobtab = jp;
+ }
+ jp = jobtab + njobs;
+ for (i = 4 ; --i >= 0 ; jobtab[njobs++].used = 0)
+ ;
+ INTON;
+ break;
+ }
+ if (jp->used == 0)
+ break;
+ }
+ INTOFF;
+ jp->state = 0;
+ jp->used = 1;
+ jp->changed = 0;
+ jp->nprocs = 0;
+ jp->foreground = 0;
+ jp->remembered = 0;
+ jp->pipefail = pipefailflag;
+#if JOBS
+ jp->jobctl = jobctl;
+ jp->next = NULL;
+#endif
+ if (nprocs > 1) {
+ jp->ps = ckmalloc(nprocs * sizeof (struct procstat));
+ } else {
+ jp->ps = &jp->ps0;
+ }
+ INTON;
+ TRACE(("makejob(%p, %d) returns %%%td\n", (void *)node, nprocs,
+ jp - jobtab + 1));
+ return jp;
+}
+
+#if JOBS
+static void
+setcurjob(struct job *cj)
+{
+ struct job *jp, *prev;
+
+ for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
+ if (jp == cj) {
+ if (prev != NULL)
+ prev->next = jp->next;
+ else
+ jobmru = jp->next;
+ jp->next = jobmru;
+ jobmru = cj;
+ return;
+ }
+ }
+ cj->next = jobmru;
+ jobmru = cj;
+}
+
+static void
+deljob(struct job *j)
+{
+ struct job *jp, *prev;
+
+ for (prev = NULL, jp = jobmru; jp != NULL; prev = jp, jp = jp->next) {
+ if (jp == j) {
+ if (prev != NULL)
+ prev->next = jp->next;
+ else
+ jobmru = jp->next;
+ return;
+ }
+ }
+}
+
+/*
+ * Return the most recently used job that isn't `nj', and preferably one
+ * that is stopped.
+ */
+static struct job *
+getcurjob(struct job *nj)
+{
+ struct job *jp;
+
+ /* Try to find a stopped one.. */
+ for (jp = jobmru; jp != NULL; jp = jp->next)
+ if (jp->used && jp != nj && jp->state == JOBSTOPPED)
+ return (jp);
+ /* Otherwise the most recently used job that isn't `nj' */
+ for (jp = jobmru; jp != NULL; jp = jp->next)
+ if (jp->used && jp != nj)
+ return (jp);
+
+ return (NULL);
+}
+
+#endif
+
+/*
+ * Fork of a subshell. If we are doing job control, give the subshell its
+ * own process group. Jp is a job structure that the job is to be added to.
+ * N is the command that will be evaluated by the child. Both jp and n may
+ * be NULL. The mode parameter can be one of the following:
+ * FORK_FG - Fork off a foreground process.
+ * FORK_BG - Fork off a background process.
+ * FORK_NOJOB - Like FORK_FG, but don't give the process its own
+ * process group even if job control is on.
+ *
+ * When job control is turned off, background processes have their standard
+ * input redirected to /dev/null (except for the second and later processes
+ * in a pipeline).
+ */
+
+pid_t
+forkshell(struct job *jp, union node *n, int mode)
+{
+ pid_t pid;
+ pid_t pgrp;
+
+ TRACE(("forkshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
+ mode));
+ INTOFF;
+ if (mode == FORK_BG && (jp == NULL || jp->nprocs == 0))
+ checkzombies();
+ flushall();
+ pid = fork();
+ if (pid == -1) {
+ TRACE(("Fork failed, errno=%d\n", errno));
+ INTON;
+ error("Cannot fork: %s", strerror(errno));
+ }
+ if (pid == 0) {
+ struct job *p;
+ int wasroot;
+ int i;
+
+ TRACE(("Child shell %d\n", (int)getpid()));
+ wasroot = rootshell;
+ rootshell = 0;
+ handler = &main_handler;
+ closescript();
+ INTON;
+ forcelocal = 0;
+ clear_traps();
+#if JOBS
+ jobctl = 0; /* do job control only in root shell */
+ if (wasroot && mode != FORK_NOJOB && mflag) {
+ if (jp == NULL || jp->nprocs == 0)
+ pgrp = getpid();
+ else
+ pgrp = jp->ps[0].pid;
+ if (setpgid(0, pgrp) == 0 && mode == FORK_FG &&
+ ttyfd >= 0) {
+ /*
+ * Each process in a pipeline must have the tty
+ * pgrp set before running its code.
+ * Only for pipelines of three or more processes
+ * could this be reduced to two calls.
+ */
+ if (tcsetpgrp(ttyfd, pgrp) < 0)
+ error("tcsetpgrp failed, errno=%d", errno);
+ }
+ setsignal(SIGTSTP);
+ setsignal(SIGTTOU);
+ } else if (mode == FORK_BG) {
+ ignoresig(SIGINT);
+ ignoresig(SIGQUIT);
+ if ((jp == NULL || jp->nprocs == 0) &&
+ ! fd0_redirected_p ()) {
+ close(0);
+ if (open(_PATH_DEVNULL, O_RDONLY) != 0)
+ error("cannot open %s: %s",
+ _PATH_DEVNULL, strerror(errno));
+ }
+ }
+#else
+ if (mode == FORK_BG) {
+ ignoresig(SIGINT);
+ ignoresig(SIGQUIT);
+ if ((jp == NULL || jp->nprocs == 0) &&
+ ! fd0_redirected_p ()) {
+ close(0);
+ if (open(_PATH_DEVNULL, O_RDONLY) != 0)
+ error("cannot open %s: %s",
+ _PATH_DEVNULL, strerror(errno));
+ }
+ }
+#endif
+ INTOFF;
+ for (i = njobs, p = jobtab ; --i >= 0 ; p++)
+ if (p->used)
+ freejob(p);
+ INTON;
+ if (wasroot && iflag) {
+ setsignal(SIGINT);
+ setsignal(SIGQUIT);
+ setsignal(SIGTERM);
+ }
+ return pid;
+ }
+ if (rootshell && mode != FORK_NOJOB && mflag) {
+ if (jp == NULL || jp->nprocs == 0)
+ pgrp = pid;
+ else
+ pgrp = jp->ps[0].pid;
+ setpgid(pid, pgrp);
+ }
+ if (mode == FORK_BG) {
+ if (bgjob != NULL && bgjob->state == JOBDONE &&
+ !bgjob->remembered && !iflag)
+ freejob(bgjob);
+ backgndpid = pid; /* set $! */
+ bgjob = jp;
+ }
+ if (jp) {
+ struct procstat *ps = &jp->ps[jp->nprocs++];
+ ps->pid = pid;
+ ps->status = -1;
+ ps->cmd = nullstr;
+ if (iflag && rootshell && n)
+ ps->cmd = commandtext(n);
+ jp->foreground = mode == FORK_FG;
+#if JOBS
+ setcurjob(jp);
+#endif
+ }
+ INTON;
+ TRACE(("In parent shell: child = %d\n", (int)pid));
+ return pid;
+}
+
+
+pid_t
+vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int idx, int pip[2])
+{
+ pid_t pid;
+ struct jmploc jmploc;
+ struct jmploc *savehandler;
+ int inton;
+
+ TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
+ (void *)pip));
+ inton = is_int_on();
+ INTOFF;
+ flushall();
+ savehandler = handler;
+ pid = vfork();
+ if (pid == -1) {
+ TRACE(("Vfork failed, errno=%d\n", errno));
+ INTON;
+ error("Cannot fork: %s", strerror(errno));
+ }
+ if (pid == 0) {
+ TRACE(("Child shell %d\n", (int)getpid()));
+ if (setjmp(jmploc.loc))
+ _exit(exitstatus);
+ if (pip != NULL) {
+ close(pip[0]);
+ if (pip[1] != 1) {
+ dup2(pip[1], 1);
+ close(pip[1]);
+ }
+ }
+ handler = &jmploc;
+ shellexec(argv, envp, path, idx);
+ }
+ handler = savehandler;
+ if (jp) {
+ struct procstat *ps = &jp->ps[jp->nprocs++];
+ ps->pid = pid;
+ ps->status = -1;
+ ps->cmd = nullstr;
+ jp->foreground = 1;
+#if JOBS
+ setcurjob(jp);
+#endif
+ }
+ SETINTON(inton);
+ TRACE(("In parent shell: child = %d\n", (int)pid));
+ return pid;
+}
+
+
+/*
+ * Wait for job to finish.
+ *
+ * Under job control we have the problem that while a child process is
+ * running interrupts generated by the user are sent to the child but not
+ * to the shell. This means that an infinite loop started by an inter-
+ * active user may be hard to kill. With job control turned off, an
+ * interactive user may place an interactive program inside a loop. If
+ * the interactive program catches interrupts, the user doesn't want
+ * these interrupts to also abort the loop. The approach we take here
+ * is to have the shell ignore interrupt signals while waiting for a
+ * foreground process to terminate, and then send itself an interrupt
+ * signal if the child process was terminated by an interrupt signal.
+ * Unfortunately, some programs want to do a bit of cleanup and then
+ * exit on interrupt; unless these processes terminate themselves by
+ * sending a signal to themselves (instead of calling exit) they will
+ * confuse this approach.
+ */
+
+int
+waitforjob(struct job *jp, int *signaled)
+{
+#if JOBS
+ int propagate_int = jp->jobctl && jp->foreground;
+#endif
+ int jobindex;
+ int status;
+ int st;
+
+ INTOFF;
+ TRACE(("waitforjob(%%%td) called\n", jp - jobtab + 1));
+ while (jp->state == 0)
+ if (dowait(DOWAIT_BLOCK | (Tflag ? DOWAIT_SIG |
+ DOWAIT_SIG_TRAP : 0), jp) == -1) {
+ jobindex = jp - jobtab;
+ dotrap();
+ jp = jobtab + jobindex;
+ }
+#if JOBS
+ if (jp->jobctl) {
+ if (ttyfd >= 0 && tcsetpgrp(ttyfd, rootpid) < 0)
+ error("tcsetpgrp failed, errno=%d\n", errno);
+ }
+ if (jp->state == JOBSTOPPED)
+ setcurjob(jp);
+#endif
+ status = getjobstatus(jp);
+ if (signaled != NULL)
+ *signaled = WIFSIGNALED(status);
+ /* convert to 8 bits */
+ if (WIFEXITED(status))
+ st = WEXITSTATUS(status);
+#if JOBS
+ else if (WIFSTOPPED(status))
+ st = WSTOPSIG(status) + 128;
+#endif
+ else
+ st = WTERMSIG(status) + 128;
+ if (! JOBS || jp->state == JOBDONE)
+ freejob(jp);
+ if (int_pending()) {
+ if (!WIFSIGNALED(status) || WTERMSIG(status) != SIGINT)
+ CLEAR_PENDING_INT;
+ }
+#if JOBS
+ else if (rootshell && propagate_int &&
+ WIFSIGNALED(status) && WTERMSIG(status) == SIGINT)
+ kill(getpid(), SIGINT);
+#endif
+ INTON;
+ return st;
+}
+
+
+static void
+dummy_handler(int sig __unused)
+{
+}
+
+/*
+ * Wait for a process to terminate.
+ */
+
+static pid_t
+dowait(int mode, struct job *job)
+{
+ struct sigaction sa, osa;
+ sigset_t mask, omask;
+ pid_t pid;
+ int status;
+ struct procstat *sp;
+ struct job *jp;
+ struct job *thisjob;
+ const char *sigstr;
+ int done;
+ int stopped;
+ int sig;
+ int coredump;
+ int wflags;
+ int restore_sigchld;
+
+ TRACE(("dowait(%d, %p) called\n", mode, job));
+ restore_sigchld = 0;
+ if ((mode & DOWAIT_SIG) != 0) {
+ sigfillset(&mask);
+ sigprocmask(SIG_BLOCK, &mask, &omask);
+ INTOFF;
+ if (!issigchldtrapped()) {
+ restore_sigchld = 1;
+ sa.sa_handler = dummy_handler;
+ sa.sa_flags = 0;
+ sigemptyset(&sa.sa_mask);
+ sigaction(SIGCHLD, &sa, &osa);
+ }
+ }
+ do {
+#if JOBS
+ if (iflag)
+ wflags = WUNTRACED | WCONTINUED;
+ else
+#endif
+ wflags = 0;
+ if ((mode & (DOWAIT_BLOCK | DOWAIT_SIG)) != DOWAIT_BLOCK)
+ wflags |= WNOHANG;
+ pid = wait3(&status, wflags, (struct rusage *)NULL);
+ TRACE(("wait returns %d, status=%d\n", (int)pid, status));
+ if (pid == 0 && (mode & DOWAIT_SIG) != 0) {
+ pid = -1;
+ if (((mode & DOWAIT_SIG_TRAP) != 0 ?
+ pendingsig : pendingsig_waitcmd) != 0) {
+ errno = EINTR;
+ break;
+ }
+ sigsuspend(&omask);
+ if (int_pending())
+ break;
+ }
+ } while (pid == -1 && errno == EINTR);
+ if (pid == -1 && errno == ECHILD && job != NULL)
+ job->state = JOBDONE;
+ if ((mode & DOWAIT_SIG) != 0) {
+ if (restore_sigchld)
+ sigaction(SIGCHLD, &osa, NULL);
+ sigprocmask(SIG_SETMASK, &omask, NULL);
+ INTON;
+ }
+ if (pid <= 0)
+ return pid;
+ INTOFF;
+ thisjob = NULL;
+ for (jp = jobtab ; jp < jobtab + njobs ; jp++) {
+ if (jp->used && jp->nprocs > 0) {
+ done = 1;
+ stopped = 1;
+ for (sp = jp->ps ; sp < jp->ps + jp->nprocs ; sp++) {
+ if (sp->pid == -1)
+ continue;
+ if (sp->pid == pid && (sp->status == -1 ||
+ WIFSTOPPED(sp->status))) {
+ TRACE(("Changing status of proc %d from 0x%x to 0x%x\n",
+ (int)pid, sp->status,
+ status));
+ if (WIFCONTINUED(status)) {
+ sp->status = -1;
+ jp->state = 0;
+ } else
+ sp->status = status;
+ thisjob = jp;
+ }
+ if (sp->status == -1)
+ stopped = 0;
+ else if (WIFSTOPPED(sp->status))
+ done = 0;
+ }
+ if (stopped) { /* stopped or done */
+ int state = done? JOBDONE : JOBSTOPPED;
+ if (jp->state != state) {
+ TRACE(("Job %td: changing state from %d to %d\n", jp - jobtab + 1, jp->state, state));
+ jp->state = state;
+ if (jp != job) {
+ if (done && !jp->remembered &&
+ !iflag && jp != bgjob)
+ freejob(jp);
+#if JOBS
+ else if (done)
+ deljob(jp);
+#endif
+ }
+ }
+ }
+ }
+ }
+ INTON;
+ if (!thisjob || thisjob->state == 0)
+ ;
+ else if ((!rootshell || !iflag || thisjob == job) &&
+ thisjob->foreground && thisjob->state != JOBSTOPPED) {
+ sig = 0;
+ coredump = 0;
+ for (sp = thisjob->ps; sp < thisjob->ps + thisjob->nprocs; sp++)
+ if (WIFSIGNALED(sp->status)) {
+ sig = WTERMSIG(sp->status);
+ coredump = WCOREDUMP(sp->status);
+ }
+ if (sig > 0 && sig != SIGINT && sig != SIGPIPE) {
+ sigstr = strsignal(sig);
+ if (sigstr != NULL)
+ out2str(sigstr);
+ else
+ out2str("Unknown signal");
+ if (coredump)
+ out2str(" (core dumped)");
+ out2c('\n');
+ flushout(out2);
+ }
+ } else {
+ TRACE(("Not printing status, rootshell=%d, job=%p\n", rootshell, job));
+ thisjob->changed = 1;
+ }
+ return pid;
+}
+
+
+
+/*
+ * return 1 if there are stopped jobs, otherwise 0
+ */
+int job_warning = 0;
+int
+stoppedjobs(void)
+{
+ int jobno;
+ struct job *jp;
+
+ if (job_warning)
+ return (0);
+ for (jobno = 1, jp = jobtab; jobno <= njobs; jobno++, jp++) {
+ if (jp->used == 0)
+ continue;
+ if (jp->state == JOBSTOPPED) {
+ out2fmt_flush("You have stopped jobs.\n");
+ job_warning = 2;
+ return (1);
+ }
+ }
+
+ return (0);
+}
+
+
+static void
+checkzombies(void)
+{
+ while (njobs > 0 && dowait(0, NULL) > 0)
+ ;
+}
+
+
+int
+backgndpidset(void)
+{
+ return backgndpid != -1;
+}
+
+
+pid_t
+backgndpidval(void)
+{
+ if (bgjob != NULL && !forcelocal)
+ bgjob->remembered = 1;
+ return backgndpid;
+}
+
+/*
+ * Return a string identifying a command (to be printed by the
+ * jobs command.
+ */
+
+static char *cmdnextc;
+static int cmdnleft;
+#define MAXCMDTEXT 200
+
+char *
+commandtext(union node *n)
+{
+ char *name;
+
+ cmdnextc = name = ckmalloc(MAXCMDTEXT);
+ cmdnleft = MAXCMDTEXT - 4;
+ cmdtxt(n);
+ *cmdnextc = '\0';
+ return name;
+}
+
+
+static void
+cmdtxtdogroup(union node *n)
+{
+ cmdputs("; do ");
+ cmdtxt(n);
+ cmdputs("; done");
+}
+
+
+static void
+cmdtxtredir(union node *n, const char *op, int deffd)
+{
+ char s[2];
+
+ if (n->nfile.fd != deffd) {
+ s[0] = n->nfile.fd + '0';
+ s[1] = '\0';
+ cmdputs(s);
+ }
+ cmdputs(op);
+ if (n->type == NTOFD || n->type == NFROMFD) {
+ if (n->ndup.dupfd >= 0)
+ s[0] = n->ndup.dupfd + '0';
+ else
+ s[0] = '-';
+ s[1] = '\0';
+ cmdputs(s);
+ } else {
+ cmdtxt(n->nfile.fname);
+ }
+}
+
+
+static void
+cmdtxt(union node *n)
+{
+ union node *np;
+ struct nodelist *lp;
+
+ if (n == NULL)
+ return;
+ switch (n->type) {
+ case NSEMI:
+ cmdtxt(n->nbinary.ch1);
+ cmdputs("; ");
+ cmdtxt(n->nbinary.ch2);
+ break;
+ case NAND:
+ cmdtxt(n->nbinary.ch1);
+ cmdputs(" && ");
+ cmdtxt(n->nbinary.ch2);
+ break;
+ case NOR:
+ cmdtxt(n->nbinary.ch1);
+ cmdputs(" || ");
+ cmdtxt(n->nbinary.ch2);
+ break;
+ case NPIPE:
+ for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
+ cmdtxt(lp->n);
+ if (lp->next)
+ cmdputs(" | ");
+ }
+ break;
+ case NSUBSHELL:
+ cmdputs("(");
+ cmdtxt(n->nredir.n);
+ cmdputs(")");
+ break;
+ case NREDIR:
+ case NBACKGND:
+ cmdtxt(n->nredir.n);
+ break;
+ case NIF:
+ cmdputs("if ");
+ cmdtxt(n->nif.test);
+ cmdputs("; then ");
+ cmdtxt(n->nif.ifpart);
+ cmdputs("...");
+ break;
+ case NWHILE:
+ cmdputs("while ");
+ cmdtxt(n->nbinary.ch1);
+ cmdtxtdogroup(n->nbinary.ch2);
+ break;
+ case NUNTIL:
+ cmdputs("until ");
+ cmdtxt(n->nbinary.ch1);
+ cmdtxtdogroup(n->nbinary.ch2);
+ break;
+ case NFOR:
+ cmdputs("for ");
+ cmdputs(n->nfor.var);
+ cmdputs(" in ...");
+ break;
+ case NCASE:
+ cmdputs("case ");
+ cmdputs(n->ncase.expr->narg.text);
+ cmdputs(" in ...");
+ break;
+ case NDEFUN:
+ cmdputs(n->narg.text);
+ cmdputs("() ...");
+ break;
+ case NNOT:
+ cmdputs("! ");
+ cmdtxt(n->nnot.com);
+ break;
+ case NCMD:
+ for (np = n->ncmd.args ; np ; np = np->narg.next) {
+ cmdtxt(np);
+ if (np->narg.next)
+ cmdputs(" ");
+ }
+ for (np = n->ncmd.redirect ; np ; np = np->nfile.next) {
+ cmdputs(" ");
+ cmdtxt(np);
+ }
+ break;
+ case NARG:
+ cmdputs(n->narg.text);
+ break;
+ case NTO:
+ cmdtxtredir(n, ">", 1);
+ break;
+ case NAPPEND:
+ cmdtxtredir(n, ">>", 1);
+ break;
+ case NTOFD:
+ cmdtxtredir(n, ">&", 1);
+ break;
+ case NCLOBBER:
+ cmdtxtredir(n, ">|", 1);
+ break;
+ case NFROM:
+ cmdtxtredir(n, "<", 0);
+ break;
+ case NFROMTO:
+ cmdtxtredir(n, "<>", 0);
+ break;
+ case NFROMFD:
+ cmdtxtredir(n, "<&", 0);
+ break;
+ case NHERE:
+ case NXHERE:
+ cmdputs("<<...");
+ break;
+ default:
+ cmdputs("???");
+ break;
+ }
+}
+
+
+
+static void
+cmdputs(const char *s)
+{
+ const char *p;
+ char *q;
+ char c;
+ int subtype = 0;
+
+ if (cmdnleft <= 0)
+ return;
+ p = s;
+ q = cmdnextc;
+ while ((c = *p++) != '\0') {
+ if (c == CTLESC)
+ *q++ = *p++;
+ else if (c == CTLVAR) {
+ *q++ = '$';
+ if (--cmdnleft > 0)
+ *q++ = '{';
+ subtype = *p++;
+ if ((subtype & VSTYPE) == VSLENGTH && --cmdnleft > 0)
+ *q++ = '#';
+ } else if (c == '=' && subtype != 0) {
+ *q = "}-+?=##%%\0X"[(subtype & VSTYPE) - VSNORMAL];
+ if (*q)
+ q++;
+ else
+ cmdnleft++;
+ if (((subtype & VSTYPE) == VSTRIMLEFTMAX ||
+ (subtype & VSTYPE) == VSTRIMRIGHTMAX) &&
+ --cmdnleft > 0)
+ *q = q[-1], q++;
+ subtype = 0;
+ } else if (c == CTLENDVAR) {
+ *q++ = '}';
+ } else if (c == CTLBACKQ || c == CTLBACKQ+CTLQUOTE) {
+ cmdnleft -= 5;
+ if (cmdnleft > 0) {
+ *q++ = '$';
+ *q++ = '(';
+ *q++ = '.';
+ *q++ = '.';
+ *q++ = '.';
+ *q++ = ')';
+ }
+ } else if (c == CTLARI) {
+ cmdnleft -= 2;
+ if (cmdnleft > 0) {
+ *q++ = '$';
+ *q++ = '(';
+ *q++ = '(';
+ }
+ p++;
+ } else if (c == CTLENDARI) {
+ if (--cmdnleft > 0) {
+ *q++ = ')';
+ *q++ = ')';
+ }
+ } else if (c == CTLQUOTEMARK || c == CTLQUOTEEND)
+ cmdnleft++; /* ignore */
+ else
+ *q++ = c;
+ if (--cmdnleft <= 0) {
+ *q++ = '.';
+ *q++ = '.';
+ *q++ = '.';
+ break;
+ }
+ }
+ cmdnextc = q;
+}
diff --git a/cmd/posix/sh/jobs.h b/cmd/posix/sh/jobs.h
@@ -0,0 +1,66 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */
+#define FORK_FG 0
+#define FORK_BG 1
+#define FORK_NOJOB 2
+
+#include <signal.h> /* for sig_atomic_t */
+
+struct job;
+
+enum {
+ SHOWJOBS_DEFAULT, /* job number, status, command */
+ SHOWJOBS_VERBOSE, /* job number, PID, status, command */
+ SHOWJOBS_PIDS, /* PID only */
+ SHOWJOBS_PGIDS /* PID of the group leader only */
+};
+
+extern int job_warning; /* user was warned about stopped jobs */
+
+void setjobctl(int);
+void showjobs(int, int);
+struct job *makejob(union node *, int);
+pid_t forkshell(struct job *, union node *, int);
+pid_t vforkexecshell(struct job *, char **, char **, const char *, int, int [2]);
+int waitforjob(struct job *, int *);
+int stoppedjobs(void);
+int backgndpidset(void);
+pid_t backgndpidval(void);
+char *commandtext(union node *);
+
+#if ! JOBS
+#define setjobctl(on) /* do nothing */
+#endif
diff --git a/cmd/posix/sh/kill.c b/cmd/posix/sh/kill.c
@@ -0,0 +1,187 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1988, 1993, 1994
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/*
+ * Important: This file is used both as a standalone program /bin/kill and
+ * as a builtin for /bin/sh (#define SHELL).
+ */
+
+#include "sig.h"
+
+#ifdef SHELL
+#define main killcmd
+#include "bltin.h"
+#endif
+
+#ifndef __dead2
+#define __dead2 __attribute__((__noreturn__))
+#endif
+
+#include <ctype.h>
+#ifndef SHELL
+#include <err.h>
+#endif
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void nosig(const char *);
+static void printsignals(FILE *);
+static void usage(void) __dead2;
+
+int
+main(int argc, char *argv[])
+{
+ char signame[SIG2STR_MAX];
+ long pidl;
+ pid_t pid;
+ int errors, numsig, ret;
+ char *ep;
+
+ if (argc < 2)
+ usage();
+
+ numsig = SIGTERM;
+
+ argc--, argv++;
+ if (!strcmp(*argv, "-l")) {
+ argc--, argv++;
+ if (argc > 1)
+ usage();
+ if (argc == 1) {
+ if (!isdigit(**argv))
+ usage();
+ numsig = strtol(*argv, &ep, 10);
+ if (!**argv || *ep)
+ errx(2, "invalid signal number: %s", *argv);
+ if (numsig >= 128)
+ numsig -= 128;
+ if (sig2str(numsig, signame) < 0)
+ nosig(*argv);
+ printf("%s\n", signame);
+ return (0);
+ }
+ printsignals(stdout);
+ return (0);
+ }
+
+ if (!strcmp(*argv, "-s")) {
+ argc--, argv++;
+ if (argc < 1) {
+ warnx("option requires an argument -- s");
+ usage();
+ }
+ if (strcmp(*argv, "0") == 0)
+ numsig = 0;
+ else if (str2sig(*argv, &numsig) < 0)
+ nosig(*argv);
+ argc--, argv++;
+ } else if (**argv == '-' && *(*argv + 1) != '-') {
+ ++*argv;
+ if (strcmp(*argv, "0") == 0)
+ numsig = 0;
+ else if (str2sig(*argv, &numsig) < 0)
+ nosig(*argv);
+ argc--, argv++;
+ }
+
+ if (argc > 0 && strncmp(*argv, "--", 2) == 0)
+ argc--, argv++;
+
+ if (argc == 0)
+ usage();
+
+ for (errors = 0; argc; argc--, argv++) {
+#ifdef SHELL
+ if (**argv == '%')
+ ret = killjob(*argv, numsig);
+ else
+#endif
+ {
+ pidl = strtol(*argv, &ep, 10);
+ /* Check for overflow of pid_t. */
+ pid = (pid_t)pidl;
+ if (!**argv || *ep || pid != pidl)
+ errx(2, "illegal process id: %s", *argv);
+ ret = kill(pid, numsig);
+ }
+ if (ret == -1) {
+ warn("%s", *argv);
+ errors = 1;
+ }
+ }
+
+ return (errors);
+}
+
+static void
+nosig(const char *name)
+{
+
+ warnx("unknown signal %s; valid signals:", name);
+ printsignals(stderr);
+#ifdef SHELL
+ error(NULL);
+#else
+ exit(2);
+#endif
+}
+
+static void
+printsignals(FILE *fp)
+{
+ int n;
+
+ for (n = 1; n < sys_nsig; n++) {
+ (void)fprintf(fp, "%s", sys_signame[n]);
+ if (n == (sys_nsig / 2) || n == (sys_nsig - 1))
+ (void)fprintf(fp, "\n");
+ else
+ (void)fprintf(fp, " ");
+ }
+}
+
+static void
+usage(void)
+{
+
+ (void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
+ "usage: kill [-s signal_name] pid ...",
+ " kill -l [exit_status]",
+ " kill -signal_name pid ...",
+ " kill -signal_number pid ...");
+#ifdef SHELL
+ error(NULL);
+#else
+ exit(2);
+#endif
+}
diff --git a/cmd/posix/sh/mail.c b/cmd/posix/sh/mail.c
@@ -0,0 +1,113 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Routines to check for mail. (Perhaps make part of main.c?)
+ */
+
+#include "shell.h"
+#include "mail.h"
+#include "var.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <stdlib.h>
+
+
+#define MAXMBOXES 10
+
+
+static int nmboxes; /* number of mailboxes */
+static time_t mailtime[MAXMBOXES]; /* times of mailboxes */
+
+
+
+/*
+ * Print appropriate message(s) if mail has arrived. If the argument is
+ * non-zero, then the value of MAIL has changed, so we just update the
+ * values.
+ */
+
+void
+chkmail(int silent)
+{
+ int i;
+ char *mpath;
+ char *p;
+ char *msg;
+ struct stackmark smark;
+ struct stat statb;
+
+ if (silent)
+ nmboxes = 10;
+ if (nmboxes == 0)
+ return;
+ setstackmark(&smark);
+ mpath = stsavestr(mpathset()? mpathval() : mailval());
+ for (i = 0 ; i < nmboxes ; i++) {
+ p = mpath;
+ if (*p == '\0')
+ break;
+ mpath = strchrnul(mpath, ':');
+ if (*mpath != '\0') {
+ *mpath++ = '\0';
+ if (p == mpath - 1)
+ continue;
+ }
+ msg = strchr(p, '%');
+ if (msg != NULL)
+ *msg++ = '\0';
+#ifdef notdef /* this is what the System V shell claims to do (it lies) */
+ if (stat(p, &statb) < 0)
+ statb.st_mtime = 0;
+ if (statb.st_mtime > mailtime[i] && ! silent) {
+ out2str(msg? msg : "you have mail");
+ out2c('\n');
+ }
+ mailtime[i] = statb.st_mtime;
+#else /* this is what it should do */
+ if (stat(p, &statb) < 0)
+ statb.st_size = 0;
+ if (statb.st_size > mailtime[i] && ! silent) {
+ out2str(msg? msg : "you have mail");
+ out2c('\n');
+ }
+ mailtime[i] = statb.st_size;
+#endif
+ }
+ nmboxes = i;
+ popstackmark(&smark);
+}
diff --git a/cmd/posix/sh/mail.h b/cmd/posix/sh/mail.h
@@ -0,0 +1,35 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+void chkmail(int);
diff --git a/cmd/posix/sh/main.c b/cmd/posix/sh/main.c
@@ -0,0 +1,367 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <locale.h>
+#include <errno.h>
+#include <termios.h>
+#include <paths.h>
+#include <unistd.h>
+
+#include "shell.h"
+#include "main.h"
+#include "mail.h"
+#include "options.h"
+#include "output.h"
+#include "parser.h"
+#include "nodes.h"
+#include "expand.h"
+#include "eval.h"
+#include "jobs.h"
+#include "input.h"
+#include "trap.h"
+#include "var.h"
+#include "show.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "exec.h"
+#include "cd.h"
+#include "redir.h"
+#include "builtins.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+int rootpid;
+int rootshell;
+struct jmploc main_handler;
+int localeisutf8, initial_localeisutf8;
+
+static void reset(void);
+static void cmdloop(int);
+static void read_profile(const char *);
+static char *find_dot_file(char *);
+
+/*
+ * Main routine. We initialize things, parse the arguments, execute
+ * profiles if we're a login shell, and then call cmdloop to execute
+ * commands. The setjmp call sets up the location to jump to when an
+ * exception occurs. When an exception occurs the variable "state"
+ * is used to figure out how far we had gotten.
+ */
+
+int
+main(int argc, char *argv[])
+{
+ /*
+ * As smark is accessed after a longjmp, it cannot be a local in main().
+ * The C standard specifies that the values of non-volatile local
+ * variables are unspecified after a jump if modified between the
+ * setjmp and longjmp.
+ */
+ static struct stackmark smark, smark2;
+ volatile int state;
+ char *shinit;
+ int login;
+
+ (void) setlocale(LC_ALL, "");
+ initcharset();
+ state = 0;
+ if (setjmp(main_handler.loc)) {
+ if (state == 0 || iflag == 0 || ! rootshell ||
+ exception == EXEXIT)
+ exitshell(exitstatus);
+ reset();
+ if (exception == EXINT)
+ out2fmt_flush("\n");
+ popstackmark(&smark);
+ FORCEINTON; /* enable interrupts */
+ if (state == 1)
+ goto state1;
+ else if (state == 2)
+ goto state2;
+ else if (state == 3)
+ goto state3;
+ else
+ goto state4;
+ }
+ handler = &main_handler;
+#ifdef DEBUG
+ opentrace();
+ trputs("Shell args: "); trargs(argv);
+#endif
+ rootpid = getpid();
+ if (rootpid == 1) {
+ /*
+ * Make sh usable for invocation as interactive init
+ * substitute with init_path=/bin/sh, by opening
+ * file descriptors 0, 1, and 2 on /dev/console.
+ */
+ if (fcntl(STDIN_FILENO, F_GETFL, NULL) == -1 && errno == EBADF) {
+ (void)open(_PATH_CONSOLE, O_RDWR);
+ (void)setsid();
+ (void)tcsetsid(STDIN_FILENO, rootpid);
+ }
+ if (fcntl(STDOUT_FILENO, F_GETFL, NULL) == -1 && errno == EBADF)
+ (void)dup2(STDIN_FILENO, STDOUT_FILENO);
+ if (fcntl(STDERR_FILENO, F_GETFL, NULL) == -1 && errno == EBADF)
+ (void)dup2(STDIN_FILENO, STDERR_FILENO);
+ }
+ rootshell = 1;
+ INTOFF;
+ initvar();
+ setstackmark(&smark);
+ setstackmark(&smark2);
+ login = procargs(argc, argv);
+ trap_init();
+ pwd_init(iflag);
+ INTON;
+ if (iflag)
+ chkmail(1);
+ if (login) {
+ state = 1;
+ read_profile("/etc/profile");
+state1:
+ state = 2;
+ if (privileged == 0)
+ read_profile("${HOME-}/.profile");
+ else
+ read_profile("/etc/suid_profile");
+ }
+state2:
+ state = 3;
+ if (!privileged && iflag) {
+ if ((shinit = lookupvar("ENV")) != NULL && *shinit != '\0') {
+ state = 3;
+ read_profile(shinit);
+ }
+ }
+#ifndef NO_HISTORY
+ if (iflag)
+ histload();
+#endif
+state3:
+ state = 4;
+ popstackmark(&smark2);
+ if (minusc) {
+ evalstring(minusc, sflag ? 0 : EV_EXIT);
+ }
+state4:
+ if (sflag || minusc == NULL) {
+ cmdloop(1);
+ }
+ exitshell(exitstatus);
+ /*NOTREACHED*/
+ return 0;
+}
+
+static void
+reset(void)
+{
+ reseteval();
+ resetinput();
+}
+
+/*
+ * Read and execute commands. "Top" is nonzero for the top level command
+ * loop; it turns on prompting if the shell is interactive.
+ */
+
+static void
+cmdloop(int top)
+{
+ union node *n;
+ struct stackmark smark;
+ int inter;
+ int numeof = 0;
+
+ TRACE(("cmdloop(%d) called\n", top));
+ setstackmark(&smark);
+ for (;;) {
+ if (pendingsig)
+ dotrap();
+ inter = 0;
+ if (iflag && top) {
+ inter++;
+ showjobs(1, SHOWJOBS_DEFAULT);
+ chkmail(0);
+ flushout(&output);
+ }
+ n = parsecmd(inter);
+ /* showtree(n); DEBUG */
+ if (n == NEOF) {
+ if (!top || numeof >= 50)
+ break;
+ if (!stoppedjobs()) {
+ if (!Iflag)
+ break;
+ out2fmt_flush("\nUse \"exit\" to leave shell.\n");
+ }
+ numeof++;
+ } else if (n != NULL && nflag == 0) {
+ job_warning = (job_warning == 2) ? 1 : 0;
+ numeof = 0;
+ evaltree(n, 0);
+ }
+ popstackmark(&smark);
+ setstackmark(&smark);
+ if (evalskip != 0) {
+ if (evalskip == SKIPRETURN)
+ evalskip = 0;
+ break;
+ }
+ }
+ popstackmark(&smark);
+ if (top && iflag) {
+ out2c('\n');
+ flushout(out2);
+ }
+}
+
+
+
+/*
+ * Read /etc/profile or .profile. Return on error.
+ */
+
+static void
+read_profile(const char *name)
+{
+ int fd;
+ const char *expandedname;
+ int oflags = O_RDONLY | O_CLOEXEC;
+
+ if (verifyflag)
+ oflags |= O_VERIFY;
+
+ expandedname = expandstr(name);
+ if (expandedname == NULL)
+ return;
+ INTOFF;
+ if ((fd = open(expandedname, oflags)) >= 0)
+ setinputfd(fd, 1);
+ INTON;
+ if (fd < 0)
+ return;
+ cmdloop(0);
+ popfile();
+}
+
+
+
+/*
+ * Read a file containing shell functions.
+ */
+
+void
+readcmdfile(const char *name, int verify)
+{
+ setinputfile(name, 1, verify);
+ cmdloop(0);
+ popfile();
+}
+
+
+
+/*
+ * Take commands from a file. To be compatible we should do a path
+ * search for the file, which is necessary to find sub-commands.
+ */
+
+
+static char *
+find_dot_file(char *basename)
+{
+ char *fullname;
+ const char *opt;
+ const char *path = pathval();
+ struct stat statb;
+
+ /* don't try this for absolute or relative paths */
+ if( strchr(basename, '/'))
+ return basename;
+
+ while ((fullname = padvance(&path, &opt, basename)) != NULL) {
+ if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) {
+ /*
+ * Don't bother freeing here, since it will
+ * be freed by the caller.
+ */
+ return fullname;
+ }
+ stunalloc(fullname);
+ }
+ return basename;
+}
+
+int
+dotcmd(int argc, char **argv)
+{
+ char *filename, *fullname;
+
+ if (argc < 2)
+ error("missing filename");
+
+ exitstatus = 0;
+
+ /*
+ * Because we have historically not supported any options,
+ * only treat "--" specially.
+ */
+ filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1];
+
+ fullname = find_dot_file(filename);
+ setinputfile(fullname, 1, -1 /* verify */);
+ commandname = fullname;
+ cmdloop(0);
+ popfile();
+ return exitstatus;
+}
+
+
+int
+exitcmd(int argc, char **argv)
+{
+ if (stoppedjobs())
+ return 0;
+ if (argc > 1)
+ exitshell(number(argv[1]));
+ else
+ exitshell_savedstatus();
+}
diff --git a/cmd/posix/sh/main.h b/cmd/posix/sh/main.h
@@ -0,0 +1,39 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+extern int rootpid; /* pid of main shell */
+extern int rootshell; /* true if we aren't a child of the main shell */
+extern struct jmploc main_handler; /* top level exception handler */
+
+void readcmdfile(const char *, int);
diff --git a/cmd/posix/sh/memalloc.c b/cmd/posix/sh/memalloc.c
@@ -0,0 +1,345 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/param.h>
+#include "shell.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "expand.h"
+#include <stdlib.h>
+#include <unistd.h>
+
+static void
+badalloc(const char *message)
+{
+ write(2, message, strlen(message));
+ abort();
+}
+
+/*
+ * Like malloc, but returns an error when out of space.
+ */
+
+pointer
+ckmalloc(size_t nbytes)
+{
+ pointer p;
+
+ if (!is_int_on())
+ badalloc("Unsafe ckmalloc() call\n");
+ p = malloc(nbytes);
+ if (p == NULL)
+ error("Out of space");
+ return p;
+}
+
+
+/*
+ * Same for realloc.
+ */
+
+pointer
+ckrealloc(pointer p, int nbytes)
+{
+ if (!is_int_on())
+ badalloc("Unsafe ckrealloc() call\n");
+ p = realloc(p, nbytes);
+ if (p == NULL)
+ error("Out of space");
+ return p;
+}
+
+void
+ckfree(pointer p)
+{
+ if (!is_int_on())
+ badalloc("Unsafe ckfree() call\n");
+ free(p);
+}
+
+
+/*
+ * Make a copy of a string in safe storage.
+ */
+
+char *
+savestr(const char *s)
+{
+ char *p;
+ size_t len;
+
+ len = strlen(s);
+ p = ckmalloc(len + 1);
+ memcpy(p, s, len + 1);
+ return p;
+}
+
+
+/*
+ * Parse trees for commands are allocated in lifo order, so we use a stack
+ * to make this more efficient, and also to avoid all sorts of exception
+ * handling code to handle interrupts in the middle of a parse.
+ *
+ * The size 496 was chosen because with 16-byte alignment the total size
+ * for the allocated block is 512.
+ */
+
+#define MINSIZE 496 /* minimum size of a block. */
+
+
+struct stack_block {
+ struct stack_block *prev;
+ /* Data follows */
+};
+#define SPACE(sp) ((char*)(sp) + ALIGN(sizeof(struct stack_block)))
+
+static struct stack_block *stackp;
+char *stacknxt;
+int stacknleft;
+char *sstrend;
+
+
+static void
+stnewblock(int nbytes)
+{
+ struct stack_block *sp;
+ int allocsize;
+
+ if (nbytes < MINSIZE)
+ nbytes = MINSIZE;
+
+ allocsize = ALIGN(sizeof(struct stack_block)) + ALIGN(nbytes);
+
+ INTOFF;
+ sp = ckmalloc(allocsize);
+ sp->prev = stackp;
+ stacknxt = SPACE(sp);
+ stacknleft = allocsize - (stacknxt - (char*)sp);
+ sstrend = stacknxt + stacknleft;
+ stackp = sp;
+ INTON;
+}
+
+
+pointer
+stalloc(int nbytes)
+{
+ char *p;
+
+ nbytes = ALIGN(nbytes);
+ if (nbytes > stacknleft)
+ stnewblock(nbytes);
+ p = stacknxt;
+ stacknxt += nbytes;
+ stacknleft -= nbytes;
+ return p;
+}
+
+
+void
+stunalloc(pointer p)
+{
+ if (p == NULL) { /*DEBUG */
+ write(STDERR_FILENO, "stunalloc\n", 10);
+ abort();
+ }
+ stacknleft += stacknxt - (char *)p;
+ stacknxt = p;
+}
+
+
+char *
+stsavestr(const char *s)
+{
+ char *p;
+ size_t len;
+
+ len = strlen(s);
+ p = stalloc(len + 1);
+ memcpy(p, s, len + 1);
+ return p;
+}
+
+
+void
+setstackmark(struct stackmark *mark)
+{
+ mark->stackp = stackp;
+ mark->stacknxt = stacknxt;
+ mark->stacknleft = stacknleft;
+ /* Ensure this block stays in place. */
+ if (stackp != NULL && stacknxt == SPACE(stackp))
+ stalloc(1);
+}
+
+
+void
+popstackmark(struct stackmark *mark)
+{
+ struct stack_block *sp;
+
+ INTOFF;
+ while (stackp != mark->stackp) {
+ sp = stackp;
+ stackp = sp->prev;
+ ckfree(sp);
+ }
+ stacknxt = mark->stacknxt;
+ stacknleft = mark->stacknleft;
+ if (stacknleft != 0)
+ sstrend = stacknxt + stacknleft;
+ else
+ sstrend = stacknxt;
+ INTON;
+}
+
+
+/*
+ * When the parser reads in a string, it wants to stick the string on the
+ * stack and only adjust the stack pointer when it knows how big the
+ * string is. Stackblock (defined in stack.h) returns a pointer to a block
+ * of space on top of the stack and stackblocklen returns the length of
+ * this block. Growstackblock will grow this space by at least one byte,
+ * possibly moving it (like realloc). Grabstackblock actually allocates the
+ * part of the block that has been used.
+ */
+
+static void
+growstackblock(int min)
+{
+ char *p;
+ int newlen;
+ char *oldspace;
+ int oldlen;
+ struct stack_block *sp;
+ struct stack_block *oldstackp;
+
+ if (min < stacknleft)
+ min = stacknleft;
+ if ((unsigned int)min >=
+ INT_MAX / 2 - ALIGN(sizeof(struct stack_block)))
+ error("Out of space");
+ min += stacknleft;
+ min += ALIGN(sizeof(struct stack_block));
+ newlen = 512;
+ while (newlen < min)
+ newlen <<= 1;
+ oldspace = stacknxt;
+ oldlen = stacknleft;
+
+ if (stackp != NULL && stacknxt == SPACE(stackp)) {
+ INTOFF;
+ oldstackp = stackp;
+ stackp = oldstackp->prev;
+ sp = ckrealloc((pointer)oldstackp, newlen);
+ sp->prev = stackp;
+ stackp = sp;
+ stacknxt = SPACE(sp);
+ stacknleft = newlen - (stacknxt - (char*)sp);
+ sstrend = stacknxt + stacknleft;
+ INTON;
+ } else {
+ newlen -= ALIGN(sizeof(struct stack_block));
+ p = stalloc(newlen);
+ if (oldlen != 0)
+ memcpy(p, oldspace, oldlen);
+ stunalloc(p);
+ }
+}
+
+
+/*
+ * The following routines are somewhat easier to use than the above.
+ * The user declares a variable of type STACKSTR, which may be declared
+ * to be a register. The macro STARTSTACKSTR initializes things. Then
+ * the user uses the macro STPUTC to add characters to the string. In
+ * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
+ * grown as necessary. When the user is done, she can just leave the
+ * string there and refer to it using stackblock(). Or she can allocate
+ * the space for it using grabstackstr(). If it is necessary to allow
+ * someone else to use the stack temporarily and then continue to grow
+ * the string, the user should use grabstack to allocate the space, and
+ * then call ungrabstr(p) to return to the previous mode of operation.
+ *
+ * USTPUTC is like STPUTC except that it doesn't check for overflow.
+ * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
+ * is space for at least one character.
+ */
+
+static char *
+growstrstackblock(int n, int min)
+{
+ growstackblock(min);
+ return stackblock() + n;
+}
+
+char *
+growstackstr(void)
+{
+ int len;
+
+ len = stackblocksize();
+ return (growstrstackblock(len, 0));
+}
+
+
+/*
+ * Called from CHECKSTRSPACE.
+ */
+
+char *
+makestrspace(int min, char *p)
+{
+ int len;
+
+ len = p - stackblock();
+ return (growstrstackblock(len, min));
+}
+
+
+char *
+stputbin(const char *data, size_t len, char *p)
+{
+ CHECKSTRSPACE(len, p);
+ memcpy(p, data, len);
+ return (p + len);
+}
+
+char *
+stputs(const char *data, char *p)
+{
+ return (stputbin(data, strlen(data), p));
+}
diff --git a/cmd/posix/sh/memalloc.h b/cmd/posix/sh/memalloc.h
@@ -0,0 +1,85 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+
+struct stackmark {
+ struct stack_block *stackp;
+ char *stacknxt;
+ int stacknleft;
+};
+
+
+extern char *stacknxt;
+extern int stacknleft;
+extern char *sstrend;
+
+pointer ckmalloc(size_t);
+pointer ckrealloc(pointer, int);
+void ckfree(pointer);
+char *savestr(const char *);
+pointer stalloc(int);
+void stunalloc(pointer);
+char *stsavestr(const char *);
+void setstackmark(struct stackmark *);
+void popstackmark(struct stackmark *);
+char *growstackstr(void);
+char *makestrspace(int, char *);
+char *stputbin(const char *data, size_t len, char *p);
+char *stputs(const char *data, char *p);
+
+
+
+#define stackblock() stacknxt
+#define stackblocksize() stacknleft
+#define grabstackblock(n) stalloc(n)
+#define STARTSTACKSTR(p) p = stackblock()
+#define STPUTC(c, p) do { if (p == sstrend) p = growstackstr(); *p++ = (c); } while(0)
+#define CHECKSTRSPACE(n, p) { if ((size_t)(sstrend - p) < n) p = makestrspace(n, p); }
+#define USTPUTC(c, p) (*p++ = (c))
+/*
+ * STACKSTRNUL's use is where we want to be able to turn a stack
+ * (non-sentinel, character counting string) into a C string,
+ * and later pretend the NUL is not there.
+ * Note: Because of STACKSTRNUL's semantics, STACKSTRNUL cannot be used
+ * on a stack that will grabstackstr()ed.
+ */
+#define STACKSTRNUL(p) (p == sstrend ? (p = growstackstr(), *p = '\0') : (*p = '\0'))
+#define STUNPUTC(p) (--p)
+#define STTOPC(p) p[-1]
+#define STADJUST(amount, p) (p += (amount))
+#define grabstackstr(p) stalloc((char *)p - stackblock())
+#define ungrabstackstr(s, p) stunalloc((s))
+#define STPUTBIN(s, len, p) p = stputbin((s), (len), p)
+#define STPUTS(s, p) p = stputs((s), p)
diff --git a/cmd/posix/sh/miscbltin.c b/cmd/posix/sh/miscbltin.c
@@ -0,0 +1,642 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Miscellaneous builtins.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/resource.h>
+
+#include <errno.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "shell.h"
+
+#ifndef timespeccmp
+#define timespeccmp(tvp, uvp, cmp) \
+ (((tvp)->tv_sec == (uvp)->tv_sec) ? \
+ ((tvp)->tv_nsec cmp (uvp)->tv_nsec) : \
+ ((tvp)->tv_sec cmp (uvp)->tv_sec))
+#endif
+#include "options.h"
+#include "var.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "syntax.h"
+#include "trap.h"
+
+#undef eflag
+
+#define READ_BUFLEN 1024
+struct fdctx {
+ int fd;
+ size_t off; /* offset in buf */
+ size_t buflen;
+ char *ep; /* tail pointer */
+ char buf[READ_BUFLEN];
+};
+
+static void fdctx_init(int, struct fdctx *);
+static void fdctx_destroy(struct fdctx *);
+static ssize_t fdgetc(struct fdctx *, char *);
+int readcmd(int, char **);
+int umaskcmd(int, char **);
+int ulimitcmd(int, char **);
+
+extern mode_t parsemode(const char *str, mode_t mode, mode_t mask);
+
+static void
+fdctx_init(int fd, struct fdctx *fdc)
+{
+ off_t cur;
+
+ /* Check if fd is seekable. */
+ cur = lseek(fd, 0, SEEK_CUR);
+ *fdc = (struct fdctx){
+ .fd = fd,
+ .buflen = (cur != -1) ? READ_BUFLEN : 1,
+ .ep = &fdc->buf[0], /* No data */
+ };
+}
+
+static ssize_t
+fdgetc(struct fdctx *fdc, char *c)
+{
+ ssize_t nread;
+
+ if (&fdc->buf[fdc->off] == fdc->ep) {
+ nread = read(fdc->fd, fdc->buf, fdc->buflen);
+ if (nread > 0) {
+ fdc->off = 0;
+ fdc->ep = fdc->buf + nread;
+ } else
+ return (nread);
+ }
+ *c = fdc->buf[fdc->off++];
+
+ return (1);
+}
+
+static void
+fdctx_destroy(struct fdctx *fdc)
+{
+ off_t residue;
+
+ if (fdc->buflen > 1) {
+ /*
+ * Reposition the file offset. Here is the layout of buf:
+ *
+ * | off
+ * v
+ * |*****************|-------|
+ * buf ep buf+buflen
+ * |<- residue ->|
+ *
+ * off: current character
+ * ep: offset just after read(2)
+ * residue: length for reposition
+ */
+ residue = (fdc->ep - fdc->buf) - fdc->off;
+ if (residue > 0)
+ (void) lseek(fdc->fd, -residue, SEEK_CUR);
+ }
+}
+
+/*
+ * The read builtin. The -r option causes backslashes to be treated like
+ * ordinary characters.
+ *
+ * Note that if IFS=' :' then read x y should work so that:
+ * 'a b' x='a', y='b'
+ * ' a b ' x='a', y='b'
+ * ':b' x='', y='b'
+ * ':' x='', y=''
+ * '::' x='', y=''
+ * ': :' x='', y=''
+ * ':::' x='', y='::'
+ * ':b c:' x='', y='b c:'
+ */
+
+int
+readcmd(int argc __unused, char **argv __unused)
+{
+ char **ap;
+ int backslash;
+ char c;
+ int rflag;
+ char *prompt;
+ const char *ifs;
+ char *p;
+ int startword;
+ int status;
+ int i;
+ int is_ifs;
+ int saveall = 0;
+ ptrdiff_t lastnonifs, lastnonifsws;
+ sigset_t set, oset;
+ intmax_t number, timeout;
+ struct timespec tnow, tend, tresid;
+ struct pollfd pfd;
+ char *endptr;
+ ssize_t nread;
+ int sig;
+ struct fdctx fdctx;
+
+ rflag = 0;
+ prompt = NULL;
+ timeout = -1;
+ while ((i = nextopt("erp:t:")) != '\0') {
+ switch(i) {
+ case 'p':
+ prompt = shoptarg;
+ break;
+ case 'e':
+ break;
+ case 'r':
+ rflag = 1;
+ break;
+ case 't':
+ timeout = 0;
+ do {
+ number = strtol(shoptarg, &endptr, 0);
+ if (number < 0 || endptr == shoptarg)
+ error("timeout value");
+ switch (*endptr) {
+ case 's':
+ endptr++;
+ break;
+ case 'h':
+ number *= 60;
+ /* FALLTHROUGH */
+ case 'm':
+ number *= 60;
+ endptr++;
+ break;
+ }
+ if (*endptr != '\0' &&
+ !(*endptr >= '0' && *endptr <= '9'))
+ error("timeout unit");
+ timeout += number;
+ shoptarg = endptr;
+ } while (*shoptarg != '\0');
+ break;
+ }
+ }
+ if (prompt && isatty(0)) {
+ out2str(prompt);
+ flushall();
+ }
+ if (*(ap = argptr) == NULL)
+ error("arg count");
+ if ((ifs = bltinlookup("IFS", 1)) == NULL)
+ ifs = " \t\n";
+
+ if (timeout >= 0) {
+ /*
+ * Wait for something to become available.
+ */
+ pfd.fd = STDIN_FILENO;
+ pfd.events = POLLIN;
+ status = sig = 0;
+ sigfillset(&set);
+ sigprocmask(SIG_SETMASK, &set, &oset);
+ if (pendingsig) {
+ /* caught a signal already */
+ status = -1;
+ } else if (timeout == 0) {
+ status = poll(&pfd, 1, 0);
+ } else {
+ clock_gettime(CLOCK_UPTIME, &tnow);
+ tend = tnow;
+ tend.tv_sec += timeout;
+ do {
+ timespecsub(&tend, &tnow, &tresid);
+ status = ppoll(&pfd, 1, &tresid, &oset);
+ if (status >= 0 || pendingsig != 0)
+ break;
+ clock_gettime(CLOCK_UPTIME, &tnow);
+ } while (timespeccmp(&tnow, &tend, <));
+ }
+ sigprocmask(SIG_SETMASK, &oset, NULL);
+ /*
+ * If there's nothing ready, return an error.
+ */
+ if (status <= 0) {
+ while (*ap != NULL)
+ setvar(*ap++, "", 0);
+ sig = pendingsig;
+ return (128 + (sig != 0 ? sig : SIGALRM));
+ }
+ }
+
+ status = 0;
+ startword = 2;
+ backslash = 0;
+ STARTSTACKSTR(p);
+ lastnonifs = lastnonifsws = -1;
+ fdctx_init(STDIN_FILENO, &fdctx);
+ for (;;) {
+ c = 0;
+ nread = fdgetc(&fdctx, &c);
+ if (nread == -1) {
+ if (errno == EINTR) {
+ sig = pendingsig;
+ if (sig == 0)
+ continue;
+ status = 128 + sig;
+ break;
+ }
+ warning("read error: %s", strerror(errno));
+ status = 2;
+ break;
+ } else if (nread != 1) {
+ status = 1;
+ break;
+ }
+ if (c == '\0')
+ continue;
+ CHECKSTRSPACE(1, p);
+ if (backslash) {
+ backslash = 0;
+ if (c != '\n') {
+ startword = 0;
+ lastnonifs = lastnonifsws = p - stackblock();
+ USTPUTC(c, p);
+ }
+ continue;
+ }
+ if (!rflag && c == '\\' && !backslash) {
+ backslash++;
+ continue;
+ }
+ if (c == '\n')
+ break;
+ if (strchr(ifs, c))
+ is_ifs = strchr(" \t\n", c) ? 1 : 2;
+ else
+ is_ifs = 0;
+
+ if (startword != 0) {
+ if (is_ifs == 1) {
+ /* Ignore leading IFS whitespace */
+ if (saveall)
+ USTPUTC(c, p);
+ continue;
+ }
+ if (is_ifs == 2 && startword == 1) {
+ /* Only one non-whitespace IFS per word */
+ startword = 2;
+ if (saveall) {
+ lastnonifsws = p - stackblock();
+ USTPUTC(c, p);
+ }
+ continue;
+ }
+ }
+
+ if (is_ifs == 0) {
+ /* append this character to the current variable */
+ startword = 0;
+ if (saveall)
+ /* Not just a spare terminator */
+ saveall++;
+ lastnonifs = lastnonifsws = p - stackblock();
+ USTPUTC(c, p);
+ continue;
+ }
+
+ /* end of variable... */
+ startword = is_ifs;
+
+ if (ap[1] == NULL) {
+ /* Last variable needs all IFS chars */
+ saveall++;
+ if (is_ifs == 2)
+ lastnonifsws = p - stackblock();
+ USTPUTC(c, p);
+ continue;
+ }
+
+ STACKSTRNUL(p);
+ setvar(*ap, stackblock(), 0);
+ ap++;
+ STARTSTACKSTR(p);
+ lastnonifs = lastnonifsws = -1;
+ }
+ fdctx_destroy(&fdctx);
+ STACKSTRNUL(p);
+
+ /*
+ * Remove trailing IFS chars: always remove whitespace, don't remove
+ * non-whitespace unless it was naked
+ */
+ if (saveall <= 1)
+ lastnonifsws = lastnonifs;
+ stackblock()[lastnonifsws + 1] = '\0';
+ setvar(*ap, stackblock(), 0);
+
+ /* Set any remaining args to "" */
+ while (*++ap != NULL)
+ setvar(*ap, "", 0);
+ return status;
+}
+
+
+
+int
+umaskcmd(int argc __unused, char **argv __unused)
+{
+ char *ap;
+ int mask;
+ int i;
+ int symbolic_mode = 0;
+
+ while ((i = nextopt("S")) != '\0') {
+ symbolic_mode = 1;
+ }
+
+ INTOFF;
+ mask = umask(0);
+ umask(mask);
+ INTON;
+
+ if ((ap = *argptr) == NULL) {
+ if (symbolic_mode) {
+ char u[4], g[4], o[4];
+
+ i = 0;
+ if ((mask & S_IRUSR) == 0)
+ u[i++] = 'r';
+ if ((mask & S_IWUSR) == 0)
+ u[i++] = 'w';
+ if ((mask & S_IXUSR) == 0)
+ u[i++] = 'x';
+ u[i] = '\0';
+
+ i = 0;
+ if ((mask & S_IRGRP) == 0)
+ g[i++] = 'r';
+ if ((mask & S_IWGRP) == 0)
+ g[i++] = 'w';
+ if ((mask & S_IXGRP) == 0)
+ g[i++] = 'x';
+ g[i] = '\0';
+
+ i = 0;
+ if ((mask & S_IROTH) == 0)
+ o[i++] = 'r';
+ if ((mask & S_IWOTH) == 0)
+ o[i++] = 'w';
+ if ((mask & S_IXOTH) == 0)
+ o[i++] = 'x';
+ o[i] = '\0';
+
+ out1fmt("u=%s,g=%s,o=%s\n", u, g, o);
+ } else {
+ out1fmt("%.4o\n", mask);
+ }
+ } else {
+ if (is_digit(*ap)) {
+ mask = 0;
+ do {
+ if (*ap >= '8' || *ap < '0')
+ error("Illegal number: %s", *argptr);
+ mask = (mask << 3) + (*ap - '0');
+ } while (*++ap != '\0');
+ umask(mask);
+ } else {
+ mode_t newmask;
+ INTOFF;
+ newmask = parsemode(ap, ~mask & 0777, mask);
+ umask(~newmask & 0777);
+ INTON;
+ }
+ }
+ return 0;
+}
+
+/*
+ * ulimit builtin
+ *
+ * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and
+ * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with
+ * ash by J.T. Conklin.
+ *
+ * Public domain.
+ */
+
+struct limits {
+ const char *name;
+ const char *units;
+ int cmd;
+ short factor; /* multiply by to get rlim_{cur,max} values */
+ char option;
+};
+
+static const struct limits limits[] = {
+#ifdef RLIMIT_CPU
+ { "cpu time", "seconds", RLIMIT_CPU, 1, 't' },
+#endif
+#ifdef RLIMIT_FSIZE
+ { "file size", "512-blocks", RLIMIT_FSIZE, 512, 'f' },
+#endif
+#ifdef RLIMIT_DATA
+ { "data seg size", "kbytes", RLIMIT_DATA, 1024, 'd' },
+#endif
+#ifdef RLIMIT_STACK
+ { "stack size", "kbytes", RLIMIT_STACK, 1024, 's' },
+#endif
+#ifdef RLIMIT_CORE
+ { "core file size", "512-blocks", RLIMIT_CORE, 512, 'c' },
+#endif
+#ifdef RLIMIT_RSS
+ { "max memory size", "kbytes", RLIMIT_RSS, 1024, 'm' },
+#endif
+#ifdef RLIMIT_MEMLOCK
+ { "locked memory", "kbytes", RLIMIT_MEMLOCK, 1024, 'l' },
+#endif
+#ifdef RLIMIT_NPROC
+ { "max user processes", (char *)0, RLIMIT_NPROC, 1, 'u' },
+#endif
+#ifdef RLIMIT_NOFILE
+ { "open files", (char *)0, RLIMIT_NOFILE, 1, 'n' },
+#endif
+#ifdef RLIMIT_VMEM
+ { "virtual mem size", "kbytes", RLIMIT_VMEM, 1024, 'v' },
+#endif
+#ifdef RLIMIT_SWAP
+ { "swap limit", "kbytes", RLIMIT_SWAP, 1024, 'w' },
+#endif
+#ifdef RLIMIT_SBSIZE
+ { "socket buffer size", "bytes", RLIMIT_SBSIZE, 1, 'b' },
+#endif
+#ifdef RLIMIT_NPTS
+ { "pseudo-terminals", (char *)0, RLIMIT_NPTS, 1, 'p' },
+#endif
+#ifdef RLIMIT_KQUEUES
+ { "kqueues", (char *)0, RLIMIT_KQUEUES, 1, 'k' },
+#endif
+#ifdef RLIMIT_UMTXP
+ { "umtx shared locks", (char *)0, RLIMIT_UMTXP, 1, 'o' },
+#endif
+#ifdef RLIMIT_PIPEBUF
+ { "pipebuf", "kbytes", RLIMIT_PIPEBUF, 1024, 'y' },
+#endif
+#ifdef RLIMIT_VMM
+ { "virtual machines", (char *)0, RLIMIT_VMM, 1, 'V' },
+#endif
+ { (char *) 0, (char *)0, 0, 0, '\0' }
+};
+
+enum limithow { SOFT = 0x1, HARD = 0x2 };
+
+static void
+printlimit(enum limithow how, const struct rlimit *limit,
+ const struct limits *l)
+{
+ rlim_t val = 0;
+
+ if (how & SOFT)
+ val = limit->rlim_cur;
+ else if (how & HARD)
+ val = limit->rlim_max;
+ if (val == RLIM_INFINITY)
+ out1str("unlimited\n");
+ else
+ {
+ val /= l->factor;
+ out1fmt("%jd\n", (intmax_t)val);
+ }
+}
+
+int
+ulimitcmd(int argc __unused, char **argv __unused)
+{
+ rlim_t val = 0;
+ enum limithow how = SOFT | HARD;
+ const struct limits *l;
+ int set, all = 0;
+ int optc, what;
+ struct rlimit limit;
+
+ what = 'f';
+ while ((optc = nextopt("abcdfHklmnopSstuVvwy")) != '\0')
+ switch (optc) {
+ case 'H':
+ how = HARD;
+ break;
+ case 'S':
+ how = SOFT;
+ break;
+ case 'a':
+ all = 1;
+ break;
+ default:
+ what = optc;
+ }
+
+ for (l = limits; l->name && l->option != what; l++)
+ ;
+ if (!l->name)
+ error("internal error (%c)", what);
+
+ set = *argptr ? 1 : 0;
+ if (set) {
+ char *p = *argptr;
+
+ if (all || argptr[1])
+ error("too many arguments");
+ if (strcmp(p, "unlimited") == 0)
+ val = RLIM_INFINITY;
+ else {
+ char *end;
+ uintmax_t uval;
+
+ if (*p < '0' || *p > '9')
+ error("bad number");
+ errno = 0;
+ uval = strtoumax(p, &end, 10);
+ if (errno != 0 || *end != '\0')
+ error("bad number");
+ if (uval > UINTMAX_MAX / l->factor)
+ error("bad number");
+ uval *= l->factor;
+ val = (rlim_t)uval;
+ if ((intmax_t)val < 0 || (uintmax_t)val != uval ||
+ val == RLIM_INFINITY)
+ error("bad number");
+ }
+ }
+ if (all) {
+ for (l = limits; l->name; l++) {
+ char optbuf[40];
+ if (getrlimit(l->cmd, &limit) < 0)
+ error("can't get limit: %s", strerror(errno));
+
+ if (l->units)
+ snprintf(optbuf, sizeof(optbuf),
+ "(%s, -%c) ", l->units, l->option);
+ else
+ snprintf(optbuf, sizeof(optbuf),
+ "(-%c) ", l->option);
+ out1fmt("%-18s %18s ", l->name, optbuf);
+ printlimit(how, &limit, l);
+ }
+ return 0;
+ }
+
+ if (getrlimit(l->cmd, &limit) < 0)
+ error("can't get limit: %s", strerror(errno));
+ if (set) {
+ if (how & SOFT)
+ limit.rlim_cur = val;
+ if (how & HARD)
+ limit.rlim_max = val;
+ if (setrlimit(l->cmd, &limit) < 0)
+ error("bad limit: %s", strerror(errno));
+ } else
+ printlimit(how, &limit, l);
+ return 0;
+}
diff --git a/cmd/posix/sh/mkbuiltins b/cmd/posix/sh/mkbuiltins
@@ -0,0 +1,156 @@
+#!/bin/sh -
+
+#-
+# Copyright (c) 1991, 1993
+# The Regents of the University of California. All rights reserved.
+#
+# This code is derived from software contributed to Berkeley by
+# Kenneth Almquist.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the University nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+temp=`mktemp -t ka.XXXXXX`
+srcdir=$1
+havejobs=0
+if grep '^#define[ ]*JOBS[ ]*1' $srcdir/shell.h > /dev/null
+then havejobs=1
+fi
+
+feature_histedit=0
+feature_local=1
+feature_let=1
+feature_ulimit=1
+feature_setvar=1
+feature_wordexp=1
+
+if [ -f ../../config.mk ]; then
+ feature_histedit=$(grep '^[[:space:]]*FEATURE_SH_HISTEDIT[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+ feature_local=$(grep '^[[:space:]]*FEATURE_SH_LOCAL[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+ feature_let=$(grep '^[[:space:]]*FEATURE_SH_LET[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+ feature_ulimit=$(grep '^[[:space:]]*FEATURE_SH_ULIMIT[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+ feature_setvar=$(grep '^[[:space:]]*FEATURE_SH_SETVAR[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+ feature_wordexp=$(grep '^[[:space:]]*FEATURE_SH_WORDEXP[[:space:]]*=' ../../config.mk | cut -d= -f2 | tr -d '[:space:]')
+fi
+
+exec > builtins.c
+cat <<\!
+/*
+ * This file was generated by the mkbuiltins program.
+ */
+
+#include <stdlib.h>
+#include "shell.h"
+#include "builtins.h"
+
+!
+awk '/^[^#]/ {
+ if ($0 ~ /#FEATURE_SH_HISTEDIT/ && '$feature_histedit' != 1) next;
+ if ($0 ~ /#FEATURE_SH_LOCAL/ && '$feature_local' != 1) next;
+ if ($0 ~ /#FEATURE_SH_LET/ && '$feature_let' != 1) next;
+ if ($0 ~ /#FEATURE_SH_ULIMIT/ && '$feature_ulimit' != 1) next;
+ if ($0 ~ /#FEATURE_SH_SETVAR/ && '$feature_setvar' != 1) next;
+ if ($0 ~ /#FEATURE_SH_WORDEXP/ && '$feature_wordexp' != 1) next;
+
+ if ('$havejobs' || $2 != "-j") {
+ sub(/#[A-Z0-9_]*/, "");
+ print $0
+ }
+}' $srcdir/builtins.def | sed 's/-j//' > $temp
+echo 'int (*const builtinfunc[])(int, char **) = {'
+awk '/^[^#]/ { printf "\t%s,\n", $1}' $temp
+echo '};
+
+const unsigned char builtincmd[] = {'
+awk '{ for (i = 2 ; i <= NF ; i++) {
+ if ($i == "-s") {
+ spc = 1;
+ } else if ($i == "-n") {
+ # Handled later for builtins.h
+ continue
+ } else {
+ printf "\t\"\\%03o\\%03o%s\"\n", length($i), (spc ? 128 : 0) + NR-1, $i
+ spc = 0;
+ }
+ }}' $temp
+echo '};'
+
+exec > builtins.h
+cat <<\!
+/*
+ * This file was generated by the mkbuiltins program.
+ */
+
+!
+tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ < $temp |
+ awk '{ printf "#define %s %d\n", $1, NR-1}'
+echo '
+#define BUILTIN_SPECIAL 0x80
+
+extern int (*const builtinfunc[])(int, char **);
+extern const unsigned char builtincmd[];
+'
+awk '{ printf "int %s(int, char **);\n", $1}' $temp
+
+# Build safe_builtin_always()
+cat <<EOF
+
+static inline int
+safe_builtin_always(int idx)
+{
+EOF
+awk '
+BEGIN { printed = 0 }
+{
+ for (i = 2 ; i <= NF ; i++) {
+ if ($i == "-s") {
+ continue
+ } else if ($i == "-n") {
+ nofork = 1;
+ } else {
+ if (nofork == 0) {
+ continue
+ }
+ if (printed == 1) {
+ printf " || \n\t "
+ } else {
+ printf "\tif ("
+ }
+ printf "idx == " toupper($1)
+ printed = 1
+ nofork = 0;
+ # Only need to check each once
+ break
+ }
+ }
+}' $temp
+
+cat << EOF
+)
+ return (1);
+ return(0);
+}
+EOF
+
+rm -f $temp
diff --git a/cmd/posix/sh/mknodes.c b/cmd/posix/sh/mknodes.c
@@ -0,0 +1,454 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This program reads the nodetypes file and nodes.c.pat file. It generates
+ * the files nodes.h and nodes.c.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <stdarg.h>
+
+#ifndef __printf0like
+#define __printf0like(n, m) __attribute__((__format__(__printf__, n, m)))
+#endif
+#ifndef __dead2
+#define __dead2 __attribute__((__noreturn__))
+#endif
+
+#define MAXTYPES 50 /* max number of node types */
+#define MAXFIELDS 20 /* max fields in a structure */
+#define BUFLEN 100 /* size of character buffers */
+
+/* field types */
+#define T_NODE 1 /* union node *field */
+#define T_NODELIST 2 /* struct nodelist *field */
+#define T_STRING 3
+#define T_INT 4 /* int field */
+#define T_OTHER 5 /* other */
+#define T_TEMP 6 /* don't copy this field */
+
+
+struct field { /* a structure field */
+ char *name; /* name of field */
+ int type; /* type of field */
+ char *decl; /* declaration of field */
+};
+
+
+struct str { /* struct representing a node structure */
+ char *tag; /* structure tag */
+ int nfields; /* number of fields in the structure */
+ struct field field[MAXFIELDS]; /* the fields of the structure */
+ int done; /* set if fully parsed */
+};
+
+
+static int ntypes; /* number of node types */
+static char *nodename[MAXTYPES]; /* names of the nodes */
+static struct str *nodestr[MAXTYPES]; /* type of structure used by the node */
+static int nstr; /* number of structures */
+static struct str str[MAXTYPES]; /* the structures */
+static struct str *curstr; /* current structure */
+static char line[1024];
+static int linno;
+static char *linep;
+
+static void parsenode(void);
+static void parsefield(void);
+static void output(char *);
+static void outsizes(FILE *);
+static void outfunc(FILE *, int);
+static void indent(int, FILE *);
+static int nextfield(char *);
+static void skipbl(void);
+static int readline(FILE *);
+static void error(const char *, ...) __printf0like(1, 2) __dead2;
+static char *savestr(const char *);
+
+
+int
+main(int argc, char *argv[])
+{
+ FILE *infp;
+
+ if (argc != 3)
+ error("usage: mknodes file");
+ if ((infp = fopen(argv[1], "r")) == NULL)
+ error("Can't open %s: %s", argv[1], strerror(errno));
+ while (readline(infp)) {
+ if (line[0] == ' ' || line[0] == '\t')
+ parsefield();
+ else if (line[0] != '\0')
+ parsenode();
+ }
+ fclose(infp);
+ output(argv[2]);
+ exit(0);
+}
+
+
+
+static void
+parsenode(void)
+{
+ char name[BUFLEN];
+ char tag[BUFLEN];
+ struct str *sp;
+
+ if (curstr && curstr->nfields > 0)
+ curstr->done = 1;
+ nextfield(name);
+ if (! nextfield(tag))
+ error("Tag expected");
+ if (*linep != '\0')
+ error("Garbage at end of line");
+ nodename[ntypes] = savestr(name);
+ for (sp = str ; sp < str + nstr ; sp++) {
+ if (strcmp(sp->tag, tag) == 0)
+ break;
+ }
+ if (sp >= str + nstr) {
+ sp->tag = savestr(tag);
+ sp->nfields = 0;
+ curstr = sp;
+ nstr++;
+ }
+ nodestr[ntypes] = sp;
+ ntypes++;
+}
+
+
+static void
+parsefield(void)
+{
+ char name[BUFLEN];
+ char type[BUFLEN];
+ char decl[2 * BUFLEN];
+ struct field *fp;
+
+ if (curstr == NULL || curstr->done)
+ error("No current structure to add field to");
+ if (! nextfield(name))
+ error("No field name");
+ if (! nextfield(type))
+ error("No field type");
+ fp = &curstr->field[curstr->nfields];
+ fp->name = savestr(name);
+ if (strcmp(type, "nodeptr") == 0) {
+ fp->type = T_NODE;
+ sprintf(decl, "union node *%s", name);
+ } else if (strcmp(type, "nodelist") == 0) {
+ fp->type = T_NODELIST;
+ sprintf(decl, "struct nodelist *%s", name);
+ } else if (strcmp(type, "string") == 0) {
+ fp->type = T_STRING;
+ sprintf(decl, "char *%s", name);
+ } else if (strcmp(type, "int") == 0) {
+ fp->type = T_INT;
+ sprintf(decl, "int %s", name);
+ } else if (strcmp(type, "other") == 0) {
+ fp->type = T_OTHER;
+ } else if (strcmp(type, "temp") == 0) {
+ fp->type = T_TEMP;
+ } else {
+ error("Unknown type %s", type);
+ }
+ if (fp->type == T_OTHER || fp->type == T_TEMP) {
+ skipbl();
+ fp->decl = savestr(linep);
+ } else {
+ if (*linep)
+ error("Garbage at end of line");
+ fp->decl = savestr(decl);
+ }
+ curstr->nfields++;
+}
+
+
+static const char writer[] = "\
+/*\n\
+ * This file was generated by the mknodes program.\n\
+ */\n\
+\n";
+
+static void
+output(char *file)
+{
+ FILE *hfile;
+ FILE *cfile;
+ FILE *patfile;
+ int i;
+ struct str *sp;
+ struct field *fp;
+ char *p;
+
+ if ((patfile = fopen(file, "r")) == NULL)
+ error("Can't open %s: %s", file, strerror(errno));
+ if ((hfile = fopen("nodes.h", "w")) == NULL)
+ error("Can't create nodes.h: %s", strerror(errno));
+ if ((cfile = fopen("nodes.c", "w")) == NULL)
+ error("Can't create nodes.c");
+ fputs(writer, hfile);
+ for (i = 0 ; i < ntypes ; i++)
+ fprintf(hfile, "#define %s %d\n", nodename[i], i);
+ fputs("\n\n\n", hfile);
+ for (sp = str ; sp < &str[nstr] ; sp++) {
+ fprintf(hfile, "struct %s {\n", sp->tag);
+ for (i = sp->nfields, fp = sp->field ; --i >= 0 ; fp++) {
+ fprintf(hfile, " %s;\n", fp->decl);
+ }
+ fputs("};\n\n\n", hfile);
+ }
+ fputs("union node {\n", hfile);
+ fprintf(hfile, " int type;\n");
+ for (sp = str ; sp < &str[nstr] ; sp++) {
+ fprintf(hfile, " struct %s %s;\n", sp->tag, sp->tag);
+ }
+ fputs("};\n\n\n", hfile);
+ fputs("struct nodelist {\n", hfile);
+ fputs("\tstruct nodelist *next;\n", hfile);
+ fputs("\tunion node *n;\n", hfile);
+ fputs("};\n\n\n", hfile);
+ fputs("struct funcdef;\n", hfile);
+ fputs("struct funcdef *copyfunc(union node *);\n", hfile);
+ fputs("union node *getfuncnode(struct funcdef *);\n", hfile);
+ fputs("void reffunc(struct funcdef *);\n", hfile);
+ fputs("void unreffunc(struct funcdef *);\n", hfile);
+ if (ferror(hfile))
+ error("Can't write to nodes.h");
+ if (fclose(hfile))
+ error("Can't close nodes.h");
+
+ fputs(writer, cfile);
+ while (fgets(line, sizeof line, patfile) != NULL) {
+ for (p = line ; *p == ' ' || *p == '\t' ; p++);
+ if (strcmp(p, "%SIZES\n") == 0)
+ outsizes(cfile);
+ else if (strcmp(p, "%CALCSIZE\n") == 0)
+ outfunc(cfile, 1);
+ else if (strcmp(p, "%COPY\n") == 0)
+ outfunc(cfile, 0);
+ else
+ fputs(line, cfile);
+ }
+ fclose(patfile);
+ if (ferror(cfile))
+ error("Can't write to nodes.c");
+ if (fclose(cfile))
+ error("Can't close nodes.c");
+}
+
+
+
+static void
+outsizes(FILE *cfile)
+{
+ int i;
+
+ fprintf(cfile, "static const short nodesize[%d] = {\n", ntypes);
+ for (i = 0 ; i < ntypes ; i++) {
+ fprintf(cfile, " ALIGN(sizeof (struct %s)),\n", nodestr[i]->tag);
+ }
+ fprintf(cfile, "};\n");
+}
+
+
+static void
+outfunc(FILE *cfile, int calcsize)
+{
+ struct str *sp;
+ struct field *fp;
+ int i;
+
+ fputs(" if (n == NULL)\n", cfile);
+ if (calcsize)
+ fputs(" return;\n", cfile);
+ else
+ fputs(" return NULL;\n", cfile);
+ if (calcsize)
+ fputs(" result->blocksize += nodesize[n->type];\n", cfile);
+ else {
+ fputs(" new = state->block;\n", cfile);
+ fputs(" state->block = (char *)state->block + nodesize[n->type];\n", cfile);
+ }
+ fputs(" switch (n->type) {\n", cfile);
+ for (sp = str ; sp < &str[nstr] ; sp++) {
+ for (i = 0 ; i < ntypes ; i++) {
+ if (nodestr[i] == sp)
+ fprintf(cfile, " case %s:\n", nodename[i]);
+ }
+ for (i = sp->nfields ; --i >= 1 ; ) {
+ fp = &sp->field[i];
+ switch (fp->type) {
+ case T_NODE:
+ if (calcsize) {
+ indent(12, cfile);
+ fprintf(cfile, "calcsize(n->%s.%s, result);\n",
+ sp->tag, fp->name);
+ } else {
+ indent(12, cfile);
+ fprintf(cfile, "new->%s.%s = copynode(n->%s.%s, state);\n",
+ sp->tag, fp->name, sp->tag, fp->name);
+ }
+ break;
+ case T_NODELIST:
+ if (calcsize) {
+ indent(12, cfile);
+ fprintf(cfile, "sizenodelist(n->%s.%s, result);\n",
+ sp->tag, fp->name);
+ } else {
+ indent(12, cfile);
+ fprintf(cfile, "new->%s.%s = copynodelist(n->%s.%s, state);\n",
+ sp->tag, fp->name, sp->tag, fp->name);
+ }
+ break;
+ case T_STRING:
+ if (calcsize) {
+ indent(12, cfile);
+ fprintf(cfile, "result->stringsize += strlen(n->%s.%s) + 1;\n",
+ sp->tag, fp->name);
+ } else {
+ indent(12, cfile);
+ fprintf(cfile, "new->%s.%s = nodesavestr(n->%s.%s, state);\n",
+ sp->tag, fp->name, sp->tag, fp->name);
+ }
+ break;
+ case T_INT:
+ case T_OTHER:
+ if (! calcsize) {
+ indent(12, cfile);
+ fprintf(cfile, "new->%s.%s = n->%s.%s;\n",
+ sp->tag, fp->name, sp->tag, fp->name);
+ }
+ break;
+ }
+ }
+ indent(12, cfile);
+ fputs("break;\n", cfile);
+ }
+ fputs(" };\n", cfile);
+ if (! calcsize)
+ fputs(" new->type = n->type;\n", cfile);
+}
+
+
+static void
+indent(int amount, FILE *fp)
+{
+ while (amount >= 8) {
+ putc('\t', fp);
+ amount -= 8;
+ }
+ while (--amount >= 0) {
+ putc(' ', fp);
+ }
+}
+
+
+static int
+nextfield(char *buf)
+{
+ char *p, *q;
+
+ p = linep;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ q = buf;
+ while (*p != ' ' && *p != '\t' && *p != '\0')
+ *q++ = *p++;
+ *q = '\0';
+ linep = p;
+ return (q > buf);
+}
+
+
+static void
+skipbl(void)
+{
+ while (*linep == ' ' || *linep == '\t')
+ linep++;
+}
+
+
+static int
+readline(FILE *infp)
+{
+ char *p;
+
+ if (fgets(line, 1024, infp) == NULL)
+ return 0;
+ for (p = line ; *p != '#' && *p != '\n' && *p != '\0' ; p++);
+ while (p > line && (p[-1] == ' ' || p[-1] == '\t'))
+ p--;
+ *p = '\0';
+ linep = line;
+ linno++;
+ if (p - line > BUFLEN)
+ error("Line too long");
+ return 1;
+}
+
+
+
+static void
+error(const char *msg, ...)
+{
+ va_list va;
+ va_start(va, msg);
+
+ (void) fprintf(stderr, "line %d: ", linno);
+ (void) vfprintf(stderr, msg, va);
+ (void) fputc('\n', stderr);
+
+ va_end(va);
+
+ exit(2);
+}
+
+
+
+static char *
+savestr(const char *s)
+{
+ char *p;
+
+ if ((p = malloc(strlen(s) + 1)) == NULL)
+ error("Out of space");
+ (void) strcpy(p, s);
+ return p;
+}
diff --git a/cmd/posix/sh/mksyntax.c b/cmd/posix/sh/mksyntax.c
@@ -0,0 +1,321 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * This program creates syntax.h and syntax.c.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "parser.h"
+
+#ifndef __unused
+#define __unused __attribute__((__unused__))
+#endif
+
+
+struct synclass {
+ const char *name;
+ const char *comment;
+};
+
+/* Syntax classes */
+static const struct synclass synclass[] = {
+ { "CWORD", "character is nothing special" },
+ { "CNL", "newline character" },
+ { "CQNL", "newline character in quotes" },
+ { "CBACK", "a backslash character" },
+ { "CSBACK", "a backslash character in single quotes" },
+ { "CSQUOTE", "single quote" },
+ { "CDQUOTE", "double quote" },
+ { "CENDQUOTE", "a terminating quote" },
+ { "CBQUOTE", "backwards single quote" },
+ { "CVAR", "a dollar sign" },
+ { "CENDVAR", "a '}' character" },
+ { "CLP", "a left paren in arithmetic" },
+ { "CRP", "a right paren in arithmetic" },
+ { "CEOF", "end of file" },
+ { "CCTL", "like CWORD, except it must be escaped" },
+ { "CSPCL", "these terminate a word" },
+ { "CIGN", "character should be ignored" },
+ { NULL, NULL }
+};
+
+
+/*
+ * Syntax classes for is_ functions. Warning: if you add new classes
+ * you may have to change the definition of the is_in_name macro.
+ */
+static const struct synclass is_entry[] = {
+ { "ISDIGIT", "a digit" },
+ { "ISUPPER", "an upper case letter" },
+ { "ISLOWER", "a lower case letter" },
+ { "ISUNDER", "an underscore" },
+ { "ISSPECL", "the name of a special parameter" },
+ { NULL, NULL }
+};
+
+static const char writer[] = "\
+/*\n\
+ * This file was generated by the mksyntax program.\n\
+ */\n\
+\n";
+
+
+static FILE *cfile;
+static FILE *hfile;
+
+static void add_default(void);
+static void finish(void);
+static void init(const char *);
+static void add(const char *, const char *);
+static void output_type_macros(void);
+
+int
+main(int argc __unused, char **argv __unused)
+{
+ int i;
+ char buf[80];
+ int pos;
+
+ /* Create output files */
+ if ((cfile = fopen("syntax.c", "w")) == NULL) {
+ perror("syntax.c");
+ exit(2);
+ }
+ if ((hfile = fopen("syntax.h", "w")) == NULL) {
+ perror("syntax.h");
+ exit(2);
+ }
+ fputs(writer, hfile);
+ fputs(writer, cfile);
+
+ fputs("#include <limits.h>\n\n", hfile);
+
+ /* Generate the #define statements in the header file */
+ fputs("/* Syntax classes */\n", hfile);
+ for (i = 0 ; synclass[i].name ; i++) {
+ sprintf(buf, "#define %s %d", synclass[i].name, i);
+ fputs(buf, hfile);
+ for (pos = strlen(buf) ; pos < 32 ; pos = (pos + 8) & ~07)
+ putc('\t', hfile);
+ fprintf(hfile, "/* %s */\n", synclass[i].comment);
+ }
+ putc('\n', hfile);
+ fputs("/* Syntax classes for is_ functions */\n", hfile);
+ for (i = 0 ; is_entry[i].name ; i++) {
+ sprintf(buf, "#define %s %#o", is_entry[i].name, 1 << i);
+ fputs(buf, hfile);
+ for (pos = strlen(buf) ; pos < 32 ; pos = (pos + 8) & ~07)
+ putc('\t', hfile);
+ fprintf(hfile, "/* %s */\n", is_entry[i].comment);
+ }
+ putc('\n', hfile);
+ fputs("#define SYNBASE (1 - CHAR_MIN)\n", hfile);
+ fputs("#define PEOF -SYNBASE\n\n", hfile);
+ putc('\n', hfile);
+ fputs("#define BASESYNTAX (basesyntax + SYNBASE)\n", hfile);
+ fputs("#define DQSYNTAX (dqsyntax + SYNBASE)\n", hfile);
+ fputs("#define SQSYNTAX (sqsyntax + SYNBASE)\n", hfile);
+ fputs("#define ARISYNTAX (arisyntax + SYNBASE)\n", hfile);
+ putc('\n', hfile);
+ output_type_macros(); /* is_digit, etc. */
+ putc('\n', hfile);
+
+ /* Generate the syntax tables. */
+ fputs("#include \"parser.h\"\n", cfile);
+ fputs("#include \"shell.h\"\n", cfile);
+ fputs("#include \"syntax.h\"\n\n", cfile);
+
+ fputs("/* syntax table used when not in quotes */\n", cfile);
+ init("basesyntax");
+ add_default();
+ add("\n", "CNL");
+ add("\\", "CBACK");
+ add("'", "CSQUOTE");
+ add("\"", "CDQUOTE");
+ add("`", "CBQUOTE");
+ add("$", "CVAR");
+ add("}", "CENDVAR");
+ add("<>();&| \t", "CSPCL");
+ finish();
+
+ fputs("\n/* syntax table used when in double quotes */\n", cfile);
+ init("dqsyntax");
+ add_default();
+ add("\n", "CQNL");
+ add("\\", "CBACK");
+ add("\"", "CENDQUOTE");
+ add("`", "CBQUOTE");
+ add("$", "CVAR");
+ add("}", "CENDVAR");
+ /* ':/' for tilde expansion, '-^]' for [a\-x] pattern ranges */
+ add("!*?[]=~:/-^", "CCTL");
+ finish();
+
+ fputs("\n/* syntax table used when in single quotes */\n", cfile);
+ init("sqsyntax");
+ add_default();
+ add("\n", "CQNL");
+ add("\\", "CSBACK");
+ add("'", "CENDQUOTE");
+ /* ':/' for tilde expansion, '-^]' for [a\-x] pattern ranges */
+ add("!*?[]=~:/-^", "CCTL");
+ finish();
+
+ fputs("\n/* syntax table used when in arithmetic */\n", cfile);
+ init("arisyntax");
+ add_default();
+ add("\n", "CQNL");
+ add("\\", "CBACK");
+ add("`", "CBQUOTE");
+ add("\"", "CIGN");
+ add("$", "CVAR");
+ add("}", "CENDVAR");
+ add("(", "CLP");
+ add(")", "CRP");
+ finish();
+
+ fputs("\n/* character classification table */\n", cfile);
+ init("is_type");
+ add("0123456789", "ISDIGIT");
+ add("abcdefghijklmnopqrstuvwxyz", "ISLOWER");
+ add("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ISUPPER");
+ add("_", "ISUNDER");
+ add("#?$!-*@", "ISSPECL");
+ finish();
+
+ exit(0);
+}
+
+
+/*
+ * Output the header and declaration of a syntax table.
+ */
+
+static void
+init(const char *name)
+{
+ fprintf(hfile, "extern const char %s[];\n", name);
+ fprintf(cfile, "const char %s[SYNBASE + CHAR_MAX + 1] = {\n", name);
+}
+
+
+static void
+add_one(const char *key, const char *type)
+{
+ fprintf(cfile, "\t[SYNBASE + %s] = %s,\n", key, type);
+}
+
+
+/*
+ * Add default values to the syntax table.
+ */
+
+static void
+add_default(void)
+{
+ add_one("PEOF", "CEOF");
+ add_one("CTLESC", "CCTL");
+ add_one("CTLVAR", "CCTL");
+ add_one("CTLENDVAR", "CCTL");
+ add_one("CTLBACKQ", "CCTL");
+ add_one("CTLBACKQ + CTLQUOTE", "CCTL");
+ add_one("CTLARI", "CCTL");
+ add_one("CTLENDARI", "CCTL");
+ add_one("CTLQUOTEMARK", "CCTL");
+ add_one("CTLQUOTEEND", "CCTL");
+}
+
+
+/*
+ * Output the footer of a syntax table.
+ */
+
+static void
+finish(void)
+{
+ fputs("};\n", cfile);
+}
+
+
+/*
+ * Add entries to the syntax table.
+ */
+
+static void
+add(const char *p, const char *type)
+{
+ for (; *p; ++p) {
+ char c = *p;
+ switch (c) {
+ case '\t': c = 't'; break;
+ case '\n': c = 'n'; break;
+ case '\'': c = '\''; break;
+ case '\\': c = '\\'; break;
+
+ default:
+ fprintf(cfile, "\t[SYNBASE + '%c'] = %s,\n", c, type);
+ continue;
+ }
+ fprintf(cfile, "\t[SYNBASE + '\\%c'] = %s,\n", c, type);
+ }
+}
+
+
+/*
+ * Output character classification macros (e.g. is_digit). If digits are
+ * contiguous, we can test for them quickly.
+ */
+
+static const char *macro[] = {
+ "#define is_digit(c)\t((unsigned int)((c) - '0') <= 9)",
+ "#define is_eof(c)\t((c) == PEOF)",
+ "#define is_alpha(c)\t((is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER))",
+ "#define is_name(c)\t((is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER|ISUNDER))",
+ "#define is_in_name(c)\t((is_type+SYNBASE)[(int)c] & (ISUPPER|ISLOWER|ISUNDER|ISDIGIT))",
+ "#define is_special(c)\t((is_type+SYNBASE)[(int)c] & (ISSPECL|ISDIGIT))",
+ "#define digit_val(c)\t((c) - '0')",
+ NULL
+};
+
+static void
+output_type_macros(void)
+{
+ const char **pp;
+
+ for (pp = macro ; *pp ; pp++)
+ fprintf(hfile, "%s\n", *pp);
+}
diff --git a/cmd/posix/sh/mktokens b/cmd/posix/sh/mktokens
@@ -0,0 +1,90 @@
+#!/bin/sh -
+
+#-
+# Copyright (c) 1991, 1993
+# The Regents of the University of California. All rights reserved.
+#
+# This code is derived from software contributed to Berkeley by
+# Kenneth Almquist.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the University nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+# The following is a list of tokens. The second column is nonzero if the
+# token marks the end of a list. The third column is the name to print in
+# error messages.
+
+temp=`mktemp -t ka.XXXXXX`
+cat > $temp <<\!
+TEOF 1 end of file
+TNL 0 newline
+TSEMI 0 ";"
+TBACKGND 0 "&"
+TAND 0 "&&"
+TOR 0 "||"
+TPIPE 0 "|"
+TLP 0 "("
+TRP 1 ")"
+TENDCASE 1 ";;"
+TFALLTHRU 1 ";&"
+TREDIR 0 redirection
+TWORD 0 word
+TIF 0 "if"
+TTHEN 1 "then"
+TELSE 1 "else"
+TELIF 1 "elif"
+TFI 1 "fi"
+TWHILE 0 "while"
+TUNTIL 0 "until"
+TFOR 0 "for"
+TDO 1 "do"
+TDONE 1 "done"
+TBEGIN 0 "{"
+TEND 1 "}"
+TCASE 0 "case"
+TESAC 1 "esac"
+TNOT 0 "!"
+!
+nl=`wc -l $temp`
+exec > token.h
+awk '{print "#define " $1 " " NR-1}' $temp
+echo '
+/* Array indicating which tokens mark the end of a list */
+static const char tokendlist[] = {'
+awk '{print "\t" $2 ","}' $temp
+echo '};
+
+static const char *const tokname[] = {'
+sed -e 's/"/\\"/g' \
+ -e 's/[^ ]*[ ][ ]*[^ ]*[ ][ ]*\(.*\)/ "\1",/' \
+ $temp
+echo '};
+'
+sed 's/"//g' $temp | awk '
+/TIF/{print "#define KWDOFFSET " NR-1; print ""; print "const char *const parsekwd[] = {"}
+/TIF/,/neverfound/{print " \"" $3 "\","}'
+echo ' 0
+};'
+
+rm $temp
diff --git a/cmd/posix/sh/myhistedit.h b/cmd/posix/sh/myhistedit.h
@@ -0,0 +1,37 @@
+#ifndef MYHISTEDIT_H_
+#define MYHISTEDIT_H_
+
+#if FEATURE_SH_HISTEDIT
+
+#include <histedit.h>
+#include <filecomplete.h>
+
+extern History *hist;
+extern EditLine *el;
+
+void histedit(void);
+void sethistsize(const char *);
+void setterm(const char *);
+void histload(void);
+void histsave(void);
+
+#else
+
+/* stubbed histedit definitions */
+typedef void History;
+typedef void EditLine;
+
+extern History *hist;
+extern EditLine *el;
+
+#define histedit() ((void)0)
+#define sethistsize(s) ((void)0)
+#define setterm(t) ((void)0)
+#define histload() ((void)0)
+#define histsave() ((void)0)
+
+#endif
+
+extern int displayhist;
+
+#endif /* !MYHISTEDIT_H_ */
diff --git a/cmd/posix/sh/mystring.c b/cmd/posix/sh/mystring.c
@@ -0,0 +1,92 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * String functions.
+ *
+ * equal(s1, s2) Return true if strings are equal.
+ * number(s) Convert a string of digits to an integer.
+ * is_number(s) Return true if s is a string of digits.
+ */
+
+#include <stdlib.h>
+#include "shell.h"
+#include "syntax.h"
+#include "error.h"
+#include "mystring.h"
+
+
+char nullstr[1]; /* zero length string */
+
+/*
+ * equal - #defined in mystring.h
+ */
+
+
+/*
+ * Convert a string of digits to an integer, printing an error message on
+ * failure.
+ */
+
+int
+number(const char *s)
+{
+ if (! is_number(s))
+ error("Illegal number: %s", s);
+ return atoi(s);
+}
+
+
+
+/*
+ * Check for a valid number. This should be elsewhere.
+ */
+
+int
+is_number(const char *p)
+{
+ const char *q;
+
+ if (*p == '\0')
+ return 0;
+ while (*p == '0')
+ p++;
+ for (q = p; *q != '\0'; q++)
+ if (! is_digit(*q))
+ return 0;
+ if (q - p > 10 ||
+ (q - p == 10 && memcmp(p, "2147483647", 10) > 0))
+ return 0;
+ return 1;
+}
diff --git a/cmd/posix/sh/mystring.h b/cmd/posix/sh/mystring.h
@@ -0,0 +1,40 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <string.h>
+
+int number(const char *);
+int is_number(const char *);
+
+#define equal(s1, s2) (strcmp(s1, s2) == 0)
diff --git a/cmd/posix/sh/nodes.c.pat b/cmd/posix/sh/nodes.c.pat
@@ -0,0 +1,190 @@
+/*-
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/param.h>
+#include <stdlib.h>
+#include <stddef.h>
+/*
+ * Routine for dealing with parsed shell commands.
+ */
+
+#include "shell.h"
+#include "nodes.h"
+#include "memalloc.h"
+#include "mystring.h"
+
+
+struct nodesize {
+ int blocksize; /* size of structures in function */
+ int stringsize; /* size of strings in node */
+};
+
+struct nodecopystate {
+ pointer block; /* block to allocate function from */
+ char *string; /* block to allocate strings from */
+};
+
+%SIZES
+
+
+static void calcsize(union node *, struct nodesize *);
+static void sizenodelist(struct nodelist *, struct nodesize *);
+static union node *copynode(union node *, struct nodecopystate *);
+static struct nodelist *copynodelist(struct nodelist *, struct nodecopystate *);
+static char *nodesavestr(const char *, struct nodecopystate *);
+
+
+struct funcdef {
+ unsigned int refcount;
+ union node n;
+};
+
+/*
+ * Make a copy of a parse tree.
+ */
+
+struct funcdef *
+copyfunc(union node *n)
+{
+ struct nodesize sz;
+ struct nodecopystate st;
+ struct funcdef *fn;
+
+ if (n == NULL)
+ return NULL;
+ sz.blocksize = offsetof(struct funcdef, n);
+ sz.stringsize = 0;
+ calcsize(n, &sz);
+ fn = ckmalloc(sz.blocksize + sz.stringsize);
+ fn->refcount = 1;
+ st.block = (char *)fn + offsetof(struct funcdef, n);
+ st.string = (char *)fn + sz.blocksize;
+ copynode(n, &st);
+ return fn;
+}
+
+
+union node *
+getfuncnode(struct funcdef *fn)
+{
+ return fn == NULL ? NULL : &fn->n;
+}
+
+
+static void
+calcsize(union node *n, struct nodesize *result)
+{
+ %CALCSIZE
+}
+
+
+
+static void
+sizenodelist(struct nodelist *lp, struct nodesize *result)
+{
+ while (lp) {
+ result->blocksize += ALIGN(sizeof(struct nodelist));
+ calcsize(lp->n, result);
+ lp = lp->next;
+ }
+}
+
+
+
+static union node *
+copynode(union node *n, struct nodecopystate *state)
+{
+ union node *new;
+
+ %COPY
+ return new;
+}
+
+
+static struct nodelist *
+copynodelist(struct nodelist *lp, struct nodecopystate *state)
+{
+ struct nodelist *start;
+ struct nodelist **lpp;
+
+ lpp = &start;
+ while (lp) {
+ *lpp = state->block;
+ state->block = (char *)state->block +
+ ALIGN(sizeof(struct nodelist));
+ (*lpp)->n = copynode(lp->n, state);
+ lp = lp->next;
+ lpp = &(*lpp)->next;
+ }
+ *lpp = NULL;
+ return start;
+}
+
+
+
+static char *
+nodesavestr(const char *s, struct nodecopystate *state)
+{
+ const char *p = s;
+ char *q = state->string;
+ char *rtn = state->string;
+
+ while ((*q++ = *p++) != '\0')
+ continue;
+ state->string = q;
+ return rtn;
+}
+
+
+void
+reffunc(struct funcdef *fn)
+{
+ if (fn)
+ fn->refcount++;
+}
+
+
+/*
+ * Decrement the reference count of a function definition, freeing it
+ * if it falls to 0.
+ */
+
+void
+unreffunc(struct funcdef *fn)
+{
+ if (fn) {
+ fn->refcount--;
+ if (fn->refcount > 0)
+ return;
+ ckfree(fn);
+ }
+}
diff --git a/cmd/posix/sh/nodetypes b/cmd/posix/sh/nodetypes
@@ -0,0 +1,142 @@
+#-
+# Copyright (c) 1991, 1993
+# The Regents of the University of California. All rights reserved.
+#
+# This code is derived from software contributed to Berkeley by
+# Kenneth Almquist.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+# 3. Neither the name of the University nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+# SUCH DAMAGE.
+
+# This file describes the nodes used in parse trees. Unindented lines
+# contain a node type followed by a structure tag. Subsequent indented
+# lines specify the fields of the structure. Several node types can share
+# the same structure, in which case the fields of the structure should be
+# specified only once.
+#
+# A field of a structure is described by the name of the field followed
+# by a type. The currently implemented types are:
+# nodeptr - a pointer to a node
+# nodelist - a pointer to a list of nodes
+# string - a pointer to a nul terminated string
+# int - an integer
+# other - any type that can be copied by assignment
+# temp - a field that doesn't have to be copied when the node is copied
+# The last two types should be followed by the text of a C declaration for
+# the field.
+
+NSEMI nbinary # two commands separated by a semicolon
+ type int
+ ch1 nodeptr # the first child
+ ch2 nodeptr # the second child
+
+NCMD ncmd # a simple command
+ type int
+ args nodeptr # the arguments
+ redirect nodeptr # list of file redirections
+
+NPIPE npipe # a pipeline
+ type int
+ backgnd int # set to run pipeline in background
+ cmdlist nodelist # the commands in the pipeline
+
+NREDIR nredir # redirection (of a complex command)
+ type int
+ n nodeptr # the command
+ redirect nodeptr # list of file redirections
+
+NBACKGND nredir # run command in background
+NSUBSHELL nredir # run command in a subshell
+
+NAND nbinary # the && operator
+NOR nbinary # the || operator
+
+NIF nif # the if statement. Elif clauses are handled
+ type int # using multiple if nodes.
+ test nodeptr # if test
+ ifpart nodeptr # then ifpart
+ elsepart nodeptr # else elsepart
+
+NWHILE nbinary # the while statement. First child is the test
+NUNTIL nbinary # the until statement
+
+NFOR nfor # the for statement
+ type int
+ args nodeptr # for var in args
+ body nodeptr # do body; done
+ var string # the for variable
+
+NCASE ncase # a case statement
+ type int
+ expr nodeptr # the word to switch on
+ cases nodeptr # the list of cases (NCLIST nodes)
+
+NCLIST nclist # a case ending with ;;
+ type int
+ next nodeptr # the next case in list
+ pattern nodeptr # list of patterns for this case
+ body nodeptr # code to execute for this case
+
+NCLISTFALLTHRU nclist # a case ending with ;&
+
+NDEFUN narg # define a function. The "next" field contains
+ # the body of the function.
+
+NARG narg # represents a word
+ type int
+ next nodeptr # next word in list
+ text string # the text of the word
+ backquote nodelist # list of commands in back quotes
+
+NTO nfile # fd> fname
+NFROM nfile # fd< fname
+NFROMTO nfile # fd<> fname
+NAPPEND nfile # fd>> fname
+NCLOBBER nfile # fd>| fname
+ type int
+ fd int # file descriptor being redirected
+ next nodeptr # next redirection in list
+ fname nodeptr # file name, in a NARG node
+ expfname temp char *expfname # actual file name
+
+NTOFD ndup # fd<&dupfd
+NFROMFD ndup # fd>&dupfd
+ type int
+ fd int # file descriptor being redirected
+ next nodeptr # next redirection in list
+ dupfd int # file descriptor to duplicate
+ vname nodeptr # file name if fd>&$var
+
+
+NHERE nhere # fd<<\!
+NXHERE nhere # fd<<!
+ type int
+ fd int # file descriptor being redirected
+ next nodeptr # next redirection in list
+ doc nodeptr # input to command (NARG node)
+ expdoc temp const char *expdoc # actual document (for NXHERE)
+
+NNOT nnot # ! command (actually pipeline)
+ type int
+ com nodeptr
diff --git a/cmd/posix/sh/options.c b/cmd/posix/sh/options.c
@@ -0,0 +1,597 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <signal.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+#include "shell.h"
+#define DEFINE_OPTIONS
+#include "options.h"
+#undef DEFINE_OPTIONS
+#include "nodes.h" /* for other header files */
+#include "eval.h"
+#include "jobs.h"
+#include "input.h"
+#include "output.h"
+#include "trap.h"
+#include "var.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "builtins.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+char *arg0; /* value of $0 */
+struct shparam shellparam; /* current positional parameters */
+char **argptr; /* argument list for builtin commands */
+char *shoptarg; /* set by nextopt (like getopt) */
+char *nextopt_optptr; /* used by nextopt */
+
+char *minusc; /* argument to -c option */
+
+
+static int options(int);
+static void minus_o(char *, int);
+static void setoption(int, int);
+static void setoptionbyindex(int, int);
+static void setparam(int, char **);
+static int getopts(char *, char *, char **, char ***, char **);
+
+
+/*
+ * Process the shell command line arguments.
+ */
+
+int
+procargs(int argc, char **argv)
+{
+ int i, login;
+ char *scriptname;
+
+ argptr = argv;
+ login = argptr[0] != NULL && argptr[0][0] == '-';
+ if (argc > 0)
+ argptr++;
+ for (i = 0; i < NOPTS; i++)
+ optval[i] = 2;
+ privileged = (getuid() != geteuid() || getgid() != getegid());
+ login |= options(1);
+ if (*argptr == NULL && minusc == NULL)
+ sflag = 1;
+ if (iflag != 0 && sflag == 1 && isatty(0) && isatty(1)) {
+ iflag = 1;
+ if (Eflag == 2)
+ Eflag = 1;
+ }
+ if (mflag == 2)
+ mflag = iflag;
+ for (i = 0; i < NOPTS; i++)
+ if (optval[i] == 2)
+ optval[i] = 0;
+ arg0 = argv[0];
+ if (sflag == 0 && minusc == NULL) {
+ scriptname = *argptr++;
+ setinputfile(scriptname, 0, -1 /* verify */);
+ commandname = arg0 = scriptname;
+ }
+ /* POSIX 1003.2: first arg after -c cmd is $0, remainder $1... */
+ if (argptr && minusc && *argptr)
+ arg0 = *argptr++;
+
+ shellparam.p = argptr;
+ shellparam.reset = 1;
+ /* assert(shellparam.malloc == 0 && shellparam.nparam == 0); */
+ while (*argptr) {
+ shellparam.nparam++;
+ argptr++;
+ }
+ optschanged();
+
+ return (login);
+}
+
+
+void
+optschanged(void)
+{
+ setinteractive();
+#ifndef NO_HISTORY
+ histedit();
+#endif
+ setjobctl(mflag);
+}
+
+/*
+ * Process shell options. The global variable argptr contains a pointer
+ * to the argument list; we advance it past the options.
+ * If cmdline is true, process the shell's argv; otherwise, process arguments
+ * to the set special builtin.
+ */
+
+static int
+options(int cmdline)
+{
+ char *kp, *p;
+ int val;
+ int c;
+ int login = 0;
+
+ if (cmdline)
+ minusc = NULL;
+ while ((p = *argptr) != NULL) {
+ argptr++;
+ if ((c = *p++) == '-') {
+ val = 1;
+ /* A "-" or "--" terminates options */
+ if (p[0] == '\0')
+ goto end_options1;
+ if (p[0] == '-' && p[1] == '\0')
+ goto end_options2;
+ /**
+ * For the benefit of `#!' lines in shell scripts,
+ * treat a string of '-- *#.*' the same as '--'.
+ * This is needed so that a script starting with:
+ * #!/bin/sh -- # -*- perl -*-
+ * will continue to work after a change is made to
+ * kern/imgact_shell.c to NOT token-ize the options
+ * specified on a '#!' line. A bit of a kludge,
+ * but that trick is recommended in documentation
+ * for some scripting languages, and we might as
+ * well continue to support it.
+ */
+ if (p[0] == '-') {
+ kp = p + 1;
+ while (*kp == ' ' || *kp == '\t')
+ kp++;
+ if (*kp == '#' || *kp == '\0')
+ goto end_options2;
+ }
+ } else if (c == '+') {
+ val = 0;
+ } else {
+ argptr--;
+ break;
+ }
+ while ((c = *p++) != '\0') {
+ if (c == 'c' && cmdline) {
+ char *q;
+
+ q = *argptr++;
+ if (q == NULL || minusc != NULL)
+ error("Bad -c option");
+ minusc = q;
+ } else if (c == 'l' && cmdline) {
+ login = 1;
+ } else if (c == 'o') {
+ minus_o(*argptr, val);
+ if (*argptr)
+ argptr++;
+ } else
+ setoption(c, val);
+ }
+ }
+ return (login);
+
+ /* When processing `set', a single "-" means turn off -x and -v */
+end_options1:
+ if (!cmdline) {
+ xflag = vflag = 0;
+ return (login);
+ }
+
+ /*
+ * When processing `set', a "--" means the remaining arguments
+ * replace the positional parameters in the active shell. If
+ * there are no remaining options, then all the positional
+ * parameters are cleared (equivalent to doing ``shift $#'').
+ */
+end_options2:
+ if (!cmdline) {
+ if (*argptr == NULL)
+ setparam(0, argptr);
+ return (login);
+ }
+
+ /*
+ * At this point we are processing options given to 'sh' on a command
+ * line. If an end-of-options marker ("-" or "--") is followed by an
+ * arg of "#", then skip over all remaining arguments. Some scripting
+ * languages (e.g.: perl) document that /bin/sh will implement this
+ * behavior, and they recommend that users take advantage of it to
+ * solve certain issues that can come up when writing a perl script.
+ * Yes, this feature is in /bin/sh to help users write perl scripts.
+ */
+ p = *argptr;
+ if (p != NULL && p[0] == '#' && p[1] == '\0') {
+ while (*argptr != NULL)
+ argptr++;
+ /* We need to keep the final argument */
+ argptr--;
+ }
+
+ return (login);
+}
+
+static void
+minus_o(char *name, int val)
+{
+ int i;
+ const unsigned char *on;
+ size_t len;
+
+ if (name == NULL) {
+ if (val) {
+ /* "Pretty" output. */
+ out1str("Current option settings\n");
+ for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
+ out1fmt("%-16.*s%s\n", *on, on + 1,
+ optval[i] ? "on" : "off");
+ } else {
+ /* Output suitable for re-input to shell. */
+ for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
+ out1fmt("%s %co %.*s%s",
+ i % 6 == 0 ? "set" : "",
+ optval[i] ? '-' : '+',
+ *on, on + 1,
+ i % 6 == 5 || i == NOPTS - 1 ? "\n" : "");
+ }
+ } else {
+ len = strlen(name);
+ for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1)
+ if (*on == len && memcmp(on + 1, name, len) == 0) {
+ setoptionbyindex(i, val);
+ return;
+ }
+ error("Illegal option -o %s", name);
+ }
+}
+
+
+static void
+setoptionbyindex(int idx, int val)
+{
+ if (&optval[idx] == &privileged && !val && privileged) {
+ if (setgid(getgid()) == -1)
+ error("setgid");
+ if (setuid(getuid()) == -1)
+ error("setuid");
+ }
+ optval[idx] = val;
+ if (val) {
+ /* #%$ hack for ksh semantics */
+ if (&optval[idx] == &Vflag)
+ Eflag = 0;
+ else if (&optval[idx] == &Eflag)
+ Vflag = 0;
+ }
+}
+
+static void
+setoption(int flag, int val)
+{
+ int i;
+
+ for (i = 0; i < NSHORTOPTS; i++)
+ if (optletter[i] == flag) {
+ setoptionbyindex(i, val);
+ return;
+ }
+ error("Illegal option -%c", flag);
+}
+
+
+/*
+ * Set the shell parameters.
+ */
+
+static void
+setparam(int argc, char **argv)
+{
+ char **newparam;
+ char **ap;
+
+ ap = newparam = ckmalloc((argc + 1) * sizeof *ap);
+ while (*argv) {
+ *ap++ = savestr(*argv++);
+ }
+ *ap = NULL;
+ freeparam(&shellparam);
+ shellparam.malloc = 1;
+ shellparam.nparam = argc;
+ shellparam.p = newparam;
+ shellparam.optp = NULL;
+ shellparam.reset = 1;
+ shellparam.optnext = NULL;
+}
+
+
+/*
+ * Free the list of positional parameters.
+ */
+
+void
+freeparam(struct shparam *param)
+{
+ char **ap;
+
+ if (param->malloc) {
+ for (ap = param->p ; *ap ; ap++)
+ ckfree(*ap);
+ ckfree(param->p);
+ }
+ if (param->optp) {
+ for (ap = param->optp ; *ap ; ap++)
+ ckfree(*ap);
+ ckfree(param->optp);
+ }
+}
+
+
+
+/*
+ * The shift builtin command.
+ */
+
+int
+shiftcmd(int argc, char **argv)
+{
+ int i, n;
+
+ n = 1;
+ if (argc > 1)
+ n = number(argv[1]);
+ if (n > shellparam.nparam)
+ return 1;
+ INTOFF;
+ shellparam.nparam -= n;
+ if (shellparam.malloc)
+ for (i = 0; i < n; i++)
+ ckfree(shellparam.p[i]);
+ memmove(shellparam.p, shellparam.p + n,
+ (shellparam.nparam + 1) * sizeof(shellparam.p[0]));
+ shellparam.reset = 1;
+ INTON;
+ return 0;
+}
+
+
+
+/*
+ * The set builtin command.
+ */
+
+int
+setcmd(int argc, char **argv)
+{
+ if (argc == 1)
+ return showvarscmd(argc, argv);
+ INTOFF;
+ options(0);
+ optschanged();
+ if (*argptr != NULL) {
+ setparam(argc - (argptr - argv), argptr);
+ }
+ INTON;
+ return 0;
+}
+
+
+void
+getoptsreset(const char *value)
+{
+ while (*value == '0')
+ value++;
+ if (strcmp(value, "1") == 0)
+ shellparam.reset = 1;
+}
+
+/*
+ * The getopts builtin. Shellparam.optnext points to the next argument
+ * to be processed. Shellparam.optptr points to the next character to
+ * be processed in the current argument. If shellparam.optnext is NULL,
+ * then it's the first time getopts has been called.
+ */
+
+int
+getoptscmd(int argc, char **argv)
+{
+ char **optbase = NULL, **ap;
+ int i;
+
+ if (argc < 3)
+ error("usage: getopts optstring var [arg]");
+
+ if (shellparam.reset == 1) {
+ INTOFF;
+ if (shellparam.optp) {
+ for (ap = shellparam.optp ; *ap ; ap++)
+ ckfree(*ap);
+ ckfree(shellparam.optp);
+ shellparam.optp = NULL;
+ }
+ if (argc > 3) {
+ shellparam.optp = ckmalloc((argc - 2) * sizeof *ap);
+ memset(shellparam.optp, '\0', (argc - 2) * sizeof *ap);
+ for (i = 0; i < argc - 3; i++)
+ shellparam.optp[i] = savestr(argv[i + 3]);
+ }
+ INTON;
+ optbase = argc == 3 ? shellparam.p : shellparam.optp;
+ shellparam.optnext = optbase;
+ shellparam.optptr = NULL;
+ shellparam.reset = 0;
+ } else
+ optbase = shellparam.optp ? shellparam.optp : shellparam.p;
+
+ return getopts(argv[1], argv[2], optbase, &shellparam.optnext,
+ &shellparam.optptr);
+}
+
+static int
+getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
+ char **optptr)
+{
+ char *p, *q;
+ char c = '?';
+ int done = 0;
+ int ind = 0;
+ int err = 0;
+ char s[10];
+ const char *newoptarg = NULL;
+
+ if ((p = *optptr) == NULL || *p == '\0') {
+ /* Current word is done, advance */
+ if (*optnext == NULL)
+ return 1;
+ p = **optnext;
+ if (p == NULL || *p != '-' || *++p == '\0') {
+ atend:
+ ind = *optnext - optfirst + 1;
+ *optnext = NULL;
+ p = NULL;
+ done = 1;
+ goto out;
+ }
+ (*optnext)++;
+ if (p[0] == '-' && p[1] == '\0') /* check for "--" */
+ goto atend;
+ }
+
+ c = *p++;
+ for (q = optstr; *q != c; ) {
+ if (*q == '\0') {
+ if (optstr[0] == ':') {
+ s[0] = c;
+ s[1] = '\0';
+ newoptarg = s;
+ }
+ else
+ out2fmt_flush("Illegal option -%c\n", c);
+ c = '?';
+ goto out;
+ }
+ if (*++q == ':')
+ q++;
+ }
+
+ if (*++q == ':') {
+ if (*p == '\0' && (p = **optnext) == NULL) {
+ if (optstr[0] == ':') {
+ s[0] = c;
+ s[1] = '\0';
+ newoptarg = s;
+ c = ':';
+ }
+ else {
+ out2fmt_flush("No arg for -%c option\n", c);
+ c = '?';
+ }
+ goto out;
+ }
+
+ if (p == **optnext)
+ (*optnext)++;
+ newoptarg = p;
+ p = NULL;
+ }
+
+out:
+ if (*optnext != NULL)
+ ind = *optnext - optfirst + 1;
+ *optptr = p;
+ if (newoptarg != NULL)
+ err |= setvarsafe("OPTARG", newoptarg, 0);
+ else {
+ INTOFF;
+ err |= unsetvar("OPTARG");
+ INTON;
+ }
+ fmtstr(s, sizeof(s), "%d", ind);
+ err |= setvarsafe("OPTIND", s, VNOFUNC);
+ s[0] = c;
+ s[1] = '\0';
+ err |= setvarsafe(optvar, s, 0);
+ if (err) {
+ *optnext = NULL;
+ *optptr = NULL;
+ flushall();
+ exraise(EXERROR);
+ }
+ return done;
+}
+
+/*
+ * Standard option processing (a la getopt) for builtin routines. The
+ * only argument that is passed to nextopt is the option string; the
+ * other arguments are unnecessary. It returns the option, or '\0' on
+ * end of input.
+ */
+
+int
+nextopt(const char *optstring)
+{
+ char *p;
+ const char *q;
+ char c;
+
+ if ((p = nextopt_optptr) == NULL || *p == '\0') {
+ p = *argptr;
+ if (p == NULL || *p != '-' || *++p == '\0')
+ return '\0';
+ argptr++;
+ if (p[0] == '-' && p[1] == '\0') /* check for "--" */
+ return '\0';
+ }
+ c = *p++;
+ for (q = optstring ; *q != c ; ) {
+ if (*q == '\0')
+ error("Illegal option -%c", c);
+ if (*++q == ':')
+ q++;
+ }
+ if (*++q == ':') {
+ if (*p == '\0' && (p = *argptr++) == NULL)
+ error("No arg for -%c option", c);
+ shoptarg = p;
+ p = NULL;
+ }
+ if (p != NULL && *p != '\0')
+ nextopt_optptr = p;
+ else
+ nextopt_optptr = NULL;
+ return c;
+}
diff --git a/cmd/posix/sh/options.h b/cmd/posix/sh/options.h
@@ -0,0 +1,116 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+struct shparam {
+ int nparam; /* # of positional parameters (without $0) */
+ unsigned char malloc; /* if parameter list dynamically allocated */
+ unsigned char reset; /* if getopts has been reset */
+ char **p; /* parameter list */
+ char **optp; /* parameter list for getopts */
+ char **optnext; /* next parameter to be processed by getopts */
+ char *optptr; /* used by getopts */
+};
+
+
+
+#define eflag optval[0]
+#define fflag optval[1]
+#define Iflag optval[2]
+#define iflag optval[3]
+#define mflag optval[4]
+#define nflag optval[5]
+#define sflag optval[6]
+#define xflag optval[7]
+#define vflag optval[8]
+#define Vflag optval[9]
+#define Eflag optval[10]
+#define Cflag optval[11]
+#define aflag optval[12]
+#define bflag optval[13]
+#define uflag optval[14]
+#define privileged optval[15]
+#define Tflag optval[16]
+#define Pflag optval[17]
+#define hflag optval[18]
+#define nologflag optval[19]
+#define pipefailflag optval[20]
+#define verifyflag optval[21]
+
+#define NSHORTOPTS 19
+#define NOPTS 22
+
+extern char optval[NOPTS];
+extern const char optletter[NSHORTOPTS];
+#ifdef DEFINE_OPTIONS
+char optval[NOPTS];
+const char optletter[NSHORTOPTS] __nonstring = "efIimnsxvVECabupTPh";
+static const unsigned char optname[] =
+ "\007errexit"
+ "\006noglob"
+ "\011ignoreeof"
+ "\013interactive"
+ "\007monitor"
+ "\006noexec"
+ "\005stdin"
+ "\006xtrace"
+ "\007verbose"
+ "\002vi"
+ "\005emacs"
+ "\011noclobber"
+ "\011allexport"
+ "\006notify"
+ "\007nounset"
+ "\012privileged"
+ "\012trapsasync"
+ "\010physical"
+ "\010trackall"
+ "\005nolog"
+ "\010pipefail"
+ "\006verify"
+;
+#endif
+
+
+extern char *minusc; /* argument to -c option */
+extern char *arg0; /* $0 */
+extern struct shparam shellparam; /* $@ */
+extern char **argptr; /* argument list for builtin commands */
+extern char *shoptarg; /* set by nextopt */
+extern char *nextopt_optptr; /* used by nextopt */
+
+int procargs(int, char **);
+void optschanged(void);
+void freeparam(struct shparam *);
+int nextopt(const char *);
+void getoptsreset(const char *);
diff --git a/cmd/posix/sh/output.c b/cmd/posix/sh/output.c
@@ -0,0 +1,415 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Shell output routines. We use our own output routines because:
+ * When a builtin command is interrupted we have to discard
+ * any pending output.
+ * When a builtin command appears in back quotes, we want to
+ * save the output of the command in a region obtained
+ * via malloc, rather than doing a fork and reading the
+ * output of the command via a pipe.
+ */
+
+#include <stdio.h> /* defines BUFSIZ */
+#include <string.h>
+#include <stdarg.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#if defined(__linux__) || defined(__CYGWIN__)
+struct fwopen_cookie {
+ void *cookie;
+ int (*writefn)(void *, const char *, int);
+};
+
+static ssize_t
+compat_fwopen_write(void *cookie, const char *buf, size_t size)
+{
+ struct fwopen_cookie *c = cookie;
+ return c->writefn(c->cookie, buf, (int)size);
+}
+
+static int
+compat_fwopen_close(void *cookie)
+{
+ free(cookie);
+ return 0;
+}
+
+static FILE *
+fwopen(void *cookie, int (*writefn)(void *, const char *, int))
+{
+ struct fwopen_cookie *c;
+ cookie_io_functions_t io_funcs = {
+ .read = NULL,
+ .write = compat_fwopen_write,
+ .seek = NULL,
+ .close = compat_fwopen_close
+ };
+ FILE *fp;
+
+ c = malloc(sizeof(struct fwopen_cookie));
+ if (c == NULL)
+ return NULL;
+ c->cookie = cookie;
+ c->writefn = writefn;
+
+ fp = fopencookie(c, "w", io_funcs);
+ if (fp == NULL) {
+ free(c);
+ return NULL;
+ }
+ return fp;
+}
+#endif
+
+#include "shell.h"
+#include "syntax.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "var.h"
+
+
+#define OUTBUFSIZ BUFSIZ
+#define MEM_OUT -2 /* output to dynamically allocated memory */
+#define OUTPUT_ERR 01 /* error occurred on output */
+
+static int doformat_wr(void *, const char *, int);
+
+struct output output = {NULL, NULL, NULL, OUTBUFSIZ, 1, 0};
+struct output errout = {NULL, NULL, NULL, 256, 2, 0};
+struct output memout = {NULL, NULL, NULL, 64, MEM_OUT, 0};
+struct output *out1 = &output;
+struct output *out2 = &errout;
+
+void
+outcslow(int c, struct output *file)
+{
+ outc(c, file);
+}
+
+void
+out1str(const char *p)
+{
+ outstr(p, out1);
+}
+
+void
+out1qstr(const char *p)
+{
+ outqstr(p, out1);
+}
+
+void
+out2str(const char *p)
+{
+ outstr(p, out2);
+}
+
+void
+out2qstr(const char *p)
+{
+ outqstr(p, out2);
+}
+
+void
+outstr(const char *p, struct output *file)
+{
+ outbin(p, strlen(p), file);
+}
+
+static void
+byteseq(int ch, struct output *file)
+{
+ char seq[4];
+
+ seq[0] = '\\';
+ seq[1] = (ch >> 6 & 0x3) + '0';
+ seq[2] = (ch >> 3 & 0x7) + '0';
+ seq[3] = (ch & 0x7) + '0';
+ outbin(seq, 4, file);
+}
+
+static void
+outdqstr(const char *p, struct output *file)
+{
+ const char *end;
+ mbstate_t mbs;
+ size_t clen;
+ wchar_t wc;
+
+ memset(&mbs, '\0', sizeof(mbs));
+ end = p + strlen(p);
+ outstr("$'", file);
+ while ((clen = mbrtowc(&wc, p, end - p + 1, &mbs)) != 0) {
+ if (clen == (size_t)-2) {
+ while (p < end)
+ byteseq(*p++, file);
+ break;
+ }
+ if (clen == (size_t)-1) {
+ memset(&mbs, '\0', sizeof(mbs));
+ byteseq(*p++, file);
+ continue;
+ }
+ if (wc == L'\n')
+ outcslow('\n', file), p++;
+ else if (wc == L'\r')
+ outstr("\\r", file), p++;
+ else if (wc == L'\t')
+ outstr("\\t", file), p++;
+ else if (!iswprint(wc)) {
+ for (; clen > 0; clen--)
+ byteseq(*p++, file);
+ } else {
+ if (wc == L'\'' || wc == L'\\')
+ outcslow('\\', file);
+ outbin(p, clen, file);
+ p += clen;
+ }
+ }
+ outcslow('\'', file);
+}
+
+/* Like outstr(), but quote for re-input into the shell. */
+void
+outqstr(const char *p, struct output *file)
+{
+ int i;
+
+ if (p[0] == '\0') {
+ outstr("''", file);
+ return;
+ }
+ for (i = 0; p[i] != '\0'; i++) {
+ if ((p[i] > '\0' && p[i] < ' ' && p[i] != '\n') ||
+ (p[i] & 0x80) != 0 || p[i] == '\'') {
+ outdqstr(p, file);
+ return;
+ }
+ }
+
+ if (p[strcspn(p, "|&;<>()$`\\\" \n*?[~#=")] == '\0' ||
+ strcmp(p, "[") == 0) {
+ outstr(p, file);
+ return;
+ }
+
+ outcslow('\'', file);
+ outstr(p, file);
+ outcslow('\'', file);
+}
+
+void
+outbin(const void *data, size_t len, struct output *file)
+{
+ const char *p;
+
+ p = data;
+ while (len-- > 0)
+ outc(*p++, file);
+}
+
+void
+emptyoutbuf(struct output *dest)
+{
+ int offset, newsize;
+
+ if (dest->buf == NULL) {
+ INTOFF;
+ dest->buf = ckmalloc(dest->bufsize);
+ dest->nextc = dest->buf;
+ dest->bufend = dest->buf + dest->bufsize;
+ INTON;
+ } else if (dest->fd == MEM_OUT) {
+ offset = dest->nextc - dest->buf;
+ newsize = dest->bufsize << 1;
+ INTOFF;
+ dest->buf = ckrealloc(dest->buf, newsize);
+ dest->bufsize = newsize;
+ dest->bufend = dest->buf + newsize;
+ dest->nextc = dest->buf + offset;
+ INTON;
+ } else {
+ flushout(dest);
+ }
+}
+
+
+void
+flushall(void)
+{
+ flushout(&output);
+ flushout(&errout);
+}
+
+
+void
+flushout(struct output *dest)
+{
+
+ if (dest->buf == NULL || dest->nextc == dest->buf || dest->fd < 0)
+ return;
+ if (xwrite(dest->fd, dest->buf, dest->nextc - dest->buf) < 0)
+ dest->flags |= OUTPUT_ERR;
+ dest->nextc = dest->buf;
+}
+
+
+void
+freestdout(void)
+{
+ output.nextc = output.buf;
+}
+
+
+int
+outiserror(struct output *file)
+{
+ return (file->flags & OUTPUT_ERR);
+}
+
+
+void
+outclearerror(struct output *file)
+{
+ file->flags &= ~OUTPUT_ERR;
+}
+
+
+void
+outfmt(struct output *file, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ doformat(file, fmt, ap);
+ va_end(ap);
+}
+
+
+void
+out1fmt(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ doformat(out1, fmt, ap);
+ va_end(ap);
+}
+
+void
+out2fmt_flush(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ doformat(out2, fmt, ap);
+ va_end(ap);
+ flushout(out2);
+}
+
+void
+fmtstr(char *outbuf, int length, const char *fmt, ...)
+{
+ va_list ap;
+
+ INTOFF;
+ va_start(ap, fmt);
+ vsnprintf(outbuf, length, fmt, ap);
+ va_end(ap);
+ INTON;
+}
+
+static int
+doformat_wr(void *cookie, const char *buf, int len)
+{
+ struct output *o;
+
+ o = (struct output *)cookie;
+ outbin(buf, len, o);
+
+ return (len);
+}
+
+void
+doformat(struct output *dest, const char *f, va_list ap)
+{
+ FILE *fp;
+
+ if ((fp = fwopen(dest, doformat_wr)) != NULL) {
+ vfprintf(fp, f, ap);
+ fclose(fp);
+ }
+}
+
+FILE *
+out1fp(void)
+{
+ return fwopen(out1, doformat_wr);
+}
+
+/*
+ * Version of write which resumes after a signal is caught.
+ */
+
+int
+xwrite(int fd, const char *buf, int nbytes)
+{
+ int ntry;
+ int i;
+ int n;
+
+ n = nbytes;
+ ntry = 0;
+ for (;;) {
+ i = write(fd, buf, n);
+ if (i > 0) {
+ if ((n -= i) <= 0)
+ return nbytes;
+ buf += i;
+ ntry = 0;
+ } else if (i == 0) {
+ if (++ntry > 10)
+ return nbytes - n;
+ } else if (errno != EINTR) {
+ return -1;
+ }
+ }
+}
diff --git a/cmd/posix/sh/output.h b/cmd/posix/sh/output.h
@@ -0,0 +1,84 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef OUTPUT_INCL
+
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdio.h>
+
+struct output {
+ char *nextc;
+ char *bufend;
+ char *buf;
+ int bufsize;
+ short fd;
+ short flags;
+};
+
+extern struct output output; /* to fd 1 */
+extern struct output errout; /* to fd 2 */
+extern struct output memout;
+extern struct output *out1; /* &memout if backquote, otherwise &output */
+extern struct output *out2; /* &memout if backquote with 2>&1, otherwise
+ &errout */
+
+void outcslow(int, struct output *);
+void out1str(const char *);
+void out1qstr(const char *);
+void out2str(const char *);
+void out2qstr(const char *);
+void outstr(const char *, struct output *);
+void outqstr(const char *, struct output *);
+void outbin(const void *, size_t, struct output *);
+void emptyoutbuf(struct output *);
+void flushall(void);
+void flushout(struct output *);
+void freestdout(void);
+int outiserror(struct output *);
+void outclearerror(struct output *);
+void outfmt(struct output *, const char *, ...) __printflike(2, 3);
+void out1fmt(const char *, ...) __printflike(1, 2);
+void out2fmt_flush(const char *, ...) __printflike(1, 2);
+void fmtstr(char *, int, const char *, ...) __printflike(3, 4);
+void doformat(struct output *, const char *, va_list) __printflike(2, 0);
+FILE *out1fp(void);
+int xwrite(int, const char *, int);
+
+#define outc(c, file) ((file)->nextc == (file)->bufend ? (emptyoutbuf(file), *(file)->nextc++ = (c)) : (*(file)->nextc++ = (c)))
+#define out1c(c) outc(c, out1);
+#define out2c(c) outcslow(c, out2);
+
+#define OUTPUT_INCL
+#endif
diff --git a/cmd/posix/sh/parser.c b/cmd/posix/sh/parser.c
@@ -0,0 +1,2404 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/param.h>
+#include <pwd.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <time.h>
+
+#include "shell.h"
+
+#undef strlcpy
+#define strlcpy xstrlcpy
+size_t xstrlcpy(char *, const char *, size_t);
+
+#include "parser.h"
+#include "nodes.h"
+#include "expand.h" /* defines rmescapes() */
+#include "syntax.h"
+#include "options.h"
+#include "input.h"
+#include "output.h"
+#include "var.h"
+#include "error.h"
+#include "memalloc.h"
+#include "mystring.h"
+#include "alias.h"
+#include "show.h"
+#include "eval.h"
+#include "exec.h" /* to check for special builtins */
+#include "main.h"
+#include "jobs.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+/*
+ * Shell command parser.
+ */
+
+#define PROMPTLEN 192
+
+/* values of checkkwd variable */
+#define CHKALIAS 0x1
+#define CHKKWD 0x2
+#define CHKNL 0x4
+
+/* values returned by readtoken */
+#include "token.h"
+
+
+
+struct heredoc {
+ struct heredoc *next; /* next here document in list */
+ union node *here; /* redirection node */
+ char *eofmark; /* string indicating end of input */
+ int striptabs; /* if set, strip leading tabs */
+};
+
+struct parser_temp {
+ struct parser_temp *next;
+ void *data;
+};
+
+
+static struct heredoc *heredoclist; /* list of here documents to read */
+static int doprompt; /* if set, prompt the user */
+static int needprompt; /* true if interactive and at start of line */
+static int lasttoken; /* last token read */
+static int tokpushback; /* last token pushed back */
+static char *wordtext; /* text of last word returned by readtoken */
+static int checkkwd;
+static struct nodelist *backquotelist;
+static union node *redirnode;
+static struct heredoc *heredoc;
+static int quoteflag; /* set if (part of) last token was quoted */
+static int startlinno; /* line # where last token started */
+static int funclinno; /* line # where the current function started */
+static struct parser_temp *parser_temp;
+
+#define NOEOFMARK ((const char *)&heredoclist)
+
+
+static union node *list(int);
+static union node *andor(void);
+static union node *pipeline(void);
+static union node *command(void);
+static union node *simplecmd(union node **, union node *);
+static union node *makename(void);
+static union node *makebinary(int type, union node *n1, union node *n2);
+static void parsefname(void);
+static void parseheredoc(void);
+static int peektoken(void);
+static int readtoken(void);
+static int xxreadtoken(void);
+static int readtoken1(int, const char *, const char *, int);
+static int noexpand(char *);
+static void consumetoken(int);
+static void synexpect(int) __dead2;
+static void synerror(const char *) __dead2;
+static void setprompt(int);
+static int pgetc_linecont(void);
+static void getusername(char *, size_t);
+
+
+static void *
+parser_temp_alloc(size_t len)
+{
+ struct parser_temp *t;
+
+ INTOFF;
+ t = ckmalloc(sizeof(*t));
+ t->data = NULL;
+ t->next = parser_temp;
+ parser_temp = t;
+ t->data = ckmalloc(len);
+ INTON;
+ return t->data;
+}
+
+
+static void *
+parser_temp_realloc(void *ptr, size_t len)
+{
+ struct parser_temp *t;
+
+ INTOFF;
+ t = parser_temp;
+ if (ptr != t->data)
+ error("bug: parser_temp_realloc misused");
+ t->data = ckrealloc(t->data, len);
+ INTON;
+ return t->data;
+}
+
+
+static void
+parser_temp_free_upto(void *ptr)
+{
+ struct parser_temp *t;
+ int done = 0;
+
+ INTOFF;
+ while (parser_temp != NULL && !done) {
+ t = parser_temp;
+ parser_temp = t->next;
+ done = t->data == ptr;
+ ckfree(t->data);
+ ckfree(t);
+ }
+ INTON;
+ if (!done)
+ error("bug: parser_temp_free_upto misused");
+}
+
+
+static void
+parser_temp_free_all(void)
+{
+ struct parser_temp *t;
+
+ INTOFF;
+ while (parser_temp != NULL) {
+ t = parser_temp;
+ parser_temp = t->next;
+ ckfree(t->data);
+ ckfree(t);
+ }
+ INTON;
+}
+
+
+/*
+ * Read and parse a command. Returns NEOF on end of file. (NULL is a
+ * valid parse tree indicating a blank line.)
+ */
+
+union node *
+parsecmd(int interact)
+{
+ int t;
+
+ /* This assumes the parser is not re-entered,
+ * which could happen if we add command substitution on PS1/PS2.
+ */
+ parser_temp_free_all();
+ heredoclist = NULL;
+
+ tokpushback = 0;
+ checkkwd = 0;
+ doprompt = interact;
+ if (doprompt)
+ setprompt(1);
+ else
+ setprompt(0);
+ needprompt = 0;
+ t = readtoken();
+ if (t == TEOF)
+ return NEOF;
+ if (t == TNL)
+ return NULL;
+ tokpushback++;
+ return list(1);
+}
+
+
+/*
+ * Read and parse words for wordexp.
+ * Returns a list of NARG nodes; NULL if there are no words.
+ */
+union node *
+parsewordexp(void)
+{
+ union node *n, *first = NULL, **pnext;
+ int t;
+
+ /* This assumes the parser is not re-entered,
+ * which could happen if we add command substitution on PS1/PS2.
+ */
+ parser_temp_free_all();
+ heredoclist = NULL;
+
+ tokpushback = 0;
+ checkkwd = 0;
+ doprompt = 0;
+ setprompt(0);
+ needprompt = 0;
+ pnext = &first;
+ while ((t = readtoken()) != TEOF) {
+ if (t != TWORD)
+ synexpect(TWORD);
+ n = makename();
+ *pnext = n;
+ pnext = &n->narg.next;
+ }
+ return first;
+}
+
+
+static union node *
+list(int nlflag)
+{
+ union node *ntop, *n1, *n2, *n3;
+ int tok;
+
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ if (!nlflag && tokendlist[peektoken()])
+ return NULL;
+ ntop = n1 = NULL;
+ for (;;) {
+ n2 = andor();
+ tok = readtoken();
+ if (tok == TBACKGND) {
+ if (n2 != NULL && n2->type == NPIPE) {
+ n2->npipe.backgnd = 1;
+ } else if (n2 != NULL && n2->type == NREDIR) {
+ n2->type = NBACKGND;
+ } else {
+ n3 = (union node *)stalloc(sizeof (struct nredir));
+ n3->type = NBACKGND;
+ n3->nredir.n = n2;
+ n3->nredir.redirect = NULL;
+ n2 = n3;
+ }
+ }
+ if (ntop == NULL)
+ ntop = n2;
+ else if (n1 == NULL) {
+ n1 = makebinary(NSEMI, ntop, n2);
+ ntop = n1;
+ }
+ else {
+ n3 = makebinary(NSEMI, n1->nbinary.ch2, n2);
+ n1->nbinary.ch2 = n3;
+ n1 = n3;
+ }
+ switch (tok) {
+ case TBACKGND:
+ case TSEMI:
+ tok = readtoken();
+ /* FALLTHROUGH */
+ case TNL:
+ if (tok == TNL) {
+ parseheredoc();
+ if (nlflag)
+ return ntop;
+ } else if (tok == TEOF && nlflag) {
+ parseheredoc();
+ return ntop;
+ } else {
+ tokpushback++;
+ }
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ if (!nlflag && tokendlist[peektoken()])
+ return ntop;
+ break;
+ case TEOF:
+ if (heredoclist)
+ parseheredoc();
+ else
+ pungetc(); /* push back EOF on input */
+ return ntop;
+ default:
+ if (nlflag)
+ synexpect(-1);
+ tokpushback++;
+ return ntop;
+ }
+ }
+}
+
+
+
+static union node *
+andor(void)
+{
+ union node *n;
+ int t;
+
+ n = pipeline();
+ for (;;) {
+ if ((t = readtoken()) == TAND) {
+ t = NAND;
+ } else if (t == TOR) {
+ t = NOR;
+ } else {
+ tokpushback++;
+ return n;
+ }
+ n = makebinary(t, n, pipeline());
+ }
+}
+
+
+
+static union node *
+pipeline(void)
+{
+ union node *n1, *n2, *pipenode;
+ struct nodelist *lp, *prev;
+ int negate, t;
+
+ negate = 0;
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ TRACE(("pipeline: entered\n"));
+ while (readtoken() == TNOT)
+ negate = !negate;
+ tokpushback++;
+ n1 = command();
+ if (readtoken() == TPIPE) {
+ pipenode = (union node *)stalloc(sizeof (struct npipe));
+ pipenode->type = NPIPE;
+ pipenode->npipe.backgnd = 0;
+ lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
+ pipenode->npipe.cmdlist = lp;
+ lp->n = n1;
+ do {
+ prev = lp;
+ lp = (struct nodelist *)stalloc(sizeof (struct nodelist));
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ t = readtoken();
+ tokpushback++;
+ if (t == TNOT)
+ lp->n = pipeline();
+ else
+ lp->n = command();
+ prev->next = lp;
+ } while (readtoken() == TPIPE);
+ lp->next = NULL;
+ n1 = pipenode;
+ }
+ tokpushback++;
+ if (negate) {
+ n2 = (union node *)stalloc(sizeof (struct nnot));
+ n2->type = NNOT;
+ n2->nnot.com = n1;
+ return n2;
+ } else
+ return n1;
+}
+
+
+
+static union node *
+command(void)
+{
+ union node *n1, *n2;
+ union node *ap, **app;
+ union node *cp, **cpp;
+ union node *redir, **rpp;
+ int t;
+ int is_subshell;
+
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ is_subshell = 0;
+ redir = NULL;
+ n1 = NULL;
+ rpp = &redir;
+
+ /* Check for redirection which may precede command */
+ while (readtoken() == TREDIR) {
+ *rpp = n2 = redirnode;
+ rpp = &n2->nfile.next;
+ parsefname();
+ }
+ tokpushback++;
+
+ switch (readtoken()) {
+ case TIF:
+ n1 = (union node *)stalloc(sizeof (struct nif));
+ n1->type = NIF;
+ if ((n1->nif.test = list(0)) == NULL)
+ synexpect(-1);
+ consumetoken(TTHEN);
+ n1->nif.ifpart = list(0);
+ n2 = n1;
+ while (readtoken() == TELIF) {
+ n2->nif.elsepart = (union node *)stalloc(sizeof (struct nif));
+ n2 = n2->nif.elsepart;
+ n2->type = NIF;
+ if ((n2->nif.test = list(0)) == NULL)
+ synexpect(-1);
+ consumetoken(TTHEN);
+ n2->nif.ifpart = list(0);
+ }
+ if (lasttoken == TELSE)
+ n2->nif.elsepart = list(0);
+ else {
+ n2->nif.elsepart = NULL;
+ tokpushback++;
+ }
+ consumetoken(TFI);
+ checkkwd = CHKKWD | CHKALIAS;
+ break;
+ case TWHILE:
+ case TUNTIL:
+ t = lasttoken;
+ if ((n1 = list(0)) == NULL)
+ synexpect(-1);
+ consumetoken(TDO);
+ n1 = makebinary((t == TWHILE)? NWHILE : NUNTIL, n1, list(0));
+ consumetoken(TDONE);
+ checkkwd = CHKKWD | CHKALIAS;
+ break;
+ case TFOR:
+ if (readtoken() != TWORD || quoteflag || ! goodname(wordtext))
+ synerror("Bad for loop variable");
+ n1 = (union node *)stalloc(sizeof (struct nfor));
+ n1->type = NFOR;
+ n1->nfor.var = wordtext;
+ checkkwd = CHKNL;
+ if (readtoken() == TWORD && !quoteflag &&
+ equal(wordtext, "in")) {
+ app = ≈
+ while (readtoken() == TWORD) {
+ n2 = makename();
+ *app = n2;
+ app = &n2->narg.next;
+ }
+ *app = NULL;
+ n1->nfor.args = ap;
+ if (lasttoken == TNL)
+ tokpushback++;
+ else if (lasttoken != TSEMI)
+ synexpect(-1);
+ } else {
+ static char argvars[5] = {
+ CTLVAR, (char)(VSNORMAL|VSQUOTE), '@', '=', '\0'
+ };
+ n2 = (union node *)stalloc(sizeof (struct narg));
+ n2->type = NARG;
+ n2->narg.text = argvars;
+ n2->narg.backquote = NULL;
+ n2->narg.next = NULL;
+ n1->nfor.args = n2;
+ /*
+ * Newline or semicolon here is optional (but note
+ * that the original Bourne shell only allowed NL).
+ */
+ if (lasttoken != TSEMI)
+ tokpushback++;
+ }
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ if ((t = readtoken()) == TDO)
+ t = TDONE;
+ else if (t == TBEGIN)
+ t = TEND;
+ else
+ synexpect(-1);
+ n1->nfor.body = list(0);
+ consumetoken(t);
+ checkkwd = CHKKWD | CHKALIAS;
+ break;
+ case TCASE:
+ n1 = (union node *)stalloc(sizeof (struct ncase));
+ n1->type = NCASE;
+ consumetoken(TWORD);
+ n1->ncase.expr = makename();
+ checkkwd = CHKNL;
+ if (readtoken() != TWORD || ! equal(wordtext, "in"))
+ synerror("expecting \"in\"");
+ cpp = &n1->ncase.cases;
+ checkkwd = CHKNL | CHKKWD, readtoken();
+ while (lasttoken != TESAC) {
+ *cpp = cp = (union node *)stalloc(sizeof (struct nclist));
+ cp->type = NCLIST;
+ app = &cp->nclist.pattern;
+ if (lasttoken == TLP)
+ readtoken();
+ for (;;) {
+ *app = ap = makename();
+ checkkwd = CHKNL | CHKKWD;
+ if (readtoken() != TPIPE)
+ break;
+ app = &ap->narg.next;
+ readtoken();
+ }
+ ap->narg.next = NULL;
+ if (lasttoken != TRP)
+ synexpect(TRP);
+ cp->nclist.body = list(0);
+
+ checkkwd = CHKNL | CHKKWD | CHKALIAS;
+ if ((t = readtoken()) != TESAC) {
+ if (t == TENDCASE)
+ ;
+ else if (t == TFALLTHRU)
+ cp->type = NCLISTFALLTHRU;
+ else
+ synexpect(TENDCASE);
+ checkkwd = CHKNL | CHKKWD, readtoken();
+ }
+ cpp = &cp->nclist.next;
+ }
+ *cpp = NULL;
+ checkkwd = CHKKWD | CHKALIAS;
+ break;
+ case TLP:
+ n1 = (union node *)stalloc(sizeof (struct nredir));
+ n1->type = NSUBSHELL;
+ n1->nredir.n = list(0);
+ n1->nredir.redirect = NULL;
+ consumetoken(TRP);
+ checkkwd = CHKKWD | CHKALIAS;
+ is_subshell = 1;
+ break;
+ case TBEGIN:
+ n1 = list(0);
+ consumetoken(TEND);
+ checkkwd = CHKKWD | CHKALIAS;
+ break;
+ /* A simple command must have at least one redirection or word. */
+ case TBACKGND:
+ case TSEMI:
+ case TAND:
+ case TOR:
+ case TPIPE:
+ case TENDCASE:
+ case TFALLTHRU:
+ case TEOF:
+ case TNL:
+ case TRP:
+ if (!redir)
+ synexpect(-1);
+ /* fallthrough */
+ case TWORD:
+ tokpushback++;
+ n1 = simplecmd(rpp, redir);
+ return n1;
+ default:
+ synexpect(-1);
+ }
+
+ /* Now check for redirection which may follow command */
+ while (readtoken() == TREDIR) {
+ *rpp = n2 = redirnode;
+ rpp = &n2->nfile.next;
+ parsefname();
+ }
+ tokpushback++;
+ *rpp = NULL;
+ if (redir) {
+ if (!is_subshell) {
+ n2 = (union node *)stalloc(sizeof (struct nredir));
+ n2->type = NREDIR;
+ n2->nredir.n = n1;
+ n1 = n2;
+ }
+ n1->nredir.redirect = redir;
+ }
+
+ return n1;
+}
+
+
+static union node *
+simplecmd(union node **rpp, union node *redir)
+{
+ union node *args, **app;
+ union node **orig_rpp = rpp;
+ union node *n = NULL;
+ int special;
+ int savecheckkwd;
+
+ /* If we don't have any redirections already, then we must reset */
+ /* rpp to be the address of the local redir variable. */
+ if (redir == NULL)
+ rpp = &redir;
+
+ args = NULL;
+ app = &args;
+ /*
+ * We save the incoming value, because we need this for shell
+ * functions. There can not be a redirect or an argument between
+ * the function name and the open parenthesis.
+ */
+ orig_rpp = rpp;
+
+ savecheckkwd = CHKALIAS;
+
+ for (;;) {
+ checkkwd = savecheckkwd;
+ if (readtoken() == TWORD) {
+ n = makename();
+ *app = n;
+ app = &n->narg.next;
+ if (savecheckkwd != 0 && !isassignment(wordtext))
+ savecheckkwd = 0;
+ } else if (lasttoken == TREDIR) {
+ *rpp = n = redirnode;
+ rpp = &n->nfile.next;
+ parsefname(); /* read name of redirection file */
+ } else if (lasttoken == TLP && app == &args->narg.next
+ && rpp == orig_rpp) {
+ /* We have a function */
+ consumetoken(TRP);
+ funclinno = plinno;
+ /*
+ * - Require plain text.
+ * - Functions with '/' cannot be called.
+ * - Reject name=().
+ * - Reject ksh extended glob patterns.
+ */
+ if (!noexpand(n->narg.text) || quoteflag ||
+ strchr(n->narg.text, '/') ||
+ strchr("!%*+-=?@}~",
+ n->narg.text[strlen(n->narg.text) - 1]))
+ synerror("Bad function name");
+ rmescapes(n->narg.text);
+ if (find_builtin(n->narg.text, &special) >= 0 &&
+ special)
+ synerror("Cannot override a special builtin with a function");
+ n->type = NDEFUN;
+ n->narg.next = command();
+ funclinno = 0;
+ return n;
+ } else {
+ tokpushback++;
+ break;
+ }
+ }
+ *app = NULL;
+ *rpp = NULL;
+ n = (union node *)stalloc(sizeof (struct ncmd));
+ n->type = NCMD;
+ n->ncmd.args = args;
+ n->ncmd.redirect = redir;
+ return n;
+}
+
+static union node *
+makename(void)
+{
+ union node *n;
+
+ n = (union node *)stalloc(sizeof (struct narg));
+ n->type = NARG;
+ n->narg.next = NULL;
+ n->narg.text = wordtext;
+ n->narg.backquote = backquotelist;
+ return n;
+}
+
+static union node *
+makebinary(int type, union node *n1, union node *n2)
+{
+ union node *n;
+
+ n = (union node *)stalloc(sizeof (struct nbinary));
+ n->type = type;
+ n->nbinary.ch1 = n1;
+ n->nbinary.ch2 = n2;
+ return (n);
+}
+
+void
+forcealias(void)
+{
+ checkkwd |= CHKALIAS;
+}
+
+void
+fixredir(union node *n, const char *text, int err)
+{
+ TRACE(("Fix redir %s %d\n", text, err));
+ if (!err)
+ n->ndup.vname = NULL;
+
+ if (is_digit(text[0]) && text[1] == '\0')
+ n->ndup.dupfd = digit_val(text[0]);
+ else if (text[0] == '-' && text[1] == '\0')
+ n->ndup.dupfd = -1;
+ else {
+
+ if (err)
+ synerror("Bad fd number");
+ else
+ n->ndup.vname = makename();
+ }
+}
+
+
+static void
+parsefname(void)
+{
+ union node *n = redirnode;
+
+ consumetoken(TWORD);
+ if (n->type == NHERE) {
+ struct heredoc *here = heredoc;
+ struct heredoc *p;
+
+ if (quoteflag == 0)
+ n->type = NXHERE;
+ TRACE(("Here document %d\n", n->type));
+ if (here->striptabs) {
+ while (*wordtext == '\t')
+ wordtext++;
+ }
+ if (! noexpand(wordtext))
+ synerror("Illegal eof marker for << redirection");
+ rmescapes(wordtext);
+ here->eofmark = wordtext;
+ here->next = NULL;
+ if (heredoclist == NULL)
+ heredoclist = here;
+ else {
+ for (p = heredoclist ; p->next ; p = p->next);
+ p->next = here;
+ }
+ } else if (n->type == NTOFD || n->type == NFROMFD) {
+ fixredir(n, wordtext, 0);
+ } else {
+ n->nfile.fname = makename();
+ }
+}
+
+
+/*
+ * Input any here documents.
+ */
+
+static void
+parseheredoc(void)
+{
+ struct heredoc *here;
+ union node *n;
+
+ while (heredoclist) {
+ here = heredoclist;
+ heredoclist = here->next;
+ if (needprompt) {
+ setprompt(2);
+ needprompt = 0;
+ }
+ readtoken1(pgetc(), here->here->type == NHERE? SQSYNTAX : DQSYNTAX,
+ here->eofmark, here->striptabs);
+ n = makename();
+ here->here->nhere.doc = n;
+ }
+}
+
+static int
+peektoken(void)
+{
+ int t;
+
+ t = readtoken();
+ tokpushback++;
+ return (t);
+}
+
+static int
+readtoken(void)
+{
+ int t;
+ struct alias *ap;
+#ifdef DEBUG
+ int alreadyseen = tokpushback;
+#endif
+
+ top:
+ t = xxreadtoken();
+
+ /*
+ * eat newlines
+ */
+ if (checkkwd & CHKNL) {
+ while (t == TNL) {
+ parseheredoc();
+ t = xxreadtoken();
+ }
+ }
+
+ /*
+ * check for keywords and aliases
+ */
+ if (t == TWORD && !quoteflag)
+ {
+ const char * const *pp;
+
+ if (checkkwd & CHKKWD)
+ for (pp = parsekwd; *pp; pp++) {
+ if (**pp == *wordtext && equal(*pp, wordtext))
+ {
+ lasttoken = t = pp - parsekwd + KWDOFFSET;
+ TRACE(("keyword %s recognized\n", tokname[t]));
+ goto out;
+ }
+ }
+ if (checkkwd & CHKALIAS &&
+ (ap = lookupalias(wordtext, 1)) != NULL) {
+ pushstring(ap->val, strlen(ap->val), ap);
+ goto top;
+ }
+ }
+out:
+ if (t != TNOT)
+ checkkwd = 0;
+
+#ifdef DEBUG
+ if (!alreadyseen)
+ TRACE(("token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
+ else
+ TRACE(("reread token %s %s\n", tokname[t], t == TWORD ? wordtext : ""));
+#endif
+ return (t);
+}
+
+
+/*
+ * Read the next input token.
+ * If the token is a word, we set backquotelist to the list of cmds in
+ * backquotes. We set quoteflag to true if any part of the word was
+ * quoted.
+ * If the token is TREDIR, then we set redirnode to a structure containing
+ * the redirection.
+ * In all cases, the variable startlinno is set to the number of the line
+ * on which the token starts.
+ *
+ * [Change comment: here documents and internal procedures]
+ * [Readtoken shouldn't have any arguments. Perhaps we should make the
+ * word parsing code into a separate routine. In this case, readtoken
+ * doesn't need to have any internal procedures, but parseword does.
+ * We could also make parseoperator in essence the main routine, and
+ * have parseword (readtoken1?) handle both words and redirection.]
+ */
+
+#define RETURN(token) return lasttoken = token
+
+static int
+xxreadtoken(void)
+{
+ int c;
+
+ if (tokpushback) {
+ tokpushback = 0;
+ return lasttoken;
+ }
+ if (needprompt) {
+ setprompt(2);
+ needprompt = 0;
+ }
+ startlinno = plinno;
+ for (;;) { /* until token or start of word found */
+ c = pgetc_macro();
+ switch (c) {
+ case ' ': case '\t':
+ continue;
+ case '#':
+ while ((c = pgetc()) != '\n' && c != PEOF);
+ pungetc();
+ continue;
+ case '\\':
+ if (pgetc() == '\n') {
+ startlinno = ++plinno;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ continue;
+ }
+ pungetc();
+ /* FALLTHROUGH */
+ default:
+ return readtoken1(c, BASESYNTAX, (char *)NULL, 0);
+ case '\n':
+ plinno++;
+ needprompt = doprompt;
+ RETURN(TNL);
+ case PEOF:
+ RETURN(TEOF);
+ case '&':
+ if (pgetc_linecont() == '&')
+ RETURN(TAND);
+ pungetc();
+ RETURN(TBACKGND);
+ case '|':
+ if (pgetc_linecont() == '|')
+ RETURN(TOR);
+ pungetc();
+ RETURN(TPIPE);
+ case ';':
+ c = pgetc_linecont();
+ if (c == ';')
+ RETURN(TENDCASE);
+ else if (c == '&')
+ RETURN(TFALLTHRU);
+ pungetc();
+ RETURN(TSEMI);
+ case '(':
+ RETURN(TLP);
+ case ')':
+ RETURN(TRP);
+ }
+ }
+#undef RETURN
+}
+
+
+#define MAXNEST_static 8
+struct tokenstate
+{
+ const char *syntax; /* *SYNTAX */
+ int parenlevel; /* levels of parentheses in arithmetic */
+ enum tokenstate_category
+ {
+ TSTATE_TOP,
+ TSTATE_VAR_OLD, /* ${var+-=?}, inherits dquotes */
+ TSTATE_VAR_NEW, /* other ${var...}, own dquote state */
+ TSTATE_ARITH
+ } category;
+};
+
+
+/*
+ * Check to see whether we are at the end of the here document. When this
+ * is called, c is set to the first character of the next input line. If
+ * we are at the end of the here document, this routine sets the c to PEOF.
+ * The new value of c is returned.
+ */
+
+static int
+checkend(int c, const char *eofmark, int striptabs)
+{
+ if (striptabs) {
+ while (c == '\t')
+ c = pgetc();
+ }
+ if (c == *eofmark) {
+ int c2;
+ const char *q;
+
+ for (q = eofmark + 1; c2 = pgetc(), *q != '\0' && c2 == *q; q++)
+ ;
+ if ((c2 == PEOF || c2 == '\n') && *q == '\0') {
+ c = PEOF;
+ if (c2 == '\n') {
+ plinno++;
+ needprompt = doprompt;
+ }
+ } else {
+ pungetc();
+ pushstring(eofmark + 1, q - (eofmark + 1), NULL);
+ }
+ } else if (c == '\n' && *eofmark == '\0') {
+ c = PEOF;
+ plinno++;
+ needprompt = doprompt;
+ }
+ return (c);
+}
+
+
+/*
+ * Parse a redirection operator. The variable "out" points to a string
+ * specifying the fd to be redirected. The variable "c" contains the
+ * first character of the redirection operator.
+ */
+
+static void
+parseredir(char *out, int c)
+{
+ char fd = *out;
+ union node *np;
+
+ np = (union node *)stalloc(sizeof (struct nfile));
+ if (c == '>') {
+ np->nfile.fd = 1;
+ c = pgetc_linecont();
+ if (c == '>')
+ np->type = NAPPEND;
+ else if (c == '&')
+ np->type = NTOFD;
+ else if (c == '|')
+ np->type = NCLOBBER;
+ else {
+ np->type = NTO;
+ pungetc();
+ }
+ } else { /* c == '<' */
+ np->nfile.fd = 0;
+ c = pgetc_linecont();
+ if (c == '<') {
+ if (sizeof (struct nfile) != sizeof (struct nhere)) {
+ np = (union node *)stalloc(sizeof (struct nhere));
+ np->nfile.fd = 0;
+ }
+ np->type = NHERE;
+ heredoc = (struct heredoc *)stalloc(sizeof (struct heredoc));
+ heredoc->here = np;
+ if ((c = pgetc_linecont()) == '-') {
+ heredoc->striptabs = 1;
+ } else {
+ heredoc->striptabs = 0;
+ pungetc();
+ }
+ } else if (c == '&')
+ np->type = NFROMFD;
+ else if (c == '>')
+ np->type = NFROMTO;
+ else {
+ np->type = NFROM;
+ pungetc();
+ }
+ }
+ if (fd != '\0')
+ np->nfile.fd = digit_val(fd);
+ redirnode = np;
+}
+
+/*
+ * Called to parse command substitutions.
+ */
+
+static char *
+parsebackq(char *out, struct nodelist **pbqlist,
+ int oldstyle, int dblquote, int quoted)
+{
+ struct nodelist **nlpp;
+ union node *n;
+ char *volatile str;
+ struct jmploc jmploc;
+ struct jmploc *const savehandler = handler;
+ size_t savelen;
+ int saveprompt;
+ const int bq_startlinno = plinno;
+ char *volatile ostr = NULL;
+ struct parsefile *const savetopfile = getcurrentfile();
+ struct heredoc *const saveheredoclist = heredoclist;
+ struct heredoc *here;
+
+ str = NULL;
+ if (setjmp(jmploc.loc)) {
+ popfilesupto(savetopfile);
+ if (str)
+ ckfree(str);
+ if (ostr)
+ ckfree(ostr);
+ heredoclist = saveheredoclist;
+ handler = savehandler;
+ if (exception == EXERROR) {
+ startlinno = bq_startlinno;
+ synerror("Error in command substitution");
+ }
+ longjmp(handler->loc, 1);
+ }
+ INTOFF;
+ savelen = out - stackblock();
+ if (savelen > 0) {
+ str = ckmalloc(savelen);
+ memcpy(str, stackblock(), savelen);
+ }
+ handler = &jmploc;
+ heredoclist = NULL;
+ INTON;
+ if (oldstyle) {
+ /* We must read until the closing backquote, giving special
+ treatment to some slashes, and then push the string and
+ reread it as input, interpreting it normally. */
+ char *oout;
+ int c;
+ int olen;
+
+
+ STARTSTACKSTR(oout);
+ for (;;) {
+ if (needprompt) {
+ setprompt(2);
+ needprompt = 0;
+ }
+ CHECKSTRSPACE(2, oout);
+ c = pgetc_linecont();
+ if (c == '`')
+ break;
+ switch (c) {
+ case '\\':
+ c = pgetc();
+ if (c != '\\' && c != '`' && c != '$'
+ && (!dblquote || c != '"'))
+ USTPUTC('\\', oout);
+ break;
+
+ case '\n':
+ plinno++;
+ needprompt = doprompt;
+ break;
+
+ case PEOF:
+ startlinno = plinno;
+ synerror("EOF in backquote substitution");
+ break;
+
+ default:
+ break;
+ }
+ USTPUTC(c, oout);
+ }
+ USTPUTC('\0', oout);
+ olen = oout - stackblock();
+ INTOFF;
+ ostr = ckmalloc(olen);
+ memcpy(ostr, stackblock(), olen);
+ setinputstring(ostr);
+ INTON;
+ }
+ nlpp = pbqlist;
+ while (*nlpp)
+ nlpp = &(*nlpp)->next;
+ *nlpp = (struct nodelist *)stalloc(sizeof (struct nodelist));
+ (*nlpp)->next = NULL;
+
+ if (oldstyle) {
+ saveprompt = doprompt;
+ doprompt = 0;
+ }
+
+ n = list(0);
+
+ if (oldstyle) {
+ if (peektoken() != TEOF)
+ synexpect(-1);
+ doprompt = saveprompt;
+ } else
+ consumetoken(TRP);
+
+ (*nlpp)->n = n;
+ if (oldstyle) {
+ /*
+ * Start reading from old file again, ignoring any pushed back
+ * tokens left from the backquote parsing
+ */
+ popfile();
+ tokpushback = 0;
+ }
+ STARTSTACKSTR(out);
+ CHECKSTRSPACE(savelen + 1, out);
+ INTOFF;
+ if (str) {
+ memcpy(out, str, savelen);
+ STADJUST(savelen, out);
+ ckfree(str);
+ str = NULL;
+ }
+ if (ostr) {
+ ckfree(ostr);
+ ostr = NULL;
+ }
+ here = saveheredoclist;
+ if (here != NULL) {
+ while (here->next != NULL)
+ here = here->next;
+ here->next = heredoclist;
+ heredoclist = saveheredoclist;
+ }
+ handler = savehandler;
+ INTON;
+ if (quoted)
+ USTPUTC(CTLBACKQ | CTLQUOTE, out);
+ else
+ USTPUTC(CTLBACKQ, out);
+ return out;
+}
+
+
+/*
+ * Called to parse a backslash escape sequence inside $'...'.
+ * The backslash has already been read.
+ */
+static char *
+readcstyleesc(char *out)
+{
+ int c, vc, i, n;
+ unsigned int v;
+
+ c = pgetc();
+ switch (c) {
+ case '\0':
+ synerror("Unterminated quoted string");
+ case '\n':
+ plinno++;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ return out;
+ case '\\':
+ case '\'':
+ case '"':
+ v = c;
+ break;
+ case 'a': v = '\a'; break;
+ case 'b': v = '\b'; break;
+ case 'e': v = '\033'; break;
+ case 'f': v = '\f'; break;
+ case 'n': v = '\n'; break;
+ case 'r': v = '\r'; break;
+ case 't': v = '\t'; break;
+ case 'v': v = '\v'; break;
+ case 'x':
+ v = 0;
+ for (;;) {
+ c = pgetc();
+ if (c >= '0' && c <= '9')
+ v = (v << 4) + c - '0';
+ else if (c >= 'A' && c <= 'F')
+ v = (v << 4) + c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ v = (v << 4) + c - 'a' + 10;
+ else
+ break;
+ }
+ pungetc();
+ break;
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ v = c - '0';
+ c = pgetc();
+ if (c >= '0' && c <= '7') {
+ v <<= 3;
+ v += c - '0';
+ c = pgetc();
+ if (c >= '0' && c <= '7') {
+ v <<= 3;
+ v += c - '0';
+ } else
+ pungetc();
+ } else
+ pungetc();
+ break;
+ case 'c':
+ c = pgetc();
+ if (c < 0x3f || c > 0x7a || c == 0x60)
+ synerror("Bad escape sequence");
+ if (c == '\\' && pgetc() != '\\')
+ synerror("Bad escape sequence");
+ if (c == '?')
+ v = 127;
+ else
+ v = c & 0x1f;
+ break;
+ case 'u':
+ case 'U':
+ n = c == 'U' ? 8 : 4;
+ v = 0;
+ for (i = 0; i < n; i++) {
+ c = pgetc();
+ if (c >= '0' && c <= '9')
+ v = (v << 4) + c - '0';
+ else if (c >= 'A' && c <= 'F')
+ v = (v << 4) + c - 'A' + 10;
+ else if (c >= 'a' && c <= 'f')
+ v = (v << 4) + c - 'a' + 10;
+ else
+ synerror("Bad escape sequence");
+ }
+ if (v == 0 || (v >= 0xd800 && v <= 0xdfff))
+ synerror("Bad escape sequence");
+ /* We really need iconv here. */
+ if (initial_localeisutf8 && v > 127) {
+ CHECKSTRSPACE(4, out);
+ /*
+ * We cannot use wctomb() as the locale may have
+ * changed.
+ */
+ if (v <= 0x7ff) {
+ USTPUTC(0xc0 | v >> 6, out);
+ USTPUTC(0x80 | (v & 0x3f), out);
+ return out;
+ } else if (v <= 0xffff) {
+ USTPUTC(0xe0 | v >> 12, out);
+ USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
+ USTPUTC(0x80 | (v & 0x3f), out);
+ return out;
+ } else if (v <= 0x10ffff) {
+ USTPUTC(0xf0 | v >> 18, out);
+ USTPUTC(0x80 | ((v >> 12) & 0x3f), out);
+ USTPUTC(0x80 | ((v >> 6) & 0x3f), out);
+ USTPUTC(0x80 | (v & 0x3f), out);
+ return out;
+ }
+ }
+ if (v > 127)
+ v = '?';
+ break;
+ default:
+ synerror("Bad escape sequence");
+ }
+ vc = (char)v;
+ /*
+ * We can't handle NUL bytes.
+ * POSIX says we should skip till the closing quote.
+ */
+ if (vc == '\0') {
+ while ((c = pgetc()) != '\'') {
+ if (c == '\\')
+ c = pgetc();
+ if (c == PEOF)
+ synerror("Unterminated quoted string");
+ if (c == '\n') {
+ plinno++;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ }
+ }
+ pungetc();
+ return out;
+ }
+ if (SQSYNTAX[vc] == CCTL)
+ USTPUTC(CTLESC, out);
+ USTPUTC(vc, out);
+ return out;
+}
+
+
+/*
+ * If eofmark is NULL, read a word or a redirection symbol. If eofmark
+ * is not NULL, read a here document. In the latter case, eofmark is the
+ * word which marks the end of the document and striptabs is true if
+ * leading tabs should be stripped from the document. The argument firstc
+ * is the first character of the input token or document.
+ *
+ * Because C does not have internal subroutines, I have simulated them
+ * using goto's to implement the subroutine linkage. The following macros
+ * will run code that appears at the end of readtoken1.
+ */
+
+#define PARSESUB() {goto parsesub; parsesub_return:;}
+#define PARSEARITH() {goto parsearith; parsearith_return:;}
+
+static int
+readtoken1(int firstc, char const *initialsyntax, const char *eofmark,
+ int striptabs)
+{
+ int c = firstc;
+ char *out;
+ int len;
+ struct nodelist *bqlist;
+ int quotef;
+ int newvarnest;
+ int level;
+ int synentry;
+ struct tokenstate state_static[MAXNEST_static];
+ int maxnest = MAXNEST_static;
+ struct tokenstate *state = state_static;
+ int sqiscstyle = 0;
+
+ startlinno = plinno;
+ quotef = 0;
+ bqlist = NULL;
+ newvarnest = 0;
+ level = 0;
+ state[level].syntax = initialsyntax;
+ state[level].parenlevel = 0;
+ state[level].category = TSTATE_TOP;
+
+ STARTSTACKSTR(out);
+ loop: { /* for each line, until end of word */
+ if (eofmark && eofmark != NOEOFMARK)
+ /* set c to PEOF if at end of here document */
+ c = checkend(c, eofmark, striptabs);
+ for (;;) { /* until end of line or end of word */
+ CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */
+
+ synentry = state[level].syntax[c];
+
+ switch(synentry) {
+ case CNL: /* '\n' */
+ if (level == 0)
+ goto endword; /* exit outer loop */
+ /* FALLTHROUGH */
+ case CQNL:
+ USTPUTC(c, out);
+ plinno++;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ c = pgetc();
+ goto loop; /* continue outer loop */
+ case CSBACK:
+ if (sqiscstyle) {
+ out = readcstyleesc(out);
+ break;
+ }
+ /* FALLTHROUGH */
+ case CWORD:
+ USTPUTC(c, out);
+ break;
+ case CCTL:
+ if (eofmark == NULL || initialsyntax != SQSYNTAX)
+ USTPUTC(CTLESC, out);
+ USTPUTC(c, out);
+ break;
+ case CBACK: /* backslash */
+ c = pgetc();
+ if (c == PEOF) {
+ USTPUTC('\\', out);
+ pungetc();
+ } else if (c == '\n') {
+ plinno++;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ } else {
+ if (state[level].syntax == DQSYNTAX &&
+ c != '\\' && c != '`' && c != '$' &&
+ (c != '"' || (eofmark != NULL &&
+ newvarnest == 0)) &&
+ (c != '}' || state[level].category != TSTATE_VAR_OLD))
+ USTPUTC('\\', out);
+ if ((eofmark == NULL ||
+ newvarnest > 0) &&
+ state[level].syntax == BASESYNTAX)
+ USTPUTC(CTLQUOTEMARK, out);
+ if (SQSYNTAX[c] == CCTL)
+ USTPUTC(CTLESC, out);
+ USTPUTC(c, out);
+ if ((eofmark == NULL ||
+ newvarnest > 0) &&
+ state[level].syntax == BASESYNTAX &&
+ state[level].category == TSTATE_VAR_OLD)
+ USTPUTC(CTLQUOTEEND, out);
+ quotef++;
+ }
+ break;
+ case CSQUOTE:
+ USTPUTC(CTLQUOTEMARK, out);
+ state[level].syntax = SQSYNTAX;
+ sqiscstyle = 0;
+ break;
+ case CDQUOTE:
+ USTPUTC(CTLQUOTEMARK, out);
+ state[level].syntax = DQSYNTAX;
+ break;
+ case CENDQUOTE:
+ if (eofmark != NULL && newvarnest == 0)
+ USTPUTC(c, out);
+ else {
+ if (state[level].category == TSTATE_VAR_OLD)
+ USTPUTC(CTLQUOTEEND, out);
+ state[level].syntax = BASESYNTAX;
+ quotef++;
+ }
+ break;
+ case CVAR: /* '$' */
+ PARSESUB(); /* parse substitution */
+ break;
+ case CENDVAR: /* '}' */
+ if (level > 0 &&
+ ((state[level].category == TSTATE_VAR_OLD &&
+ state[level].syntax ==
+ state[level - 1].syntax) ||
+ (state[level].category == TSTATE_VAR_NEW &&
+ state[level].syntax == BASESYNTAX))) {
+ if (state[level].category == TSTATE_VAR_NEW)
+ newvarnest--;
+ level--;
+ USTPUTC(CTLENDVAR, out);
+ } else {
+ USTPUTC(c, out);
+ }
+ break;
+ case CLP: /* '(' in arithmetic */
+ state[level].parenlevel++;
+ USTPUTC(c, out);
+ break;
+ case CRP: /* ')' in arithmetic */
+ if (state[level].parenlevel > 0) {
+ USTPUTC(c, out);
+ --state[level].parenlevel;
+ } else {
+ if (pgetc_linecont() == ')') {
+ if (level > 0 &&
+ state[level].category == TSTATE_ARITH) {
+ level--;
+ USTPUTC(CTLENDARI, out);
+ } else
+ USTPUTC(')', out);
+ } else {
+ /*
+ * unbalanced parens
+ * (don't 2nd guess - no error)
+ */
+ pungetc();
+ USTPUTC(')', out);
+ }
+ }
+ break;
+ case CBQUOTE: /* '`' */
+ out = parsebackq(out, &bqlist, 1,
+ state[level].syntax == DQSYNTAX &&
+ (eofmark == NULL || newvarnest > 0),
+ state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX);
+ break;
+ case CEOF:
+ goto endword; /* exit outer loop */
+ case CIGN:
+ break;
+ default:
+ if (level == 0)
+ goto endword; /* exit outer loop */
+ USTPUTC(c, out);
+ }
+ c = pgetc_macro();
+ }
+ }
+endword:
+ if (state[level].syntax == ARISYNTAX)
+ synerror("Missing '))'");
+ if (state[level].syntax != BASESYNTAX && eofmark == NULL)
+ synerror("Unterminated quoted string");
+ if (state[level].category == TSTATE_VAR_OLD ||
+ state[level].category == TSTATE_VAR_NEW) {
+ startlinno = plinno;
+ synerror("Missing '}'");
+ }
+ if (state != state_static)
+ parser_temp_free_upto(state);
+ USTPUTC('\0', out);
+ len = out - stackblock();
+ out = stackblock();
+ if (eofmark == NULL) {
+ if ((c == '>' || c == '<')
+ && quotef == 0
+ && len <= 2
+ && (*out == '\0' || is_digit(*out))) {
+ parseredir(out, c);
+ return lasttoken = TREDIR;
+ } else {
+ pungetc();
+ }
+ }
+ quoteflag = quotef;
+ backquotelist = bqlist;
+ grabstackblock(len);
+ wordtext = out;
+ return lasttoken = TWORD;
+/* end of readtoken routine */
+
+
+/*
+ * Parse a substitution. At this point, we have read the dollar sign
+ * and nothing else.
+ */
+
+parsesub: {
+ int subtype;
+ int typeloc;
+ int flags;
+ char *p;
+ static const char types[] = "}-+?=";
+ int linno;
+ int length;
+ int c1;
+
+ c = pgetc_linecont();
+ if (c == '(') { /* $(command) or $((arith)) */
+ if (pgetc_linecont() == '(') {
+ PARSEARITH();
+ } else {
+ pungetc();
+ out = parsebackq(out, &bqlist, 0,
+ state[level].syntax == DQSYNTAX &&
+ (eofmark == NULL || newvarnest > 0),
+ state[level].syntax == DQSYNTAX ||
+ state[level].syntax == ARISYNTAX);
+ }
+ } else if (c == '{' || is_name(c) || is_special(c)) {
+ USTPUTC(CTLVAR, out);
+ typeloc = out - stackblock();
+ USTPUTC(VSNORMAL, out);
+ subtype = VSNORMAL;
+ flags = 0;
+ if (c == '{') {
+ c = pgetc_linecont();
+ subtype = 0;
+ }
+varname:
+ if (!is_eof(c) && is_name(c)) {
+ length = 0;
+ do {
+ STPUTC(c, out);
+ c = pgetc_linecont();
+ length++;
+ } while (!is_eof(c) && is_in_name(c));
+ if (length == 6 &&
+ strncmp(out - length, "LINENO", length) == 0) {
+ /* Replace the variable name with the
+ * current line number. */
+ STADJUST(-6, out);
+ CHECKSTRSPACE(11, out);
+ linno = plinno;
+ if (funclinno != 0)
+ linno -= funclinno - 1;
+ length = snprintf(out, 11, "%d", linno);
+ if (length > 10)
+ length = 10;
+ out += length;
+ flags |= VSLINENO;
+ }
+ } else if (is_digit(c)) {
+ if (subtype != VSNORMAL) {
+ do {
+ STPUTC(c, out);
+ c = pgetc_linecont();
+ } while (is_digit(c));
+ } else {
+ USTPUTC(c, out);
+ c = pgetc_linecont();
+ }
+ } else if (is_special(c)) {
+ c1 = c;
+ c = pgetc_linecont();
+ if (subtype == 0 && c1 == '#') {
+ subtype = VSLENGTH;
+ if (strchr(types, c) == NULL && c != ':' &&
+ c != '#' && c != '%')
+ goto varname;
+ c1 = c;
+ c = pgetc_linecont();
+ if (c1 != '}' && c == '}') {
+ pungetc();
+ c = c1;
+ goto varname;
+ }
+ pungetc();
+ c = c1;
+ c1 = '#';
+ subtype = 0;
+ }
+ USTPUTC(c1, out);
+ } else {
+ subtype = VSERROR;
+ if (c == '}')
+ pungetc();
+ else if (c == '\n' || c == PEOF)
+ synerror("Unexpected end of line in substitution");
+ else if (BASESYNTAX[c] != CCTL)
+ USTPUTC(c, out);
+ }
+ if (subtype == 0) {
+ switch (c) {
+ case ':':
+ flags |= VSNUL;
+ c = pgetc_linecont();
+ /*FALLTHROUGH*/
+ default:
+ p = strchr(types, c);
+ if (p == NULL) {
+ if (c == '\n' || c == PEOF)
+ synerror("Unexpected end of line in substitution");
+ if (flags == VSNUL)
+ STPUTC(':', out);
+ if (BASESYNTAX[c] != CCTL)
+ STPUTC(c, out);
+ subtype = VSERROR;
+ } else
+ subtype = p - types + VSNORMAL;
+ break;
+ case '%':
+ case '#':
+ {
+ int cc = c;
+ subtype = c == '#' ? VSTRIMLEFT :
+ VSTRIMRIGHT;
+ c = pgetc_linecont();
+ if (c == cc)
+ subtype++;
+ else
+ pungetc();
+ break;
+ }
+ }
+ } else if (subtype != VSERROR) {
+ if (subtype == VSLENGTH && c != '}')
+ subtype = VSERROR;
+ pungetc();
+ }
+ STPUTC('=', out);
+ if (state[level].syntax == DQSYNTAX ||
+ state[level].syntax == ARISYNTAX)
+ flags |= VSQUOTE;
+ *(stackblock() + typeloc) = subtype | flags;
+ if (subtype != VSNORMAL) {
+ if (level + 1 >= maxnest) {
+ maxnest *= 2;
+ if (state == state_static) {
+ state = parser_temp_alloc(
+ maxnest * sizeof(*state));
+ memcpy(state, state_static,
+ MAXNEST_static * sizeof(*state));
+ } else
+ state = parser_temp_realloc(state,
+ maxnest * sizeof(*state));
+ }
+ level++;
+ state[level].parenlevel = 0;
+ if (subtype == VSMINUS || subtype == VSPLUS ||
+ subtype == VSQUESTION || subtype == VSASSIGN) {
+ /*
+ * For operators that were in the Bourne shell,
+ * inherit the double-quote state.
+ */
+ state[level].syntax = state[level - 1].syntax;
+ state[level].category = TSTATE_VAR_OLD;
+ } else {
+ /*
+ * The other operators take a pattern,
+ * so go to BASESYNTAX.
+ * Also, ' and " are now special, even
+ * in here documents.
+ */
+ state[level].syntax = BASESYNTAX;
+ state[level].category = TSTATE_VAR_NEW;
+ newvarnest++;
+ }
+ }
+ } else if (c == '\'' && state[level].syntax == BASESYNTAX) {
+ /* $'cstylequotes' */
+ USTPUTC(CTLQUOTEMARK, out);
+ state[level].syntax = SQSYNTAX;
+ sqiscstyle = 1;
+ } else {
+ USTPUTC('$', out);
+ pungetc();
+ }
+ goto parsesub_return;
+}
+
+
+/*
+ * Parse an arithmetic expansion (indicate start of one and set state)
+ */
+parsearith: {
+
+ if (level + 1 >= maxnest) {
+ maxnest *= 2;
+ if (state == state_static) {
+ state = parser_temp_alloc(
+ maxnest * sizeof(*state));
+ memcpy(state, state_static,
+ MAXNEST_static * sizeof(*state));
+ } else
+ state = parser_temp_realloc(state,
+ maxnest * sizeof(*state));
+ }
+ level++;
+ state[level].syntax = ARISYNTAX;
+ state[level].parenlevel = 0;
+ state[level].category = TSTATE_ARITH;
+ USTPUTC(CTLARI, out);
+ if (state[level - 1].syntax == DQSYNTAX)
+ USTPUTC('"',out);
+ else
+ USTPUTC(' ',out);
+ goto parsearith_return;
+}
+
+} /* end of readtoken */
+
+
+/*
+ * Returns true if the text contains nothing to expand (no dollar signs
+ * or backquotes).
+ */
+
+static int
+noexpand(char *text)
+{
+ char *p;
+ char c;
+
+ p = text;
+ while ((c = *p++) != '\0') {
+ if ( c == CTLQUOTEMARK)
+ continue;
+ if (c == CTLESC)
+ p++;
+ else if (BASESYNTAX[(int)c] == CCTL)
+ return 0;
+ }
+ return 1;
+}
+
+
+/*
+ * Return true if the argument is a legal variable name (a letter or
+ * underscore followed by zero or more letters, underscores, and digits).
+ */
+
+int
+goodname(const char *name)
+{
+ const char *p;
+
+ p = name;
+ if (! is_name(*p))
+ return 0;
+ while (*++p) {
+ if (! is_in_name(*p))
+ return 0;
+ }
+ return 1;
+}
+
+
+int
+isassignment(const char *p)
+{
+ if (!is_name(*p))
+ return 0;
+ p++;
+ for (;;) {
+ if (*p == '=')
+ return 1;
+ else if (!is_in_name(*p))
+ return 0;
+ p++;
+ }
+}
+
+
+static void
+consumetoken(int token)
+{
+ if (readtoken() != token)
+ synexpect(token);
+}
+
+
+/*
+ * Called when an unexpected token is read during the parse. The argument
+ * is the token that is expected, or -1 if more than one type of token can
+ * occur at this point.
+ */
+
+static void
+synexpect(int token)
+{
+ char msg[64];
+
+ if (token >= 0) {
+ fmtstr(msg, 64, "%s unexpected (expecting %s)",
+ tokname[lasttoken], tokname[token]);
+ } else {
+ fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
+ }
+ synerror(msg);
+}
+
+
+static void
+synerror(const char *msg)
+{
+ if (commandname)
+ outfmt(out2, "%s: %d: ", commandname, startlinno);
+ else if (arg0)
+ outfmt(out2, "%s: ", arg0);
+ outfmt(out2, "Syntax error: %s\n", msg);
+ error((char *)NULL);
+}
+
+static void
+setprompt(int which)
+{
+ whichprompt = which;
+ if (which == 0)
+ return;
+
+#ifndef NO_HISTORY
+ if (!el)
+#endif
+ {
+ out2str(getprompt(NULL));
+ flushout(out2);
+ }
+}
+
+static int
+pgetc_linecont(void)
+{
+ int c;
+
+ while ((c = pgetc_macro()) == '\\') {
+ c = pgetc();
+ if (c == '\n') {
+ plinno++;
+ if (doprompt)
+ setprompt(2);
+ else
+ setprompt(0);
+ } else {
+ pungetc();
+ /* Allow the backslash to be pushed back. */
+ pushstring("\\", 1, NULL);
+ return (pgetc());
+ }
+ }
+ return (c);
+}
+
+
+static struct passwd *
+getpwlogin(void)
+{
+ const char *login;
+
+ login = getlogin();
+ if (login == NULL)
+ return (NULL);
+
+ return (getpwnam(login));
+}
+
+
+static void
+getusername(char *name, size_t namelen)
+{
+ static char cached_name[MAXLOGNAME];
+ struct passwd *pw;
+ uid_t euid;
+
+ if (cached_name[0] == '\0') {
+ euid = geteuid();
+
+ /*
+ * Handle the case when there is more than one
+ * login with the same UID, or when the login
+ * returned by getlogin(2) does no longer match
+ * the current UID.
+ */
+ pw = getpwlogin();
+ if (pw == NULL || pw->pw_uid != euid)
+ pw = getpwuid(euid);
+
+ if (pw != NULL) {
+ strlcpy(cached_name, pw->pw_name,
+ sizeof(cached_name));
+ } else {
+ snprintf(cached_name, sizeof(cached_name),
+ "%u", euid);
+ }
+ }
+
+ strlcpy(name, cached_name, namelen);
+}
+
+
+/*
+ * called by editline -- any expansions to the prompt
+ * should be added here.
+ */
+char *
+getprompt(void *unused __unused)
+{
+ static char ps[PROMPTLEN];
+ const char *fmt;
+ const char *home;
+ const char *pwd;
+ size_t homelen;
+ int i, trim;
+ static char internal_error[] = "??";
+
+ /*
+ * Select prompt format.
+ */
+ switch (whichprompt) {
+ case 0:
+ fmt = "";
+ break;
+ case 1:
+ fmt = ps1val();
+ break;
+ case 2:
+ fmt = ps2val();
+ break;
+ default:
+ return internal_error;
+ }
+
+ /*
+ * Format prompt string.
+ */
+ for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++) {
+ if (*fmt == '$') {
+ const char *varname_start, *varname_end, *value;
+ char varname[256];
+ int namelen, braced = 0;
+
+ fmt++; /* Skip the '$' */
+
+ /* Check for ${VAR} syntax */
+ if (*fmt == '{') {
+ braced = 1;
+ fmt++;
+ }
+
+ varname_start = fmt;
+
+ /* Extract variable name */
+ if (is_digit(*fmt)) {
+ /* Positional parameter: $0, $1, etc. */
+ fmt++;
+ varname_end = fmt;
+ } else if (is_special(*fmt)) {
+ /* Special parameter: $?, $!, $$, etc. */
+ fmt++;
+ varname_end = fmt;
+ } else if (is_name(*fmt)) {
+ /* Regular variable name */
+ do
+ fmt++;
+ while (is_in_name(*fmt));
+ varname_end = fmt;
+ } else {
+ /*
+ * Not a valid variable reference.
+ * Output literal '$'.
+ */
+ ps[i] = '$';
+ if (braced && i < PROMPTLEN - 2)
+ ps[++i] = '{';
+ fmt = varname_start - 1;
+ continue;
+ }
+
+ namelen = varname_end - varname_start;
+ if (namelen == 0 || namelen >= (int)sizeof(varname)) {
+ /* Invalid or too long, output literal */
+ ps[i] = '$';
+ fmt = varname_start - 1;
+ continue;
+ }
+
+ /* Copy variable name */
+ memcpy(varname, varname_start, namelen);
+ varname[namelen] = '\0';
+
+ /* Handle closing brace for ${VAR} */
+ if (braced) {
+ if (*fmt == '}') {
+ fmt++;
+ } else {
+ /* Missing closing brace, treat as literal */
+ ps[i] = '$';
+ if (i < PROMPTLEN - 2)
+ ps[++i] = '{';
+ fmt = varname_start - 1;
+ continue;
+ }
+ }
+
+ /* Look up the variable */
+ if (namelen == 1 && is_digit(*varname)) {
+ /* Positional parameters - check digits FIRST */
+ int num = *varname - '0';
+ if (num == 0)
+ value = arg0 ? arg0 : "";
+ else if (num > 0 && num <= shellparam.nparam)
+ value = shellparam.p[num - 1];
+ else
+ value = "";
+ } else if (namelen == 1 && is_special(*varname)) {
+ /* Special parameters */
+ char valbuf[20];
+ int num;
+
+ switch (*varname) {
+ case '$':
+ num = rootpid;
+ break;
+ case '?':
+ num = exitstatus;
+ break;
+ case '#':
+ num = shellparam.nparam;
+ break;
+ case '!':
+ num = backgndpidval();
+ break;
+ default:
+ num = 0;
+ break;
+ }
+ snprintf(valbuf, sizeof(valbuf), "%d", num);
+ value = valbuf;
+ } else {
+ /* Regular variables */
+ value = lookupvar(varname);
+ if (value == NULL)
+ value = "";
+ }
+
+ /* Copy value to output, respecting buffer size */
+ while (*value != '\0' && i < PROMPTLEN - 1) {
+ ps[i++] = *value++;
+ }
+
+ /*
+ * Adjust fmt and i for the loop increment.
+ * fmt will be incremented by the for loop,
+ * so position it one before where we want.
+ */
+ fmt--;
+ i--;
+ continue;
+ } else if (*fmt != '\\') {
+ ps[i] = *fmt;
+ continue;
+ }
+
+ switch (*++fmt) {
+
+ /*
+ * Non-printing sequence begin and end.
+ */
+ case '[':
+ case ']':
+ ps[i] = '\001';
+ break;
+
+ /*
+ * Literal \ and some ASCII characters:
+ * \a BEL
+ * \e ESC
+ * \r CR
+ */
+ case '\\':
+ case 'a':
+ case 'e':
+ case 'r':
+ if (*fmt == 'a')
+ ps[i] = '\007';
+ else if (*fmt == 'e')
+ ps[i] = '\033';
+ else if (*fmt == 'r')
+ ps[i] = '\r';
+ else
+ ps[i] = '\\';
+ break;
+
+ /*
+ * CRLF sequence
+ */
+ case 'n':
+ if (i < PROMPTLEN - 3) {
+ ps[i++] = '\r';
+ ps[i] = '\n';
+ }
+ break;
+
+ /*
+ * Print the current time as per provided strftime format.
+ */
+ case 'D': {
+ char tfmt[128] = "%X"; /* \D{} means %X. */
+ struct tm *now;
+
+ if (fmt[1] != '{') {
+ /*
+ * "\D" but not "\D{", so treat the '\'
+ * literally and rewind fmt to treat 'D'
+ * literally next iteration.
+ */
+ ps[i] = '\\';
+ fmt--;
+ break;
+ }
+ fmt += 2; /* Consume "D{". */
+ if (fmt[0] != '}') {
+ char *end;
+
+ end = memccpy(tfmt, fmt, '}', sizeof(tfmt));
+ if (end == NULL) {
+ /*
+ * Format too long or no '}', so
+ * ignore "\D{" altogether.
+ * The loop will do i++, but nothing
+ * was written to ps, so do i-- here.
+ * Rewind fmt for similar reason.
+ */
+ i--;
+ fmt--;
+ break;
+ }
+ *--end = '\0'; /* Ignore the copy of '}'. */
+ fmt += end - tfmt;
+ }
+ now = localtime(&(time_t){time(NULL)});
+ i += strftime(&ps[i], PROMPTLEN - i - 1, tfmt, now);
+ i--; /* The loop will do i++. */
+ break;
+ }
+
+ /*
+ * Hostname.
+ *
+ * \h specifies just the local hostname,
+ * \H specifies fully-qualified hostname.
+ */
+ case 'h':
+ case 'H':
+ ps[i] = '\0';
+ gethostname(&ps[i], PROMPTLEN - i - 1);
+ ps[PROMPTLEN - 1] = '\0';
+ /* Skip to end of hostname. */
+ trim = (*fmt == 'h') ? '.' : '\0';
+ while ((ps[i] != '\0') && (ps[i] != trim))
+ i++;
+ --i;
+ break;
+
+ /*
+ * User name.
+ */
+ case 'u':
+ ps[i] = '\0';
+ getusername(&ps[i], PROMPTLEN - i);
+ /* Skip to end of username. */
+ while (ps[i + 1] != '\0')
+ i++;
+ break;
+
+ /*
+ * Working directory.
+ *
+ * \W specifies just the final component,
+ * \w specifies the entire path.
+ */
+ case 'W':
+ case 'w':
+ pwd = lookupvar("PWD");
+ if (pwd == NULL || *pwd == '\0')
+ pwd = "?";
+ if (*fmt == 'W' &&
+ *pwd == '/' && pwd[1] != '\0')
+ strlcpy(&ps[i], strrchr(pwd, '/') + 1,
+ PROMPTLEN - i);
+ else {
+ home = lookupvar("HOME");
+ if (home != NULL)
+ homelen = strlen(home);
+ if (home != NULL &&
+ strcmp(home, "/") != 0 &&
+ strncmp(pwd, home, homelen) == 0 &&
+ (pwd[homelen] == '/' ||
+ pwd[homelen] == '\0')) {
+ strlcpy(&ps[i], "~",
+ PROMPTLEN - i);
+ strlcpy(&ps[i + 1],
+ pwd + homelen,
+ PROMPTLEN - i - 1);
+ } else {
+ strlcpy(&ps[i], pwd, PROMPTLEN - i);
+ }
+ }
+ /* Skip to end of path. */
+ while (ps[i + 1] != '\0')
+ i++;
+ break;
+
+ /*
+ * Superuser status.
+ *
+ * '$' for normal users, '#' for root.
+ */
+ case '$':
+ ps[i] = (geteuid() != 0) ? '$' : '#';
+ break;
+
+ /*
+ * Emit unrecognized formats verbatim.
+ */
+ default:
+ ps[i] = '\\';
+ if (i < PROMPTLEN - 2)
+ ps[++i] = *fmt;
+ break;
+ }
+
+ }
+ ps[i] = '\0';
+ return (ps);
+}
+
+
+const char *
+expandstr(const char *ps)
+{
+ union node n;
+ struct jmploc jmploc;
+ struct jmploc *const savehandler = handler;
+ const int saveprompt = doprompt;
+ struct parsefile *const savetopfile = getcurrentfile();
+ struct parser_temp *const saveparser_temp = parser_temp;
+ const char *result = NULL;
+
+ if (!setjmp(jmploc.loc)) {
+ handler = &jmploc;
+ parser_temp = NULL;
+ setinputstring(ps);
+ doprompt = 0;
+ readtoken1(pgetc(), DQSYNTAX, NOEOFMARK, 0);
+ if (backquotelist != NULL)
+ error("Command substitution not allowed here");
+
+ n.narg.type = NARG;
+ n.narg.next = NULL;
+ n.narg.text = wordtext;
+ n.narg.backquote = backquotelist;
+
+ expandarg(&n, NULL, 0);
+ result = stackblock();
+ INTOFF;
+ }
+ handler = savehandler;
+ doprompt = saveprompt;
+ popfilesupto(savetopfile);
+ if (parser_temp != saveparser_temp) {
+ parser_temp_free_all();
+ parser_temp = saveparser_temp;
+ }
+ if (result != NULL) {
+ INTON;
+ } else if (exception == EXINT)
+ raise(SIGINT);
+ return result;
+}
diff --git a/cmd/posix/sh/parser.h b/cmd/posix/sh/parser.h
@@ -0,0 +1,84 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* control characters in argument strings */
+#define CTLESC '\300'
+#define CTLVAR '\301'
+#define CTLENDVAR '\371'
+#define CTLBACKQ '\372'
+#define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */
+/* CTLBACKQ | CTLQUOTE == '\373' */
+#define CTLARI '\374'
+#define CTLENDARI '\375'
+#define CTLQUOTEMARK '\376'
+#define CTLQUOTEEND '\377' /* only for ${v+-...} */
+
+/* variable substitution byte (follows CTLVAR) */
+#define VSTYPE 0x0f /* type of variable substitution */
+#define VSNUL 0x10 /* colon--treat the empty string as unset */
+#define VSLINENO 0x20 /* expansion of $LINENO, the line number \
+ follows immediately */
+#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */
+
+/* values of VSTYPE field */
+#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
+#define VSMINUS 0x2 /* ${var-text} */
+#define VSPLUS 0x3 /* ${var+text} */
+#define VSQUESTION 0x4 /* ${var?message} */
+#define VSASSIGN 0x5 /* ${var=text} */
+#define VSTRIMLEFT 0x6 /* ${var#pattern} */
+#define VSTRIMLEFTMAX 0x7 /* ${var##pattern} */
+#define VSTRIMRIGHT 0x8 /* ${var%pattern} */
+#define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */
+#define VSLENGTH 0xa /* ${#var} */
+#define VSERROR 0xb /* Syntax error, issue when expanded */
+
+
+/*
+ * NEOF is returned by parsecmd when it encounters an end of file. It
+ * must be distinct from NULL.
+ */
+#define NEOF ((union node *)-1)
+extern int whichprompt; /* 1 == PS1, 2 == PS2 */
+extern const char *const parsekwd[];
+
+
+union node *parsecmd(int);
+union node *parsewordexp(void);
+void forcealias(void);
+void fixredir(union node *, const char *, int);
+int goodname(const char *);
+int isassignment(const char *);
+char *getprompt(void *);
+const char *expandstr(const char *);
diff --git a/cmd/posix/sh/printf.c b/cmd/posix/sh/printf.c
@@ -0,0 +1,672 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright 2018 Staysail Systems, Inc. <info@staysail.tech>
+ * Copyright 2014 Garrett D'Amore <garrett@damore.org>
+ * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 1989, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+/*
+ * Important: This file is used both as a standalone program /usr/bin/printf
+ * and as a builtin for /bin/sh (#define SHELL).
+ */
+
+#include <sys/types.h>
+
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <wchar.h>
+
+#ifdef SHELL
+#define main printfcmd
+#include "bltin.h"
+#include "options.h"
+#endif
+
+#define PF(f, func) do { \
+ if (havewidth) \
+ if (haveprec) \
+ (void)printf(f, fieldwidth, precision, func); \
+ else \
+ (void)printf(f, fieldwidth, func); \
+ else if (haveprec) \
+ (void)printf(f, precision, func); \
+ else \
+ (void)printf(f, func); \
+} while (0)
+
+static int asciicode(void);
+static char *printf_doformat(char *, int *);
+static int escape(char *, int, size_t *);
+static int getchr(void);
+static int getfloating(long double *, int);
+static int getint(int *);
+static int getnum(intmax_t *, uintmax_t *, int);
+static const char
+ *getstr(void);
+static char *mknum(char *, char);
+static void usage(void);
+
+static const char digits[] = "0123456789";
+
+static char end_fmt[1];
+
+static int myargc;
+static char **myargv;
+static char **gargv;
+static char **maxargv;
+
+int
+main(int argc, char *argv[])
+{
+ size_t len;
+ int end, rval;
+ char *format, *fmt, *start;
+#ifndef SHELL
+ int ch;
+
+ (void) setlocale(LC_ALL, "");
+#endif
+
+#ifdef SHELL
+ nextopt("");
+ argc -= argptr - argv;
+ argv = argptr;
+#else
+ while ((ch = getopt(argc, argv, "")) != -1)
+ switch (ch) {
+ case '?':
+ default:
+ usage();
+ return (1);
+ }
+ argc -= optind;
+ argv += optind;
+#endif
+
+ if (argc < 1) {
+ usage();
+ return (1);
+ }
+
+#ifdef SHELL
+ INTOFF;
+#endif
+ /*
+ * Basic algorithm is to scan the format string for conversion
+ * specifications -- once one is found, find out if the field
+ * width or precision is a '*'; if it is, gather up value. Note,
+ * format strings are reused as necessary to use up the provided
+ * arguments, arguments of zero/null string are provided to use
+ * up the format string.
+ */
+ fmt = format = *argv;
+ escape(fmt, 1, &len); /* backslash interpretation */
+ rval = end = 0;
+ gargv = ++argv;
+
+ for (;;) {
+ maxargv = gargv;
+
+ myargv = gargv;
+ for (myargc = 0; gargv[myargc]; myargc++)
+ /* nop */;
+ start = fmt;
+ while (fmt < format + len) {
+ if (fmt[0] == '%') {
+ fwrite(start, 1, fmt - start, stdout);
+ if (fmt[1] == '%') {
+ /* %% prints a % */
+ putchar('%');
+ fmt += 2;
+ } else {
+ fmt = printf_doformat(fmt, &rval);
+ if (fmt == NULL || fmt == end_fmt) {
+#ifdef SHELL
+ INTON;
+#endif
+ return (fmt == NULL ? 1 : rval);
+ }
+ end = 0;
+ }
+ start = fmt;
+ } else
+ fmt++;
+ if (gargv > maxargv)
+ maxargv = gargv;
+ }
+ gargv = maxargv;
+
+ if (end == 1) {
+ warnx("missing format character");
+#ifdef SHELL
+ INTON;
+#endif
+ return (1);
+ }
+ fwrite(start, 1, fmt - start, stdout);
+ if (!*gargv) {
+#ifdef SHELL
+ INTON;
+#endif
+ return (rval);
+ }
+ /* Restart at the beginning of the format string. */
+ fmt = format;
+ end = 1;
+ }
+ /* NOTREACHED */
+}
+
+
+static char *
+printf_doformat(char *fmt, int *rval)
+{
+ static const char skip1[] = "#'-+ 0";
+ int fieldwidth, haveprec, havewidth, mod_ldbl, precision;
+ char convch, nextch;
+ char start[strlen(fmt) + 1];
+ char **fargv;
+ char *dptr;
+ int l;
+
+ dptr = start;
+ *dptr++ = '%';
+ *dptr = 0;
+
+ fmt++;
+
+ /* look for "n$" field index specifier */
+ l = strspn(fmt, digits);
+ if ((l > 0) && (fmt[l] == '$')) {
+ int idx = atoi(fmt);
+ if (idx <= myargc) {
+ gargv = &myargv[idx - 1];
+ } else {
+ gargv = &myargv[myargc];
+ }
+ if (gargv > maxargv)
+ maxargv = gargv;
+ fmt += l + 1;
+
+ /* save format argument */
+ fargv = gargv;
+ } else {
+ fargv = NULL;
+ }
+
+ /* skip to field width */
+ while (*fmt && strchr(skip1, *fmt) != NULL) {
+ *dptr++ = *fmt++;
+ *dptr = 0;
+ }
+
+ if (*fmt == '*') {
+
+ fmt++;
+ l = strspn(fmt, digits);
+ if ((l > 0) && (fmt[l] == '$')) {
+ int idx = atoi(fmt);
+ if (fargv == NULL) {
+ warnx("incomplete use of n$");
+ return (NULL);
+ }
+ if (idx <= myargc) {
+ gargv = &myargv[idx - 1];
+ } else {
+ gargv = &myargv[myargc];
+ }
+ fmt += l + 1;
+ } else if (fargv != NULL) {
+ warnx("incomplete use of n$");
+ return (NULL);
+ }
+
+ if (getint(&fieldwidth))
+ return (NULL);
+ if (gargv > maxargv)
+ maxargv = gargv;
+ havewidth = 1;
+
+ *dptr++ = '*';
+ *dptr = 0;
+ } else {
+ havewidth = 0;
+
+ /* skip to possible '.', get following precision */
+ while (isdigit(*fmt)) {
+ *dptr++ = *fmt++;
+ *dptr = 0;
+ }
+ }
+
+ if (*fmt == '.') {
+ /* precision present? */
+ fmt++;
+ *dptr++ = '.';
+
+ if (*fmt == '*') {
+
+ fmt++;
+ l = strspn(fmt, digits);
+ if ((l > 0) && (fmt[l] == '$')) {
+ int idx = atoi(fmt);
+ if (fargv == NULL) {
+ warnx("incomplete use of n$");
+ return (NULL);
+ }
+ if (idx <= myargc) {
+ gargv = &myargv[idx - 1];
+ } else {
+ gargv = &myargv[myargc];
+ }
+ fmt += l + 1;
+ } else if (fargv != NULL) {
+ warnx("incomplete use of n$");
+ return (NULL);
+ }
+
+ if (getint(&precision))
+ return (NULL);
+ if (gargv > maxargv)
+ maxargv = gargv;
+ haveprec = 1;
+ *dptr++ = '*';
+ *dptr = 0;
+ } else {
+ haveprec = 0;
+
+ /* skip to conversion char */
+ while (isdigit(*fmt)) {
+ *dptr++ = *fmt++;
+ *dptr = 0;
+ }
+ }
+ } else
+ haveprec = 0;
+ if (!*fmt) {
+ warnx("missing format character");
+ return (NULL);
+ }
+ *dptr++ = *fmt;
+ *dptr = 0;
+
+ /*
+ * Look for a length modifier. POSIX doesn't have these, so
+ * we only support them for floating-point conversions, which
+ * are extensions. This is useful because the L modifier can
+ * be used to gain extra range and precision, while omitting
+ * it is more likely to produce consistent results on different
+ * architectures. This is not so important for integers
+ * because overflow is the only bad thing that can happen to
+ * them, but consider the command printf %a 1.1
+ */
+ if (*fmt == 'L') {
+ mod_ldbl = 1;
+ fmt++;
+ if (!strchr("aAeEfFgG", *fmt)) {
+ warnx("bad modifier L for %%%c", *fmt);
+ return (NULL);
+ }
+ } else {
+ mod_ldbl = 0;
+ }
+
+ /* save the current arg offset, and set to the format arg */
+ if (fargv != NULL) {
+ gargv = fargv;
+ }
+
+ convch = *fmt;
+ nextch = *++fmt;
+
+ *fmt = '\0';
+ switch (convch) {
+ case 'b': {
+ size_t len;
+ char *p;
+ int getout;
+
+ /* Convert "b" to "s" for output. */
+ start[strlen(start) - 1] = 's';
+ if ((p = strdup(getstr())) == NULL) {
+ warnx("%s", strerror(ENOMEM));
+ return (NULL);
+ }
+ getout = escape(p, 0, &len);
+ PF(start, p);
+ /* Restore format for next loop. */
+
+ free(p);
+ if (getout)
+ return (end_fmt);
+ break;
+ }
+ case 'c': {
+ char p;
+
+ p = getchr();
+ if (p != '\0')
+ PF(start, p);
+ break;
+ }
+ case 's': {
+ const char *p;
+
+ p = getstr();
+ PF(start, p);
+ break;
+ }
+ case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': {
+ char *f;
+ intmax_t val;
+ uintmax_t uval;
+ int signedconv;
+
+ signedconv = (convch == 'd' || convch == 'i');
+ if ((f = mknum(start, convch)) == NULL)
+ return (NULL);
+ if (getnum(&val, &uval, signedconv))
+ *rval = 1;
+ if (signedconv)
+ PF(f, val);
+ else
+ PF(f, uval);
+ break;
+ }
+ case 'e': case 'E':
+ case 'f': case 'F':
+ case 'g': case 'G':
+ case 'a': case 'A': {
+ long double p;
+
+ if (getfloating(&p, mod_ldbl))
+ *rval = 1;
+ if (mod_ldbl)
+ PF(start, p);
+ else
+ PF(start, (double)p);
+ break;
+ }
+ default:
+ warnx("illegal format character %c", convch);
+ return (NULL);
+ }
+ *fmt = nextch;
+ /* return the gargv to the next element */
+ return (fmt);
+}
+
+static char *
+mknum(char *str, char ch)
+{
+ static char *copy;
+ static size_t copy_size;
+ char *newcopy;
+ size_t len, newlen;
+
+ len = strlen(str) + 2;
+ if (len > copy_size) {
+ newlen = ((len + 1023) >> 10) << 10;
+ if ((newcopy = realloc(copy, newlen)) == NULL) {
+ warnx("%s", strerror(ENOMEM));
+ return (NULL);
+ }
+ copy = newcopy;
+ copy_size = newlen;
+ }
+
+ memmove(copy, str, len - 3);
+ copy[len - 3] = 'j';
+ copy[len - 2] = ch;
+ copy[len - 1] = '\0';
+ return (copy);
+}
+
+static int
+escape(char *fmt, int percent, size_t *len)
+{
+ char *save, *store, c;
+ int value;
+
+ for (save = store = fmt; ((c = *fmt) != 0); ++fmt, ++store) {
+ if (c != '\\') {
+ *store = c;
+ continue;
+ }
+ switch (*++fmt) {
+ case '\0': /* EOS, user error */
+ *store = '\\';
+ *++store = '\0';
+ *len = store - save;
+ return (0);
+ case '\\': /* backslash */
+ case '\'': /* single quote */
+ *store = *fmt;
+ break;
+ case 'a': /* bell/alert */
+ *store = '\a';
+ break;
+ case 'b': /* backspace */
+ *store = '\b';
+ break;
+ case 'c':
+ if (!percent) {
+ *store = '\0';
+ *len = store - save;
+ return (1);
+ }
+ *store = 'c';
+ break;
+ case 'f': /* form-feed */
+ *store = '\f';
+ break;
+ case 'n': /* newline */
+ *store = '\n';
+ break;
+ case 'r': /* carriage-return */
+ *store = '\r';
+ break;
+ case 't': /* horizontal tab */
+ *store = '\t';
+ break;
+ case 'v': /* vertical tab */
+ *store = '\v';
+ break;
+ /* octal constant */
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ c = (!percent && *fmt == '0') ? 4 : 3;
+ for (value = 0;
+ c-- && *fmt >= '0' && *fmt <= '7'; ++fmt) {
+ value <<= 3;
+ value += *fmt - '0';
+ }
+ --fmt;
+ if (percent && value == '%') {
+ *store++ = '%';
+ *store = '%';
+ } else
+ *store = (char)value;
+ break;
+ default:
+ *store = *fmt;
+ break;
+ }
+ }
+ *store = '\0';
+ *len = store - save;
+ return (0);
+}
+
+static int
+getchr(void)
+{
+ if (!*gargv)
+ return ('\0');
+ return ((int)**gargv++);
+}
+
+static const char *
+getstr(void)
+{
+ if (!*gargv)
+ return ("");
+ return (*gargv++);
+}
+
+static int
+getint(int *ip)
+{
+ intmax_t val;
+ uintmax_t uval;
+ int rval;
+
+ if (getnum(&val, &uval, 1))
+ return (1);
+ rval = 0;
+ if (val < INT_MIN || val > INT_MAX) {
+ warnx("%s: %s", *gargv, strerror(ERANGE));
+ rval = 1;
+ }
+ *ip = (int)val;
+ return (rval);
+}
+
+static int
+getnum(intmax_t *ip, uintmax_t *uip, int signedconv)
+{
+ char *ep;
+ int rval;
+
+ if (!*gargv) {
+ *ip = *uip = 0;
+ return (0);
+ }
+ if (**gargv == '"' || **gargv == '\'') {
+ if (signedconv)
+ *ip = asciicode();
+ else
+ *uip = asciicode();
+ return (0);
+ }
+ rval = 0;
+ errno = 0;
+ if (signedconv)
+ *ip = strtoimax(*gargv, &ep, 0);
+ else
+ *uip = strtoumax(*gargv, &ep, 0);
+ if (ep == *gargv) {
+ warnx("%s: expected numeric value", *gargv);
+ rval = 1;
+ }
+ else if (*ep != '\0') {
+ warnx("%s: not completely converted", *gargv);
+ rval = 1;
+ }
+ if (errno == ERANGE) {
+ warnx("%s: %s", *gargv, strerror(ERANGE));
+ rval = 1;
+ }
+ ++gargv;
+ return (rval);
+}
+
+static int
+getfloating(long double *dp, int mod_ldbl)
+{
+ char *ep;
+ int rval;
+
+ if (!*gargv) {
+ *dp = 0.0;
+ return (0);
+ }
+ if (**gargv == '"' || **gargv == '\'') {
+ *dp = asciicode();
+ return (0);
+ }
+ rval = 0;
+ errno = 0;
+ if (mod_ldbl)
+ *dp = strtold(*gargv, &ep);
+ else
+ *dp = strtod(*gargv, &ep);
+ if (ep == *gargv) {
+ warnx("%s: expected numeric value", *gargv);
+ rval = 1;
+ } else if (*ep != '\0') {
+ warnx("%s: not completely converted", *gargv);
+ rval = 1;
+ }
+ if (errno == ERANGE) {
+ warnx("%s: %s", *gargv, strerror(ERANGE));
+ rval = 1;
+ }
+ ++gargv;
+ return (rval);
+}
+
+static int
+asciicode(void)
+{
+ int ch;
+ wchar_t wch;
+ mbstate_t mbs;
+
+ ch = (unsigned char)**gargv;
+ if (ch == '\'' || ch == '"') {
+ memset(&mbs, 0, sizeof(mbs));
+ switch (mbrtowc(&wch, *gargv + 1, MB_LEN_MAX, &mbs)) {
+ case (size_t)-2:
+ case (size_t)-1:
+ wch = (unsigned char)gargv[0][1];
+ break;
+ case 0:
+ wch = 0;
+ break;
+ }
+ ch = wch;
+ }
+ ++gargv;
+ return (ch);
+}
+
+static void
+usage(void)
+{
+ (void)fprintf(stderr, "usage: printf format [arguments ...]\n");
+}
diff --git a/cmd/posix/sh/redir.c b/cmd/posix/sh/redir.c
@@ -0,0 +1,357 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <signal.h>
+#include <string.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+/*
+ * Code for dealing with input/output redirection.
+ */
+
+#include "shell.h"
+#include "nodes.h"
+#include "jobs.h"
+#include "expand.h"
+#include "redir.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "options.h"
+
+
+#define EMPTY -2 /* marks an unused slot in redirtab */
+#define CLOSED -1 /* fd was not open before redir */
+
+
+struct redirtab {
+ struct redirtab *next;
+ int renamed[10];
+ int fd0_redirected;
+ unsigned int empty_redirs;
+};
+
+
+static struct redirtab *redirlist;
+
+/*
+ * We keep track of whether or not fd0 has been redirected. This is for
+ * background commands, where we want to redirect fd0 to /dev/null only
+ * if it hasn't already been redirected.
+ */
+static int fd0_redirected = 0;
+
+/* Number of redirtabs that have not been allocated. */
+static unsigned int empty_redirs = 0;
+
+static void openredirect(union node *, char[10]);
+static int openhere(union node *);
+
+
+/*
+ * Process a list of redirection commands. If the REDIR_PUSH flag is set,
+ * old file descriptors are stashed away so that the redirection can be
+ * undone by calling popredir. If the REDIR_BACKQ flag is set, then the
+ * standard output, and the standard error if it becomes a duplicate of
+ * stdout, is saved in memory.
+ *
+ * We suppress interrupts so that we won't leave open file
+ * descriptors around. Because the signal handler remains
+ * installed and we do not use system call restart, interrupts
+ * will still abort blocking opens such as fifos (they will fail
+ * with EINTR). There is, however, a race condition if an interrupt
+ * arrives after INTOFF and before open blocks.
+ */
+
+void
+redirect(union node *redir, int flags)
+{
+ union node *n;
+ struct redirtab *sv = NULL;
+ int i;
+ int fd;
+ char memory[10]; /* file descriptors to write to memory */
+
+ INTOFF;
+ for (i = 10 ; --i >= 0 ; )
+ memory[i] = 0;
+ memory[1] = flags & REDIR_BACKQ;
+ if (flags & REDIR_PUSH) {
+ empty_redirs++;
+ if (redir != NULL) {
+ sv = ckmalloc(sizeof (struct redirtab));
+ for (i = 0 ; i < 10 ; i++)
+ sv->renamed[i] = EMPTY;
+ sv->fd0_redirected = fd0_redirected;
+ sv->empty_redirs = empty_redirs - 1;
+ sv->next = redirlist;
+ redirlist = sv;
+ empty_redirs = 0;
+ }
+ }
+ for (n = redir ; n ; n = n->nfile.next) {
+ fd = n->nfile.fd;
+ if (fd == 0)
+ fd0_redirected = 1;
+ if ((n->nfile.type == NTOFD || n->nfile.type == NFROMFD) &&
+ n->ndup.dupfd == fd)
+ continue; /* redirect from/to same file descriptor */
+
+ if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
+ INTOFF;
+ if ((i = fcntl(fd, F_DUPFD_CLOEXEC, 10)) == -1) {
+ switch (errno) {
+ case EBADF:
+ i = CLOSED;
+ break;
+ default:
+ INTON;
+ error("%d: %s", fd, strerror(errno));
+ break;
+ }
+ }
+ sv->renamed[fd] = i;
+ INTON;
+ }
+ openredirect(n, memory);
+ INTON;
+ INTOFF;
+ }
+ if (memory[1])
+ out1 = &memout;
+ if (memory[2])
+ out2 = &memout;
+ INTON;
+}
+
+
+static void
+openredirect(union node *redir, char memory[10])
+{
+ struct stat sb;
+ int fd = redir->nfile.fd;
+ const char *fname;
+ int f;
+ int e;
+
+ memory[fd] = 0;
+ switch (redir->nfile.type) {
+ case NFROM:
+ fname = redir->nfile.expfname;
+ if ((f = open(fname, O_RDONLY)) < 0)
+ error("cannot open %s: %s", fname, strerror(errno));
+ break;
+ case NFROMTO:
+ fname = redir->nfile.expfname;
+ if ((f = open(fname, O_RDWR|O_CREAT, 0666)) < 0)
+ error("cannot create %s: %s", fname, strerror(errno));
+ break;
+ case NTO:
+ if (Cflag) {
+ fname = redir->nfile.expfname;
+ if (stat(fname, &sb) == -1) {
+ if ((f = open(fname, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
+ error("cannot create %s: %s", fname, strerror(errno));
+ } else if (!S_ISREG(sb.st_mode)) {
+ if ((f = open(fname, O_WRONLY, 0666)) < 0)
+ error("cannot create %s: %s", fname, strerror(errno));
+ if (fstat(f, &sb) != -1 && S_ISREG(sb.st_mode)) {
+ close(f);
+ error("cannot create %s: %s", fname,
+ strerror(EEXIST));
+ }
+ } else
+ error("cannot create %s: %s", fname,
+ strerror(EEXIST));
+ break;
+ }
+ /* FALLTHROUGH */
+ case NCLOBBER:
+ fname = redir->nfile.expfname;
+ if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
+ error("cannot create %s: %s", fname, strerror(errno));
+ break;
+ case NAPPEND:
+ fname = redir->nfile.expfname;
+ if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
+ error("cannot create %s: %s", fname, strerror(errno));
+ break;
+ case NTOFD:
+ case NFROMFD:
+ if (redir->ndup.dupfd >= 0) { /* if not ">&-" */
+ if (memory[redir->ndup.dupfd])
+ memory[fd] = 1;
+ else {
+ if (dup2(redir->ndup.dupfd, fd) < 0)
+ error("%d: %s", redir->ndup.dupfd,
+ strerror(errno));
+ }
+ } else {
+ close(fd);
+ }
+ return;
+ case NHERE:
+ case NXHERE:
+ f = openhere(redir);
+ break;
+ default:
+ abort();
+ }
+ if (f != fd) {
+ if (dup2(f, fd) == -1) {
+ e = errno;
+ close(f);
+ error("%d: %s", fd, strerror(e));
+ }
+ close(f);
+ }
+}
+
+
+/*
+ * Handle here documents. Normally we fork off a process to write the
+ * data to a pipe. If the document is short, we can stuff the data in
+ * the pipe without forking.
+ */
+
+static int
+openhere(union node *redir)
+{
+ const char *p;
+ int pip[2];
+ size_t len = 0;
+ int flags;
+ ssize_t written = 0;
+
+ if (pipe(pip) < 0)
+ error("Pipe call failed: %s", strerror(errno));
+
+ if (redir->type == NXHERE)
+ p = redir->nhere.expdoc;
+ else
+ p = redir->nhere.doc->narg.text;
+ len = strlen(p);
+ if (len == 0)
+ goto out;
+ flags = fcntl(pip[1], F_GETFL, 0);
+ if (flags != -1 && fcntl(pip[1], F_SETFL, flags | O_NONBLOCK) != -1) {
+ written = write(pip[1], p, len);
+ if (written < 0)
+ written = 0;
+ if ((size_t)written == len)
+ goto out;
+ fcntl(pip[1], F_SETFL, flags);
+ }
+
+ if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
+ close(pip[0]);
+ signal(SIGINT, SIG_IGN);
+ signal(SIGQUIT, SIG_IGN);
+ signal(SIGHUP, SIG_IGN);
+ signal(SIGTSTP, SIG_IGN);
+ signal(SIGPIPE, SIG_DFL);
+ xwrite(pip[1], p + written, len - written);
+ _exit(0);
+ }
+out:
+ close(pip[1]);
+ return pip[0];
+}
+
+
+
+/*
+ * Undo the effects of the last redirection.
+ */
+
+void
+popredir(void)
+{
+ struct redirtab *rp = redirlist;
+ int i;
+
+ INTOFF;
+ if (empty_redirs > 0) {
+ empty_redirs--;
+ INTON;
+ return;
+ }
+ for (i = 0 ; i < 10 ; i++) {
+ if (rp->renamed[i] != EMPTY) {
+ if (rp->renamed[i] >= 0) {
+ dup2(rp->renamed[i], i);
+ close(rp->renamed[i]);
+ } else {
+ close(i);
+ }
+ }
+ }
+ fd0_redirected = rp->fd0_redirected;
+ empty_redirs = rp->empty_redirs;
+ redirlist = rp->next;
+ ckfree(rp);
+ INTON;
+}
+
+/* Return true if fd 0 has already been redirected at least once. */
+int
+fd0_redirected_p(void)
+{
+ return fd0_redirected != 0;
+}
+
+/*
+ * Discard all saved file descriptors.
+ */
+
+void
+clearredir(void)
+{
+ struct redirtab *rp;
+ int i;
+
+ for (rp = redirlist ; rp ; rp = rp->next) {
+ for (i = 0 ; i < 10 ; i++) {
+ if (rp->renamed[i] >= 0) {
+ close(rp->renamed[i]);
+ }
+ rp->renamed[i] = EMPTY;
+ }
+ }
+}
diff --git a/cmd/posix/sh/redir.h b/cmd/posix/sh/redir.h
@@ -0,0 +1,43 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* flags passed to redirect */
+#define REDIR_PUSH 01 /* save previous values of file descriptors */
+#define REDIR_BACKQ 02 /* save the command output in memory */
+
+union node;
+void redirect(union node *, int);
+void popredir(void);
+int fd0_redirected_p(void);
+void clearredir(void);
diff --git a/cmd/posix/sh/shell.h b/cmd/posix/sh/shell.h
@@ -0,0 +1,170 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef SHELL_H_
+#define SHELL_H_
+
+#if !defined(FEATURE_SH_HISTEDIT) || !FEATURE_SH_HISTEDIT
+#ifndef NO_HISTORY
+#define NO_HISTORY
+#endif
+#endif
+
+#include "sig.h"
+
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdint.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifndef tcsetsid
+#if defined(__linux__) || defined(__CYGWIN__)
+#define tcsetsid(fd, pid) ioctl((fd), TIOCSCTTY, 0)
+#endif
+#endif
+
+#ifndef ALIGN
+#define ALIGNBYTES (sizeof(void *) - 1)
+#define ALIGN(p) (((uintptr_t)(p) + ALIGNBYTES) & ~ALIGNBYTES)
+#endif
+
+#ifndef __dead2
+#define __dead2 __attribute__((__noreturn__))
+#endif
+#ifndef __unused
+#define __unused __attribute__((__unused__))
+#endif
+#ifndef __nonstring
+#if defined(__has_attribute)
+#if __has_attribute(__nonstring__)
+#define __nonstring __attribute__((__nonstring__))
+#elif __has_attribute(nonstring)
+#define __nonstring __attribute__((nonstring))
+#endif
+#endif
+#endif
+#ifndef __nonstring
+#define __nonstring
+#endif
+#ifndef __printf0like
+#define __printf0like(n, m) __attribute__((__format__(__printf__, n, m)))
+#endif
+#ifndef __printflike
+#define __printflike(n, m) __attribute__((__format__(__printf__, n, m)))
+#endif
+
+#ifndef O_VERIFY
+#define O_VERIFY 0
+#endif
+
+#ifndef CLOCK_UPTIME
+#define CLOCK_UPTIME CLOCK_MONOTONIC
+#endif
+
+#ifndef timespecsub
+#define timespecsub(a, b, result) \
+ do { \
+ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
+ (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
+ if ((result)->tv_nsec < 0) { \
+ --(result)->tv_sec; \
+ (result)->tv_nsec += 1000000000L; \
+ } \
+ } while (0)
+#endif
+
+#ifndef MAXLOGNAME
+#ifdef LOGIN_NAME_MAX
+#define MAXLOGNAME LOGIN_NAME_MAX
+#else
+#define MAXLOGNAME 32
+#endif
+#endif
+
+#ifndef __DECONST
+#define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
+#endif
+
+#ifndef eaccess
+#ifdef AT_EACCESS
+#define eaccess(path, mode) faccessat(AT_FDCWD, (path), (mode), AT_EACCESS)
+#else
+#define eaccess(path, mode) access((path), (mode))
+#endif
+#endif
+
+/*
+ * The follow should be set to reflect the type of system you have:
+ * JOBS -> 1 if you have Berkeley job control, 0 otherwise.
+ * define DEBUG=1 to compile in debugging (set global "debug" to turn on)
+ * define DEBUG=2 to compile in and turn on debugging.
+ *
+ * When debugging is on, debugging info will be written to ./trace and
+ * a quit signal will generate a core dump.
+ */
+
+
+#define JOBS 1
+/* #define DEBUG 1 */
+
+/*
+ * Type of used arithmetic. SUSv3 requires us to have at least signed long.
+ */
+typedef intmax_t arith_t;
+#define ARITH_FORMAT_STR "%" PRIdMAX
+#define ARITH_MIN INTMAX_MIN
+#define ARITH_MAX INTMAX_MAX
+
+typedef void *pointer;
+
+#if defined(__has_include)
+#if __has_include(<sys/cdefs.h>)
+#include <sys/cdefs.h>
+#endif
+#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
+#include <sys/cdefs.h>
+#endif
+
+extern char nullstr[1]; /* null string */
+
+#ifdef DEBUG
+#define TRACE(param) sh_trace param
+#else
+#define TRACE(param)
+#endif
+
+#endif /* !SHELL_H_ */
diff --git a/cmd/posix/sh/show.c b/cmd/posix/sh/show.c
@@ -0,0 +1,401 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <errno.h>
+
+#include "shell.h"
+#include "parser.h"
+#include "nodes.h"
+#include "mystring.h"
+#include "show.h"
+
+
+#ifdef DEBUG
+static void shtree(union node *, int, char *, FILE*);
+static void shcmd(union node *, FILE *);
+static void sharg(union node *, FILE *);
+static void indent(int, char *, FILE *);
+static void trstring(char *);
+
+
+void
+showtree(union node *n)
+{
+ trputs("showtree called\n");
+ shtree(n, 1, NULL, stdout);
+}
+
+
+static void
+shtree(union node *n, int ind, char *pfx, FILE *fp)
+{
+ struct nodelist *lp;
+ const char *s;
+
+ if (n == NULL)
+ return;
+
+ indent(ind, pfx, fp);
+ switch(n->type) {
+ case NSEMI:
+ s = "; ";
+ goto binop;
+ case NAND:
+ s = " && ";
+ goto binop;
+ case NOR:
+ s = " || ";
+ binop:
+ shtree(n->nbinary.ch1, ind, NULL, fp);
+ /* if (ind < 0) */
+ fputs(s, fp);
+ shtree(n->nbinary.ch2, ind, NULL, fp);
+ break;
+ case NCMD:
+ shcmd(n, fp);
+ if (ind >= 0)
+ putc('\n', fp);
+ break;
+ case NPIPE:
+ for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
+ shcmd(lp->n, fp);
+ if (lp->next)
+ fputs(" | ", fp);
+ }
+ if (n->npipe.backgnd)
+ fputs(" &", fp);
+ if (ind >= 0)
+ putc('\n', fp);
+ break;
+ default:
+ fprintf(fp, "<node type %d>", n->type);
+ if (ind >= 0)
+ putc('\n', fp);
+ break;
+ }
+}
+
+
+
+static void
+shcmd(union node *cmd, FILE *fp)
+{
+ union node *np;
+ int first;
+ const char *s;
+ int dftfd;
+
+ first = 1;
+ for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
+ if (! first)
+ putchar(' ');
+ sharg(np, fp);
+ first = 0;
+ }
+ for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
+ if (! first)
+ putchar(' ');
+ switch (np->nfile.type) {
+ case NTO: s = ">"; dftfd = 1; break;
+ case NAPPEND: s = ">>"; dftfd = 1; break;
+ case NTOFD: s = ">&"; dftfd = 1; break;
+ case NCLOBBER: s = ">|"; dftfd = 1; break;
+ case NFROM: s = "<"; dftfd = 0; break;
+ case NFROMTO: s = "<>"; dftfd = 0; break;
+ case NFROMFD: s = "<&"; dftfd = 0; break;
+ case NHERE: s = "<<"; dftfd = 0; break;
+ case NXHERE: s = "<<"; dftfd = 0; break;
+ default: s = "*error*"; dftfd = 0; break;
+ }
+ if (np->nfile.fd != dftfd)
+ fprintf(fp, "%d", np->nfile.fd);
+ fputs(s, fp);
+ if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
+ if (np->ndup.dupfd >= 0)
+ fprintf(fp, "%d", np->ndup.dupfd);
+ else
+ fprintf(fp, "-");
+ } else if (np->nfile.type == NHERE) {
+ fprintf(fp, "HERE");
+ } else if (np->nfile.type == NXHERE) {
+ fprintf(fp, "XHERE");
+ } else {
+ sharg(np->nfile.fname, fp);
+ }
+ first = 0;
+ }
+}
+
+
+
+static void
+sharg(union node *arg, FILE *fp)
+{
+ char *p;
+ struct nodelist *bqlist;
+ int subtype;
+
+ if (arg->type != NARG) {
+ printf("<node type %d>\n", arg->type);
+ fflush(stdout);
+ abort();
+ }
+ bqlist = arg->narg.backquote;
+ for (p = arg->narg.text ; *p ; p++) {
+ switch (*p) {
+ case CTLESC:
+ putc(*++p, fp);
+ break;
+ case CTLVAR:
+ putc('$', fp);
+ putc('{', fp);
+ subtype = *++p;
+ if (subtype == VSLENGTH)
+ putc('#', fp);
+
+ while (*p != '=')
+ putc(*p++, fp);
+
+ if (subtype & VSNUL)
+ putc(':', fp);
+
+ switch (subtype & VSTYPE) {
+ case VSNORMAL:
+ putc('}', fp);
+ break;
+ case VSMINUS:
+ putc('-', fp);
+ break;
+ case VSPLUS:
+ putc('+', fp);
+ break;
+ case VSQUESTION:
+ putc('?', fp);
+ break;
+ case VSASSIGN:
+ putc('=', fp);
+ break;
+ case VSTRIMLEFT:
+ putc('#', fp);
+ break;
+ case VSTRIMLEFTMAX:
+ putc('#', fp);
+ putc('#', fp);
+ break;
+ case VSTRIMRIGHT:
+ putc('%', fp);
+ break;
+ case VSTRIMRIGHTMAX:
+ putc('%', fp);
+ putc('%', fp);
+ break;
+ case VSLENGTH:
+ break;
+ default:
+ printf("<subtype %d>", subtype);
+ }
+ break;
+ case CTLENDVAR:
+ putc('}', fp);
+ break;
+ case CTLBACKQ:
+ case CTLBACKQ|CTLQUOTE:
+ putc('$', fp);
+ putc('(', fp);
+ shtree(bqlist->n, -1, NULL, fp);
+ putc(')', fp);
+ break;
+ default:
+ putc(*p, fp);
+ break;
+ }
+ }
+}
+
+
+static void
+indent(int amount, char *pfx, FILE *fp)
+{
+ int i;
+
+ for (i = 0 ; i < amount ; i++) {
+ if (pfx && i == amount - 1)
+ fputs(pfx, fp);
+ putc('\t', fp);
+ }
+}
+
+
+/*
+ * Debugging stuff.
+ */
+
+
+static FILE *tracefile;
+#if DEBUG >= 2
+int debug = 1;
+#else
+int debug = 0;
+#endif
+
+
+void
+trputc(int c)
+{
+ if (tracefile == NULL)
+ return;
+ putc(c, tracefile);
+ if (c == '\n')
+ fflush(tracefile);
+}
+
+
+void
+sh_trace(const char *fmt, ...)
+{
+ va_list va;
+ va_start(va, fmt);
+ if (tracefile != NULL) {
+ (void) vfprintf(tracefile, fmt, va);
+ if (strchr(fmt, '\n'))
+ (void) fflush(tracefile);
+ }
+ va_end(va);
+}
+
+
+void
+trputs(const char *s)
+{
+ if (tracefile == NULL)
+ return;
+ fputs(s, tracefile);
+ if (strchr(s, '\n'))
+ fflush(tracefile);
+}
+
+
+static void
+trstring(char *s)
+{
+ char *p;
+ char c;
+
+ if (tracefile == NULL)
+ return;
+ putc('"', tracefile);
+ for (p = s ; *p ; p++) {
+ switch (*p) {
+ case '\n': c = 'n'; goto backslash;
+ case '\t': c = 't'; goto backslash;
+ case '\r': c = 'r'; goto backslash;
+ case '"': c = '"'; goto backslash;
+ case '\\': c = '\\'; goto backslash;
+ case CTLESC: c = 'e'; goto backslash;
+ case CTLVAR: c = 'v'; goto backslash;
+ case CTLVAR+CTLQUOTE: c = 'V'; goto backslash;
+ case CTLBACKQ: c = 'q'; goto backslash;
+ case CTLBACKQ+CTLQUOTE: c = 'Q'; goto backslash;
+backslash: putc('\\', tracefile);
+ putc(c, tracefile);
+ break;
+ default:
+ if (*p >= ' ' && *p <= '~')
+ putc(*p, tracefile);
+ else {
+ putc('\\', tracefile);
+ putc(*p >> 6 & 03, tracefile);
+ putc(*p >> 3 & 07, tracefile);
+ putc(*p & 07, tracefile);
+ }
+ break;
+ }
+ }
+ putc('"', tracefile);
+}
+
+
+void
+trargs(char **ap)
+{
+ if (tracefile == NULL)
+ return;
+ while (*ap) {
+ trstring(*ap++);
+ if (*ap)
+ putc(' ', tracefile);
+ else
+ putc('\n', tracefile);
+ }
+ fflush(tracefile);
+}
+
+
+void
+opentrace(void)
+{
+ char s[100];
+ int flags;
+
+ if (!debug)
+ return;
+#ifdef not_this_way
+ {
+ char *p;
+ if ((p = getenv("HOME")) == NULL) {
+ if (geteuid() == 0)
+ p = "/";
+ else
+ p = "/tmp";
+ }
+ strcpy(s, p);
+ strcat(s, "/trace");
+ }
+#else
+ strcpy(s, "./trace");
+#endif /* not_this_way */
+ if ((tracefile = fopen(s, "a")) == NULL) {
+ fprintf(stderr, "Can't open %s: %s\n", s, strerror(errno));
+ return;
+ }
+ if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
+ fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
+ fputs("\nTracing started.\n", tracefile);
+ fflush(tracefile);
+}
+#endif /* DEBUG */
diff --git a/cmd/posix/sh/show.h b/cmd/posix/sh/show.h
@@ -0,0 +1,41 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1995
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+void showtree(union node *);
+#ifdef DEBUG
+void sh_trace(const char *, ...) __printflike(1, 2);
+void trargs(char **);
+void trputc(int);
+void trputs(const char *);
+void opentrace(void);
+
+extern int debug;
+#endif
diff --git a/cmd/posix/sh/test.c b/cmd/posix/sh/test.c
@@ -0,0 +1,652 @@
+/* $NetBSD: test.c,v 1.21 1999/04/05 09:48:38 kleink Exp $ */
+
+/*-
+ * test(1); version 7-like -- author Erik Baalbergen
+ * modified by Eric Gisin to be used as built-in.
+ * modified by Arnold Robbins to add SVR3 compatibility
+ * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket).
+ * modified by J.T. Conklin for NetBSD.
+ *
+ * This program is in the Public Domain.
+ */
+/*
+ * Important: This file is used both as a standalone program /bin/test and
+ * as a builtin for /bin/sh (#define SHELL).
+ */
+
+#ifndef SHELL
+#ifndef __dead2
+#define __dead2 __attribute__((__noreturn__))
+#endif
+#ifndef __printf0like
+#define __printf0like(n, m) __attribute__((__format__(__printf__, n, m)))
+#endif
+#ifndef __nonstring
+#if defined(__has_attribute)
+#if __has_attribute(__nonstring__)
+#define __nonstring __attribute__((__nonstring__))
+#elif __has_attribute(nonstring)
+#define __nonstring __attribute__((nonstring))
+#endif
+#endif
+#endif
+#ifndef __nonstring
+#define __nonstring
+#endif
+#ifndef eaccess
+#ifdef AT_EACCESS
+#define eaccess(path, mode) faccessat(AT_FDCWD, (path), (mode), AT_EACCESS)
+#else
+#define eaccess(path, mode) access((path), (mode))
+#endif
+#endif
+#endif
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <ctype.h>
+#include <err.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#ifdef SHELL
+#define main testcmd
+#include "bltin.h"
+#else
+#include <locale.h>
+
+static void error(const char *, ...) __dead2 __printf0like(1, 2);
+
+static void
+error(const char *msg, ...)
+{
+ va_list ap;
+ va_start(ap, msg);
+ verrx(2, msg, ap);
+ /*NOTREACHED*/
+ va_end(ap);
+}
+#endif
+
+/* test(1) accepts the following grammar:
+ oexpr ::= aexpr | aexpr "-o" oexpr ;
+ aexpr ::= nexpr | nexpr "-a" aexpr ;
+ nexpr ::= primary | "!" primary
+ primary ::= unary-operator operand
+ | operand binary-operator operand
+ | operand
+ | "(" oexpr ")"
+ ;
+ unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"|
+ "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S";
+
+ binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"|
+ "-nt"|"-ot"|"-ef";
+ operand ::= <any legal UNIX file name>
+*/
+
+enum token_types {
+ UNOP = 0x100,
+ BINOP = 0x200,
+ BUNOP = 0x300,
+ BBINOP = 0x400,
+ PAREN = 0x500
+};
+
+enum token {
+ EOI,
+ OPERAND,
+ FILRD = UNOP + 1,
+ FILWR,
+ FILEX,
+ FILEXIST,
+ FILREG,
+ FILDIR,
+ FILCDEV,
+ FILBDEV,
+ FILFIFO,
+ FILSOCK,
+ FILSYM,
+ FILGZ,
+ FILTT,
+ FILSUID,
+ FILSGID,
+ FILSTCK,
+ STREZ,
+ STRNZ,
+ FILUID,
+ FILGID,
+ FILNT = BINOP + 1,
+ FILOT,
+ FILEQ,
+ STREQ,
+ STRNE,
+ STRLT,
+ STRGT,
+ INTEQ,
+ INTNE,
+ INTGE,
+ INTGT,
+ INTLE,
+ INTLT,
+ UNOT = BUNOP + 1,
+ BAND = BBINOP + 1,
+ BOR,
+ LPAREN = PAREN + 1,
+ RPAREN
+};
+
+#define TOKEN_TYPE(token) ((token) & 0xff00)
+
+static const struct t_op {
+ char op_text[2] __nonstring;
+ short op_num;
+} ops1[] = {
+ {"=", STREQ},
+ {"<", STRLT},
+ {">", STRGT},
+ {"!", UNOT},
+ {"(", LPAREN},
+ {")", RPAREN},
+}, opsm1[] = {
+ {"r", FILRD},
+ {"w", FILWR},
+ {"x", FILEX},
+ {"e", FILEXIST},
+ {"f", FILREG},
+ {"d", FILDIR},
+ {"c", FILCDEV},
+ {"b", FILBDEV},
+ {"p", FILFIFO},
+ {"u", FILSUID},
+ {"g", FILSGID},
+ {"k", FILSTCK},
+ {"s", FILGZ},
+ {"t", FILTT},
+ {"z", STREZ},
+ {"n", STRNZ},
+ {"h", FILSYM}, /* for backwards compat */
+ {"O", FILUID},
+ {"G", FILGID},
+ {"L", FILSYM},
+ {"S", FILSOCK},
+ {"a", BAND},
+ {"o", BOR},
+}, ops2[] = {
+ {"==", STREQ},
+ {"!=", STRNE},
+}, opsm2[] = {
+ {"eq", INTEQ},
+ {"ne", INTNE},
+ {"ge", INTGE},
+ {"gt", INTGT},
+ {"le", INTLE},
+ {"lt", INTLT},
+ {"nt", FILNT},
+ {"ot", FILOT},
+ {"ef", FILEQ},
+};
+
+static int nargc;
+static char **t_wp;
+static int parenlevel;
+
+static int aexpr(enum token);
+static int binop(enum token);
+static int equalf(const char *, const char *);
+static int filstat(char *, enum token);
+static int getn(const char *);
+static intmax_t getq(const char *);
+static int intcmp(const char *, const char *);
+static int isunopoperand(void);
+static int islparenoperand(void);
+static int isrparenoperand(void);
+static int newerf(const char *, const char *);
+static int nexpr(enum token);
+static int oexpr(enum token);
+static int olderf(const char *, const char *);
+static int primary(enum token);
+static void syntax(const char *, const char *);
+static enum token t_lex(char *);
+
+int
+main(int argc, char **argv)
+{
+ int res;
+ char *p;
+
+ if ((p = strrchr(argv[0], '/')) == NULL)
+ p = argv[0];
+ else
+ p++;
+ if (strcmp(p, "[") == 0) {
+ if (strcmp(argv[--argc], "]") != 0)
+ error("missing ']'");
+ argv[argc] = NULL;
+ }
+
+ /* no expression => false */
+ if (--argc <= 0)
+ return 1;
+
+#ifndef SHELL
+ (void)setlocale(LC_CTYPE, "");
+#endif
+ nargc = argc;
+ t_wp = &argv[1];
+ parenlevel = 0;
+ if (nargc == 4 && strcmp(*t_wp, "!") == 0) {
+ /* Things like ! "" -o x do not fit in the normal grammar. */
+ --nargc;
+ ++t_wp;
+ res = oexpr(t_lex(*t_wp));
+ } else
+ res = !oexpr(t_lex(*t_wp));
+
+ if (--nargc > 0)
+ syntax(*t_wp, "unexpected operator");
+
+ return res;
+}
+
+static void
+syntax(const char *op, const char *msg)
+{
+
+ if (op && *op)
+ error("%s: %s", op, msg);
+ else
+ error("%s", msg);
+}
+
+static int
+oexpr(enum token n)
+{
+ int res;
+
+ res = aexpr(n);
+ if (t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL) == BOR)
+ return oexpr(t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL)) ||
+ res;
+ t_wp--;
+ nargc++;
+ return res;
+}
+
+static int
+aexpr(enum token n)
+{
+ int res;
+
+ res = nexpr(n);
+ if (t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL) == BAND)
+ return aexpr(t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL)) &&
+ res;
+ t_wp--;
+ nargc++;
+ return res;
+}
+
+static int
+nexpr(enum token n)
+{
+ if (n == UNOT)
+ return !nexpr(t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL));
+ return primary(n);
+}
+
+static int
+primary(enum token n)
+{
+ enum token nn;
+ int res;
+
+ if (n == EOI)
+ return 0; /* missing expression */
+ if (n == LPAREN) {
+ parenlevel++;
+ if ((nn = t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL)) ==
+ RPAREN) {
+ parenlevel--;
+ return 0; /* missing expression */
+ }
+ res = oexpr(nn);
+ if (t_lex(nargc > 0 ? (--nargc, *++t_wp) : NULL) != RPAREN)
+ syntax(NULL, "closing paren expected");
+ parenlevel--;
+ return res;
+ }
+ if (TOKEN_TYPE(n) == UNOP) {
+ /* unary expression */
+ if (--nargc == 0)
+ syntax(NULL, "argument expected"); /* impossible */
+ switch (n) {
+ case STREZ:
+ return strlen(*++t_wp) == 0;
+ case STRNZ:
+ return strlen(*++t_wp) != 0;
+ case FILTT:
+ return isatty(getn(*++t_wp));
+ default:
+ return filstat(*++t_wp, n);
+ }
+ }
+
+ nn = t_lex(nargc > 0 ? t_wp[1] : NULL);
+ if (TOKEN_TYPE(nn) == BINOP)
+ return binop(nn);
+
+ return strlen(*t_wp) > 0;
+}
+
+static int
+binop(enum token n)
+{
+ const char *opnd1, *op, *opnd2;
+
+ opnd1 = *t_wp;
+ op = nargc > 0 ? (--nargc, *++t_wp) : NULL;
+
+ if ((opnd2 = nargc > 0 ? (--nargc, *++t_wp) : NULL) == NULL)
+ syntax(op, "argument expected");
+
+ switch (n) {
+ case STREQ:
+ return strcmp(opnd1, opnd2) == 0;
+ case STRNE:
+ return strcmp(opnd1, opnd2) != 0;
+ case STRLT:
+ return strcmp(opnd1, opnd2) < 0;
+ case STRGT:
+ return strcmp(opnd1, opnd2) > 0;
+ case INTEQ:
+ return intcmp(opnd1, opnd2) == 0;
+ case INTNE:
+ return intcmp(opnd1, opnd2) != 0;
+ case INTGE:
+ return intcmp(opnd1, opnd2) >= 0;
+ case INTGT:
+ return intcmp(opnd1, opnd2) > 0;
+ case INTLE:
+ return intcmp(opnd1, opnd2) <= 0;
+ case INTLT:
+ return intcmp(opnd1, opnd2) < 0;
+ case FILNT:
+ return newerf (opnd1, opnd2);
+ case FILOT:
+ return olderf (opnd1, opnd2);
+ case FILEQ:
+ return equalf (opnd1, opnd2);
+ default:
+ abort();
+ /* NOTREACHED */
+ }
+}
+
+static int
+filstat(char *nm, enum token mode)
+{
+ struct stat s;
+
+ if (mode == FILSYM ? lstat(nm, &s) : stat(nm, &s))
+ return 0;
+
+ switch (mode) {
+ case FILRD:
+ return (eaccess(nm, R_OK) == 0);
+ case FILWR:
+ return (eaccess(nm, W_OK) == 0);
+ case FILEX:
+ /* XXX work around eaccess(2) false positives for superuser */
+ if (eaccess(nm, X_OK) != 0)
+ return 0;
+ if (S_ISDIR(s.st_mode) || geteuid() != 0)
+ return 1;
+ return (s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0;
+ case FILEXIST:
+ return (eaccess(nm, F_OK) == 0);
+ case FILREG:
+ return S_ISREG(s.st_mode);
+ case FILDIR:
+ return S_ISDIR(s.st_mode);
+ case FILCDEV:
+ return S_ISCHR(s.st_mode);
+ case FILBDEV:
+ return S_ISBLK(s.st_mode);
+ case FILFIFO:
+ return S_ISFIFO(s.st_mode);
+ case FILSOCK:
+ return S_ISSOCK(s.st_mode);
+ case FILSYM:
+ return S_ISLNK(s.st_mode);
+ case FILSUID:
+ return (s.st_mode & S_ISUID) != 0;
+ case FILSGID:
+ return (s.st_mode & S_ISGID) != 0;
+ case FILSTCK:
+ return (s.st_mode & S_ISVTX) != 0;
+ case FILGZ:
+ return s.st_size > (off_t)0;
+ case FILUID:
+ return s.st_uid == geteuid();
+ case FILGID:
+ return s.st_gid == getegid();
+ default:
+ return 1;
+ }
+}
+
+static int
+find_op_1char(const struct t_op *op, const struct t_op *end, const char *s)
+{
+ char c;
+
+ c = s[0];
+ while (op != end) {
+ if (c == *op->op_text)
+ return op->op_num;
+ op++;
+ }
+ return OPERAND;
+}
+
+static int
+find_op_2char(const struct t_op *op, const struct t_op *end, const char *s)
+{
+ while (op != end) {
+ if (s[0] == op->op_text[0] && s[1] == op->op_text[1])
+ return op->op_num;
+ op++;
+ }
+ return OPERAND;
+}
+
+static int
+find_op(const char *s)
+{
+ if (s[0] == '\0')
+ return OPERAND;
+ else if (s[1] == '\0')
+ return find_op_1char(ops1, (&ops1)[1], s);
+ else if (s[2] == '\0')
+ return s[0] == '-' ? find_op_1char(opsm1, (&opsm1)[1], s + 1) :
+ find_op_2char(ops2, (&ops2)[1], s);
+ else if (s[3] == '\0')
+ return s[0] == '-' ? find_op_2char(opsm2, (&opsm2)[1], s + 1) :
+ OPERAND;
+ else
+ return OPERAND;
+}
+
+static enum token
+t_lex(char *s)
+{
+ int num;
+
+ if (s == NULL) {
+ return EOI;
+ }
+ num = find_op(s);
+ if (((TOKEN_TYPE(num) == UNOP || TOKEN_TYPE(num) == BUNOP)
+ && isunopoperand()) ||
+ (num == LPAREN && islparenoperand()) ||
+ (num == RPAREN && isrparenoperand()))
+ return OPERAND;
+ return num;
+}
+
+static int
+isunopoperand(void)
+{
+ char *s;
+ char *t;
+ int num;
+
+ if (nargc == 1)
+ return 1;
+ s = *(t_wp + 1);
+ if (nargc == 2)
+ return parenlevel == 1 && strcmp(s, ")") == 0;
+ t = *(t_wp + 2);
+ num = find_op(s);
+ return TOKEN_TYPE(num) == BINOP &&
+ (parenlevel == 0 || t[0] != ')' || t[1] != '\0');
+}
+
+static int
+islparenoperand(void)
+{
+ char *s;
+ int num;
+
+ if (nargc == 1)
+ return 1;
+ s = *(t_wp + 1);
+ if (nargc == 2)
+ return parenlevel == 1 && strcmp(s, ")") == 0;
+ if (nargc != 3)
+ return 0;
+ num = find_op(s);
+ return TOKEN_TYPE(num) == BINOP;
+}
+
+static int
+isrparenoperand(void)
+{
+ char *s;
+
+ if (nargc == 1)
+ return 0;
+ s = *(t_wp + 1);
+ if (nargc == 2)
+ return parenlevel == 1 && strcmp(s, ")") == 0;
+ return 0;
+}
+
+/* atoi with error detection */
+static int
+getn(const char *s)
+{
+ char *p;
+ long r;
+
+ errno = 0;
+ r = strtol(s, &p, 10);
+
+ if (s == p)
+ error("%s: bad number", s);
+
+ if (errno != 0)
+ error((errno == EINVAL) ? "%s: bad number" :
+ "%s: out of range", s);
+
+ while (isspace((unsigned char)*p))
+ p++;
+
+ if (*p)
+ error("%s: bad number", s);
+
+ return (int) r;
+}
+
+/* atoi with error detection and 64 bit range */
+static intmax_t
+getq(const char *s)
+{
+ char *p;
+ intmax_t r;
+
+ errno = 0;
+ r = strtoimax(s, &p, 10);
+
+ if (s == p)
+ error("%s: bad number", s);
+
+ if (errno != 0)
+ error((errno == EINVAL) ? "%s: bad number" :
+ "%s: out of range", s);
+
+ while (isspace((unsigned char)*p))
+ p++;
+
+ if (*p)
+ error("%s: bad number", s);
+
+ return r;
+}
+
+static int
+intcmp (const char *s1, const char *s2)
+{
+ intmax_t q1, q2;
+
+
+ q1 = getq(s1);
+ q2 = getq(s2);
+
+ if (q1 > q2)
+ return 1;
+
+ if (q1 < q2)
+ return -1;
+
+ return 0;
+}
+
+static int
+newerf (const char *f1, const char *f2)
+{
+ struct stat b1, b2;
+
+ if (stat(f1, &b1) != 0 || stat(f2, &b2) != 0)
+ return 0;
+
+ if (b1.st_mtim.tv_sec > b2.st_mtim.tv_sec)
+ return 1;
+ if (b1.st_mtim.tv_sec < b2.st_mtim.tv_sec)
+ return 0;
+
+ return (b1.st_mtim.tv_nsec > b2.st_mtim.tv_nsec);
+}
+
+static int
+olderf (const char *f1, const char *f2)
+{
+ return (newerf(f2, f1));
+}
+
+static int
+equalf (const char *f1, const char *f2)
+{
+ struct stat b1, b2;
+
+ return (stat (f1, &b1) == 0 &&
+ stat (f2, &b2) == 0 &&
+ b1.st_dev == b2.st_dev &&
+ b1.st_ino == b2.st_ino);
+}
diff --git a/cmd/posix/sh/trap.c b/cmd/posix/sh/trap.c
@@ -0,0 +1,546 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "shell.h"
+#include "main.h"
+#include "nodes.h" /* for other headers */
+#include "eval.h"
+#include "jobs.h"
+#include "show.h"
+#include "options.h"
+#include "syntax.h"
+#include "output.h"
+#include "memalloc.h"
+#include "error.h"
+#include "trap.h"
+#include "mystring.h"
+#include "builtins.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+#include <signal.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+/*
+ * Sigmode records the current value of the signal handlers for the various
+ * modes. A value of zero means that the current handler is not known.
+ * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
+ */
+
+#define S_DFL 1 /* default signal handling (SIG_DFL) */
+#define S_CATCH 2 /* signal is caught */
+#define S_IGN 3 /* signal is ignored (SIG_IGN) */
+#define S_HARD_IGN 4 /* signal is ignored permanently */
+#define S_RESET 5 /* temporary - to reset a hard ignored sig */
+
+
+static char sigmode[NSIG]; /* current value of signal */
+volatile sig_atomic_t pendingsig; /* indicates some signal received */
+volatile sig_atomic_t pendingsig_waitcmd; /* indicates wait builtin should be interrupted */
+static int in_dotrap; /* do we execute in a trap handler? */
+static char *volatile trap[NSIG]; /* trap handler commands */
+static volatile sig_atomic_t gotsig[NSIG];
+ /* indicates specified signal received */
+static int ignore_sigchld; /* Used while handling SIGCHLD traps. */
+static int last_trapsig;
+
+static int exiting; /* exitshell() has been called */
+static int exiting_exitstatus; /* value passed to exitshell() */
+
+static int getsigaction(int, sig_t *);
+
+
+/*
+ * Map a string to a signal number.
+ *
+ * Note: the signal number may exceed NSIG.
+ */
+static int
+sigstring_to_signum(char *sig)
+{
+
+ if (is_number(sig)) {
+ int signo;
+
+ signo = atoi(sig);
+ return ((signo >= 0 && signo < NSIG) ? signo : (-1));
+ } else if (strcasecmp(sig, "EXIT") == 0) {
+ return (0);
+ } else {
+ int n;
+
+ if (strncasecmp(sig, "SIG", 3) == 0)
+ sig += 3;
+ for (n = 1; n < sys_nsig; n++)
+ if (sys_signame[n] &&
+ strcasecmp(sys_signame[n], sig) == 0)
+ return (n);
+ }
+ return (-1);
+}
+
+
+/*
+ * Print a list of valid signal names.
+ */
+static void
+printsignals(void)
+{
+ int n, outlen;
+
+ outlen = 0;
+ for (n = 1; n < sys_nsig; n++) {
+ if (sys_signame[n]) {
+ out1fmt("%s", sys_signame[n]);
+ outlen += strlen(sys_signame[n]);
+ } else {
+ out1fmt("%d", n);
+ outlen += 3; /* good enough */
+ }
+ ++outlen;
+ if (outlen > 71 || n == sys_nsig - 1) {
+ out1str("\n");
+ outlen = 0;
+ } else {
+ out1c(' ');
+ }
+ }
+}
+
+
+/*
+ * The trap builtin.
+ */
+int
+trapcmd(int argc __unused, char **argv)
+{
+ char *action;
+ int signo;
+ int errors = 0;
+ int i;
+
+ while ((i = nextopt("l")) != '\0') {
+ switch (i) {
+ case 'l':
+ printsignals();
+ return (0);
+ }
+ }
+ argv = argptr;
+
+ if (*argv == NULL) {
+ for (signo = 0 ; signo < sys_nsig ; signo++) {
+ if (signo < NSIG && trap[signo] != NULL) {
+ out1str("trap -- ");
+ out1qstr(trap[signo]);
+ if (signo == 0) {
+ out1str(" EXIT\n");
+ } else if (sys_signame[signo]) {
+ out1fmt(" %s\n", sys_signame[signo]);
+ } else {
+ out1fmt(" %d\n", signo);
+ }
+ }
+ }
+ return 0;
+ }
+ action = NULL;
+ if (*argv && !is_number(*argv)) {
+ if (strcmp(*argv, "-") == 0)
+ argv++;
+ else {
+ action = *argv;
+ argv++;
+ }
+ }
+ for (; *argv; argv++) {
+ if ((signo = sigstring_to_signum(*argv)) == -1) {
+ warning("bad signal %s", *argv);
+ errors = 1;
+ continue;
+ }
+ INTOFF;
+ if (action)
+ action = savestr(action);
+ if (trap[signo])
+ ckfree(trap[signo]);
+ trap[signo] = action;
+ if (signo != 0)
+ setsignal(signo);
+ INTON;
+ }
+ return errors;
+}
+
+
+/*
+ * Clear traps on a fork.
+ */
+void
+clear_traps(void)
+{
+ char *volatile *tp;
+
+ for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
+ if (*tp && **tp) { /* trap not NULL or SIG_IGN */
+ INTOFF;
+ ckfree(*tp);
+ *tp = NULL;
+ if (tp != &trap[0])
+ setsignal(tp - trap);
+ INTON;
+ }
+ }
+}
+
+
+/*
+ * Check if we have any traps enabled.
+ */
+int
+have_traps(void)
+{
+ char *volatile *tp;
+
+ for (tp = trap ; tp <= &trap[NSIG - 1] ; tp++) {
+ if (*tp && **tp) /* trap not NULL or SIG_IGN */
+ return 1;
+ }
+ return 0;
+}
+
+/*
+ * Set the signal handler for the specified signal. The routine figures
+ * out what it should be set to.
+ */
+void
+setsignal(int signo)
+{
+ int action;
+ sig_t sigact = SIG_DFL;
+ struct sigaction sa;
+ char *t;
+
+ if ((t = trap[signo]) == NULL)
+ action = S_DFL;
+ else if (*t != '\0')
+ action = S_CATCH;
+ else
+ action = S_IGN;
+ if (action == S_DFL) {
+ switch (signo) {
+ case SIGINT:
+ action = S_CATCH;
+ break;
+ case SIGQUIT:
+#ifdef DEBUG
+ if (debug)
+ break;
+#endif
+ action = S_CATCH;
+ break;
+ case SIGTERM:
+ if (rootshell && iflag)
+ action = S_IGN;
+ break;
+#if JOBS
+ case SIGTSTP:
+ case SIGTTOU:
+ if (rootshell && mflag)
+ action = S_IGN;
+ break;
+#endif
+ }
+ }
+
+ t = &sigmode[signo];
+ if (*t == 0) {
+ /*
+ * current setting unknown
+ */
+ if (!getsigaction(signo, &sigact)) {
+ /*
+ * Pretend it worked; maybe we should give a warning
+ * here, but other shells don't. We don't alter
+ * sigmode, so that we retry every time.
+ */
+ return;
+ }
+ if (sigact == SIG_IGN) {
+ if (mflag && (signo == SIGTSTP ||
+ signo == SIGTTIN || signo == SIGTTOU)) {
+ *t = S_IGN; /* don't hard ignore these */
+ } else
+ *t = S_HARD_IGN;
+ } else {
+ *t = S_RESET; /* force to be set */
+ }
+ }
+ if (*t == S_HARD_IGN || *t == action)
+ return;
+ switch (action) {
+ case S_DFL: sigact = SIG_DFL; break;
+ case S_CATCH: sigact = onsig; break;
+ case S_IGN: sigact = SIG_IGN; break;
+ }
+ *t = action;
+ sa.sa_handler = sigact;
+ sa.sa_flags = 0;
+ sigemptyset(&sa.sa_mask);
+ sigaction(signo, &sa, NULL);
+}
+
+
+/*
+ * Return the current setting for sig w/o changing it.
+ */
+static int
+getsigaction(int signo, sig_t *sigact)
+{
+ struct sigaction sa;
+
+ if (sigaction(signo, (struct sigaction *)0, &sa) == -1)
+ return 0;
+ *sigact = (sig_t) sa.sa_handler;
+ return 1;
+}
+
+
+/*
+ * Ignore a signal.
+ */
+void
+ignoresig(int signo)
+{
+
+ if (sigmode[signo] == 0)
+ setsignal(signo);
+ if (sigmode[signo] != S_IGN && sigmode[signo] != S_HARD_IGN) {
+ signal(signo, SIG_IGN);
+ sigmode[signo] = S_IGN;
+ }
+}
+
+
+int
+issigchldtrapped(void)
+{
+
+ return (trap[SIGCHLD] != NULL && *trap[SIGCHLD] != '\0');
+}
+
+
+/*
+ * Signal handler.
+ */
+void
+onsig(int signo)
+{
+
+ if (signo == SIGINT && trap[SIGINT] == NULL) {
+ if (suppressint)
+ SET_PENDING_INT;
+ else
+ onint();
+ return;
+ }
+
+ /* If we are currently in a wait builtin, prepare to break it */
+ if (signo == SIGINT || signo == SIGQUIT)
+ pendingsig_waitcmd = signo;
+
+ if (trap[signo] != NULL && trap[signo][0] != '\0' &&
+ (signo != SIGCHLD || !ignore_sigchld)) {
+ gotsig[signo] = 1;
+ pendingsig = signo;
+ pendingsig_waitcmd = signo;
+ }
+}
+
+
+/*
+ * Called to execute a trap. Perhaps we should avoid entering new trap
+ * handlers while we are executing a trap handler.
+ */
+void
+dotrap(void)
+{
+ struct stackmark smark;
+ int i;
+ int savestatus, prev_evalskip, prev_skipcount;
+
+ in_dotrap++;
+ for (;;) {
+ pendingsig = 0;
+ pendingsig_waitcmd = 0;
+ for (i = 1; i < NSIG; i++) {
+ if (gotsig[i]) {
+ gotsig[i] = 0;
+ if (trap[i]) {
+ /*
+ * Ignore SIGCHLD to avoid infinite
+ * recursion if the trap action does
+ * a fork.
+ */
+ if (i == SIGCHLD)
+ ignore_sigchld++;
+
+ /*
+ * Backup current evalskip
+ * state and reset it before
+ * executing a trap, so that the
+ * trap is not disturbed by an
+ * ongoing break/continue/return
+ * statement.
+ */
+ prev_evalskip = evalskip;
+ prev_skipcount = skipcount;
+ evalskip = 0;
+
+ last_trapsig = i;
+ savestatus = exitstatus;
+ setstackmark(&smark);
+ evalstring(stsavestr(trap[i]), 0);
+ popstackmark(&smark);
+
+ /*
+ * If such a command was not
+ * already in progress, allow a
+ * break/continue/return in the
+ * trap action to have an effect
+ * outside of it.
+ */
+ if (evalskip == 0 ||
+ prev_evalskip != 0) {
+ evalskip = prev_evalskip;
+ skipcount = prev_skipcount;
+ exitstatus = savestatus;
+ }
+
+ if (i == SIGCHLD)
+ ignore_sigchld--;
+ }
+ break;
+ }
+ }
+ if (i >= NSIG)
+ break;
+ }
+ in_dotrap--;
+}
+
+
+void
+trap_init(void)
+{
+ setsignal(SIGINT);
+ setsignal(SIGQUIT);
+}
+
+
+/*
+ * Controls whether the shell is interactive or not based on iflag.
+ */
+void
+setinteractive(void)
+{
+ setsignal(SIGTERM);
+}
+
+
+/*
+ * Called to exit the shell.
+ */
+void
+exitshell(int status)
+{
+ TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
+ exiting = 1;
+ exiting_exitstatus = status;
+ exitshell_savedstatus();
+}
+
+void
+exitshell_savedstatus(void)
+{
+ struct jmploc loc1, loc2;
+ char *p;
+ int sig = 0;
+ sigset_t sigs;
+
+ if (!exiting) {
+ if (in_dotrap && last_trapsig) {
+ sig = last_trapsig;
+ exiting_exitstatus = sig + 128;
+ } else
+ exiting_exitstatus = oexitstatus;
+ }
+ exitstatus = oexitstatus = exiting_exitstatus;
+ if (!setjmp(loc1.loc)) {
+ handler = &loc1;
+ if ((p = trap[0]) != NULL && *p != '\0') {
+ /*
+ * Reset evalskip, or the trap on EXIT could be
+ * interrupted if the last command was a "return".
+ */
+ evalskip = 0;
+ trap[0] = NULL;
+ FORCEINTON;
+ evalstring(p, 0);
+ }
+ }
+ if (!setjmp(loc2.loc)) {
+ handler = &loc2; /* probably unnecessary */
+ FORCEINTON;
+ flushall();
+#if JOBS
+ setjobctl(0);
+#endif
+#ifndef NO_HISTORY
+ histsave();
+#endif
+ }
+ if (sig != 0 && sig != SIGSTOP && sig != SIGTSTP && sig != SIGTTIN &&
+ sig != SIGTTOU) {
+ signal(sig, SIG_DFL);
+ sigemptyset(&sigs);
+ sigaddset(&sigs, sig);
+ sigprocmask(SIG_UNBLOCK, &sigs, NULL);
+ kill(getpid(), sig);
+ /* If the default action is to ignore, fall back to _exit(). */
+ }
+ _exit(exiting_exitstatus);
+}
diff --git a/cmd/posix/sh/trap.h b/cmd/posix/sh/trap.h
@@ -0,0 +1,48 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+extern volatile sig_atomic_t pendingsig;
+extern volatile sig_atomic_t pendingsig_waitcmd;
+
+void clear_traps(void);
+int have_traps(void);
+void setsignal(int);
+void ignoresig(int);
+int issigchldtrapped(void);
+void onsig(int);
+void dotrap(void);
+void trap_init(void);
+void setinteractive(void);
+void exitshell(int) __dead2;
+void exitshell_savedstatus(void) __dead2;
diff --git a/cmd/posix/sh/var.c b/cmd/posix/sh/var.c
@@ -0,0 +1,961 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "shell.h"
+#include "output.h"
+#include "expand.h"
+#include "nodes.h" /* for other headers */
+#include "eval.h" /* defines cmdenviron */
+#include "exec.h"
+#include "syntax.h"
+#include "options.h"
+#include "mail.h"
+#include "var.h"
+#include "memalloc.h"
+#include "error.h"
+#include "mystring.h"
+#include "parser.h"
+#include "builtins.h"
+#ifndef NO_HISTORY
+#include "myhistedit.h"
+#endif
+
+#include <langinfo.h>
+#include <locale.h>
+#include <paths.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+/*
+ * Shell variables.
+ */
+
+#ifndef VTABSIZE
+#define VTABSIZE 39
+#endif
+
+
+struct varinit {
+ struct var *var;
+ int flags;
+ const char *text;
+ void (*func)(const char *);
+};
+
+
+#ifndef NO_HISTORY
+struct var vhistsize;
+struct var vterm;
+#endif
+struct var vifs;
+struct var vmail;
+struct var vmpath;
+struct var vpath;
+struct var vps1;
+struct var vps2;
+struct var vps4;
+static struct var voptind;
+struct var vdisvfork;
+
+struct localvar *localvars;
+int forcelocal;
+
+static const struct varinit varinit[] = {
+#ifndef NO_HISTORY
+ { &vhistsize, VUNSET, "HISTSIZE=",
+ sethistsize },
+#endif
+ { &vifs, 0, "IFS= \t\n",
+ NULL },
+ { &vmail, VUNSET, "MAIL=",
+ NULL },
+ { &vmpath, VUNSET, "MAILPATH=",
+ NULL },
+ { &vpath, 0, "PATH=" _PATH_DEFPATH,
+ changepath },
+ /*
+ * vps1 depends on uid
+ */
+ { &vps2, 0, "PS2=> ",
+ NULL },
+ { &vps4, 0, "PS4=+ ",
+ NULL },
+#ifndef NO_HISTORY
+ { &vterm, VUNSET, "TERM=",
+ setterm },
+#endif
+ { &voptind, 0, "OPTIND=1",
+ getoptsreset },
+ { &vdisvfork, VUNSET, "SH_DISABLE_VFORK=",
+ NULL },
+ { NULL, 0, NULL,
+ NULL }
+};
+
+static struct var *vartab[VTABSIZE];
+
+static const char *const locale_names[7] = {
+ "LC_COLLATE", "LC_CTYPE", "LC_MONETARY",
+ "LC_NUMERIC", "LC_TIME", "LC_MESSAGES", NULL
+};
+static const int locale_categories[7] = {
+ LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME, LC_MESSAGES, 0
+};
+
+static int varequal(const char *, const char *);
+static struct var *find_var(const char *, struct var ***, int *);
+static int localevar(const char *);
+static void setvareq_const(const char *s, int flags);
+
+extern char **environ;
+
+/*
+ * This routine initializes the builtin variables and imports the environment.
+ * It is called when the shell is initialized.
+ */
+
+void
+initvar(void)
+{
+ char ppid[20];
+ const struct varinit *ip;
+ struct var *vp;
+ struct var **vpp;
+ char **envp;
+
+ for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
+ if (find_var(ip->text, &vpp, &vp->name_len) != NULL)
+ continue;
+ vp->next = *vpp;
+ *vpp = vp;
+ vp->text = __DECONST(char *, ip->text);
+ vp->flags = ip->flags | VSTRFIXED | VTEXTFIXED;
+ vp->func = ip->func;
+ }
+ /*
+ * PS1 depends on uid
+ */
+ if (find_var("PS1", &vpp, &vps1.name_len) == NULL) {
+ vps1.next = *vpp;
+ *vpp = &vps1;
+ vps1.text = __DECONST(char *, geteuid() ? "PS1=$ " : "PS1=# ");
+ vps1.flags = VSTRFIXED|VTEXTFIXED;
+ }
+ fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
+ setvarsafe("PPID", ppid, 0);
+ for (envp = environ ; *envp ; envp++) {
+ if (strchr(*envp, '=')) {
+ setvareq(*envp, VEXPORT|VTEXTFIXED);
+ }
+ }
+ setvareq_const("OPTIND=1", 0);
+ setvareq_const("IFS= \t\n", 0);
+}
+
+/*
+ * Safe version of setvar, returns 1 on success 0 on failure.
+ */
+
+int
+setvarsafe(const char *name, const char *val, int flags)
+{
+ struct jmploc jmploc;
+ struct jmploc *const savehandler = handler;
+ int err = 0;
+ int inton;
+
+ inton = is_int_on();
+ if (setjmp(jmploc.loc))
+ err = 1;
+ else {
+ handler = &jmploc;
+ setvar(name, val, flags);
+ }
+ handler = savehandler;
+ SETINTON(inton);
+ return err;
+}
+
+/*
+ * Set the value of a variable. The flags argument is stored with the
+ * flags of the variable. If val is NULL, the variable is unset.
+ */
+
+void
+setvar(const char *name, const char *val, int flags)
+{
+ const char *p;
+ size_t len;
+ size_t namelen;
+ size_t vallen;
+ char *nameeq;
+ int isbad;
+
+ isbad = 0;
+ p = name;
+ if (! is_name(*p))
+ isbad = 1;
+ p++;
+ for (;;) {
+ if (! is_in_name(*p)) {
+ if (*p == '\0' || *p == '=')
+ break;
+ isbad = 1;
+ }
+ p++;
+ }
+ namelen = p - name;
+ if (isbad)
+ error("%.*s: bad variable name", (int)namelen, name);
+ len = namelen + 2; /* 2 is space for '=' and '\0' */
+ if (val == NULL) {
+ flags |= VUNSET;
+ vallen = 0;
+ } else {
+ vallen = strlen(val);
+ len += vallen;
+ }
+ INTOFF;
+ nameeq = ckmalloc(len);
+ memcpy(nameeq, name, namelen);
+ nameeq[namelen] = '=';
+ if (val)
+ memcpy(nameeq + namelen + 1, val, vallen + 1);
+ else
+ nameeq[namelen + 1] = '\0';
+ setvareq(nameeq, flags);
+ INTON;
+}
+
+static int
+localevar(const char *s)
+{
+ const char *const *ss;
+
+ if (*s != 'L')
+ return 0;
+ if (varequal(s + 1, "ANG"))
+ return 1;
+ if (strncmp(s + 1, "C_", 2) != 0)
+ return 0;
+ if (varequal(s + 3, "ALL"))
+ return 1;
+ for (ss = locale_names; *ss ; ss++)
+ if (varequal(s + 3, *ss + 3))
+ return 1;
+ return 0;
+}
+
+
+/*
+ * Sets/unsets an environment variable from a pointer that may actually be a
+ * pointer into environ where the string should not be manipulated.
+ */
+static void
+change_env(const char *s, int set)
+{
+ char *eqp;
+ char *ss;
+
+ INTOFF;
+ ss = savestr(s);
+ if ((eqp = strchr(ss, '=')) != NULL)
+ *eqp = '\0';
+ if (set && eqp != NULL)
+ (void) setenv(ss, eqp + 1, 1);
+ else
+ (void) unsetenv(ss);
+ ckfree(ss);
+ INTON;
+
+ return;
+}
+
+
+/*
+ * Same as setvar except that the variable and value are passed in
+ * the first argument as name=value. Since the first argument will
+ * be actually stored in the table, it should not be a string that
+ * will go away.
+ */
+
+void
+setvareq(char *s, int flags)
+{
+ struct var *vp, **vpp;
+ int nlen;
+
+ if (aflag)
+ flags |= VEXPORT;
+ if (forcelocal && !(flags & (VNOSET | VNOLOCAL)))
+ mklocal(s);
+ vp = find_var(s, &vpp, &nlen);
+ if (vp != NULL) {
+ if (vp->flags & VREADONLY) {
+ if ((flags & (VTEXTFIXED|VSTACK)) == 0)
+ ckfree(s);
+ error("%.*s: is read only", vp->name_len, vp->text);
+ }
+ if (flags & VNOSET) {
+ if ((flags & (VTEXTFIXED|VSTACK)) == 0)
+ ckfree(s);
+ return;
+ }
+ INTOFF;
+
+ if (vp->func && (flags & VNOFUNC) == 0)
+ (*vp->func)(s + vp->name_len + 1);
+
+ if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
+ ckfree(vp->text);
+
+ vp->flags &= ~(VTEXTFIXED|VSTACK|VUNSET);
+ vp->flags |= flags;
+ vp->text = s;
+
+ /*
+ * We could roll this to a function, to handle it as
+ * a regular variable function callback, but why bother?
+ *
+ * Note: this assumes iflag is not set to 1 initially.
+ * As part of initvar(), this is called before arguments
+ * are looked at.
+ */
+ if ((vp == &vmpath || (vp == &vmail && ! mpathset())) &&
+ iflag == 1)
+ chkmail(1);
+ if ((vp->flags & VEXPORT) && localevar(s)) {
+ change_env(s, 1);
+ (void) setlocale(LC_ALL, "");
+ updatecharset();
+ }
+ INTON;
+ return;
+ }
+ /* not found */
+ if (flags & VNOSET) {
+ if ((flags & (VTEXTFIXED|VSTACK)) == 0)
+ ckfree(s);
+ return;
+ }
+ INTOFF;
+ vp = ckmalloc(sizeof (*vp));
+ vp->flags = flags;
+ vp->text = s;
+ vp->name_len = nlen;
+ vp->next = *vpp;
+ vp->func = NULL;
+ *vpp = vp;
+ if ((vp->flags & VEXPORT) && localevar(s)) {
+ change_env(s, 1);
+ (void) setlocale(LC_ALL, "");
+ updatecharset();
+ }
+ INTON;
+}
+
+
+static void
+setvareq_const(const char *s, int flags)
+{
+ setvareq(__DECONST(char *, s), flags | VTEXTFIXED);
+}
+
+
+/*
+ * Process a linked list of variable assignments.
+ */
+
+void
+listsetvar(struct arglist *list, int flags)
+{
+ int i;
+
+ INTOFF;
+ for (i = 0; i < list->count; i++)
+ setvareq(savestr(list->args[i]), flags);
+ INTON;
+}
+
+
+
+/*
+ * Find the value of a variable. Returns NULL if not set.
+ */
+
+char *
+lookupvar(const char *name)
+{
+ struct var *v;
+
+ v = find_var(name, NULL, NULL);
+ if (v == NULL || v->flags & VUNSET)
+ return NULL;
+ return v->text + v->name_len + 1;
+}
+
+
+
+/*
+ * Search the environment of a builtin command. If the second argument
+ * is nonzero, return the value of a variable even if it hasn't been
+ * exported.
+ */
+
+char *
+bltinlookup(const char *name, int doall)
+{
+ struct var *v;
+ char *result;
+ int i;
+
+ result = NULL;
+ if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
+ if (varequal(cmdenviron->args[i], name))
+ result = strchr(cmdenviron->args[i], '=') + 1;
+ }
+ if (result != NULL)
+ return result;
+
+ v = find_var(name, NULL, NULL);
+ if (v == NULL || v->flags & VUNSET ||
+ (!doall && (v->flags & VEXPORT) == 0))
+ return NULL;
+ return v->text + v->name_len + 1;
+}
+
+
+/*
+ * Set up locale for a builtin (LANG/LC_* assignments).
+ */
+void
+bltinsetlocale(void)
+{
+ int act = 0;
+ char *loc, *locdef;
+ int i;
+
+ if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
+ if (localevar(cmdenviron->args[i])) {
+ act = 1;
+ break;
+ }
+ }
+ if (!act)
+ return;
+ loc = bltinlookup("LC_ALL", 0);
+ INTOFF;
+ if (loc != NULL) {
+ setlocale(LC_ALL, loc);
+ INTON;
+ updatecharset();
+ return;
+ }
+ locdef = bltinlookup("LANG", 0);
+ for (i = 0; locale_names[i] != NULL; i++) {
+ loc = bltinlookup(locale_names[i], 0);
+ if (loc == NULL)
+ loc = locdef;
+ if (loc != NULL)
+ setlocale(locale_categories[i], loc);
+ }
+ INTON;
+ updatecharset();
+}
+
+/*
+ * Undo the effect of bltinlocaleset().
+ */
+void
+bltinunsetlocale(void)
+{
+ int i;
+
+ INTOFF;
+ if (cmdenviron) for (i = 0; i < cmdenviron->count; i++) {
+ if (localevar(cmdenviron->args[i])) {
+ setlocale(LC_ALL, "");
+ updatecharset();
+ break;
+ }
+ }
+ INTON;
+}
+
+/*
+ * Update the localeisutf8 flag.
+ */
+void
+updatecharset(void)
+{
+ char *charset;
+
+ charset = nl_langinfo(CODESET);
+ localeisutf8 = !strcmp(charset, "UTF-8");
+}
+
+void
+initcharset(void)
+{
+ updatecharset();
+ initial_localeisutf8 = localeisutf8;
+}
+
+/*
+ * Generate a list of exported variables. This routine is used to construct
+ * the third argument to execve when executing a program.
+ */
+
+char **
+environment(void)
+{
+ int nenv;
+ struct var **vpp;
+ struct var *vp;
+ char **env, **ep;
+
+ nenv = 0;
+ for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
+ for (vp = *vpp ; vp ; vp = vp->next)
+ if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
+ nenv++;
+ }
+ ep = env = stalloc((nenv + 1) * sizeof *env);
+ for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
+ for (vp = *vpp ; vp ; vp = vp->next)
+ if ((vp->flags & (VEXPORT|VUNSET)) == VEXPORT)
+ *ep++ = vp->text;
+ }
+ *ep = NULL;
+ return env;
+}
+
+
+static int
+var_compare(const void *a, const void *b)
+{
+ const char *const *sa, *const *sb;
+
+ sa = a;
+ sb = b;
+ /*
+ * This compares two var=value strings which creates a different
+ * order from what you would probably expect. POSIX is somewhat
+ * ambiguous on what should be sorted exactly.
+ */
+ return strcoll(*sa, *sb);
+}
+
+
+/*
+ * Command to list all variables which are set. This is invoked from the
+ * set command when it is called without any options or operands.
+ */
+
+int
+showvarscmd(int argc __unused, char **argv __unused)
+{
+ struct var **vpp;
+ struct var *vp;
+ const char *s;
+ const char **vars;
+ int i, n;
+
+ /*
+ * POSIX requires us to sort the variables.
+ */
+ n = 0;
+ for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
+ for (vp = *vpp; vp; vp = vp->next) {
+ if (!(vp->flags & VUNSET))
+ n++;
+ }
+ }
+
+ INTOFF;
+ vars = ckmalloc(n * sizeof(*vars));
+ i = 0;
+ for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
+ for (vp = *vpp; vp; vp = vp->next) {
+ if (!(vp->flags & VUNSET))
+ vars[i++] = vp->text;
+ }
+ }
+
+ qsort(vars, n, sizeof(*vars), var_compare);
+ for (i = 0; i < n; i++) {
+ /*
+ * Skip improper variable names so the output remains usable as
+ * shell input.
+ */
+ if (!isassignment(vars[i]))
+ continue;
+ s = strchr(vars[i], '=');
+ s++;
+ outbin(vars[i], s - vars[i], out1);
+ out1qstr(s);
+ out1c('\n');
+ }
+ ckfree(vars);
+ INTON;
+
+ return 0;
+}
+
+
+
+/*
+ * The export and readonly commands.
+ */
+
+int
+exportcmd(int argc __unused, char **argv)
+{
+ struct var **vpp;
+ struct var *vp;
+ char **ap;
+ char *name;
+ char *p;
+ char *cmdname;
+ int ch, values;
+ int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
+
+ cmdname = argv[0];
+ values = 0;
+ while ((ch = nextopt("p")) != '\0') {
+ switch (ch) {
+ case 'p':
+ values = 1;
+ break;
+ }
+ }
+
+ if (values && *argptr != NULL)
+ error("-p requires no arguments");
+ if (*argptr != NULL) {
+ for (ap = argptr; (name = *ap) != NULL; ap++) {
+ if ((p = strchr(name, '=')) != NULL) {
+ p++;
+ } else {
+ vp = find_var(name, NULL, NULL);
+ if (vp != NULL) {
+ vp->flags |= flag;
+ if ((vp->flags & VEXPORT) && localevar(vp->text)) {
+ change_env(vp->text, 1);
+ (void) setlocale(LC_ALL, "");
+ updatecharset();
+ }
+ continue;
+ }
+ }
+ setvar(name, p, flag);
+ }
+ } else {
+ for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
+ for (vp = *vpp ; vp ; vp = vp->next) {
+ if (vp->flags & flag) {
+ if (values) {
+ /*
+ * Skip improper variable names
+ * so the output remains usable
+ * as shell input.
+ */
+ if (!isassignment(vp->text))
+ continue;
+ out1str(cmdname);
+ out1c(' ');
+ }
+ if (values && !(vp->flags & VUNSET)) {
+ outbin(vp->text,
+ vp->name_len + 1, out1);
+ out1qstr(vp->text +
+ vp->name_len + 1);
+ } else
+ outbin(vp->text, vp->name_len,
+ out1);
+ out1c('\n');
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+
+/*
+ * The "local" command.
+ */
+
+int
+localcmd(int argc __unused, char **argv __unused)
+{
+ char *name;
+
+ nextopt("");
+ if (! in_function())
+ error("Not in a function");
+ while ((name = *argptr++) != NULL) {
+ mklocal(name);
+ }
+ return 0;
+}
+
+
+/*
+ * Make a variable a local variable. When a variable is made local, it's
+ * value and flags are saved in a localvar structure. The saved values
+ * will be restored when the shell function returns. We handle the name
+ * "-" as a special case.
+ */
+
+void
+mklocal(char *name)
+{
+ struct localvar *lvp;
+ struct var **vpp;
+ struct var *vp;
+
+ INTOFF;
+ lvp = ckmalloc(sizeof (struct localvar));
+ if (name[0] == '-' && name[1] == '\0') {
+ lvp->text = ckmalloc(sizeof optval);
+ memcpy(lvp->text, optval, sizeof optval);
+ vp = NULL;
+ } else {
+ vp = find_var(name, &vpp, NULL);
+ if (vp == NULL) {
+ if (strchr(name, '='))
+ setvareq(savestr(name), VSTRFIXED | VNOLOCAL);
+ else
+ setvar(name, NULL, VSTRFIXED | VNOLOCAL);
+ vp = *vpp; /* the new variable */
+ lvp->text = NULL;
+ lvp->flags = VUNSET;
+ } else {
+ lvp->text = vp->text;
+ lvp->flags = vp->flags;
+ vp->flags |= VSTRFIXED|VTEXTFIXED;
+ if (name[vp->name_len] == '=')
+ setvareq(savestr(name), VNOLOCAL);
+ }
+ }
+ lvp->vp = vp;
+ lvp->next = localvars;
+ localvars = lvp;
+ INTON;
+}
+
+
+/*
+ * Called after a function returns.
+ */
+
+void
+poplocalvars(void)
+{
+ struct localvar *lvp;
+ struct var *vp;
+ int islocalevar;
+
+ INTOFF;
+ while ((lvp = localvars) != NULL) {
+ localvars = lvp->next;
+ vp = lvp->vp;
+ if (vp == NULL) { /* $- saved */
+ memcpy(optval, lvp->text, sizeof optval);
+ ckfree(lvp->text);
+ optschanged();
+ } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
+ vp->flags &= ~VREADONLY;
+ (void)unsetvar(vp->text);
+ } else {
+ islocalevar = (vp->flags | lvp->flags) & VEXPORT &&
+ localevar(lvp->text);
+ if ((vp->flags & VTEXTFIXED) == 0)
+ ckfree(vp->text);
+ vp->flags = lvp->flags;
+ vp->text = lvp->text;
+ if (vp->func)
+ (*vp->func)(vp->text + vp->name_len + 1);
+ if (islocalevar) {
+ change_env(vp->text, vp->flags & VEXPORT &&
+ (vp->flags & VUNSET) == 0);
+ setlocale(LC_ALL, "");
+ updatecharset();
+ }
+ }
+ ckfree(lvp);
+ }
+ INTON;
+}
+
+
+int
+setvarcmd(int argc, char **argv)
+{
+ if (argc <= 2)
+ return unsetcmd(argc, argv);
+ else if (argc == 3)
+ setvar(argv[1], argv[2], 0);
+ else
+ error("too many arguments");
+ return 0;
+}
+
+
+/*
+ * The unset builtin command.
+ */
+
+int
+unsetcmd(int argc __unused, char **argv __unused)
+{
+ char **ap;
+ int i;
+ int flg_func = 0;
+ int flg_var = 0;
+ int ret = 0;
+
+ while ((i = nextopt("vf")) != '\0') {
+ if (i == 'f')
+ flg_func = 1;
+ else
+ flg_var = 1;
+ }
+ if (flg_func == 0 && flg_var == 0)
+ flg_var = 1;
+
+ INTOFF;
+ for (ap = argptr; *ap ; ap++) {
+ if (flg_func)
+ ret |= unsetfunc(*ap);
+ if (flg_var)
+ ret |= unsetvar(*ap);
+ }
+ INTON;
+ return ret;
+}
+
+
+/*
+ * Unset the specified variable.
+ * Called with interrupts off.
+ */
+
+int
+unsetvar(const char *s)
+{
+ struct var **vpp;
+ struct var *vp;
+
+ vp = find_var(s, &vpp, NULL);
+ if (vp == NULL)
+ return (0);
+ if (vp->flags & VREADONLY)
+ return (1);
+ if (vp->text[vp->name_len + 1] != '\0')
+ setvar(s, "", 0);
+ if ((vp->flags & VEXPORT) && localevar(vp->text)) {
+ change_env(s, 0);
+ setlocale(LC_ALL, "");
+ updatecharset();
+ }
+ vp->flags &= ~VEXPORT;
+ vp->flags |= VUNSET;
+ if ((vp->flags & VSTRFIXED) == 0) {
+ if ((vp->flags & VTEXTFIXED) == 0)
+ ckfree(vp->text);
+ *vpp = vp->next;
+ ckfree(vp);
+ }
+ return (0);
+}
+
+
+
+/*
+ * Returns true if the two strings specify the same variable. The first
+ * variable name is terminated by '='; the second may be terminated by
+ * either '=' or '\0'.
+ */
+
+static int
+varequal(const char *p, const char *q)
+{
+ while (*p == *q++) {
+ if (*p++ == '=')
+ return 1;
+ }
+ if (*p == '=' && *(q - 1) == '\0')
+ return 1;
+ return 0;
+}
+
+/*
+ * Search for a variable.
+ * 'name' may be terminated by '=' or a NUL.
+ * vppp is set to the pointer to vp, or the list head if vp isn't found
+ * lenp is set to the number of characters in 'name'
+ */
+
+static struct var *
+find_var(const char *name, struct var ***vppp, int *lenp)
+{
+ unsigned int hashval;
+ int len;
+ struct var *vp, **vpp;
+ const char *p = name;
+
+ hashval = 0;
+ while (*p && *p != '=')
+ hashval = 2 * hashval + (unsigned char)*p++;
+ len = p - name;
+
+ if (lenp)
+ *lenp = len;
+ vpp = &vartab[hashval % VTABSIZE];
+ if (vppp)
+ *vppp = vpp;
+
+ for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
+ if (vp->name_len != len)
+ continue;
+ if (memcmp(vp->text, name, len) != 0)
+ continue;
+ if (vppp)
+ *vppp = vpp;
+ return vp;
+ }
+ return NULL;
+}
diff --git a/cmd/posix/sh/var.h b/cmd/posix/sh/var.h
@@ -0,0 +1,129 @@
+/*-
+ * SPDX-License-Identifier: BSD-3-Clause
+ *
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * This code is derived from software contributed to Berkeley by
+ * Kenneth Almquist.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * Shell variables.
+ */
+
+/* flags */
+#define VEXPORT 0x01 /* variable is exported */
+#define VREADONLY 0x02 /* variable cannot be modified */
+#define VSTRFIXED 0x04 /* variable struct is statically allocated */
+#define VTEXTFIXED 0x08 /* text is statically allocated */
+#define VSTACK 0x10 /* text is allocated on the stack */
+#define VUNSET 0x20 /* the variable is not set */
+#define VNOFUNC 0x40 /* don't call the callback function */
+#define VNOSET 0x80 /* do not set variable - just readonly test */
+#define VNOLOCAL 0x100 /* ignore forcelocal */
+
+
+struct var {
+ struct var *next; /* next entry in hash list */
+ int flags; /* flags are defined above */
+ int name_len; /* length of name */
+ char *text; /* name=value */
+ void (*func)(const char *);
+ /* function to be called when */
+ /* the variable gets set/unset */
+};
+
+
+struct localvar {
+ struct localvar *next; /* next local variable in list */
+ struct var *vp; /* the variable that was made local */
+ int flags; /* saved flags */
+ char *text; /* saved text */
+};
+
+
+extern struct localvar *localvars;
+extern int forcelocal;
+
+extern struct var vifs;
+extern struct var vmail;
+extern struct var vmpath;
+extern struct var vpath;
+extern struct var vps1;
+extern struct var vps2;
+extern struct var vps4;
+extern struct var vdisvfork;
+#ifndef NO_HISTORY
+extern struct var vhistsize;
+extern struct var vterm;
+#endif
+
+extern int localeisutf8;
+/* The parser uses the locale that was in effect at startup. */
+extern int initial_localeisutf8;
+
+/*
+ * The following macros access the values of the above variables.
+ * They have to skip over the name. They return the null string
+ * for unset variables.
+ */
+
+#define ifsval() (vifs.text + 4)
+#define ifsset() ((vifs.flags & VUNSET) == 0)
+#define mailval() (vmail.text + 5)
+#define mpathval() (vmpath.text + 9)
+#define pathval() (vpath.text + 5)
+#define ps1val() (vps1.text + 4)
+#define ps2val() (vps2.text + 4)
+#define ps4val() (vps4.text + 4)
+#define optindval() (voptind.text + 7)
+#ifndef NO_HISTORY
+#define histsizeval() (vhistsize.text + 9)
+#define termval() (vterm.text + 5)
+#endif
+
+#define mpathset() ((vmpath.flags & VUNSET) == 0)
+#define disvforkset() ((vdisvfork.flags & VUNSET) == 0)
+
+void initvar(void);
+void setvar(const char *, const char *, int);
+void setvareq(char *, int);
+struct arglist;
+void listsetvar(struct arglist *, int);
+char *lookupvar(const char *);
+char *bltinlookup(const char *, int);
+void bltinsetlocale(void);
+void bltinunsetlocale(void);
+void updatecharset(void);
+void initcharset(void);
+char **environment(void);
+int showvarscmd(int, char **);
+void mklocal(char *);
+void poplocalvars(void);
+int unsetvar(const char *);
+int setvarsafe(const char *, const char *, int);
diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c
@@ -1,14 +1,14 @@
/* See LICENSE file for copyright and license details. */
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
#include "queue.h"
#include "text.h"
#include "utf.h"
#include "util.h"
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
struct keydef {
int start_column;
int end_column;
@@ -36,6 +36,12 @@ enum {
static TAILQ_HEAD(kdhead, keydef) kdhead = TAILQ_HEAD_INITIALIZER(kdhead);
static int Cflag = 0, cflag = 0, uflag = 0;
+#if FEATURE_SORT_BIG
+static int zflag = 0;
+#endif
+#if FEATURE_SORT_STABLE
+static int sflag = 0;
+#endif
static char *fieldsep = NULL;
static size_t fieldseplen = 0;
static struct column col1, col2;
@@ -94,7 +100,7 @@ columns(struct line *line, const struct keydef *kd, struct column *col)
skipcolumn(&start, 1);
if (kd->flags & MOD_STARTB)
skipblank(&start);
- for (utflen = 0; start.len > 1 && utflen < kd->start_char - 1;) {
+ for (utflen = 0; start.len > 1 && utflen < (size_t)(kd->start_char - 1);) {
rlen = chartorune(&r, start.data);
start.data += rlen;
start.len -= rlen;
@@ -109,7 +115,7 @@ columns(struct line *line, const struct keydef *kd, struct column *col)
if (kd->flags & MOD_ENDB)
skipblank(&end);
if (kd->end_char) {
- for (utflen = 0; end.len > 1 && utflen < kd->end_char;) {
+ for (utflen = 0; end.len > 1 && utflen < (size_t)kd->end_char;) {
rlen = chartorune(&r, end.data);
end.data += rlen;
end.len -= rlen;
@@ -173,6 +179,33 @@ skipmodcmp(struct line *a, struct line *b, int flags)
return r1 - r2;
}
+#if FEATURE_SORT_BIG
+static void
+getlines_z(FILE *fp, struct linebuf *b)
+{
+ char *line = NULL;
+ size_t size = 0, linelen = 0;
+ ssize_t len;
+
+ while ((len = getdelim(&line, &size, '\0', fp)) > 0) {
+ if (++b->nlines > b->capacity) {
+ b->capacity += 512;
+ b->lines = ereallocarray(b->lines, b->capacity, sizeof(*b->lines));
+ }
+ linelen = len;
+ b->lines[b->nlines - 1].data = memcpy(emalloc(linelen + 1), line, linelen + 1);
+ b->lines[b->nlines - 1].len = linelen;
+ }
+ free(line);
+ if (b->lines && b->nlines && linelen && b->lines[b->nlines - 1].data[linelen - 1] != '\0') {
+ b->lines[b->nlines - 1].data = erealloc(b->lines[b->nlines - 1].data, linelen + 2);
+ b->lines[b->nlines - 1].data[linelen] = '\0';
+ b->lines[b->nlines - 1].data[linelen + 1] = '\0';
+ b->lines[b->nlines - 1].len++;
+ }
+}
+#endif
+
static int
slinecmp(struct line *a, struct line *b)
{
@@ -208,19 +241,44 @@ slinecmp(struct line *a, struct line *b)
return res;
}
+#if FEATURE_SORT_STABLE
+struct sort_item {
+ struct line line;
+ size_t index;
+};
+
+static int
+slinecmp_stable(const struct sort_item *a, const struct sort_item *b)
+{
+ int res = slinecmp((struct line *)&a->line, (struct line *)&b->line);
+ if (res == 0)
+ return (a->index < b->index) ? -1 : 1;
+ return res;
+}
+#endif
+
static int
check(FILE *fp, const char *fname)
{
static struct line prev, cur, tmp;
static size_t prevsize, cursize, tmpsize;
ssize_t len;
+ int delim = '\n';
+
+#if FEATURE_SORT_BIG
+ if (zflag)
+ delim = '\0';
+#endif
if (!prev.data) {
- if ((len = getline(&prev.data, &prevsize, fp)) < 0)
- eprintf("getline:");
+ if ((len = getdelim(&prev.data, &prevsize, delim, fp)) < 0) {
+ if (feof(fp))
+ return 0;
+ eprintf("getdelim:");
+ }
prev.len = len;
}
- while ((len = getline(&cur.data, &cursize, fp)) > 0) {
+ while ((len = getdelim(&cur.data, &cursize, delim, fp)) > 0) {
cur.len = len;
if (uflag > slinecmp(&cur, &prev)) {
if (!Cflag) {
@@ -319,8 +377,14 @@ addkeydef(char *kdstr, int flags)
static void
usage(void)
{
- enprintf(2, "usage: %s [-Cbcdfimnru] [-o outfile] [-t delim] "
- "[-k def]... [file ...]\n", argv0);
+ enprintf(2, "usage: %s [-Cbcdfimnru"
+#if FEATURE_SORT_STABLE
+ "s"
+#endif
+#if FEATURE_SORT_BIG
+ "z"
+#endif
+ "] [-o outfile] [-t delim] [-k def]... [file ...]\n", argv0);
}
int
@@ -370,6 +434,11 @@ main(int argc, char *argv[])
case 'r':
global_flags |= MOD_R;
break;
+#if FEATURE_SORT_STABLE
+ case 's':
+ sflag = 1;
+ break;
+#endif
case 't':
fieldsep = EARGF(usage());
if (!*fieldsep)
@@ -379,6 +448,11 @@ main(int argc, char *argv[])
case 'u':
uflag = 1;
break;
+#if FEATURE_SORT_BIG
+ case 'z':
+ zflag = 1;
+ break;
+#endif
default:
usage();
} ARGEND
@@ -394,7 +468,12 @@ main(int argc, char *argv[])
if (check(stdin, "<stdin>") && !ret)
ret = 1;
} else {
- getlines(stdin, &linebuf);
+#if FEATURE_SORT_BIG
+ if (zflag)
+ getlines_z(stdin, &linebuf);
+ else
+#endif
+ getlines(stdin, &linebuf);
}
} else for (; *argv; argc--, argv++) {
if (!strcmp(*argv, "-")) {
@@ -408,7 +487,12 @@ main(int argc, char *argv[])
if (check(fp, *argv) && !ret)
ret = 1;
} else {
- getlines(fp, &linebuf);
+#if FEATURE_SORT_BIG
+ if (zflag)
+ getlines_z(fp, &linebuf);
+ else
+#endif
+ getlines(fp, &linebuf);
}
if (fp != stdin && fshut(fp, *argv))
ret = 2;
@@ -418,8 +502,26 @@ main(int argc, char *argv[])
if (outfile && !(ofp = fopen(outfile, "w")))
eprintf("fopen %s:", outfile);
- qsort(linebuf.lines, linebuf.nlines, sizeof(*linebuf.lines),
- (int (*)(const void *, const void *))slinecmp);
+#if FEATURE_SORT_STABLE
+ if (sflag) {
+ struct sort_item *items = ecalloc(linebuf.nlines, sizeof(*items));
+ for (i = 0; i < linebuf.nlines; i++) {
+ items[i].line = linebuf.lines[i];
+ items[i].index = i;
+ }
+ qsort(items, linebuf.nlines, sizeof(*items),
+ (int (*)(const void *, const void *))slinecmp_stable);
+ for (i = 0; i < linebuf.nlines; i++) {
+ linebuf.lines[i] = items[i].line;
+ }
+ free(items);
+ } else {
+#endif
+ qsort(linebuf.lines, linebuf.nlines, sizeof(*linebuf.lines),
+ (int (*)(const void *, const void *))slinecmp);
+#if FEATURE_SORT_STABLE
+ }
+#endif
for (i = 0; i < linebuf.nlines; i++) {
if (!uflag || i == 0 ||
diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c
@@ -34,7 +34,7 @@ dropinit(int fd, const char *fname, size_t count)
}
break;
case 'c': /* bytes */
- if (count > n) {
+ if (count > (size_t)n) {
count -= n;
} else {
p = buf + count;
@@ -165,8 +165,8 @@ main(int argc, char *argv[])
case 'n':
mode = ARGC();
numstr = EARGF(usage());
- n = MIN(llabs(estrtonum(numstr, LLONG_MIN + 1,
- MIN(LLONG_MAX, SIZE_MAX))), SIZE_MAX);
+ n = MIN((unsigned long long)llabs(estrtonum(numstr, LLONG_MIN + 1,
+ MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX))), (unsigned long long)SIZE_MAX);
if (strchr(numstr, '+'))
tail = dropinit;
break;
diff --git a/cmd/posix/tee.c b/cmd/posix/tee.c
@@ -36,7 +36,7 @@ main(int argc, char *argv[])
nfds = argc + 1;
fds = ecalloc(nfds, sizeof(*fds));
- for (i = 0; i < argc; i++) {
+ for (i = 0; i < (size_t)argc; i++) {
if ((fds[i] = open(argv[i], O_WRONLY|O_CREAT|aflag, 0666)) < 0) {
weprintf("open %s:", argv[i]);
ret = 1;
@@ -47,7 +47,7 @@ main(int argc, char *argv[])
while ((n = read(0, buf, sizeof(buf))) > 0) {
for (i = 0; i < nfds; i++) {
if (fds[i] >= 0 && writeall(fds[i], buf, n) < 0) {
- weprintf("write %s:", (i != argc) ? argv[i] : "<stdout>");
+ weprintf("write %s:", (i != (size_t)argc) ? argv[i] : "<stdout>");
fds[i] = -1;
ret = 1;
}
diff --git a/cmd/posix/test.c b/cmd/posix/test.c
@@ -176,6 +176,7 @@ find_test(struct test *tests, char *name)
static int
noarg(char *argv[])
{
+ (void)argv;
return 0;
}
diff --git a/cmd/posix/time.c b/cmd/posix/time.c
@@ -42,6 +42,7 @@ main(int argc, char *argv[])
switch ((pid = fork())) {
case -1:
eprintf("fork:");
+ /* fallthrough */
case 0:
execvp(argv[0], argv);
savederrno = errno;
diff --git a/cmd/posix/unexpand.c b/cmd/posix/unexpand.c
@@ -21,7 +21,7 @@ parselist(const char *s)
if (*p == '\0')
eprintf("empty field in tablist\n");
tablist = ereallocarray(tablist, i + 1, sizeof(*tablist));
- tablist[i] = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX));
+ tablist[i] = estrtonum(p, 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
if (i > 0 && tablist[i - 1] >= tablist[i])
eprintf("tablist must be ascending\n");
}
@@ -140,7 +140,7 @@ main(int argc, char *argv[])
tl = EARGF(usage());
if (!*tl)
eprintf("tablist cannot be empty\n");
- /* Fallthrough: -t implies -a */
+ /* fallthrough */
case 'a':
aflag = 1;
break;
diff --git a/cmd/posix/uudecode.c b/cmd/posix/uudecode.c
@@ -113,6 +113,7 @@ uudecodeb64(FILE *fp, FILE *outfp)
case 1:
eprintf("%d: unexpected \"=\""
"appeared\n", l);
+ /* fallthrough */
case 2:
*po++ = b24[0];
b = 0;
diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c
@@ -241,6 +241,7 @@ dospawn:
switch (fork()) {
case -1:
eprintf("fork:");
+ /* fallthrough */
case 0:
execvp(*cmd, cmd);
savederrno = errno;
@@ -283,7 +284,7 @@ main(int argc, char *argv[])
case 'n':
nflag = 1;
maxargs =
- estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
+ estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
case 'p':
pflag = 1;
@@ -293,7 +294,7 @@ main(int argc, char *argv[])
break;
case 's':
argmaxsz =
- estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
+ estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
case 't':
tflag = 1;
@@ -314,11 +315,11 @@ main(int argc, char *argv[])
case 'L':
Lflag = 1;
maxlines =
- estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
+ estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
case 'P':
maxprocs =
- estrtonum(EARGF(usage()), 1, MIN(SIZE_MAX, LLONG_MAX));
+ estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX));
break;
default:
usage();
diff --git a/cmd/pseudo/base64.c b/cmd/pseudo/base64.c
@@ -0,0 +1,177 @@
+/* See LICENSE file for copyright and license details. */
+#include "util.h"
+#include "arg.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void
+usage(void)
+{
+ eprintf("usage: %s [-d] [-i] [-w cols] [file]\n", argv0);
+}
+
+static void
+base64_encode(char *dst, const unsigned char *src, size_t len)
+{
+ static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ size_t i;
+
+ for (i = 0; i < len; i += 3, dst += 4) {
+ unsigned long x = (src[i] & 0xfful) << 16;
+ dst[3] = i + 2 >= len ? '=' : b64[(x |= src[i + 2] & 0xfful) & 0x3f];
+ dst[2] = i + 1 >= len ? '=' : b64[(x |= (src[i + 1] & 0xfful) << 8) >> 6 & 0x3f];
+ dst[1] = b64[x >> 12 & 0x3f];
+ dst[0] = b64[x >> 18];
+ }
+ *dst = '\0';
+}
+
+static size_t
+base64_decode(unsigned char *dst, const char *src)
+{
+ static const char b64[] = {
+ ['A'] = 0, ['B'] = 1, ['C'] = 2, ['D'] = 3,
+ ['E'] = 4, ['F'] = 5, ['G'] = 6, ['H'] = 7,
+ ['I'] = 8, ['J'] = 9, ['K'] = 10, ['L'] = 11,
+ ['M'] = 12, ['N'] = 13, ['O'] = 14, ['P'] = 15,
+ ['Q'] = 16, ['R'] = 17, ['S'] = 18, ['T'] = 19,
+ ['U'] = 20, ['V'] = 21, ['W'] = 22, ['X'] = 23,
+ ['Y'] = 24, ['Z'] = 25, ['a'] = 26, ['b'] = 27,
+ ['c'] = 28, ['d'] = 29, ['e'] = 30, ['f'] = 31,
+ ['g'] = 32, ['h'] = 33, ['i'] = 34, ['j'] = 35,
+ ['k'] = 36, ['l'] = 37, ['m'] = 38, ['n'] = 39,
+ ['o'] = 40, ['p'] = 41, ['q'] = 42, ['r'] = 43,
+ ['s'] = 44, ['t'] = 45, ['u'] = 46, ['v'] = 47,
+ ['w'] = 48, ['x'] = 49, ['y'] = 50, ['z'] = 51,
+ ['0'] = 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
+ ['+'] = 62, ['/'] = 63, ['='] = 0,
+ };
+ unsigned long x;
+ size_t i, c, len, pad;
+
+ for (i = 0, x = 0, len = 0, pad = 0; src[i]; ++i) {
+ c = (unsigned char)src[i];
+ if (c == '=' && (!src[i + 1] || (src[i + 1] == '=' && !src[i + 2])))
+ ++pad;
+ else if (c >= sizeof(b64) || (!b64[c] && c != 'A'))
+ return 0;
+ x = x << 6 | b64[c];
+ if (i % 4 == 3) {
+ dst[len + 2] = x & 0xff, x >>= 8;
+ dst[len + 1] = x & 0xff, x >>= 8;
+ dst[len + 0] = x & 0xff;
+ len += 3;
+ }
+ }
+ if (i % 4 != 0)
+ return 0;
+ return len - pad;
+}
+
+static void
+encode_stream(FILE *fp, size_t wrap)
+{
+ unsigned char buf[3072];
+ char out[4096 + 1];
+ size_t n, i, col;
+
+ col = 0;
+ while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
+ base64_encode(out, buf, n);
+ for (i = 0; out[i]; i++) {
+ putchar(out[i]);
+ if (wrap > 0 && ++col == wrap) {
+ putchar('\n');
+ col = 0;
+ }
+ }
+ }
+ if (wrap > 0 && col > 0)
+ putchar('\n');
+}
+
+static void
+decode_stream(FILE *fp, int iflag)
+{
+ char in[5];
+ unsigned char out[4];
+ int c;
+ size_t count, n;
+
+ count = 0;
+ while ((c = fgetc(fp)) != EOF) {
+ /* skip whitespace */
+ if (c == '\r' || c == '\n' || c == '\t' || c == ' ')
+ continue;
+ /* check validity */
+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
+ (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') {
+ in[count++] = c;
+ if (count == 4) {
+ in[4] = '\0';
+ n = base64_decode(out, in);
+ if (n > 0)
+ fwrite(out, 1, n, stdout);
+ else
+ eprintf("invalid input\n");
+ if (strchr(in, '='))
+ break;
+ count = 0;
+ }
+ } else if (!iflag) {
+ eprintf("invalid character\n");
+ }
+ }
+ if (count > 0)
+ eprintf("input is truncated\n");
+}
+
+int
+main(int argc, char *argv[])
+{
+ FILE *fp;
+ int dflag, iflag, ret;
+ size_t wrap;
+
+ dflag = 0;
+ iflag = 0;
+ wrap = 76;
+ ret = 0;
+ fp = stdin;
+
+ ARGBEGIN {
+ case 'd':
+ dflag = 1;
+ break;
+ case 'i':
+ iflag = 1;
+ break;
+ case 'w':
+ wrap = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SSIZE_MAX));
+ break;
+ default:
+ usage();
+ } ARGEND
+
+ if (argc > 1)
+ usage();
+
+ if (argc == 1 && strcmp(argv[0], "-") != 0) {
+ fp = fopen(argv[0], "r");
+ if (!fp)
+ eprintf("fopen %s:", argv[0]);
+ }
+
+ if (dflag)
+ decode_stream(fp, iflag);
+ else
+ encode_stream(fp, wrap);
+
+ if (fp != stdin)
+ fclose(fp);
+
+ ret = fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>");
+ return ret;
+}
diff --git a/cmd/pseudo/base64.o b/cmd/pseudo/base64.o
Binary files differ.
diff --git a/cmd/pseudo/cols.c b/cmd/pseudo/cols.c
@@ -30,7 +30,7 @@ main(int argc, char *argv[])
ARGBEGIN {
case 'c':
cflag = 1;
- chars = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
+ chars = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
break;
default:
usage();
@@ -38,7 +38,7 @@ main(int argc, char *argv[])
if (!cflag) {
if ((p = getenv("COLUMNS")))
- chars = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX));
+ chars = estrtonum(p, 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX));
else if (!ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) && w.ws_col > 0)
chars = w.ws_col;
}
diff --git a/cmd/pseudo/cron.c b/cmd/pseudo/cron.c
@@ -345,14 +345,19 @@ freecte(struct ctabentry *cte, int nfields)
switch (nfields) {
case 6:
free(cte->cmd);
+ /* fallthrough */
case 5:
free(cte->wday.val);
+ /* fallthrough */
case 4:
free(cte->mon.val);
+ /* fallthrough */
case 3:
free(cte->mday.val);
+ /* fallthrough */
case 2:
free(cte->hour.val);
+ /* fallthrough */
case 1:
free(cte->min.val);
}
diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c
@@ -56,6 +56,7 @@ main(int argc, char *argv[])
switch ((pid = fork())) {
case -1:
eprintf("fork:");
+ /* fallthrough */
case 0:
if (oflag && close(fd) < 0)
eprintf("close:");
diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c
@@ -16,7 +16,7 @@ digitsleft(const char *d)
exp = strpbrk(d, "eE");
shift = exp ? estrtonum(exp + 1, INT_MIN, INT_MAX) : 0;
- return MAX(0, strspn(d, "-0123456789") + shift);
+ return MAX(0, (int)strspn(d, "-0123456789") + shift);
}
static int
diff --git a/cmd/pseudo/stat.c b/cmd/pseudo/stat.c
@@ -1,15 +1,404 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/stat.h>
-#include <sys/sysmacros.h>
-#include <sys/types.h>
+#include "config.h"
+#include "util.h"
+#include <grp.h>
#include <inttypes.h>
+#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <sys/types.h>
+#include <sys/vfs.h>
#include <time.h>
#include <unistd.h>
-#include "util.h"
+static void
+mode_to_str(mode_t mode, char *buf)
+{
+ buf[0] = S_ISDIR(mode) ? 'd' :
+ S_ISLNK(mode) ? 'l' :
+ S_ISCHR(mode) ? 'c' :
+ S_ISBLK(mode) ? 'b' :
+ S_ISFIFO(mode) ? 'p' :
+ S_ISSOCK(mode) ? 's' : '-';
+ buf[1] = (mode & S_IRUSR) ? 'r' : '-';
+ buf[2] = (mode & S_IWUSR) ? 'w' : '-';
+ buf[3] = (mode & S_IXUSR) ?
+ ((mode & S_ISUID) ? 's' : 'x') :
+ ((mode & S_ISUID) ? 'S' : '-');
+ buf[4] = (mode & S_IRGRP) ? 'r' : '-';
+ buf[5] = (mode & S_IWGRP) ? 'w' : '-';
+ buf[6] = (mode & S_IXGRP) ?
+ ((mode & S_ISGID) ? 's' : 'x') :
+ ((mode & S_ISGID) ? 'S' : '-');
+ buf[7] = (mode & S_IROTH) ? 'r' : '-';
+ buf[8] = (mode & S_IWOTH) ? 'w' : '-';
+ buf[9] = (mode & S_IXOTH) ?
+ ((mode & S_ISVTX) ? 't' : 'x') :
+ ((mode & S_ISVTX) ? 'T' : '-');
+ buf[10] = '\0';
+}
+
+#if FEATURE_STAT_FORMAT
+static void
+print_custom(const char *file, struct stat *st, const char *fmt)
+{
+ const char *p;
+ char fmt_spec[64];
+ int fmt_len;
+ char buf[32];
+ struct passwd *pw;
+ struct group *gr;
+
+ for (p = fmt; *p; ) {
+ if (*p == '\\') {
+ p++;
+ switch (*p) {
+ case 'n': putchar('\n'); break;
+ case 't': putchar('\t'); break;
+ case 'r': putchar('\r'); break;
+ case 'b': putchar('\b'); break;
+ case 'f': putchar('\f'); break;
+ case '\\': putchar('\\'); break;
+ case '\0': return;
+ default: putchar(*p); break;
+ }
+ p++;
+ continue;
+ }
+ if (*p != '%') {
+ putchar(*p);
+ p++;
+ continue;
+ }
+ p++;
+ if (*p == '%') {
+ putchar('%');
+ p++;
+ continue;
+ }
+ fmt_spec[0] = '%';
+ fmt_len = 1;
+ while (*p == '-' || *p == '+' || *p == '0' || *p == ' ' || *p == '#') {
+ if (fmt_len < 60)
+ fmt_spec[fmt_len++] = *p;
+ p++;
+ }
+ while (*p >= '0' && *p <= '9') {
+ if (fmt_len < 60)
+ fmt_spec[fmt_len++] = *p;
+ p++;
+ }
+ switch (*p) {
+ case 'a':
+ fmt_spec[fmt_len++] = 'o';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned int)(st->st_mode & 0777));
+ break;
+ case 'A':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ mode_to_str(st->st_mode, buf);
+ printf(fmt_spec, buf);
+ break;
+ case 'b':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long long)st->st_blocks);
+ break;
+ case 'B':
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, 512U);
+ break;
+ case 'd':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long long)st->st_dev);
+ break;
+ case 'D':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'x';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long long)st->st_dev);
+ break;
+ case 'g':
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, st->st_gid);
+ break;
+ case 'G':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ gr = getgrgid(st->st_gid);
+ printf(fmt_spec, gr ? gr->gr_name : "");
+ break;
+ case 'h':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long)st->st_nlink);
+ break;
+ case 'i':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long)st->st_ino);
+ break;
+ case 'n':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, file);
+ break;
+ case 'o':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long)st->st_blksize);
+ break;
+ case 's':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->st_size);
+ break;
+ case 't':
+ fmt_spec[fmt_len++] = 'x';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, major(st->st_rdev));
+ break;
+ case 'T':
+ fmt_spec[fmt_len++] = 'x';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, minor(st->st_rdev));
+ break;
+ case 'u':
+ fmt_spec[fmt_len++] = 'u';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, st->st_uid);
+ break;
+ case 'U':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ pw = getpwuid(st->st_uid);
+ printf(fmt_spec, pw ? pw->pw_name : "");
+ break;
+ case 'X':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->st_atime);
+ break;
+ case 'Y':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->st_mtime);
+ break;
+ case 'Z':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->st_ctime);
+ break;
+ default:
+ putchar('%');
+ if (*p) {
+ putchar(*p);
+ } else {
+ return;
+ }
+ break;
+ }
+ p++;
+ }
+ putchar('\n');
+}
+#endif
+
+#if FEATURE_STAT_FILESYSTEM
+static const char *
+fs_type_name(long type)
+{
+ switch (type) {
+ case 0x9fa0: return "proc";
+ case 0x62656567: return "beegfs";
+ case 0xef53: return "ext2/ext3";
+ case 0x1cd1: return "devpctld";
+ case 0xf15f: return "ecryptfs";
+ case 0x65737566: return "fuse";
+ case 0x4d44: return "msdos";
+ case 0x564c: return "novell";
+ case 0x6969: return "nfs";
+ case 0x534f4654: return "overlay";
+ case 0x73717368: return "squashfs";
+ case 0x01021994: return "tmpfs";
+ case 0x858458f6: return "ramfs";
+ default: return "unknown";
+ }
+}
+
+static void
+show_statfs(const char *file, struct statfs *st)
+{
+ printf(" File: \"%s\"\n", file);
+ printf(" ID: %llx Namelen: %ld Type: %s\n",
+ (unsigned long long)st->f_fsid.__val[0] | ((unsigned long long)st->f_fsid.__val[1] << 32),
+ (long)st->f_namelen, fs_type_name(st->f_type));
+ printf("Block size: %-10ld Fundamental block size: %ld\n",
+ (long)st->f_bsize, (long)st->f_frsize ? (long)st->f_frsize : (long)st->f_bsize);
+ printf("Blocks: Total: %-10lld Free: %-10lld Available: %lld\n",
+ (long long)st->f_blocks, (long long)st->f_bfree, (long long)st->f_bavail);
+ printf("Inodes: Total: %-10lld Free: %lld\n",
+ (long long)st->f_files, (long long)st->f_ffree);
+}
+
+#if FEATURE_STAT_FORMAT
+static void
+print_fs_custom(const char *file, struct statfs *st, const char *fmt)
+{
+ const char *p;
+ char fmt_spec[64];
+ int fmt_len;
+
+ for (p = fmt; *p; ) {
+ if (*p == '\\') {
+ p++;
+ switch (*p) {
+ case 'n': putchar('\n'); break;
+ case 't': putchar('\t'); break;
+ case 'r': putchar('\r'); break;
+ case 'b': putchar('\b'); break;
+ case 'f': putchar('\f'); break;
+ case '\\': putchar('\\'); break;
+ case '\0': return;
+ default: putchar(*p); break;
+ }
+ p++;
+ continue;
+ }
+ if (*p != '%') {
+ putchar(*p);
+ p++;
+ continue;
+ }
+ p++;
+ if (*p == '%') {
+ putchar('%');
+ p++;
+ continue;
+ }
+ fmt_spec[0] = '%';
+ fmt_len = 1;
+ while (*p == '-' || *p == '+' || *p == '0' || *p == ' ' || *p == '#') {
+ if (fmt_len < 60)
+ fmt_spec[fmt_len++] = *p;
+ p++;
+ }
+ while (*p >= '0' && *p <= '9') {
+ if (fmt_len < 60)
+ fmt_spec[fmt_len++] = *p;
+ p++;
+ }
+ switch (*p) {
+ case 'a':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->f_bavail);
+ break;
+ case 'b':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->f_blocks);
+ break;
+ case 'c':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->f_files);
+ break;
+ case 'd':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->f_ffree);
+ break;
+ case 'f':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long long)st->f_bfree);
+ break;
+ case 'i':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'x';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (unsigned long long)st->f_fsid.__val[0] | ((unsigned long long)st->f_fsid.__val[1] << 32));
+ break;
+ case 'l':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->f_namelen);
+ break;
+ case 'n':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, file);
+ break;
+ case 's':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->f_bsize);
+ break;
+ case 'S':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'd';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->f_frsize ? (long)st->f_frsize : (long)st->f_bsize);
+ break;
+ case 't':
+ fmt_spec[fmt_len++] = 'l';
+ fmt_spec[fmt_len++] = 'x';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, (long)st->f_type);
+ break;
+ case 'T':
+ fmt_spec[fmt_len++] = 's';
+ fmt_spec[fmt_len] = '\0';
+ printf(fmt_spec, fs_type_name(st->f_type));
+ break;
+ default:
+ putchar('%');
+ if (*p) {
+ putchar(*p);
+ } else {
+ return;
+ }
+ break;
+ }
+ p++;
+ }
+ putchar('\n');
+}
+#endif
+#endif
static void
show_stat_terse(const char *file, struct stat *st)
@@ -47,13 +436,27 @@ show_stat(const char *file, struct stat *st)
static void
usage(void)
{
- eprintf("usage: %s [-L] [-t] [file...]\n", argv0);
+ eprintf("usage: %s [-L] [-t]"
+#if FEATURE_STAT_FILESYSTEM
+ " [-f]"
+#endif
+#if FEATURE_STAT_FORMAT
+ " [-c format]"
+#endif
+ " [file...]\n", argv0);
}
int
main(int argc, char *argv[])
{
struct stat st;
+#if FEATURE_STAT_FILESYSTEM
+ struct statfs stfs;
+ int fflag = 0;
+#endif
+#if FEATURE_STAT_FORMAT
+ char *format = NULL;
+#endif
int i, ret = 0;
int (*fn)(const char *, struct stat *) = lstat;
char *fnname = "lstat";
@@ -67,23 +470,76 @@ main(int argc, char *argv[])
case 't':
showstat = show_stat_terse;
break;
+#if FEATURE_STAT_FILESYSTEM
+ case 'f':
+ fflag = 1;
+ break;
+#endif
+#if FEATURE_STAT_FORMAT
+ case 'c':
+ format = EARGF(usage());
+ break;
+#endif
default:
usage();
} ARGEND;
if (argc == 0) {
- if (fstat(0, &st) < 0)
- eprintf("stat <stdin>:");
- show_stat("<stdin>", &st);
+#if FEATURE_STAT_FILESYSTEM
+ if (fflag) {
+ if (fstatfs(0, &stfs) < 0)
+ eprintf("fstatfs <stdin>:");
+#if FEATURE_STAT_FORMAT
+ if (format)
+ print_fs_custom("<stdin>", &stfs, format);
+ else
+#endif
+ show_statfs("<stdin>", &stfs);
+ } else {
+#endif
+ if (fstat(0, &st) < 0)
+ eprintf("fstat <stdin>:");
+#if FEATURE_STAT_FORMAT
+ if (format)
+ print_custom("<stdin>", &st, format);
+ else
+#endif
+ show_stat("<stdin>", &st);
+#if FEATURE_STAT_FILESYSTEM
+ }
+#endif
}
for (i = 0; i < argc; i++) {
- if (fn(argv[i], &st) == -1) {
- weprintf("%s %s:", fnname, argv[i]);
- ret = 1;
- continue;
+#if FEATURE_STAT_FILESYSTEM
+ if (fflag) {
+ if (statfs(argv[i], &stfs) == -1) {
+ weprintf("statfs %s:", argv[i]);
+ ret = 1;
+ continue;
+ }
+#if FEATURE_STAT_FORMAT
+ if (format)
+ print_fs_custom(argv[i], &stfs, format);
+ else
+#endif
+ show_statfs(argv[i], &stfs);
+ } else {
+#endif
+ if (fn(argv[i], &st) == -1) {
+ weprintf("%s %s:", fnname, argv[i]);
+ ret = 1;
+ continue;
+ }
+#if FEATURE_STAT_FORMAT
+ if (format)
+ print_custom(argv[i], &st, format);
+ else
+#endif
+ showstat(argv[i], &st);
+#if FEATURE_STAT_FILESYSTEM
}
- showstat(argv[i], &st);
+#endif
}
return ret;
diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c
@@ -1,26 +1,24 @@
-/* See LICENSE file for copyright and license details. */
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#ifndef major
-#include <sys/sysmacros.h>
-#endif
+#include "config.h"
+#include "fs.h"
+#include "utf.h"
+#include "util.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
+#include <fnmatch.h>
#include <grp.h>
#include <libgen.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <sys/time.h>
+#include <sys/types.h>
#include <unistd.h>
-#include "fs.h"
-#include "utf.h"
-#include "util.h"
-
#ifdef STD_NON_POSIX
static void
safe_puts(const char *s)
@@ -98,6 +96,33 @@ static dev_t tardev;
static int mflag, vflag;
static int filtermode;
+
+#if FEATURE_TAR_EXCLUDE
+static char **excludes = NULL;
+static size_t excludes_cnt = 0;
+
+static void
+add_exclude(const char *pattern)
+{
+ excludes = ereallocarray(excludes, excludes_cnt + 1, sizeof(*excludes));
+ excludes[excludes_cnt++] = estrdup(pattern);
+}
+
+static int
+is_excluded(const char *path)
+{
+ size_t i;
+ const char *base = strrchr(path, '/');
+ base = base ? base + 1 : path;
+
+ for (i = 0; i < excludes_cnt; i++) {
+ if (fnmatch(excludes[i], path, 0) == 0 ||
+ fnmatch(excludes[i], base, 0) == 0)
+ return 1;
+ }
+ return 0;
+}
+#endif
static const char *filtertool;
static const char *filtertools[] = {
@@ -138,6 +163,7 @@ comp(int fd, const char *tool, const char *flags)
switch (fork()) {
case -1:
eprintf("fork:");
+ /* fallthrough */
case 0:
dup2(fd, 1);
dup2(fds[0], 0);
@@ -163,6 +189,7 @@ decomp(int fd, const char *tool, const char *flags)
switch (fork()) {
case -1:
eprintf("fork:");
+ /* fallthrough */
case 0:
dup2(fd, 0);
dup2(fds[1], 1);
@@ -197,7 +224,7 @@ ewrite(int fd, const void *buf, size_t n)
{
ssize_t r;
- if ((r = write(fd, buf, n)) != n)
+ if ((r = write(fd, buf, n)) < 0 || (size_t)r != n)
eprintf("write:");
return r;
}
@@ -213,6 +240,7 @@ chksum(struct header *h)
return sum;
}
+#if FEATURE_TAR_CREATE
static void
putoctal(char *dst, unsigned num, int size)
{
@@ -224,8 +252,17 @@ static int
archive(const char *path)
{
static const struct header blank = {
- "././@LongLink", "0000600", "0000000", "0000000", "00000000000",
- "00000000000" , " ", AREG , "" , "ustar", "00",
+ .name = "././@LongLink",
+ .mode = "0000600",
+ .uid = "0000000",
+ .gid = "0000000",
+ .size = "00000000000",
+ .mtime = "00000000000",
+ .chksum = " ",
+ .type = AREG,
+ .linkname = "",
+ .magic = "ustar",
+ .version = { '0', '0' }
};
char b[BLKSIZ + BLKSIZ], *p;
struct header *h = (struct header *)b;
@@ -247,7 +284,7 @@ archive(const char *path)
*h = blank;
n = strlcpy(h->name, path, sizeof(h->name));
- if (n >= sizeof(h->name)) {
+ if ((size_t)n >= sizeof(h->name)) {
*++h = blank;
h->type = 'L';
putoctal(h->size, n, sizeof(h->size));
@@ -255,9 +292,9 @@ archive(const char *path)
ewrite(tarfd, (char *)h, BLKSIZ);
for (p = (char *)path; n > 0; n -= BLKSIZ, p += BLKSIZ) {
- if (n < BLKSIZ) {
+ if ((size_t)n < BLKSIZ) {
p = memcpy(h--, p, n);
- memset(p + n, 0, BLKSIZ - n);
+ memset(p + n, 0, BLKSIZ - (size_t)n);
}
ewrite(tarfd, p, BLKSIZ);
}
@@ -296,8 +333,8 @@ archive(const char *path)
if (fd != -1) {
while ((l = eread(fd, b, BLKSIZ)) > 0) {
- if (l < BLKSIZ)
- memset(b + l, 0, BLKSIZ - l);
+ if ((size_t)l < BLKSIZ)
+ memset(b + l, 0, BLKSIZ - (size_t)l);
ewrite(tarfd, b, BLKSIZ);
}
close(fd);
@@ -305,6 +342,7 @@ archive(const char *path)
return 0;
}
+#endif
static int
unarchive(char *fname, ssize_t l, char b[BLKSIZ])
@@ -420,14 +458,21 @@ skipblk(ssize_t l)
static int
print(char *fname, ssize_t l, char b[BLKSIZ])
{
+ (void)b;
safe_puts(fname);
skipblk(l);
return 0;
}
+#if FEATURE_TAR_CREATE
static void
c(int dirfd, const char *name, struct stat *st, void *data, struct recursor *r)
{
+ (void)data;
+#if FEATURE_TAR_EXCLUDE
+ if (is_excluded(r->path))
+ return;
+#endif
archive(r->path);
if (vflag)
safe_puts(r->path);
@@ -435,6 +480,7 @@ c(int dirfd, const char *name, struct stat *st, void *data, struct recursor *r)
if (S_ISDIR(st->st_mode))
recurse(dirfd, name, NULL, r);
}
+#endif
static void
sanitize(struct header *h)
@@ -489,7 +535,7 @@ chktar(struct header *h)
tmp[i] = '\0';
}
sum = strtol(tmp, &err, 8);
- if (sum < 0 || sum >= BLKSIZ*256 || *err != '\0') {
+ if (sum < 0 || sum >= (long)(BLKSIZ*256) || *err != '\0') {
reason = "invalid checksum";
goto bad;
}
@@ -594,27 +640,40 @@ int argn;
static void
usage(void)
{
+#if FEATURE_TAR_CREATE
eprintf("usage: %s [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p] "
"[-f file] [file ...]\n"
" %s [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] path ... "
"[-f file]\n", argv0, argv0);
+#else
+ eprintf("usage: %s [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p] "
+ "[-f file] [file ...]\n", argv0);
+#endif
}
int
main(int argc, char *argv[])
{
+#if FEATURE_TAR_CREATE
struct recursor r = { .fn = c, .follow = 'P', .flags = DIRFIRST };
+#endif
struct stat st;
char *file = NULL, *dir = ".", mode = '\0';
int fd;
argv0 = argv[0];
+#if FEATURE_TAR_CREATE
if (argc > 1 && strchr("cxt", mode = *argv[1]))
+#else
+ if (argc > 1 && strchr("xt", mode = *argv[1]))
+#endif
*(argv[1]+1) ? *argv[1] = '-' : (*++argv = argv0, --argc);
ARGBEGIN {
case 'x':
+#if FEATURE_TAR_CREATE
case 'c':
+#endif
case 't':
mode = ARGC();
break;
@@ -636,18 +695,35 @@ main(int argc, char *argv[])
filtertool = filtertools[filtermode];
break;
case 'h':
+#if FEATURE_TAR_CREATE
r.follow = 'L';
+#endif
break;
case 'v':
vflag = 1;
break;
case 'p':
- break; /* Do nothing as already default behaviour */
+ break; /* do nothing as already default behaviour */
+#if FEATURE_TAR_EXCLUDE
+ case '-':
+ if (strncmp(argv[0], "-exclude=", 9) == 0) {
+ add_exclude(argv[0] + 9);
+ brk_ = 1;
+ } else if (strcmp(argv[0], "-exclude") == 0) {
+ argv[0] = "-";
+ add_exclude(EARGF(usage()));
+ brk_ = 1;
+ } else {
+ usage();
+ }
+ break;
+#endif
default:
usage();
} ARGEND
switch (mode) {
+#if FEATURE_TAR_CREATE
case 'c':
if (!argc)
usage();
@@ -670,6 +746,7 @@ main(int argc, char *argv[])
for (; *argv; argc--, argv++)
recurse(AT_FDCWD, *argv, NULL, &r);
break;
+#endif
case 't':
case 'x':
tarfd = 0;
@@ -693,5 +770,13 @@ main(int argc, char *argv[])
usage();
}
+#if FEATURE_TAR_EXCLUDE
+ if (excludes) {
+ size_t i;
+ for (i = 0; i < excludes_cnt; i++)
+ free(excludes[i]);
+ free(excludes);
+ }
+#endif
return recurse_status;
}
diff --git a/cmd/pseudo/xinstall.c b/cmd/pseudo/xinstall.c
@@ -45,6 +45,8 @@ install(const char *s1, const char *s2, int depth)
{
int f1, f2;
+ (void)depth;
+
if ((f1 = open(s1, O_RDONLY)) < 0)
eprintf("open %s:", s1);
if ((f2 = creat(s2, 0600)) < 0) {
diff --git a/config.mk b/config.mk
@@ -7,6 +7,214 @@ RANLIB = ranlib
AR = ar
ARFLAGS = rc
+# build toggles for groups of binaries
+BUILD_POSIX = 1
+BUILD_LINUX = 1
+BUILD_NET = 1
+BUILD_XSI = 1
+BUILD_PSEUDO = 1
+BUILD_MAKE = 1
+
+# posix tools
+BUILD_POSIX_BASENAME = $(BUILD_POSIX)
+BUILD_POSIX_CAL = $(BUILD_POSIX)
+BUILD_POSIX_CAT = $(BUILD_POSIX)
+BUILD_POSIX_CHGRP = $(BUILD_POSIX)
+BUILD_POSIX_CHMOD = $(BUILD_POSIX)
+BUILD_POSIX_CHOWN = $(BUILD_POSIX)
+BUILD_POSIX_CKSUM = $(BUILD_POSIX)
+BUILD_POSIX_CMP = $(BUILD_POSIX)
+BUILD_POSIX_COMM = $(BUILD_POSIX)
+BUILD_POSIX_CP = $(BUILD_POSIX)
+BUILD_POSIX_CUT = $(BUILD_POSIX)
+BUILD_POSIX_DATE = $(BUILD_POSIX)
+BUILD_POSIX_DD = $(BUILD_POSIX)
+BUILD_POSIX_DF = $(BUILD_POSIX)
+BUILD_POSIX_DIRNAME = $(BUILD_POSIX)
+BUILD_POSIX_DU = $(BUILD_POSIX)
+BUILD_POSIX_ECHO = $(BUILD_POSIX)
+BUILD_POSIX_ED = $(BUILD_POSIX)
+BUILD_POSIX_ENV = $(BUILD_POSIX)
+BUILD_POSIX_EXPAND = $(BUILD_POSIX)
+BUILD_POSIX_EXPR = $(BUILD_POSIX)
+BUILD_POSIX_FALSE = $(BUILD_POSIX)
+BUILD_POSIX_FIND = $(BUILD_POSIX)
+BUILD_POSIX_FOLD = $(BUILD_POSIX)
+BUILD_POSIX_GETCONF = $(BUILD_POSIX)
+BUILD_POSIX_GREP = $(BUILD_POSIX)
+BUILD_POSIX_HEAD = $(BUILD_POSIX)
+BUILD_POSIX_ID = $(BUILD_POSIX)
+BUILD_POSIX_JOIN = $(BUILD_POSIX)
+BUILD_POSIX_KILL = $(BUILD_POSIX)
+BUILD_POSIX_LINK = $(BUILD_POSIX)
+BUILD_POSIX_LN = $(BUILD_POSIX)
+BUILD_POSIX_LOGGER = $(BUILD_POSIX)
+BUILD_POSIX_LOGNAME = $(BUILD_POSIX)
+BUILD_POSIX_LS = $(BUILD_POSIX)
+BUILD_POSIX_MESG = $(BUILD_POSIX)
+BUILD_POSIX_MKDIR = $(BUILD_POSIX)
+BUILD_POSIX_MKFIFO = $(BUILD_POSIX)
+BUILD_POSIX_MV = $(BUILD_POSIX)
+BUILD_POSIX_NICE = $(BUILD_POSIX)
+BUILD_POSIX_NL = $(BUILD_POSIX)
+BUILD_POSIX_NOHUP = $(BUILD_POSIX)
+BUILD_POSIX_OD = $(BUILD_POSIX)
+BUILD_POSIX_PASTE = $(BUILD_POSIX)
+BUILD_POSIX_PATHCHK = $(BUILD_POSIX)
+BUILD_POSIX_PRINTF = $(BUILD_POSIX)
+BUILD_POSIX_PS = $(BUILD_POSIX)
+BUILD_POSIX_PWD = $(BUILD_POSIX)
+BUILD_POSIX_READLINK = $(BUILD_POSIX)
+BUILD_POSIX_RENICE = $(BUILD_POSIX)
+BUILD_POSIX_RM = $(BUILD_POSIX)
+BUILD_POSIX_RMDIR = $(BUILD_POSIX)
+BUILD_POSIX_SED = $(BUILD_POSIX)
+BUILD_POSIX_SLEEP = $(BUILD_POSIX)
+BUILD_POSIX_SORT = $(BUILD_POSIX)
+BUILD_POSIX_SPLIT = $(BUILD_POSIX)
+BUILD_POSIX_TAIL = $(BUILD_POSIX)
+BUILD_POSIX_TEE = $(BUILD_POSIX)
+BUILD_POSIX_TEST = $(BUILD_POSIX)
+BUILD_POSIX_TIME = $(BUILD_POSIX)
+BUILD_POSIX_TOUCH = $(BUILD_POSIX)
+BUILD_POSIX_TR = $(BUILD_POSIX)
+BUILD_POSIX_TRUE = $(BUILD_POSIX)
+BUILD_POSIX_TSORT = $(BUILD_POSIX)
+BUILD_POSIX_TTY = $(BUILD_POSIX)
+BUILD_POSIX_UNAME = $(BUILD_POSIX)
+BUILD_POSIX_UNEXPAND = $(BUILD_POSIX)
+BUILD_POSIX_UNIQ = $(BUILD_POSIX)
+BUILD_POSIX_UNLINK = $(BUILD_POSIX)
+BUILD_POSIX_UUDECODE = $(BUILD_POSIX)
+BUILD_POSIX_UUENCODE = $(BUILD_POSIX)
+BUILD_POSIX_WC = $(BUILD_POSIX)
+BUILD_POSIX_WHO = $(BUILD_POSIX)
+BUILD_POSIX_XARGS = $(BUILD_POSIX)
+BUILD_POSIX_AWK = $(BUILD_POSIX)
+BUILD_POSIX_SH = $(BUILD_POSIX)
+BUILD_POSIX_PAX = $(BUILD_POSIX)
+
+# linux tools
+BUILD_LINUX_BLKDISCARD = $(BUILD_LINUX)
+BUILD_LINUX_CHVT = $(BUILD_LINUX)
+BUILD_LINUX_CTRLALTDEL = $(BUILD_LINUX)
+BUILD_LINUX_DMESG = $(BUILD_LINUX)
+BUILD_LINUX_EJECT = $(BUILD_LINUX)
+BUILD_LINUX_FALLOCATE = $(BUILD_LINUX)
+BUILD_LINUX_FREE = $(BUILD_LINUX)
+BUILD_LINUX_FREERAMDISK = $(BUILD_LINUX)
+BUILD_LINUX_FSFREEZE = $(BUILD_LINUX)
+BUILD_LINUX_HWCLOCK = $(BUILD_LINUX)
+BUILD_LINUX_INSMOD = $(BUILD_LINUX)
+BUILD_LINUX_LSMOD = $(BUILD_LINUX)
+BUILD_LINUX_MKSWAP = $(BUILD_LINUX)
+BUILD_LINUX_MOUNT = $(BUILD_LINUX)
+BUILD_LINUX_MOUNTPOINT = $(BUILD_LINUX)
+BUILD_LINUX_PIDOF = $(BUILD_LINUX)
+BUILD_LINUX_PIVOT_ROOT = $(BUILD_LINUX)
+BUILD_LINUX_PWDX = $(BUILD_LINUX)
+BUILD_LINUX_READAHEAD = $(BUILD_LINUX)
+BUILD_LINUX_RMMOD = $(BUILD_LINUX)
+BUILD_LINUX_SWAPLABEL = $(BUILD_LINUX)
+BUILD_LINUX_SWAPOFF = $(BUILD_LINUX)
+BUILD_LINUX_SWAPON = $(BUILD_LINUX)
+BUILD_LINUX_SWITCH_ROOT = $(BUILD_LINUX)
+BUILD_LINUX_UMOUNT = $(BUILD_LINUX)
+BUILD_LINUX_UNSHARE = $(BUILD_LINUX)
+BUILD_LINUX_UPTIME = $(BUILD_LINUX)
+BUILD_LINUX_VTALLOW = $(BUILD_LINUX)
+
+# net tools
+BUILD_NET_NETCAT = $(BUILD_NET)
+BUILD_NET_TFTP = $(BUILD_NET)
+BUILD_NET_TUNCTL = $(BUILD_NET)
+BUILD_NET_WGET = $(BUILD_NET)
+BUILD_NET_PING = $(BUILD_NET)
+BUILD_NET_IFCONFIG = $(BUILD_NET)
+BUILD_NET_HOST = $(BUILD_NET)
+BUILD_NET_HTTPD = $(BUILD_NET)
+
+# xsi tools
+BUILD_XSI_MKNOD = $(BUILD_XSI)
+BUILD_XSI_PASSWD = $(BUILD_XSI)
+BUILD_XSI_SU = $(BUILD_XSI)
+
+# pseudo tools
+BUILD_PSEUDO_CHROOT = $(BUILD_PSEUDO)
+BUILD_PSEUDO_CLEAR = $(BUILD_PSEUDO)
+BUILD_PSEUDO_COLS = $(BUILD_PSEUDO)
+BUILD_PSEUDO_CRON = $(BUILD_PSEUDO)
+BUILD_PSEUDO_FLOCK = $(BUILD_PSEUDO)
+BUILD_PSEUDO_GETTY = $(BUILD_PSEUDO)
+BUILD_PSEUDO_HALT = $(BUILD_PSEUDO)
+BUILD_PSEUDO_HOSTNAME = $(BUILD_PSEUDO)
+BUILD_PSEUDO_KILLALL5 = $(BUILD_PSEUDO)
+BUILD_PSEUDO_LAST = $(BUILD_PSEUDO)
+BUILD_PSEUDO_LASTLOG = $(BUILD_PSEUDO)
+BUILD_PSEUDO_LOGIN = $(BUILD_PSEUDO)
+BUILD_PSEUDO_MD5SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_MKTEMP = $(BUILD_PSEUDO)
+BUILD_PSEUDO_NOLOGIN = $(BUILD_PSEUDO)
+BUILD_PSEUDO_PAGESIZE = $(BUILD_PSEUDO)
+BUILD_PSEUDO_PRINTENV = $(BUILD_PSEUDO)
+BUILD_PSEUDO_RESPAWN = $(BUILD_PSEUDO)
+BUILD_PSEUDO_REV = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SEQ = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SETSID = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA1SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA224SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA256SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA384SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA512SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA512_224SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SHA512_256SUM = $(BUILD_PSEUDO)
+BUILD_PSEUDO_SPONGE = $(BUILD_PSEUDO)
+BUILD_PSEUDO_STAT = $(BUILD_PSEUDO)
+BUILD_PSEUDO_TAR = $(BUILD_PSEUDO)
+BUILD_PSEUDO_TRUNCATE = $(BUILD_PSEUDO)
+BUILD_PSEUDO_WATCH = $(BUILD_PSEUDO)
+BUILD_PSEUDO_WHICH = $(BUILD_PSEUDO)
+BUILD_PSEUDO_WHOAMI = $(BUILD_PSEUDO)
+BUILD_PSEUDO_XINSTALL = $(BUILD_PSEUDO)
+BUILD_PSEUDO_YES = $(BUILD_PSEUDO)
+BUILD_PSEUDO_BASE64 = $(BUILD_PSEUDO)
+
+# make tool
+BUILD_MAKE_MAKE = $(BUILD_MAKE)
+
+# feature gates for specific utilities
+FEATURE_FIND_DELETE = 1
+FEATURE_FIND_QUIT = 1
+FEATURE_FIND_EMPTY = 1
+FEATURE_FIND_INUM = 1
+FEATURE_FIND_SAMEFILE = 1
+FEATURE_FIND_MAXDEPTH = 1
+FEATURE_FIND_MINDEPTH = 1
+FEATURE_FIND_MMIN = 1
+FEATURE_FIND_AMIN = 1
+FEATURE_FIND_CMIN = 1
+FEATURE_FIND_INAME = 1
+FEATURE_FIND_IPATH = 1
+FEATURE_FIND_REGEX = 1
+FEATURE_FIND_PRINT0 = 1
+FEATURE_SED_INPLACE = 1
+FEATURE_GREP_CONTEXT = 1
+FEATURE_GREP_MAX_COUNT = 1
+FEATURE_TAR_CREATE = 1
+FEATURE_TAR_EXCLUDE = 1
+FEATURE_STAT_FILESYSTEM = 1
+FEATURE_STAT_FORMAT = 1
+FEATURE_SORT_BIG = 1
+FEATURE_SORT_STABLE = 1
+FEATURE_OD_ENDIAN = 1
+FEATURE_SH_HISTEDIT = 0
+FEATURE_SH_LOCAL = 1
+FEATURE_SH_LET = 1
+FEATURE_SH_ULIMIT = 1
+FEATURE_SH_SETVAR = 1
+FEATURE_SH_WORDEXP = 1
+FEATURE_CAL_EXT = 1
+
CPPFLAGS =\
-Ishared\
-DPREFIX=\"$(PREFIX)\"\
@@ -16,8 +224,41 @@ CPPFLAGS =\
-D_BSD_SOURCE\
-D_XOPEN_SOURCE=700\
-D_FILE_OFFSET_BITS=64\
- -DSTD_NON_POSIX
+ -DSTD_NON_POSIX\
+ -DFEATURE_FIND_DELETE=$(FEATURE_FIND_DELETE)\
+ -DFEATURE_FIND_QUIT=$(FEATURE_FIND_QUIT)\
+ -DFEATURE_FIND_EMPTY=$(FEATURE_FIND_EMPTY)\
+ -DFEATURE_FIND_INUM=$(FEATURE_FIND_INUM)\
+ -DFEATURE_FIND_SAMEFILE=$(FEATURE_FIND_SAMEFILE)\
+ -DFEATURE_FIND_MAXDEPTH=$(FEATURE_FIND_MAXDEPTH)\
+ -DFEATURE_FIND_MINDEPTH=$(FEATURE_FIND_MINDEPTH)\
+ -DFEATURE_FIND_MMIN=$(FEATURE_FIND_MMIN)\
+ -DFEATURE_FIND_AMIN=$(FEATURE_FIND_AMIN)\
+ -DFEATURE_FIND_CMIN=$(FEATURE_FIND_CMIN)\
+ -DFEATURE_FIND_INAME=$(FEATURE_FIND_INAME)\
+ -DFEATURE_FIND_IPATH=$(FEATURE_FIND_IPATH)\
+ -DFEATURE_FIND_REGEX=$(FEATURE_FIND_REGEX)\
+ -DFEATURE_FIND_PRINT0=$(FEATURE_FIND_PRINT0)\
+ -DFEATURE_SED_INPLACE=$(FEATURE_SED_INPLACE)\
+ -DFEATURE_GREP_CONTEXT=$(FEATURE_GREP_CONTEXT)\
+ -DFEATURE_GREP_MAX_COUNT=$(FEATURE_GREP_MAX_COUNT)\
+ -DFEATURE_TAR_CREATE=$(FEATURE_TAR_CREATE)\
+ -DFEATURE_TAR_EXCLUDE=$(FEATURE_TAR_EXCLUDE)\
+ -DFEATURE_STAT_FILESYSTEM=$(FEATURE_STAT_FILESYSTEM)\
+ -DFEATURE_STAT_FORMAT=$(FEATURE_STAT_FORMAT)\
+ -DFEATURE_SORT_BIG=$(FEATURE_SORT_BIG)\
+ -DFEATURE_SORT_STABLE=$(FEATURE_SORT_STABLE)\
+ -DFEATURE_OD_ENDIAN=$(FEATURE_OD_ENDIAN)\
+ -DFEATURE_SH_HISTEDIT=$(FEATURE_SH_HISTEDIT)\
+ -DFEATURE_SH_LOCAL=$(FEATURE_SH_LOCAL)\
+ -DFEATURE_SH_LET=$(FEATURE_SH_LET)\
+ -DFEATURE_SH_ULIMIT=$(FEATURE_SH_ULIMIT)\
+ -DFEATURE_SH_SETVAR=$(FEATURE_SH_SETVAR)\
+ -DFEATURE_SH_WORDEXP=$(FEATURE_SH_WORDEXP)\
+ -DFEATURE_CAL_EXT=$(FEATURE_CAL_EXT)
CFLAGS = -std=c99 -Wall -Wextra -pedantic
LDFLAGS =
-LDLIBS = -lcrypt -lresolv
+LDLIBS_HISTEDIT_0 =
+LDLIBS_HISTEDIT_1 = -ledit
+LDLIBS = -lcrypt -lresolv $(LDLIBS_HISTEDIT_$(FEATURE_SH_HISTEDIT))
diff --git a/shared/config.h b/shared/config.h
@@ -1,10 +1,83 @@
/* See LICENSE file for copyright and license details. */
-#define ENV_PATH "/bin"
-#define PW_CIPHER "$6$" /* SHA-512 */
+#define ENV_PATH "/bin"
+#define PW_CIPHER "$6$" /* sha-512 */
#undef UTMP_PATH
-#define UTMP_PATH "/var/run/utmp"
+#define UTMP_PATH "/var/run/utmp"
#undef BTMP_PATH
-#define BTMP_PATH "/var/log/btmp"
+#define BTMP_PATH "/var/log/btmp"
#undef WTMP_PATH
-#define WTMP_PATH "/var/log/wtmp"
+#define WTMP_PATH "/var/log/wtmp"
+
+#ifndef FEATURE_FIND_DELETE
+#define FEATURE_FIND_DELETE 1
+#endif
+#ifndef FEATURE_FIND_QUIT
+#define FEATURE_FIND_QUIT 1
+#endif
+#ifndef FEATURE_FIND_EMPTY
+#define FEATURE_FIND_EMPTY 1
+#endif
+#ifndef FEATURE_FIND_INUM
+#define FEATURE_FIND_INUM 1
+#endif
+#ifndef FEATURE_FIND_SAMEFILE
+#define FEATURE_FIND_SAMEFILE 1
+#endif
+#ifndef FEATURE_FIND_MAXDEPTH
+#define FEATURE_FIND_MAXDEPTH 1
+#endif
+#ifndef FEATURE_FIND_MINDEPTH
+#define FEATURE_FIND_MINDEPTH 1
+#endif
+#ifndef FEATURE_FIND_MMIN
+#define FEATURE_FIND_MMIN 1
+#endif
+#ifndef FEATURE_FIND_AMIN
+#define FEATURE_FIND_AMIN 1
+#endif
+#ifndef FEATURE_FIND_CMIN
+#define FEATURE_FIND_CMIN 1
+#endif
+#ifndef FEATURE_FIND_INAME
+#define FEATURE_FIND_INAME 1
+#endif
+#ifndef FEATURE_FIND_IPATH
+#define FEATURE_FIND_IPATH 1
+#endif
+#ifndef FEATURE_FIND_REGEX
+#define FEATURE_FIND_REGEX 1
+#endif
+#ifndef FEATURE_FIND_PRINT0
+#define FEATURE_FIND_PRINT0 1
+#endif
+#ifndef FEATURE_SED_INPLACE
+#define FEATURE_SED_INPLACE 1
+#endif
+#ifndef FEATURE_GREP_CONTEXT
+#define FEATURE_GREP_CONTEXT 1
+#endif
+#ifndef FEATURE_GREP_MAX_COUNT
+#define FEATURE_GREP_MAX_COUNT 1
+#endif
+#ifndef FEATURE_TAR_CREATE
+#define FEATURE_TAR_CREATE 1
+#endif
+#ifndef FEATURE_TAR_EXCLUDE
+#define FEATURE_TAR_EXCLUDE 1
+#endif
+#ifndef FEATURE_STAT_FILESYSTEM
+#define FEATURE_STAT_FILESYSTEM 1
+#endif
+#ifndef FEATURE_STAT_FORMAT
+#define FEATURE_STAT_FORMAT 1
+#endif
+#ifndef FEATURE_SORT_BIG
+#define FEATURE_SORT_BIG 1
+#endif
+#ifndef FEATURE_SORT_STABLE
+#define FEATURE_SORT_STABLE 1
+#endif
+#ifndef FEATURE_OD_ENDIAN
+#define FEATURE_OD_ENDIAN 1
+#endif
diff --git a/shared/libutil/crypt.c b/shared/libutil/crypt.c
@@ -54,7 +54,7 @@ mdchecklist(FILE *listfp, struct crypt_ops *ops, uint8_t *md, size_t sz,
(*formatsucks)++;
continue;
}
- if (file - line != sz * 2) {
+ if ((size_t)(file - line) != sz * 2) {
(*formatsucks)++; /* checksum length mismatch */
continue;
}
diff --git a/shared/libutil/enmasse.c b/shared/libutil/enmasse.c
@@ -29,7 +29,7 @@ enmasse(int argc, char *argv[], int (*fn)(const char *, const char *, int))
len = snprintf(buf, sizeof(buf), "%s%s", dir, basename(argv[i]));
else
len = snprintf(buf, sizeof(buf), "%s/%s", dir, basename(argv[i]));
- if (len < 0 || len >= sizeof(buf)) {
+ if (len < 0 || (size_t)len >= sizeof(buf)) {
eprintf("%s/%s: filename too long\n", dir,
basename(argv[i]));
}
diff --git a/shared/libutil/human.c b/shared/libutil/human.c
@@ -13,7 +13,7 @@ humansize(off_t n)
double size;
int i;
- for (size = n, i = 0; size >= 1024 && i < strlen(postfixes); i++)
+ for (size = n, i = 0; size >= 1024 && i < (int)strlen(postfixes); i++)
size /= 1024;
if (!i)
diff --git a/shared/libutil/rm.c b/shared/libutil/rm.c
@@ -16,6 +16,8 @@ rm(int dirfd, const char *name, struct stat *st, void *data, struct recursor *r)
{
int quiet, ask, write, flags, ignore;
+ (void)data;
+
ignore = r->flags & IGNORE;
quiet = r->flags & SILENT;
ask = r->flags & CONFIRM;
@@ -27,7 +29,7 @@ rm(int dirfd, const char *name, struct stat *st, void *data, struct recursor *r)
goto err;
}
- if (!quiet && (!write && isatty(0) || ask)) {
+ if (!quiet && ((!write && isatty(0)) || ask)) {
if (!confirm("remove file '%s'? ", r->path))
return;
}
diff --git a/shared/libutil/sig.c b/shared/libutil/sig.c
@@ -0,0 +1,163 @@
+/* See LICENSE file for copyright and license details. */
+#include "../sig.h"
+
+#include <signal.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+const char *const aruu_sys_signame[NSIG] = {
+ [0] = "EXIT",
+#ifdef SIGHUP
+ [SIGHUP] = "HUP",
+#endif
+#ifdef SIGINT
+ [SIGINT] = "INT",
+#endif
+#ifdef SIGQUIT
+ [SIGQUIT] = "QUIT",
+#endif
+#ifdef SIGILL
+ [SIGILL] = "ILL",
+#endif
+#ifdef SIGTRAP
+ [SIGTRAP] = "TRAP",
+#endif
+#ifdef SIGABRT
+ [SIGABRT] = "ABRT",
+#endif
+#ifdef SIGBUS
+ [SIGBUS] = "BUS",
+#endif
+#ifdef SIGFPE
+ [SIGFPE] = "FPE",
+#endif
+#ifdef SIGKILL
+ [SIGKILL] = "KILL",
+#endif
+#ifdef SIGUSR1
+ [SIGUSR1] = "USR1",
+#endif
+#ifdef SIGSEGV
+ [SIGSEGV] = "SEGV",
+#endif
+#ifdef SIGUSR2
+ [SIGUSR2] = "USR2",
+#endif
+#ifdef SIGPIPE
+ [SIGPIPE] = "PIPE",
+#endif
+#ifdef SIGALRM
+ [SIGALRM] = "ALRM",
+#endif
+#ifdef SIGTERM
+ [SIGTERM] = "TERM",
+#endif
+#ifdef SIGCHLD
+ [SIGCHLD] = "CHLD",
+#endif
+#ifdef SIGCONT
+ [SIGCONT] = "CONT",
+#endif
+#ifdef SIGSTOP
+ [SIGSTOP] = "STOP",
+#endif
+#ifdef SIGTSTP
+ [SIGTSTP] = "TSTP",
+#endif
+#ifdef SIGTTIN
+ [SIGTTIN] = "TTIN",
+#endif
+#ifdef SIGTTOU
+ [SIGTTOU] = "TTOU",
+#endif
+#ifdef SIGURG
+ [SIGURG] = "URG",
+#endif
+#ifdef SIGXCPU
+ [SIGXCPU] = "XCPU",
+#endif
+#ifdef SIGXFSZ
+ [SIGXFSZ] = "XFSZ",
+#endif
+#ifdef SIGVTALRM
+ [SIGVTALRM] = "VTALRM",
+#endif
+#ifdef SIGPROF
+ [SIGPROF] = "PROF",
+#endif
+#ifdef SIGWINCH
+ [SIGWINCH] = "WINCH",
+#endif
+#ifdef SIGIO
+ [SIGIO] = "IO",
+#endif
+#ifdef SIGPWR
+ [SIGPWR] = "PWR",
+#endif
+#ifdef SIGSYS
+ [SIGSYS] = "SYS",
+#endif
+};
+
+const int aruu_sys_nsig = NSIG;
+
+int
+aruu_sig2str(int signo, char *str)
+{
+ const char *name;
+
+#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+ if (signo <= 0 || signo >= sys_nsig)
+ return -1;
+ name = sys_signame[signo];
+#else
+ if (signo <= 0 || signo >= aruu_sys_nsig)
+ return -1;
+ name = aruu_sys_signame[signo];
+#endif
+
+ if (name == NULL)
+ return -1;
+ strcpy(str, name);
+ return 0;
+}
+
+int
+aruu_str2sig(const char *str, int *signop)
+{
+ int n;
+ const char *s = str;
+ const char *const *table;
+ int limit;
+
+#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+ table = sys_signame;
+ limit = sys_nsig;
+#else
+ table = aruu_sys_signame;
+ limit = aruu_sys_nsig;
+#endif
+
+ if (strncasecmp(s, "SIG", 3) == 0)
+ s += 3;
+
+ /* check if it is a number */
+ char *ep;
+ long l = strtol(s, &ep, 10);
+ if (*s && !*ep) {
+ if (l >= 0 && l < limit) {
+ *signop = (int)l;
+ return 0;
+ }
+ return -1;
+ }
+
+ for (n = 1; n < limit; n++) {
+ if (table[n] && strcasecmp(table[n], s) == 0) {
+ *signop = n;
+ return 0;
+ }
+ }
+ return -1;
+}
diff --git a/shared/libutil/unescape.c b/shared/libutil/unescape.c
@@ -39,7 +39,7 @@ unescape(char *s)
} else if (is_odigit(*r)) {
for (q = 0, m = 3; m && is_odigit(*r); m--, r++)
q = q * 8 + (*r - '0');
- *w++ = MIN(q, 255);
+ *w++ = MIN(q, (size_t)255);
} else if (*r == 'x' && isxdigit(r[1])) {
r++;
for (q = 0, m = 2; m && isxdigit(*r); m--, r++)
diff --git a/shared/sig.h b/shared/sig.h
@@ -0,0 +1,36 @@
+/* See LICENSE file for copyright and license details. */
+#ifndef SIG_H_
+#define SIG_H_
+
+#include <signal.h>
+#include <sys/types.h>
+
+#ifndef SIG2STR_MAX
+#define SIG2STR_MAX 32
+#endif
+
+#ifndef NSIG
+#ifdef _NSIG
+#define NSIG _NSIG
+#else
+#define NSIG 64
+#endif
+#endif
+
+extern const char *const aruu_sys_signame[NSIG];
+extern const int aruu_sys_nsig;
+
+#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+/* system already provides sys_signame and sys_nsig */
+#else
+#define sys_signame aruu_sys_signame
+#define sys_nsig aruu_sys_nsig
+#endif
+
+#define sig2str aruu_sig2str
+#define str2sig aruu_str2sig
+
+int aruu_sig2str(int signo, char *str);
+int aruu_str2sig(const char *str, int *signop);
+
+#endif /* !SIG_H_ */
diff --git a/shared/text.h b/shared/text.h
@@ -1,5 +1,9 @@
/* See LICENSE file for copyright and license details. */
+#include <stddef.h>
+#include <stdio.h>
+#include <sys/types.h>
+
struct line {
char *data;
size_t len;