aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

commit c4b4d741f1e09d1e6a116490e2e173df0186bcff
parent fd3a93f5d70d0950c13e24b7d74faacca2674812
Author: xplshn <anto@xplshn.com.ar>
Date:   Tue, 30 Jun 2026 22:09:02 -0300

clang-format, mkpasswd, lsblk, fdisk, blkid, in-process execution, etc

Signed-off-by: xplshn <anto@xplshn.com.ar>

Diffstat:
MMakefile | 40++++++++++++++++++++++++++--------------
MMakefile.sh | 799++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mbuild.cfg | 22+++++++++++++++++++++-
Mcmd/extra/blkid.c | 193++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/linux/chvt.c | 7++++---
Mcmd/linux/depmod.c | 9+++++----
Mcmd/linux/eject.c | 3++-
Mcmd/linux/freeramdisk.c | 1+
Mcmd/linux/hwclock.c | 3++-
Mcmd/linux/lsmod.c | 3++-
Mcmd/linux/lsusb.c | 3++-
Mcmd/linux/modprobe.c | 3++-
Mcmd/linux/mount.c | 14++++++++------
Mcmd/linux/mountpoint.c | 5+++--
Mcmd/linux/sysctl.c | 330+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/linux/tunctl.c | 1+
Mcmd/linux/umount.c | 5+++--
Mcmd/linux/unshare.c | 5+++--
Mcmd/linux/vtallow.c | 3++-
Mcmd/net/sdhcp.c | 852++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/posix/diff.c | 3987++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/posix/diff3.c | 1284++++++++++++++++++++++++++++---------------------------------------------------
Mcmd/posix/ed.c | 15++++++++-------
Mcmd/posix/env.c | 5+++--
Mcmd/posix/find.c | 3++-
Mcmd/posix/make/main.c | 487++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/posix/make/make.h | 53++++++++++++++++++++++++++---------------------------
Mcmd/posix/make/parser.c | 1893+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mcmd/posix/make/rules.c | 923++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/posix/nice.c | 5+++--
Mcmd/posix/nohup.c | 5+++--
Mcmd/posix/patch.c | 4845+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/eval.c | 6+++---
Mcmd/posix/sh/exec.c | 6+++---
Mcmd/posix/sh/jobs.c | 12++++++------
Mcmd/posix/sh/lineedit.c | 4++--
Mcmd/posix/sh/main.c | 4++--
Mcmd/posix/sh/var.c | 4++--
Mcmd/posix/time.c | 5+++--
Mcmd/posix/xargs.c | 5+++--
Mcmd/pseudo/chroot.c | 7++++---
Mcmd/pseudo/cron.c | 4+++-
Mcmd/pseudo/flock.c | 5+++--
Mcmd/pseudo/getty.c | 231++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/pseudo/last.c | 2+-
Mcmd/pseudo/lastlog.c | 10+++++-----
Mcmd/pseudo/login.c | 5+++--
Mcmd/pseudo/mkpasswd.c | 258+++++++++++++++++++++++++++++++++++--------------------------------------------
Mcmd/pseudo/respawn.c | 5+++--
Mcmd/pseudo/setsid.c | 5+++--
Mcmd/pseudo/tar.c | 1543++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/pseudo/watch.c | 3++-
Mcmd/xsi/mknod.c | 27+++++++++++++--------------
Mcmd/xsi/passwd.c | 279+++++++++++++++----------------------------------------------------------------
Mcmd/xsi/su.c | 32++++++++++++++++++--------------
Mconfig.mk | 146+++++++++++++++++++++++++++++++++++++++++++++----------------------------------
Mdeps.mk | 2252+++++++++++++++++++++++++++++++++++--------------------------------------------
Mscripts/mkbox | 686++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mshared/config.h | 44+++++++++++++++++++++++++++++++++++++++-----
Ashared/diffutil.h | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/diskutil.h | 29++++++++++-------------------
Mshared/libredline/redline.c | 2075++++++++++++++++++++++++++++++++++++++++---------------------------------------
Ashared/libutil/diffutil.c | 586+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/libutil/diskutil.c | 1235++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mshared/libutil/net.c | 907++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mshared/libutil/passwd.c | 423++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mshared/libutil/proc.c | 7++++---
Mshared/libutil/tls.c | 595++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mshared/libutil/tty.c | 131++++++++++++++++++++++++++++++++++++++++---------------------------------------
Ashared/libutil/wexec.c | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/passwd.h | 25+++++++++++++++++++++++--
Ashared/paths.h | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/util.h | 66+++++++++++++++++++++++++++++++++---------------------------------
Ashared/wexec.h | 27+++++++++++++++++++++++++++
74 files changed, 14544 insertions(+), 13463 deletions(-)

diff --git a/Makefile b/Makefile @@ -7,6 +7,7 @@ HDR =\ shared/compat.h\ shared/config.h\ shared/crypt.h\ + shared/wexec.h\ shared/fs.h\ shared/md5.h\ shared/queue.h\ @@ -21,6 +22,7 @@ HDR =\ shared/utf.h\ shared/util.h\ shared/passwd.h\ + shared/paths.h\ shared/reboot.h\ shared/rtc.h\ shared/proc.h\ @@ -52,6 +54,8 @@ LIBUTILOBJ =\ shared/libutil/cp.o\ shared/libutil/crypt.o\ shared/libutil/confirm.o\ + shared/libutil/diffutil.o\ + shared/libutil/wexec.o\ shared/libutil/ealloc.o\ shared/libutil/enmasse.o\ shared/libutil/eprintf.o\ @@ -734,20 +738,28 @@ man: scripts/mkman/mkman done clean: - rm -f shared/libutf/*.o shared/libutil/*.o shared/libredline/*.o - rm -f cmd/posix/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o - rm -f cmd/linux/*.o cmd/net/*.o cmd/xsi/*.o cmd/pseudo/*.o - rm -f cmd/extra/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o cmd/dev/xcutil/*.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 - 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 -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar shared/libaruuelf.so - rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h - rm -rf aruu-box .box man/man1 man/man8 scripts/mkman/mkman - + @printf " CLEAN object files\n" + @find shared cmd -name "*.o" -exec rm -f {} + + @printf " CLEAN static libraries\n" + @rm -f $(LIB) + @printf " CLEAN compiled binaries\n" + @rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) + @printf " CLEAN generated headers\n" + @rm -f cmd/posix/getconf.h cmd/posix/bc.c + @rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h + @rm -f cmd/posix/sh/token.h cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h + @rm -f cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h + @printf " CLEAN generated sources\n" + @rm -f cmd/posix/awk/proctab.c + @printf " CLEAN build tools\n" + @rm -f cmd/posix/awk/maketab cmd/posix/sh/mknodes cmd/posix/sh/mksyntax + @rm -f scripts/mkman/mkman + @printf " CLEAN dev artifacts\n" + @rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar shared/libaruuelf.so + @rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h + @printf " CLEAN misc\n" + @rm -rf aruu-box .box man/man1 man/man8 + @printf " CLEAN done\n" AWKOBJ =\ cmd/posix/awk/b.o\ cmd/posix/awk/main.o\ diff --git a/Makefile.sh b/Makefile.sh @@ -14,15 +14,15 @@ LOAD=0 TARGET=all while [ $# -gt 0 ]; do - case "$1" in - -j) shift; JOBS="${1:?-j requires a number}" ;; - -j*) JOBS="${1#-j}" ;; - -l) shift; LOAD="${1:?-l requires a number}" ;; - -l*) LOAD="${1#-l}" ;; - -*) printf 'unknown flag: %s\n' "$1" >&2; exit 1 ;; - *) TARGET="$1" ;; - esac - shift + case "$1" in + -j) shift; JOBS="${1:?-j requires a number}" ;; + -j*) JOBS="${1#-j}" ;; + -l) shift; LOAD="${1:?-l requires a number}" ;; + -l*) LOAD="${1#-l}" ;; + -*) printf 'unknown flag: %s\n' "$1" >&2; exit 1 ;; + *) TARGET="$1" ;; + esac + shift done [ -f build.cfg ] || { printf 'build.cfg not found; see the repository README\n' >&2; exit 1; } @@ -32,45 +32,45 @@ done # cppflags derived from build.cfg; any feature_* added there is picked up automatically _feature_flags="" while IFS= read -r _line; do - _trimmed=$(printf '%s' "$_line" | tr -d ' \t') - case "$_trimmed" in - FEATURE_*=*) - _key=${_trimmed%%=*} - eval "_val=\$$_key" - _feature_flags="$_feature_flags -D${_key}=${_val}" - ;; - esac + _trimmed=$(printf '%s' "$_line" | tr -d ' \t') + case "$_trimmed" in + FEATURE_*=*) + _key=${_trimmed%%=*} + eval "_val=\$$_key" + _feature_flags="$_feature_flags -D${_key}=${_val}" + ;; + esac done <<EOF $(tr ';' '\n' < build.cfg) EOF unset _line _key _val _trimmed CPPFLAGS="-Ishared -DPREFIX=\"$PREFIX\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64$_feature_flags" if [ "$FEATURE_USE_BEARSSL" = "1" ]; then - if pkg-config --exists libbearssl 2>/dev/null; then - CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libbearssl)" - TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libbearssl)" - elif pkg-config --exists bearssl 2>/dev/null; then - CPPFLAGS="$CPPFLAGS $(pkg-config --cflags bearssl)" - TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs bearssl)" - else - TLS_LDLIBS="$TLS_LDLIBS -LexternalRepos/BearSSL/build -lbearssl" - fi + if pkg-config --exists libbearssl 2>/dev/null; then + CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libbearssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libbearssl)" + elif pkg-config --exists bearssl 2>/dev/null; then + CPPFLAGS="$CPPFLAGS $(pkg-config --cflags bearssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs bearssl)" + else + TLS_LDLIBS="$TLS_LDLIBS -LexternalRepos/BearSSL/build -lbearssl" + fi fi if [ "$FEATURE_USE_LIBRESSL" = "1" ]; then - if pkg-config --exists libtls 2>/dev/null; then - CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libtls)" - TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libtls)" - else - TLS_LDLIBS="$TLS_LDLIBS -ltls" - fi + if pkg-config --exists libtls 2>/dev/null; then + CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libtls)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libtls)" + else + TLS_LDLIBS="$TLS_LDLIBS -ltls" + fi fi if [ "$FEATURE_USE_OPENSSL" = "1" ]; then - if pkg-config --exists openssl 2>/dev/null; then - CPPFLAGS="$CPPFLAGS $(pkg-config --cflags openssl)" - TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs openssl)" - else - TLS_LDLIBS="$TLS_LDLIBS -lssl -lcrypto" - fi + if pkg-config --exists openssl 2>/dev/null; then + CPPFLAGS="$CPPFLAGS $(pkg-config --cflags openssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs openssl)" + else + TLS_LDLIBS="$TLS_LDLIBS -lssl -lcrypto" + fi fi unset _feature_flags @@ -91,22 +91,22 @@ EXTRA_HDR= # timestamp comparison # mtime() { - stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0 + stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0 } newer_than() { - local s t - [ -e "$2" ] || return 0 - s=$(mtime "$1"); t=$(mtime "$2") - [ "$s" -gt "$t" ] + local s t + [ -e "$2" ] || return 0 + s=$(mtime "$1"); t=$(mtime "$2") + [ "$s" -gt "$t" ] } any_newer_than() { - local target="$1"; shift - for src do - newer_than "$src" "$target" && return 0 - done - return 1 + local target="$1"; shift + for src do + newer_than "$src" "$target" && return 0 + done + return 1 } # parallel job queue @@ -119,441 +119,454 @@ _objs="" # wraps arg in single quotes, escaping embedded ones, for safe eval shquote() { - printf "'" - printf '%s' "$1" | sed "s/'/'\\\\''/g" - printf "'" + printf "'" + printf '%s' "$1" | sed "s/'/'\\\\''/g" + printf "'" } enqueue() { - local desc="$1" cmd="$2" - _qn=$((_qn + 1)) - local s="$WORKDIR/j${_qn}.sh" - { - printf '#!/bin/sh\n' - printf 'printf "%%s\\n" %s\n' "$(shquote "$desc")" - printf 'eval %s\n' "$(shquote "$cmd")" - } > "$s" - _queue="$_queue $_qn" + local desc="$1" cmd="$2" + _qn=$((_qn + 1)) + local s="$WORKDIR/j${_qn}.sh" + { + printf '#!/bin/sh\n' + printf 'printf "%%s\\n" %s\n' "$(shquote "$desc")" + printf 'eval %s\n' "$(shquote "$cmd")" + } > "$s" + _queue="$_queue $_qn" } # silently skipped on systems without /proc/loadavg _wait_for_load() { - [ "$LOAD" -eq 0 ] && return 0 - local avg - while true; do - avg=$(awk '{printf "%d", int($1 + 0.5)}' /proc/loadavg 2>/dev/null) || return 0 - [ "$avg" -le "$LOAD" ] && return 0 - sleep 1 - done + [ "$LOAD" -eq 0 ] && return 0 + local avg + while true; do + avg=$(awk '{printf "%d", int($1 + 0.5)}' /proc/loadavg 2>/dev/null) || return 0 + [ "$avg" -le "$LOAD" ] && return 0 + sleep 1 + done } drain() { - [ -z "$_queue" ] && return 0 - local n - _wait_for_load - if [ "$JOBS" -le 1 ]; then - for n in $_queue; do - sh "$WORKDIR/j${n}.sh" || { printf 'error: build step failed\n' >&2; exit 1; } - done - else - # xargs -P (POSIX 2024), -n 1 so each path becomes its own sh invocation - for n in $_queue; do - printf '%s\n' "$WORKDIR/j${n}.sh" - done | xargs -P "$JOBS" -n 1 sh || { printf 'error: build step failed\n' >&2; exit 1; } - fi - _queue="" + [ -z "$_queue" ] && return 0 + local n + _wait_for_load + if [ "$JOBS" -le 1 ]; then + for n in $_queue; do + sh "$WORKDIR/j${n}.sh" || { printf 'error: build step failed\n' >&2; exit 1; } + done + else + # xargs -P (POSIX 2024), -n 1 so each path becomes its own sh invocation + for n in $_queue; do + printf '%s\n' "$WORKDIR/j${n}.sh" + done | xargs -P "$JOBS" -n 1 sh || { printf 'error: build step failed\n' >&2; exit 1; } + fi + _queue="" } # compile and link primitives # compile_c() { - local src="$1" obj="$2"; shift 2 - # shellcheck disable=SC2086 - any_newer_than "$obj" "$src" $HDR $EXTRA_HDR || return 0 - enqueue " CC $obj" "$CC $* $CPPFLAGS $CFLAGS -o $obj -c $src" + local src="$1" obj="$2"; shift 2 + # shellcheck disable=SC2086 + any_newer_than "$obj" "$src" $HDR $EXTRA_HDR || return 0 + enqueue " CC $obj" "$CC $* $CPPFLAGS $CFLAGS -o $obj -c $src" } link_bin() { - local bin="$1" objs="" libs="" sep=0; shift - for a do - if [ "$a" = "--" ]; then sep=1 - elif [ "$sep" = 0 ]; then objs="$objs $a" - else libs="$libs $a" - fi - done - drain - # shellcheck disable=SC2086 - any_newer_than "$bin" $objs || return 0 - printf ' LD %s\n' "$bin" - # shellcheck disable=SC2086 - if [ "${bin##*/}" = "wget" ]; then - eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS $TLS_LDLIBS" - else - eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS" - fi + local bin="$1" objs="" libs="" sep=0; shift + for a do + if [ "$a" = "--" ]; then sep=1 + elif [ "$sep" = 0 ]; then objs="$objs $a" + else libs="$libs $a" + fi + done + drain + # shellcheck disable=SC2086 + any_newer_than "$bin" $objs || return 0 + printf ' LD %s\n' "$bin" + # shellcheck disable=SC2086 + if [ "${bin##*/}" = "wget" ]; then + eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS $TLS_LDLIBS" + else + eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS" + fi } # writes to _objs rather than stdout so the caller avoids a subshell that # would discard enqueued jobs objs_for() { - local dir="$1" skip=" $2 " flags="$3" src base - _objs="" - for src in "$dir"/*.c; do - [ -f "$src" ] || continue - base=${src##*/} - case "$skip" in *" $base "*) continue ;; esac - compile_c "$src" "${src%.c}.o" $flags - _objs="$_objs ${src%.c}.o" - done + local dir="$1" skip=" $2 " flags="$3" src base + _objs="" + for src in "$dir"/*.c; do + [ -f "$src" ] || continue + base=${src##*/} + case "$skip" in *" $base "*) continue ;; esac + compile_c "$src" "${src%.c}.o" $flags + _objs="$_objs ${src%.c}.o" + done } # static libraries # # both directories enqueued before the single drain so they compile in parallel build_lib() { - local utf_objs util_objs redline_objs - objs_for shared/libutf "" "" - utf_objs="$_objs" - objs_for shared/libutil "" "" - util_objs="$_objs" - objs_for shared/libredline "" "" - redline_objs="$_objs" - drain - # shellcheck disable=SC2086 - any_newer_than shared/libutf/libutf.a $utf_objs && { - printf ' AR shared/libutf/libutf.a\n' - $AR $ARFLAGS shared/libutf/libutf.a $utf_objs - $RANLIB shared/libutf/libutf.a - } - # shellcheck disable=SC2086 - any_newer_than shared/libutil/libutil.a $util_objs && { - printf ' AR shared/libutil/libutil.a\n' - $AR $ARFLAGS shared/libutil/libutil.a $util_objs - $RANLIB shared/libutil/libutil.a - } - # shellcheck disable=SC2086 - any_newer_than shared/libredline/libredline.a $redline_objs && { - printf ' AR shared/libredline/libredline.a\n' - $AR $ARFLAGS shared/libredline/libredline.a $redline_objs - $RANLIB shared/libredline/libredline.a - } - return 0 + local utf_objs util_objs redline_objs + objs_for shared/libutf "" "" + utf_objs="$_objs" + objs_for shared/libutil "" "" + util_objs="$_objs" + objs_for shared/libredline "" "" + redline_objs="$_objs" + drain + # shellcheck disable=SC2086 + any_newer_than shared/libutf/libutf.a $utf_objs && { + printf ' AR shared/libutf/libutf.a\n' + $AR $ARFLAGS shared/libutf/libutf.a $utf_objs + $RANLIB shared/libutf/libutf.a + } + # shellcheck disable=SC2086 + any_newer_than shared/libutil/libutil.a $util_objs && { + printf ' AR shared/libutil/libutil.a\n' + $AR $ARFLAGS shared/libutil/libutil.a $util_objs + $RANLIB shared/libutil/libutil.a + } + # shellcheck disable=SC2086 + any_newer_than shared/libredline/libredline.a $redline_objs && { + printf ' AR shared/libredline/libredline.a\n' + $AR $ARFLAGS shared/libredline/libredline.a $redline_objs + $RANLIB shared/libredline/libredline.a + } + return 0 } # per-tool category builder # cfgvar() { - local cat="$1" base="$2" - [ "$cat" = extra ] && cat=pseudo - printf 'BUILD_%s_%s' "$cat" "$base" | tr 'a-z-' 'A-Z_' + local cat="$1" base="$2" + [ "$cat" = extra ] && cat=pseudo + printf 'BUILD_%s_%s' "$cat" "$base" | tr 'a-z-' 'A-Z_' } # individual flag overrides group flag cfg_enabled() { - local _var="$1" _v - while [ -n "$_var" ]; do - eval "_v=\${${_var}-UNSET}" - if [ "$_v" = "1" ]; then - return 0 - elif [ "$_v" = "0" ]; then - return 1 - fi - case "$_var" in - *_[!_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;; - *) break ;; - esac - done - return 1 + local _var="$1" _v + while [ -n "$_var" ]; do + eval "_v=\${${_var}-UNSET}" + if [ "$_v" = "1" ]; then + return 0 + elif [ "$_v" = "0" ]; then + return 1 + fi + case "$_var" in + *_[!_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;; + *) break ;; + esac + done + return 1 } build_simple_tools() { - local cat="$1" src base var staged="" - for src in cmd/"$cat"/*.c; do - [ -f "$src" ] || continue - base=${src##*/}; base=${base%.c} - var=$(cfgvar "$cat" "$base") - cfg_enabled "$var" || continue - compile_c "$src" "${src%.c}.o" - staged="$staged ${src%.c}" - done - drain - local bin - for bin in $staged; do - if [ "${bin##*/}" = "diff" ]; then - link_bin "$bin" "${bin}.o" -- $LIB -lm - else - link_bin "$bin" "${bin}.o" -- $LIB - fi - done + local cat="$1" src base var staged="" + for src in cmd/"$cat"/*.c; do + [ -f "$src" ] || continue + base=${src##*/}; base=${base%.c} + var=$(cfgvar "$cat" "$base") + cfg_enabled "$var" || continue + compile_c "$src" "${src%.c}.o" + staged="$staged ${src%.c}" + done + drain + local bin + for bin in $staged; do + if [ "${bin##*/}" = "diff" ]; then + link_bin "$bin" "${bin}.o" -- $LIB -lm + else + link_bin "$bin" "${bin}.o" -- $LIB + fi + done } build_awk() { - cfg_enabled BUILD_POSIX_AWK || return 0 - local dir=cmd/posix/awk - - any_newer_than "$dir/awkgram.tab.c" "$dir/awkgram.y" && { - if command -v yacc >/dev/null 2>&1; then - printf ' YACC %s/awkgram.tab.c\n' "$dir" - yacc -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" - if [ ! -f "$dir/awkgram.tab.h" ]; then - if [ -f y.tab.h ]; then - mv y.tab.h "$dir/awkgram.tab.h" - elif [ -f "$dir/y.tab.h" ]; then - mv "$dir/y.tab.h" "$dir/awkgram.tab.h" - fi - fi - elif command -v bison >/dev/null 2>&1; then - printf ' BISON %s/awkgram.tab.c\n' "$dir" - bison -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" - else - printf 'awk: no yacc/bison; using pre-generated awkgram.tab.c\n' >&2 - fi - } - - any_newer_than "$dir/maketab" "$dir/maketab.c" "$dir/awkgram.tab.h" && { - printf ' CC %s/maketab\n' "$dir" - eval "$CC $CFLAGS -o $dir/maketab $dir/maketab.c" - } - - any_newer_than "$dir/proctab.c" "$dir/maketab" && { - printf ' GEN %s/proctab.c\n' "$dir" - "$dir/maketab" "$dir/awkgram.tab.h" > "$dir/proctab.c" - } - - EXTRA_HDR="$dir/awk.h $dir/awkgram.tab.h $dir/proto.h" - objs_for "$dir" maketab.c "-I$dir" - EXTRA_HDR= - link_bin "$dir/awk" $_objs -- $LIB -lm + cfg_enabled BUILD_POSIX_AWK || return 0 + local dir=cmd/posix/awk + + any_newer_than "$dir/awkgram.tab.c" "$dir/awkgram.y" && { + if command -v yacc >/dev/null 2>&1; then + printf ' YACC %s/awkgram.tab.c\n' "$dir" + yacc -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" + if [ ! -f "$dir/awkgram.tab.h" ]; then + if [ -f y.tab.h ]; then + mv y.tab.h "$dir/awkgram.tab.h" + elif [ -f "$dir/y.tab.h" ]; then + mv "$dir/y.tab.h" "$dir/awkgram.tab.h" + fi + fi + elif command -v bison >/dev/null 2>&1; then + printf ' BISON %s/awkgram.tab.c\n' "$dir" + bison -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" + else + printf 'awk: no yacc/bison; using pre-generated awkgram.tab.c\n' >&2 + fi + } + + any_newer_than "$dir/maketab" "$dir/maketab.c" "$dir/awkgram.tab.h" && { + printf ' CC %s/maketab\n' "$dir" + eval "$CC $CFLAGS -o $dir/maketab $dir/maketab.c" + } + + any_newer_than "$dir/proctab.c" "$dir/maketab" && { + printf ' GEN %s/proctab.c\n' "$dir" + "$dir/maketab" "$dir/awkgram.tab.h" > "$dir/proctab.c" + } + + EXTRA_HDR="$dir/awk.h $dir/awkgram.tab.h $dir/proto.h" + objs_for "$dir" maketab.c "-I$dir" + EXTRA_HDR= + link_bin "$dir/awk" $_objs -- $LIB -lm } build_sh() { - cfg_enabled BUILD_POSIX_SH || return 0 - local dir=cmd/posix/sh - - any_newer_than "$dir/mknodes" "$dir/mknodes.c" && { - printf ' CC %s/mknodes\n' "$dir" - eval "$CC $CFLAGS -o $dir/mknodes $dir/mknodes.c" - } - - any_newer_than "$dir/mksyntax" "$dir/mksyntax.c" && { - printf ' CC %s/mksyntax\n' "$dir" - eval "$CC $CPPFLAGS -I$dir $CFLAGS -o $dir/mksyntax $dir/mksyntax.c" - } - - any_newer_than "$dir/token.h" "$dir/mktokens" && { - printf ' GEN %s/token.h\n' "$dir" - (cd "$dir" && sh mktokens) - } - - any_newer_than "$dir/syntax.c" "$dir/mksyntax" && { - printf ' GEN %s/syntax.c\n' "$dir" - (cd "$dir" && ./mksyntax) - } - - any_newer_than "$dir/nodes.c" "$dir/mknodes" "$dir/nodetypes" "$dir/nodes.c.pat" && { - printf ' GEN %s/nodes.c\n' "$dir" - (cd "$dir" && ./mknodes nodetypes nodes.c.pat) - } - - any_newer_than "$dir/builtins.c" "$dir/mkbuiltins" "$dir/builtins.def" "$dir/shell.h" && { - printf ' GEN %s/builtins.c\n' "$dir" - (cd "$dir" && sh mkbuiltins .) - } - - EXTRA_HDR="$dir/syntax.h $dir/nodes.h $dir/builtins.h $dir/token.h" - objs_for "$dir" "mknodes.c mksyntax.c" "-DSHELL -I$dir" - EXTRA_HDR= - link_bin "$dir/sh" $_objs -- $LIB + cfg_enabled BUILD_POSIX_SH || return 0 + local dir=cmd/posix/sh + + any_newer_than "$dir/mknodes" "$dir/mknodes.c" && { + printf ' CC %s/mknodes\n' "$dir" + eval "$CC $CFLAGS -o $dir/mknodes $dir/mknodes.c" + } + + any_newer_than "$dir/mksyntax" "$dir/mksyntax.c" && { + printf ' CC %s/mksyntax\n' "$dir" + eval "$CC $CPPFLAGS -I$dir $CFLAGS -o $dir/mksyntax $dir/mksyntax.c" + } + + any_newer_than "$dir/token.h" "$dir/mktokens" && { + printf ' GEN %s/token.h\n' "$dir" + (cd "$dir" && sh mktokens) + } + + any_newer_than "$dir/syntax.c" "$dir/mksyntax" && { + printf ' GEN %s/syntax.c\n' "$dir" + (cd "$dir" && ./mksyntax) + } + + any_newer_than "$dir/nodes.c" "$dir/mknodes" "$dir/nodetypes" "$dir/nodes.c.pat" && { + printf ' GEN %s/nodes.c\n' "$dir" + (cd "$dir" && ./mknodes nodetypes nodes.c.pat) + } + + any_newer_than "$dir/builtins.c" "$dir/mkbuiltins" "$dir/builtins.def" "$dir/shell.h" && { + printf ' GEN %s/builtins.c\n' "$dir" + (cd "$dir" && sh mkbuiltins .) + } + + EXTRA_HDR="$dir/syntax.h $dir/nodes.h $dir/builtins.h $dir/token.h" + objs_for "$dir" "mknodes.c mksyntax.c" "-DSHELL -I$dir" + EXTRA_HDR= + link_bin "$dir/sh" $_objs -- $LIB } build_make() { - cfg_enabled BUILD_POSIX_MAKE || return 0 - local dir=cmd/posix/make - EXTRA_HDR="$dir/make.h" - objs_for "$dir" "" "" - EXTRA_HDR= - link_bin "$dir/make" $_objs -- $LIB + cfg_enabled BUILD_POSIX_MAKE || return 0 + local dir=cmd/posix/make + EXTRA_HDR="$dir/make.h" + objs_for "$dir" "" "" + EXTRA_HDR= + link_bin "$dir/make" $_objs -- $LIB } build_posix() { - cfg_enabled BUILD_POSIX_GETCONF && [ ! -f cmd/posix/getconf.h ] && { - printf ' GEN cmd/posix/getconf.h\n' - scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; } - } - build_simple_tools posix - build_awk - build_sh - build_make + cfg_enabled BUILD_POSIX_GETCONF && [ ! -f cmd/posix/getconf.h ] && { + printf ' GEN cmd/posix/getconf.h\n' + scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; } + } + build_simple_tools posix + build_awk + build_sh + build_make } # multi-file dev toolchain # build_ar() { - cfg_enabled BUILD_DEV_AR || return 0 - local dir=cmd/dev/ar - objs_for "$dir" tinyar.c "-I$dir" - link_bin "$dir/ar" $_objs -- $LIB + cfg_enabled BUILD_DEV_AR || return 0 + local dir=cmd/dev/ar + objs_for "$dir" tinyar.c "-I$dir" + link_bin "$dir/ar" $_objs -- $LIB } build_as() { - cfg_enabled BUILD_DEV_AS || return 0 - local dir="cmd/dev/as" - local flags="-Icmd/dev/xcutil -I$dir -Ishared" - local objs="" - objs_for "cmd/dev/xcutil" "" "$flags" - objs="$objs $_objs" - objs_for "$dir" "" "$flags" - objs="$objs $_objs" - objs_for "$dir/arch/x64" "" "-Icmd/dev/xcutil -I$dir -I$dir/arch/x64 -Ishared" - objs="$objs $_objs" - link_bin "$dir/as" $objs -- $LIB + cfg_enabled BUILD_DEV_AS || return 0 + local dir="cmd/dev/as" + local flags="-Icmd/dev/xcutil -I$dir -Ishared" + local objs="" + objs_for "cmd/dev/xcutil" "" "$flags" + objs="$objs $_objs" + objs_for "$dir" "" "$flags" + objs="$objs $_objs" + objs_for "$dir/arch/x64" "" "-Icmd/dev/xcutil -I$dir -I$dir/arch/x64 -Ishared" + objs="$objs $_objs" + link_bin "$dir/as" $objs -- $LIB } build_ld() { - cfg_enabled BUILD_DEV_LD || return 0 - local dir="cmd/dev/ld" - local flags="-Icmd/dev/xcutil -I$dir" - local objs="" - objs_for "cmd/dev/xcutil" "" "$flags" - objs="$objs $_objs" - objs_for "$dir" "" "$flags" - objs="$objs $_objs" - link_bin "$dir/ld" $objs -- $LIB + cfg_enabled BUILD_DEV_LD || return 0 + local dir="cmd/dev/ld" + local flags="-Icmd/dev/xcutil -I$dir" + local objs="" + objs_for "cmd/dev/xcutil" "" "$flags" + objs="$objs $_objs" + objs_for "$dir" "" "$flags" + objs="$objs $_objs" + link_bin "$dir/ld" $objs -- $LIB } build_cc() { - cfg_enabled BUILD_DEV_CC || return 0 - local dir="cmd/dev/cc" - local cflags="-I$dir" - local common - - # compiled once, linked into both cc1 and cpp - objs_for "$dir" "driver.c cc1.c cpp.c" "$cflags" - common="$_objs" - drain - - compile_c "$dir/cc1.c" "$dir/cc1.o" $cflags - compile_c "$dir/cpp.c" "$dir/cpp.o" $cflags - compile_c "$dir/driver.c" "$dir/driver.o" $cflags - drain - - link_bin "$dir/cc1" "$dir/cc1.o" $common -- $LIB - link_bin "$dir/cpp" "$dir/cpp.o" $common -- $LIB - link_bin "$dir/cc" "$dir/driver.o" "$dir/util.o" -- $LIB + cfg_enabled BUILD_DEV_CC || return 0 + local dir="cmd/dev/cc" + local cflags="-I$dir" + local common + + # compiled once, linked into both cc1 and cpp + objs_for "$dir" "driver.c cc1.c cpp.c" "$cflags" + common="$_objs" + drain + + compile_c "$dir/cc1.c" "$dir/cc1.o" $cflags + compile_c "$dir/cpp.c" "$dir/cpp.o" $cflags + compile_c "$dir/driver.c" "$dir/driver.o" $cflags + drain + + link_bin "$dir/cc1" "$dir/cc1.o" $common -- $LIB + link_bin "$dir/cpp" "$dir/cpp.o" $common -- $LIB + link_bin "$dir/cc" "$dir/driver.o" "$dir/util.o" -- $LIB } build_dev() { - [ -f cmd/dev/configure ] && sh cmd/dev/configure - build_ar - build_as - build_ld - build_cc + [ -f cmd/dev/configure ] && sh cmd/dev/configure + build_ar + build_as + build_ld + build_cc } # manual page generation # man_section() { - case "$1" in - */linux/*|*/net/*|*/xsi/*) printf '8\n' ;; - *) printf '1\n' ;; - esac + case "$1" in + */linux/*|*/net/*|*/xsi/*) printf '8\n' ;; + *) printf '1\n' ;; + esac } build_man_for() { - local var="$1" src="$2" base sec out_mdoc out_txt - cfg_enabled "$var" || return 0 - [ -x scripts/mkman/mkman ] || { printf 'error: mkman not built\n' >&2; exit 1; } - - grep -qE '!man|\?man' "$src" || return 0 - - base=${src##*/}; base=${base%.c} - sec=$(man_section "$src") - - mkdir -p "man/man${sec}" - out_mdoc="man/man${sec}/${base}.${sec}" - out_txt="man/man${sec}/${base}.${sec}.txt" - if any_newer_than "$out_mdoc" "$src" config.mk scripts/mkman/mkman; then - printf ' MAN %s\n' "$out_mdoc" - scripts/mkman/mkman -fmt mdoc -config config.mk -section "$sec" "$src" > "$out_mdoc" - fi - if any_newer_than "$out_txt" "$src" config.mk scripts/mkman/mkman; then - printf ' MAN %s\n' "$out_txt" - scripts/mkman/mkman -fmt txt -config config.mk -section "$sec" "$src" > "$out_txt" - fi + local var="$1" src="$2" base sec out_mdoc out_txt + cfg_enabled "$var" || return 0 + [ -x scripts/mkman/mkman ] || { printf 'error: mkman not built\n' >&2; exit 1; } + + grep -qE '!man|\?man' "$src" || return 0 + + base=${src##*/}; base=${base%.c} + sec=$(man_section "$src") + + mkdir -p "man/man${sec}" + out_mdoc="man/man${sec}/${base}.${sec}" + out_txt="man/man${sec}/${base}.${sec}.txt" + if any_newer_than "$out_mdoc" "$src" config.mk scripts/mkman/mkman; then + printf ' MAN %s\n' "$out_mdoc" + scripts/mkman/mkman -fmt mdoc -config config.mk -section "$sec" "$src" > "$out_mdoc" + fi + if any_newer_than "$out_txt" "$src" config.mk scripts/mkman/mkman; then + printf ' MAN %s\n' "$out_txt" + scripts/mkman/mkman -fmt txt -config config.mk -section "$sec" "$src" > "$out_txt" + fi } build_man() { - local dir cat src base - if [ ! -x scripts/mkman/mkman ] || any_newer_than scripts/mkman/mkman scripts/mkman/main.go scripts/mkman/page.go scripts/mkman/parse.go scripts/mkman/mdoc.go; then - printf ' GO scripts/mkman/mkman\n' - (cd scripts/mkman && go build -o mkman .) - fi - for dir in cmd/*; do - [ -d "$dir" ] || continue - cat=${dir##*/} - for src in "$dir"/*.c; do - [ -f "$src" ] || continue - base=${src##*/}; base=${base%.c} - build_man_for "$(cfgvar "$cat" "$base")" "$src" - done - done + local dir cat src base + if [ ! -x scripts/mkman/mkman ] || any_newer_than scripts/mkman/mkman scripts/mkman/main.go scripts/mkman/page.go scripts/mkman/parse.go scripts/mkman/mdoc.go; then + printf ' GO scripts/mkman/mkman\n' + (cd scripts/mkman && go build -o mkman .) + fi + for dir in cmd/*; do + [ -d "$dir" ] || continue + cat=${dir##*/} + for src in "$dir"/*.c; do + [ -f "$src" ] || continue + base=${src##*/}; base=${base%.c} + build_man_for "$(cfgvar "$cat" "$base")" "$src" + done + done } # install and clean # do_install() { - local bin f sec - mkdir -p "$PREFIX/bin" "$MANPREFIX/man1" "$MANPREFIX/man8" - find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do - printf ' INSTALL %s/bin/%s\n' "$PREFIX" "${bin##*/}" - cp "$bin" "$PREFIX/bin/${bin##*/}" - chmod 755 "$PREFIX/bin/${bin##*/}" - done - find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do - sec=${f%/*}; sec=${sec##*/} - cp "$f" "$MANPREFIX/${sec}/${f##*/}" - done + local bin f sec + mkdir -p "$PREFIX/bin" "$MANPREFIX/man1" "$MANPREFIX/man8" + find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do + printf ' INSTALL %s/bin/%s\n' "$PREFIX" "${bin##*/}" + cp "$bin" "$PREFIX/bin/${bin##*/}" + chmod 755 "$PREFIX/bin/${bin##*/}" + done + find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do + sec=${f%/*}; sec=${sec##*/} + cp "$f" "$MANPREFIX/${sec}/${f##*/}" + done } do_clean() { - find shared cmd -name '*.o' -exec rm -f {} + - find shared -name '*.a' -exec rm -f {} + - find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} + - rm -f shared/libaruuelf.so - rm -f cmd/posix/bc.c cmd/posix/getconf.h - rm -f cmd/posix/awk/maketab cmd/posix/awk/proctab.c - rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h - rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax - rm -f cmd/posix/sh/token.h cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h - rm -f cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h - rm -f cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h - rm -rf man/man1 man/man8 - rm -rf aruu-box .box - rm -f scripts/mkman/mkman + printf ' CLEAN object files\n' + find shared cmd -name '*.o' -exec rm -f {} + + printf ' CLEAN static libraries\n' + find shared -name '*.a' -exec rm -f {} + + printf ' CLEAN compiled binaries\n' + find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} + + printf ' CLEAN generated headers\n' + rm -f cmd/posix/getconf.h + rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h + rm -f cmd/posix/sh/token.h cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h + rm -f cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h + rm -f cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h + printf ' CLEAN generated sources\n' + rm -f cmd/posix/awk/proctab.c + rm -f cmd/posix/bc.c + printf ' CLEAN build tools\n' + rm -f cmd/posix/awk/maketab + rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax + rm -f scripts/mkman/mkman + printf ' CLEAN dev artifacts\n' + rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar + rm -f shared/libaruuelf.so + rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h + printf ' CLEAN misc\n' + rm -rf man/man1 man/man8 + rm -rf aruu-box .box + printf ' CLEAN done\n' } case "$TARGET" in - all) - build_lib - build_posix - build_dev - build_simple_tools linux - build_simple_tools net - build_simple_tools xsi - build_simple_tools pseudo - build_simple_tools extra - ;; - lib) build_lib ;; - posix) build_lib; build_posix ;; - dev) build_lib; build_dev ;; - make) build_lib; build_make ;; - linux|net|xsi|pseudo|extra) - build_lib; build_simple_tools "$TARGET" ;; - man) build_man ;; - install) do_install ;; - clean) do_clean ;; - *) - printf 'usage: sh Makefile.sh [-jN] [-lN] [all|clean|install|man|lib|posix|linux|net|xsi|pseudo|extra|dev|make]\n' >&2 - exit 1 - ;; + all) + build_lib + build_posix + build_dev + build_simple_tools linux + build_simple_tools net + build_simple_tools xsi + build_simple_tools pseudo + build_simple_tools extra + ;; + lib) build_lib ;; + posix) build_lib; build_posix ;; + dev) build_lib; build_dev ;; + make) build_lib; build_make ;; + linux|net|xsi|pseudo|extra) + build_lib; build_simple_tools "$TARGET" ;; + man) build_man ;; + install) do_install ;; + clean) do_clean ;; + *) + printf 'usage: sh Makefile.sh [-jN] [-lN] [all|clean|install|man|lib|posix|linux|net|xsi|pseudo|extra|dev|make]\n' >&2 + exit 1 + ;; esac diff --git a/build.cfg b/build.cfg @@ -40,6 +40,12 @@ posix) FEATURE_SH_SETVAR=0; FEATURE_SH_WORDEXP=0 FEATURE_CAL_EXT=0 FEATURE_LS_COLOR=0 + FEATURE_DIFF3_MERGE=0; FEATURE_DIFF3_EDSCRIPT=0 + FEATURE_DIFF_CONTEXT=0; FEATURE_DIFF_UNIFIED=0 + FEATURE_DIFF_ED=0; FEATURE_DIFF_BRIEF=0 + FEATURE_DIFF_SIDEBYSIDE=0 + FEATURE_PATCH_BACKUP=0; FEATURE_PATCH_FUZZ=0 + FEATURE_PATCH_STRIP_CR=0 FEATURE_MODPROBE_SHOW_DEPENDS=0; FEATURE_MODPROBE_BLACKLIST=0 FEATURE_MODPROBE_SYSLOG=0; FEATURE_MODPROBE_DIR_OVERRIDE=0 FEATURE_DEPMOD_ALIAS=0; FEATURE_DEPMOD_SYMBOLS=0 @@ -69,6 +75,12 @@ common) FEATURE_SH_SETVAR=0; FEATURE_SH_WORDEXP=0 FEATURE_CAL_EXT=1 FEATURE_LS_COLOR=1 + FEATURE_DIFF3_MERGE=0; FEATURE_DIFF3_EDSCRIPT=1 + FEATURE_DIFF_CONTEXT=1; FEATURE_DIFF_UNIFIED=1 + FEATURE_DIFF_ED=1; FEATURE_DIFF_BRIEF=1 + FEATURE_DIFF_SIDEBYSIDE=0 + FEATURE_PATCH_BACKUP=1; FEATURE_PATCH_FUZZ=1 + FEATURE_PATCH_STRIP_CR=1 FEATURE_MODPROBE_SHOW_DEPENDS=1; FEATURE_MODPROBE_BLACKLIST=1 FEATURE_MODPROBE_SYSLOG=1; FEATURE_MODPROBE_DIR_OVERRIDE=1 FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1 @@ -94,11 +106,18 @@ all) FEATURE_STAT_FILESYSTEM=1; FEATURE_STAT_FORMAT=1 FEATURE_SORT_BIG=1; FEATURE_SORT_STABLE=1 FEATURE_OD_ENDIAN=1; - FEATURE_SH_HISTEDIT=1; FEATURE_SH_LOCAL=1 + FEATURE_SH_HISTEDIT=1 +FEATURE_INPROC_EXEC=0 # set to 1 for aruu-box in-process dispatch; FEATURE_SH_LOCAL=1 FEATURE_SH_LET=1; FEATURE_SH_ULIMIT=1 FEATURE_SH_SETVAR=1; FEATURE_SH_WORDEXP=1 FEATURE_CAL_EXT=1 FEATURE_LS_COLOR=1 + FEATURE_DIFF3_MERGE=1; FEATURE_DIFF3_EDSCRIPT=1 + FEATURE_DIFF_CONTEXT=1; FEATURE_DIFF_UNIFIED=1 + FEATURE_DIFF_ED=1; FEATURE_DIFF_BRIEF=1 + FEATURE_DIFF_SIDEBYSIDE=1 + FEATURE_PATCH_BACKUP=1; FEATURE_PATCH_FUZZ=1 + FEATURE_PATCH_STRIP_CR=1 FEATURE_MODPROBE_SHOW_DEPENDS=1; FEATURE_MODPROBE_BLACKLIST=1 FEATURE_MODPROBE_SYSLOG=1; FEATURE_MODPROBE_DIR_OVERRIDE=1 FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1 @@ -137,6 +156,7 @@ unset _p # BUILD_POSIX_SH=0 # disable a tool when its group is active # BUILD_DEV_AS=1 # enable a tool whose group isnt in PRESET_UTILS FEATURE_SH_HISTEDIT=1 +FEATURE_INPROC_EXEC=0 # set to 1 for aruu-box in-process dispatch # tls backend: set exactly one to 1 to enable tls FEATURE_USE_BEARSSL=0 FEATURE_USE_LIBRESSL=0 diff --git a/cmd/extra/blkid.c b/cmd/extra/blkid.c @@ -16,64 +16,65 @@ static int Lflag = 0; static void usage(void) { - eprintf("usage: %s [-o format] [-s tag] [-U] [-L] [device ...]\n", argv0); + eprintf("usage: %s [-o format] [-s tag] [-U] [-L] [device ...]\n", argv0); } static void print_tag(const char *devname, const char *tag, const char *value) { - if (sflag && strcasecmp(sflag, tag) != 0) - return; - - if (strcmp(oflag, "value") == 0) { - printf("%s\n", value); - } else if (strcmp(oflag, "export") == 0) { - printf("%s=%s\n", tag, value); - } else { - printf(" %s=\"%s\"", tag, value); - } + (void)devname; + if (sflag && strcasecmp(sflag, tag) != 0) + return; + + if (strcmp(oflag, "value") == 0) { + printf("%s\n", value); + } else if (strcmp(oflag, "export") == 0) { + printf("%s=%s\n", tag, value); + } else { + printf(" %s=\"%s\"", tag, value); + } } static int do_blkid(const char *path) { - struct BlockDev dev; - char type[64] = {0}; - char label[256] = {0}; - char uuid[256] = {0}; - int res; - - if (blockdev_open(&dev, path, 0) < 0) - return -1; - - res = blockdev_detect_fs(&dev, type, sizeof(type), label, sizeof(label), uuid, sizeof(uuid)); - if (res == 0) { - if (Uflag || Lflag) { - if (Uflag) { - printf("%s\n", uuid); - } else { - printf("%s\n", label); - } - } else { - if (strcmp(oflag, "export") == 0) { - printf("DEVNAME=%s\n", path); - } else if (strcmp(oflag, "value") != 0) { - printf("%s:", path); - } - - if (label[0]) - print_tag(path, "LABEL", label); - if (uuid[0]) - print_tag(path, "UUID", uuid); - print_tag(path, "TYPE", type); - - if (strcmp(oflag, "full") == 0) - printf("\n"); - } - } - - blockdev_close(&dev); - return res == 0 ? 0 : -2; + struct BlockDev dev; + char type[64] = {0}; + char label[256] = {0}; + char uuid[256] = {0}; + int res; + + if (blockdev_open(&dev, path, 0) < 0) + return -1; + + res = blockdev_detect_fs(&dev, type, sizeof(type), label, sizeof(label), uuid, sizeof(uuid)); + if (res == 0) { + if (Uflag || Lflag) { + if (Uflag) { + printf("%s\n", uuid); + } else { + printf("%s\n", label); + } + } else { + if (strcmp(oflag, "export") == 0) { + printf("DEVNAME=%s\n", path); + } else if (strcmp(oflag, "value") != 0) { + printf("%s:", path); + } + + if (label[0]) + print_tag(path, "LABEL", label); + if (uuid[0]) + print_tag(path, "UUID", uuid); + print_tag(path, "TYPE", type); + + if (strcmp(oflag, "full") == 0) + printf("\n"); + } + } + + blockdev_close(&dev); + return res == 0 ? 0 : -2; } // ?man blkid: print block device attributes @@ -83,52 +84,52 @@ do_blkid(const char *path) int main(int argc, char *argv[]) { - int ret = 0; - - ARGBEGIN { - // ?man -o:specify output format (full, value, export) - case 'o': - oflag = EARGF(usage()); - break; - // ?man -s:only show specified tag (e.g. UUID, LABEL, TYPE) - case 's': - sflag = EARGF(usage()); - break; - // ?man -U:print UUID only - case 'U': - Uflag = 1; - break; - // ?man -L:print volume label only - case 'L': - Lflag = 1; - break; - default: - usage(); - } ARGEND - - if (argc > 0) { - for (; *argv; argv++) { - if (do_blkid(*argv) < 0) - ret = 1; - } - } else { - struct BlockDevInfo *list = blockdev_get_list(); - struct BlockDevInfo *curr; - if (!list) { - return 1; - } - for (curr = list; curr; curr = curr->next) { - do_blkid(curr->path); - struct BlockDevInfo *part; - for (part = curr->parts; part; part = part->next) { - do_blkid(part->path); - } - } - blockdev_free_list(list); - } - - if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) - ret = 2; - - return ret; + int ret = 0; + + ARGBEGIN { + // ?man -o:specify output format (full, value, export) + case 'o': + oflag = EARGF(usage()); + break; + // ?man -s:only show specified tag (e.g. UUID, LABEL, TYPE) + case 's': + sflag = EARGF(usage()); + break; + // ?man -U:print UUID only + case 'U': + Uflag = 1; + break; + // ?man -L:print volume label only + case 'L': + Lflag = 1; + break; + default: + usage(); + } ARGEND + + if (argc > 0) { + for (; *argv; argv++) { + if (do_blkid(*argv) < 0) + ret = 1; + } + } else { + struct BlockDevInfo *list = blockdev_get_list(); + struct BlockDevInfo *curr; + if (!list) { + return 1; + } + for (curr = list; curr; curr = curr->next) { + do_blkid(curr->path); + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + do_blkid(part->path); + } + } + blockdev_free_list(list); + } + + if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) + ret = 2; + + return ret; } diff --git a/cmd/linux/chvt.c b/cmd/linux/chvt.c @@ -10,6 +10,7 @@ #include <string.h> #include <unistd.h> +#include "paths.h" #include "util.h" #define KDGKBTYPE 0x4B33 /* get keyboard type */ @@ -18,9 +19,9 @@ #define VT_WAITACTIVE 0x5607 /* wait for vt active */ static char *vt[] = { - "/proc/self/fd/0", - "/dev/console", - "/dev/tty", + ARUU_LINUX_PATH_PROC "/self/fd/0", + ARUU_PATH_DEVCONSOLE, + ARUU_PATH_DEVTTY, "/dev/tty0", }; diff --git a/cmd/linux/depmod.c b/cmd/linux/depmod.c @@ -1,6 +1,7 @@ #include "fs.h" +#include "wexec.h" #include "util.h" #include <dirent.h> @@ -181,15 +182,15 @@ scan_cb(int fd, const char *name, struct stat *st, void *data, struct recursor * fp = fopen(r->path, "r"); } else if (strcmp(comp, ".gz") == 0) { snprintf(cmd, sizeof(cmd), "gzip -dc '%s'", r->path); - fp = popen(cmd, "r"); + fp = wpopen(cmd, NULL, "r"); is_pipe = 1; } else if (strcmp(comp, ".xz") == 0) { snprintf(cmd, sizeof(cmd), "xz -dc '%s'", r->path); - fp = popen(cmd, "r"); + fp = wpopen(cmd, NULL, "r"); is_pipe = 1; } else if (strcmp(comp, ".zst") == 0) { snprintf(cmd, sizeof(cmd), "zstd -dc '%s'", r->path); - fp = popen(cmd, "r"); + fp = wpopen(cmd, NULL, "r"); is_pipe = 1; } else { fp = fopen(r->path, "r"); @@ -202,7 +203,7 @@ scan_cb(int fd, const char *name, struct stat *st, void *data, struct recursor * buf = read_all(fp, &len); if (is_pipe) - pclose(fp); + wpclose(fp); else fclose(fp); diff --git a/cmd/linux/eject.c b/cmd/linux/eject.c @@ -9,6 +9,7 @@ #include <stdio.h> #include <unistd.h> +#include "paths.h" #include "util.h" enum { @@ -64,7 +65,7 @@ main(int argc, char *argv[]) } ARGEND; if (!argc) { - eject("/dev/sr0"); + eject(ARUU_PATH_DEV "/sr0"); } else { for (; *argv; argc--, argv++) eject(*argv); diff --git a/cmd/linux/freeramdisk.c b/cmd/linux/freeramdisk.c @@ -10,6 +10,7 @@ #include <stdlib.h> #include <unistd.h> +#include "paths.h" #include "util.h" static void diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c @@ -14,6 +14,7 @@ #include <unistd.h> #include "rtc.h" +#include "paths.h" #include "util.h" static void @@ -120,7 +121,7 @@ usage(void) int main(int argc, char *argv[]) { - char *dev = "/dev/rtc"; + char *dev = ARUU_PATH_DEV "/rtc"; int rflag = 0; int sflag = 0; int wflag = 0; diff --git a/cmd/linux/lsmod.c b/cmd/linux/lsmod.c @@ -4,6 +4,7 @@ #include <string.h> #include "text.h" +#include "paths.h" #include "util.h" static void parse_modline(char *buf, char **name, char **size, @@ -20,7 +21,7 @@ usage(void) int main(int argc, char *argv[]) { - const char *modfile = "/proc/modules"; + const char *modfile = ARUU_LINUX_PATH_PROC_MODULES; FILE *fp; char *buf = NULL; char *name, *size, *refcount, *users; diff --git a/cmd/linux/lsusb.c b/cmd/linux/lsusb.c @@ -6,6 +6,7 @@ #include <stdlib.h> #include "text.h" +#include "paths.h" #include "util.h" static void @@ -57,6 +58,6 @@ main(int argc, char *argv[]) usage(); } ARGEND; - recurse_dir("/sys/bus/usb/devices", lsusb); + recurse_dir(ARUU_LINUX_PATH_SYS_BUS_USB, lsusb); return 0; } diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -1,6 +1,7 @@ #include "arg.h" #include "fs.h" +#include "paths.h" #include "util.h" #include <ctype.h> @@ -344,7 +345,7 @@ mark_loaded(void) char *p; struct Module *m; - if (!(fp = fopen("/proc/modules", "r"))) + if (!(fp = fopen(ARUU_LINUX_PATH_PROC_MODULES, "r"))) return; while (fgets(line, sizeof(line), fp)) { diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -15,6 +15,8 @@ #include <unistd.h> #include "text.h" +#include "paths.h" +#include "wexec.h" #include "util.h" #define FSOPTS_MAXLEN 512 @@ -134,10 +136,10 @@ mounthelper(const char *fsname, const char *dir, const char *fstype) eargv[i++] = dir; eargv[i] = NULL; - execvp(eprog, (char * const *)eargv); + wexecvp_self(eprog, (char *const *)eargv); if (errno == ENOENT) _exit(1); - weprintf("execvp:"); + weprintf("wexecvp:"); _exit(1); break; default: @@ -166,8 +168,8 @@ mounted(const char *dir) weprintf("stat %s:", dir); return 0; } - if (!(fp = setmntent("/proc/mounts", "r"))) - eprintf("setmntent %s:", "/proc/mounts"); + if (!(fp = setmntent(ARUU_LINUX_PATH_PROC_MOUNTS, "r"))) + eprintf("setmntent %s:", ARUU_LINUX_PATH_PROC_MOUNTS); while ((me = getmntent_r(fp, &mebuf, linebuf, sizeof(linebuf)))) { if (stat(me->mnt_dir, &st2) < 0) { @@ -197,7 +199,7 @@ int main(int argc, char *argv[]) { char *types = NULL, data[FSOPTS_MAXLEN] = "", *resolvpath = NULL; - char *files[] = { "/proc/mounts", "/etc/fstab", NULL }; + char *files[] = { ARUU_LINUX_PATH_PROC_MOUNTS, "/etc/fstab", NULL }; const char *source, *target; struct mntent *me = NULL; int aflag = 0, status = 0, i, r; @@ -263,7 +265,7 @@ main(int argc, char *argv[]) for (i = 0; files[i]; i++) { if (!(fp = setmntent(files[i], "r"))) { - if (strcmp(files[i], "/proc/mounts") != 0) + if (strcmp(files[i], ARUU_LINUX_PATH_PROC_MOUNTS) != 0) weprintf("setmntent %s:", files[i]); continue; } diff --git a/cmd/linux/mountpoint.c b/cmd/linux/mountpoint.c @@ -11,6 +11,7 @@ #include <string.h> #include <unistd.h> +#include "paths.h" #include "util.h" static void @@ -81,11 +82,11 @@ main(int argc, char *argv[]) return 0; } - fp = setmntent("/proc/mounts", "r"); + fp = setmntent(ARUU_LINUX_PATH_PROC_MOUNTS, "r"); if (!fp) { if (qflag) return 1; - eprintf("setmntent %s:", "/proc/mounts"); + eprintf("setmntent %s:", ARUU_LINUX_PATH_PROC_MOUNTS); } while ((me = getmntent(fp)) != NULL) { if (stat(me->mnt_dir, &st2) < 0) { diff --git a/cmd/linux/sysctl.c b/cmd/linux/sysctl.c @@ -9,155 +9,151 @@ #include <unistd.h> #include "text.h" +#include "paths.h" #include "util.h" static void replacestr(char *s, int a, int b) { - for (; *s; s++) - if (*s == a) - *s = b; + for (; *s; s++) + if (*s == a) + *s = b; } static int getsysctl(char *variable, char **value) { - char path[PATH_MAX]; - char *p; - char *buf, *tmp, c; - int fd; - ssize_t n; - size_t sz, i; - - replacestr(variable, '.', '/'); - - strlcpy(path, "/proc/sys/", sizeof(path)); - if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) { - replacestr(variable, '/', '.'); - return -1; - } - - replacestr(variable, '/', '.'); - - fd = open(path, O_RDONLY); - if (fd < 0) - return -1; - - i = 0; - sz = 1; - buf = NULL; - while (1) { - n = read(fd, &c, 1); - if (n < 0) { - close(fd); - free(buf); - return -1; - } - if (n == 0) - break; - if (i == sz - 1) { - sz *= 2; - tmp = realloc(buf, sz); - if (!tmp) { - close(fd); - free(buf); - return -1; - } - buf = tmp; - } - buf[i++] = c; - } - buf[i] = '\0'; - - p = strrchr(buf, '\n'); - if (p) - *p = '\0'; - - *value = buf; - - close(fd); - - return 0; + char path[PATH_MAX]; + char *p; + char *buf, *tmp, c; + int fd; + ssize_t n; + size_t sz, i; + + replacestr(variable, '.', '/'); + + strlcpy(path, ARUU_LINUX_PATH_PROC_SYS "/", sizeof(path)); + if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) { + replacestr(variable, '/', '.'); + return -1; + } + + replacestr(variable, '/', '.'); + + fd = open(path, O_RDONLY); + if (fd < 0) + return -1; + + i = 0; + sz = 1; + buf = NULL; + while (1) { + n = read(fd, &c, 1); + if (n < 0) { + close(fd); + free(buf); + return -1; + } + if (n == 0) + break; + if (i == sz - 1) { + sz *= 2; + tmp = erealloc(buf, sz); + buf = tmp; + } + buf[i++] = c; + } + buf[i] = '\0'; + + p = strrchr(buf, '\n'); + if (p) + *p = '\0'; + + *value = buf; + + close(fd); + + return 0; } static int setsysctl(char *variable, char *value) { - char path[PATH_MAX]; - int fd; - ssize_t n; + char path[PATH_MAX]; + int fd; + ssize_t n; - replacestr(variable, '.', '/'); + replacestr(variable, '.', '/'); - strlcpy(path, "/proc/sys/", sizeof(path)); - if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) { - replacestr(variable, '/', '.'); - return -1; - } + strlcpy(path, ARUU_LINUX_PATH_PROC_SYS "/", sizeof(path)); + if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) { + replacestr(variable, '/', '.'); + return -1; + } - replacestr(variable, '/', '.'); + replacestr(variable, '/', '.'); - fd = open(path, O_WRONLY); - if (fd < 0) - return -1; + fd = open(path, O_WRONLY); + if (fd < 0) + return -1; - n = write(fd, value, strlen(value)); - if ((size_t)n != strlen(value)) { - close(fd); - return -1; - } + n = write(fd, value, strlen(value)); + if ((size_t)n != strlen(value)) { + close(fd); + return -1; + } - close(fd); + close(fd); - return 0; + return 0; } static int parsepair(char *pair) { - char *p; - char *variable; - char *value; - - for (p = pair; *p; p++) { - if (p[0] == '.' && p[1] == '.') { - weprintf("malformed input: %s\n", pair); - return -1; - } - } - p = strchr(pair, '='); - if (p) { - if (p[1] == '\0') { - weprintf("malformed input: %s\n", pair); - return -1; - } - *p = '\0'; - value = &p[1]; - } else { - value = NULL; - } - variable = pair; - if (value) { - if (setsysctl(variable, value) < 0) { - weprintf("failed to set sysctl for %s\n", variable); - return -1; - } - } else { - if (getsysctl(variable, &value) < 0) { - weprintf("failed to get sysctl for %s\n", variable); - return -1; - } - printf("%s = %s\n", variable, value); - free(value); - } - - return 0; + char *p; + char *variable; + char *value; + + for (p = pair; *p; p++) { + if (p[0] == '.' && p[1] == '.') { + weprintf("malformed input: %s\n", pair); + return -1; + } + } + p = strchr(pair, '='); + if (p) { + if (p[1] == '\0') { + weprintf("malformed input: %s\n", pair); + return -1; + } + *p = '\0'; + value = &p[1]; + } else { + value = NULL; + } + variable = pair; + if (value) { + if (setsysctl(variable, value) < 0) { + weprintf("failed to set sysctl for %s\n", variable); + return -1; + } + } else { + if (getsysctl(variable, &value) < 0) { + weprintf("failed to get sysctl for %s\n", variable); + return -1; + } + printf("%s = %s\n", variable, value); + free(value); + } + + return 0; } static void usage(void) { - eprintf("usage: %s [-p file] variable[=value]...\n", argv0); + eprintf("usage: %s [-p file] variable[=value]...\n", argv0); } // ?man sysctl: configure kernel parameters @@ -166,54 +162,54 @@ usage(void) int main(int argc, char *argv[]) { - FILE *fp; - char *buf = NULL, *p; - char *file = NULL; - size_t size = 0; - int i; - int r = 0; - - ARGBEGIN { - // ?man -p:file: preserve file attributes - case 'p': - file = EARGF(usage()); - break; - default: - usage(); - } ARGEND; - - if (!file && argc < 1) - usage(); - - if (!file) { - for (i = 0; i < argc; i++) - if (parsepair(argv[i]) < 0) - r = 1; - } else { - fp = fopen(file, "r"); - if (!fp) - eprintf("fopen %s:", file); - while (agetline(&buf, &size, fp) != -1) { - p = buf; - for (p = buf; *p == ' ' || *p == '\t'; p++) - ; - if (*p == '#' || *p == '\n') - continue; - for (p = buf; *p; p++) { - if (*p == '\n') { - *p = '\0'; - break; - } - } - p = buf; - if (parsepair(p) < 0) - r = 1; - } - if (ferror(fp)) - eprintf("%s: read error:", file); - free(buf); - fclose(fp); - } - - return r; + FILE *fp; + char *buf = NULL, *p; + char *file = NULL; + size_t size = 0; + int i; + int r = 0; + + ARGBEGIN { + // ?man -p:file: preserve file attributes + case 'p': + file = EARGF(usage()); + break; + default: + usage(); + } ARGEND; + + if (!file && argc < 1) + usage(); + + if (!file) { + for (i = 0; i < argc; i++) + if (parsepair(argv[i]) < 0) + r = 1; + } else { + fp = fopen(file, "r"); + if (!fp) + eprintf("fopen %s:", file); + while (agetline(&buf, &size, fp) != -1) { + p = buf; + for (p = buf; *p == ' ' || *p == '\t'; p++) + ; + if (*p == '#' || *p == '\n') + continue; + for (p = buf; *p; p++) { + if (*p == '\n') { + *p = '\0'; + break; + } + } + p = buf; + if (parsepair(p) < 0) + r = 1; + } + if (ferror(fp)) + eprintf("%s: read error:", file); + free(buf); + fclose(fp); + } + + return r; } diff --git a/cmd/linux/tunctl.c b/cmd/linux/tunctl.c @@ -17,6 +17,7 @@ #include <linux/if.h> #include <linux/if_tun.h> +#include "paths.h" #include "util.h" static int dflag; diff --git a/cmd/linux/umount.c b/cmd/linux/umount.c @@ -8,6 +8,7 @@ #include <stdlib.h> #include <string.h> +#include "paths.h" #include "util.h" #if FEATURE_UMOUNT_OPTIONS @@ -87,9 +88,9 @@ umountall(int flags char **mntdirs = NULL; int len = 0; - fp = setmntent("/proc/mounts", "r"); + fp = setmntent(ARUU_LINUX_PATH_PROC_MOUNTS, "r"); if (!fp) - eprintf("setmntent %s:", "/proc/mounts"); + eprintf("setmntent %s:", ARUU_LINUX_PATH_PROC_MOUNTS); while ((me = getmntent(fp))) { if (strcmp(me->mnt_type, "proc") == 0) continue; diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c @@ -7,6 +7,7 @@ #include <string.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -58,8 +59,8 @@ main(int argc, char *argv[]) if (unshare(flags) < 0) eprintf("unshare:"); - if (execvp(argv[0], argv) < 0) - eprintf("execvp:"); + if (0) wexecvp_self(argv[0], argv); + eprintf("wexecvp:"); return 0; } diff --git a/cmd/linux/vtallow.c b/cmd/linux/vtallow.c @@ -10,9 +10,10 @@ #include <string.h> #include <unistd.h> +#include "paths.h" #include "util.h" -#define CONSOLE "/dev/console" +#define CONSOLE ARUU_PATH_DEVCONSOLE #define VT_LOCKSWITCH 0x560B /* disallow vt switching */ #define VT_UNLOCKSWITCH 0x560C /* allow vt switching */ diff --git a/cmd/net/sdhcp.c b/cmd/net/sdhcp.c @@ -1,6 +1,7 @@ /* sdhcp: simple DHCP client, ported from git.2f30.org/sdhcp */ /* See LICENSE file for copyright and license details */ #include "arg.h" +#include "wexec.h" #include "util.h" #include <errno.h> @@ -23,67 +24,67 @@ /* bootp packet layout: fields are byte arrays to avoid alignment/endian issues */ struct Bootp { - unsigned char op [1]; - unsigned char htype [1]; - unsigned char hlen [1]; - unsigned char hops [1]; - unsigned char xid [4]; - unsigned char secs [2]; - unsigned char flags [2]; - unsigned char ciaddr [4]; - unsigned char yiaddr [4]; - unsigned char siaddr [4]; - unsigned char giaddr [4]; - unsigned char chaddr [16]; - unsigned char sname [64]; - unsigned char file [128]; - unsigned char magic [4]; - unsigned char optdata [312-4]; + unsigned char op [1]; + unsigned char htype [1]; + unsigned char hlen [1]; + unsigned char hops [1]; + unsigned char xid [4]; + unsigned char secs [2]; + unsigned char flags [2]; + unsigned char ciaddr [4]; + unsigned char yiaddr [4]; + unsigned char siaddr [4]; + unsigned char giaddr [4]; + unsigned char chaddr [16]; + unsigned char sname [64]; + unsigned char file [128]; + unsigned char magic [4]; + unsigned char optdata [312-4]; }; enum { - DHCP_DISCOVER = 1, - DHCP_OFFER, - DHCP_REQUEST, - DHCP_DECLINE, - DHCP_ACK, - DHCP_NAK, - DHCP_RELEASE, - DHCP_INFORM, - /* internal sentinel values returned by dhcprecv */ - TIMEOUT0 = 200, - TIMEOUT1, - TIMEOUT2, - - BOOT_REQUEST = 1, - BOOT_REPLY = 2, - /* bootp flags */ - F_BROADCAST = 1 << 15, - - /* bootp options */ - OB_PAD = 0, - OB_MASK = 1, - OB_ROUTER = 3, - OB_NAMESERVER = 5, - OB_DNSSERVER = 6, - OB_HOSTNAME = 12, - OB_BADDR = 28, - /* DHCP-specific options */ - OD_IPADDR = 50, /* 0x32 */ - OD_LEASE = 51, - OD_OVERLOAD = 52, - OD_TYPE = 53, /* 0x35 */ - OD_SERVERID = 54, /* 0x36 */ - OD_PARAMS = 55, /* 0x37 */ - OD_MESSAGE = 56, - OD_MAXMSG = 57, - OD_RENEWALTIME = 58, - OD_REBINDINGTIME = 59, - OD_VENDORCLASS = 60, - OD_CLIENTID = 61, /* 0x3d */ - OD_TFTPSERVER = 66, - OD_BOOTFILE = 67, - OB_END = 255, + DHCP_DISCOVER = 1, + DHCP_OFFER, + DHCP_REQUEST, + DHCP_DECLINE, + DHCP_ACK, + DHCP_NAK, + DHCP_RELEASE, + DHCP_INFORM, + /* internal sentinel values returned by dhcprecv */ + TIMEOUT0 = 200, + TIMEOUT1, + TIMEOUT2, + + BOOT_REQUEST = 1, + BOOT_REPLY = 2, + /* bootp flags */ + F_BROADCAST = 1 << 15, + + /* bootp options */ + OB_PAD = 0, + OB_MASK = 1, + OB_ROUTER = 3, + OB_NAMESERVER = 5, + OB_DNSSERVER = 6, + OB_HOSTNAME = 12, + OB_BADDR = 28, + /* DHCP-specific options */ + OD_IPADDR = 50, /* 0x32 */ + OD_LEASE = 51, + OD_OVERLOAD = 52, + OD_TYPE = 53, /* 0x35 */ + OD_SERVERID = 54, /* 0x36 */ + OD_PARAMS = 55, /* 0x37 */ + OD_MESSAGE = 56, + OD_MAXMSG = 57, + OD_RENEWALTIME = 58, + OD_REBINDINGTIME = 59, + OD_VENDORCLASS = 60, + OD_CLIENTID = 61, /* 0x3d */ + OD_TFTPSERVER = 66, + OD_BOOTFILE = 67, + OB_END = 255, }; enum { BROADCAST, UNICAST }; @@ -118,485 +119,488 @@ static int fflag = 0; static void hnput(unsigned char *dst, uint32_t src, size_t n) { - unsigned int i; + unsigned int i; - for (i = 0; n--; i++) - dst[i] = (src >> (n * 8)) & 0xff; + for (i = 0; n--; i++) + dst[i] = (src >> (n * 8)) & 0xff; } static struct sockaddr * iptoaddr(struct sockaddr *ifaddr, unsigned char ip[4], int port) { - struct sockaddr_in *in = (struct sockaddr_in *)ifaddr; + struct sockaddr_in *in = (struct sockaddr_in *)ifaddr; - in->sin_family = AF_INET; - in->sin_port = htons(port); - memcpy(&(in->sin_addr), ip, sizeof(in->sin_addr)); + in->sin_family = AF_INET; + in->sin_port = htons(port); + memcpy(&(in->sin_addr), ip, sizeof(in->sin_addr)); - return ifaddr; + return ifaddr; } /* sendto UDP wrapper: sends n bytes of data to bootp server port on ip */ static ssize_t udpsend(unsigned char ip[4], int fd, void *data, size_t n) { - struct sockaddr addr; - socklen_t addrlen = sizeof(addr); - ssize_t sent; + struct sockaddr addr; + socklen_t addrlen = sizeof(addr); + ssize_t sent; - iptoaddr(&addr, ip, 67); /* bootp server */ - if ((sent = sendto(fd, data, n, 0, &addr, addrlen)) == -1) - eprintf("sendto:"); + iptoaddr(&addr, ip, 67); /* bootp server */ + if ((sent = sendto(fd, data, n, 0, &addr, addrlen)) == -1) + eprintf("sendto:"); - return sent; + return sent; } /* recvfrom UDP wrapper: receives into data from bootp client port */ static ssize_t udprecv(unsigned char ip[4], int fd, void *data, size_t n) { - struct sockaddr addr; - socklen_t addrlen = sizeof(addr); - ssize_t r; + struct sockaddr addr; + socklen_t addrlen = sizeof(addr); + ssize_t r; - iptoaddr(&addr, ip, 68); /* bootp client */ - if ((r = recvfrom(fd, data, n, 0, &addr, &addrlen)) == -1) - eprintf("recvfrom:"); + iptoaddr(&addr, ip, 68); /* bootp client */ + if ((r = recvfrom(fd, data, n, 0, &addr, &addrlen)) == -1) + eprintf("recvfrom:"); - return r; + return r; } static void setip(unsigned char ip[4], unsigned char mask[4], unsigned char gateway[4]) { - struct ifreq ifreq; - struct rtentry rtreq; - int fd; - - memset(&ifreq, 0, sizeof(ifreq)); - memset(&rtreq, 0, sizeof(rtreq)); - - strlcpy(ifreq.ifr_name, ifname, IF_NAMESIZE); - iptoaddr(&(ifreq.ifr_addr), ip, 0); - if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) - eprintf("can't set ip, socket:"); - ioctl(fd, SIOCSIFADDR, &ifreq); - iptoaddr(&(ifreq.ifr_netmask), mask, 0); - ioctl(fd, SIOCSIFNETMASK, &ifreq); - ifreq.ifr_flags = IFF_UP | IFF_RUNNING | IFF_BROADCAST | IFF_MULTICAST; - ioctl(fd, SIOCSIFFLAGS, &ifreq); - /* default gw */ - rtreq.rt_flags = RTF_UP | RTF_GATEWAY; - iptoaddr(&(rtreq.rt_gateway), gateway, 0); - iptoaddr(&(rtreq.rt_genmask), IP(0, 0, 0, 0), 0); - iptoaddr(&(rtreq.rt_dst), IP(0, 0, 0, 0), 0); - ioctl(fd, SIOCADDRT, &rtreq); - - close(fd); + struct ifreq ifreq; + struct rtentry rtreq; + int fd; + + memset(&ifreq, 0, sizeof(ifreq)); + memset(&rtreq, 0, sizeof(rtreq)); + + strlcpy(ifreq.ifr_name, ifname, IF_NAMESIZE); + iptoaddr(&(ifreq.ifr_addr), ip, 0); + if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) + eprintf("can't set ip, socket:"); + ioctl(fd, SIOCSIFADDR, &ifreq); + iptoaddr(&(ifreq.ifr_netmask), mask, 0); + ioctl(fd, SIOCSIFNETMASK, &ifreq); + ifreq.ifr_flags = IFF_UP | IFF_RUNNING | IFF_BROADCAST | IFF_MULTICAST; + ioctl(fd, SIOCSIFFLAGS, &ifreq); + /* default gw */ + rtreq.rt_flags = RTF_UP | RTF_GATEWAY; + iptoaddr(&(rtreq.rt_gateway), gateway, 0); + iptoaddr(&(rtreq.rt_genmask), IP(0, 0, 0, 0), 0); + iptoaddr(&(rtreq.rt_dst), IP(0, 0, 0, 0), 0); + ioctl(fd, SIOCADDRT, &rtreq); + + close(fd); } /* copy contents of src path into dfd; silently skips missing files */ static void appendfile(int dfd, char *src) { - char buf[BUFSIZ]; - int fd, n; - - if ((fd = open(src, O_RDONLY)) == -1) - return; - while ((n = read(fd, buf, sizeof(buf))) > 0) - writeall(dfd, buf, n); - close(fd); + char buf[BUFSIZ]; + int fd, n; + + if ((fd = open(src, O_RDONLY)) == -1) + return; + while ((n = read(fd, buf, sizeof(buf))) > 0) + writeall(dfd, buf, n); + close(fd); } static void setdns(unsigned char ip[4]) { - char buf[128]; - int fd, n; - - if ((fd = creat("/etc/resolv.conf", 0644)) == -1) { - weprintf("can't change /etc/resolv.conf:"); - return; - } - appendfile(fd, "/etc/resolv.conf.head"); - n = snprintf(buf, sizeof(buf), "\nnameserver %d.%d.%d.%d\n", - ip[0], ip[1], ip[2], ip[3]); - if (n > 0) - writeall(fd, buf, n); - appendfile(fd, "/etc/resolv.conf.tail"); - close(fd); + char buf[128]; + int fd, n; + + if ((fd = creat("/etc/resolv.conf", 0644)) == -1) { + weprintf("can't change /etc/resolv.conf:"); + return; + } + appendfile(fd, "/etc/resolv.conf.head"); + n = snprintf(buf, sizeof(buf), "\nnameserver %d.%d.%d.%d\n", + ip[0], ip[1], ip[2], ip[3]); + if (n > 0) + writeall(fd, buf, n); + appendfile(fd, "/etc/resolv.conf.tail"); + close(fd); } /* scan b's option data for opt; copy up to n bytes into data */ static void optget(struct Bootp *b, void *data, int opt, int n) { - unsigned char *p = b->optdata; - unsigned char *top = ((unsigned char *)b) + sizeof(*b); - int code, len; - - while (p < top) { - code = *p++; - if (code == OB_PAD) - continue; - if (code == OB_END || p == top) - break; - len = *p++; - if (len > top - p) - break; - if (code == opt) { - memcpy(data, p, MIN(len, n)); - break; - } - p += len; - } + unsigned char *p = b->optdata; + unsigned char *top = ((unsigned char *)b) + sizeof(*b); + int code, len; + + while (p < top) { + code = *p++; + if (code == OB_PAD) + continue; + if (code == OB_END || p == top) + break; + len = *p++; + if (len > top - p) + break; + if (code == opt) { + memcpy(data, p, MIN(len, n)); + break; + } + p += len; + } } /* append a raw-bytes option to p; return new write cursor */ static unsigned char * optput(unsigned char *p, int opt, unsigned char *data, size_t len) { - *p++ = opt; - *p++ = (unsigned char)len; - memcpy(p, data, len); + *p++ = opt; + *p++ = (unsigned char)len; + memcpy(p, data, len); - return p + len; + return p + len; } /* append a big-endian numeric option to p; return new write cursor */ static unsigned char * hnoptput(unsigned char *p, int opt, uint32_t data, size_t len) { - *p++ = opt; - *p++ = (unsigned char)len; - hnput(p, data, len); + *p++ = opt; + *p++ = (unsigned char)len; + hnput(p, data, len); - return p + len; + return p + len; } static void dhcpsend(int type, int how) { - unsigned char *ip, *p; - - memset(&bp, 0, sizeof(bp)); - hnput(bp.op, BOOT_REQUEST, 1); - hnput(bp.htype, 1, 1); - hnput(bp.hlen, 6, 1); - memcpy(bp.xid, xid, sizeof(xid)); - hnput(bp.flags, F_BROADCAST, sizeof(bp.flags)); - hnput(bp.secs, time(NULL) - starttime, sizeof(bp.secs)); - memcpy(bp.magic, magic, sizeof(bp.magic)); - memcpy(bp.chaddr, hwaddr, sizeof(bp.chaddr)); - p = bp.optdata; - p = hnoptput(p, OD_TYPE, type, 1); - p = optput(p, OD_CLIENTID, cid, sizeof(cid)); - p = optput(p, OB_HOSTNAME, (unsigned char *)hostname, strlen(hostname)); - - switch (type) { - case DHCP_DISCOVER: - break; - case DHCP_REQUEST: - p = optput(p, OD_IPADDR, client, sizeof(client)); - p = optput(p, OD_SERVERID, server, sizeof(server)); - break; - case DHCP_RELEASE: - memcpy(bp.ciaddr, client, sizeof(client)); - p = optput(p, OD_IPADDR, client, sizeof(client)); - p = optput(p, OD_SERVERID, server, sizeof(server)); - break; - } - *p++ = OB_END; - - ip = (how == BROADCAST) ? IP(255, 255, 255, 255) : server; - udpsend(ip, sock, &bp, p - (unsigned char *)&bp); + unsigned char *ip, *p; + + memset(&bp, 0, sizeof(bp)); + hnput(bp.op, BOOT_REQUEST, 1); + hnput(bp.htype, 1, 1); + hnput(bp.hlen, 6, 1); + memcpy(bp.xid, xid, sizeof(xid)); + hnput(bp.flags, F_BROADCAST, sizeof(bp.flags)); + hnput(bp.secs, time(NULL) - starttime, sizeof(bp.secs)); + memcpy(bp.magic, magic, sizeof(bp.magic)); + memcpy(bp.chaddr, hwaddr, sizeof(bp.chaddr)); + p = bp.optdata; + p = hnoptput(p, OD_TYPE, type, 1); + p = optput(p, OD_CLIENTID, cid, sizeof(cid)); + p = optput(p, OB_HOSTNAME, (unsigned char *)hostname, strlen(hostname)); + + switch (type) { + case DHCP_DISCOVER: + break; + case DHCP_REQUEST: + p = optput(p, OD_IPADDR, client, sizeof(client)); + p = optput(p, OD_SERVERID, server, sizeof(server)); + break; + case DHCP_RELEASE: + memcpy(bp.ciaddr, client, sizeof(client)); + p = optput(p, OD_IPADDR, client, sizeof(client)); + p = optput(p, OD_SERVERID, server, sizeof(server)); + break; + } + *p++ = OB_END; + + ip = (how == BROADCAST) ? IP(255, 255, 255, 255) : server; + udpsend(ip, sock, &bp, p - (unsigned char *)&bp); } /* block on poll; return DHCP message type or a TIMEOUT* sentinel */ static int dhcprecv(void) { - unsigned char type = 0; - uint64_t n; - struct pollfd pfd[] = { - { .fd = sock, .events = POLLIN }, - { .fd = timers[0], .events = POLLIN }, - { .fd = timers[1], .events = POLLIN }, - { .fd = timers[2], .events = POLLIN }, - }; - - if (poll(pfd, LEN(pfd), -1) == -1) - eprintf("poll:"); - if (pfd[0].revents) { - memset(&bp, 0, sizeof(bp)); - udprecv(IP(255, 255, 255, 255), sock, &bp, sizeof(bp)); - optget(&bp, &type, OD_TYPE, sizeof(type)); - return type; - } - if (pfd[1].revents) { - type = TIMEOUT0; - read(timers[0], &n, sizeof(n)); - } - if (pfd[2].revents) { - type = TIMEOUT1; - read(timers[1], &n, sizeof(n)); - } - if (pfd[3].revents) { - type = TIMEOUT2; - read(timers[2], &n, sizeof(n)); - } - return type; + unsigned char type = 0; + uint64_t n; + struct pollfd pfd[] = { + { .fd = sock, .events = POLLIN }, + { .fd = timers[0], .events = POLLIN }, + { .fd = timers[1], .events = POLLIN }, + { .fd = timers[2], .events = POLLIN }, + }; + + if (poll(pfd, LEN(pfd), -1) == -1) + eprintf("poll:"); + if (pfd[0].revents) { + memset(&bp, 0, sizeof(bp)); + udprecv(IP(255, 255, 255, 255), sock, &bp, sizeof(bp)); + optget(&bp, &type, OD_TYPE, sizeof(type)); + return type; + } + if (pfd[1].revents) { + type = TIMEOUT0; + read(timers[0], &n, sizeof(n)); + } + if (pfd[2].revents) { + type = TIMEOUT1; + read(timers[1], &n, sizeof(n)); + } + if (pfd[3].revents) { + type = TIMEOUT2; + read(timers[2], &n, sizeof(n)); + } + return type; } static void acceptlease(void) { - char buf[128]; - - if (iflag) - setip(client, mask, router); - if (dflag) - setdns(dns); - if (*program) { - snprintf(buf, sizeof(buf), "%d.%d.%d.%d", - server[0], server[1], server[2], server[3]); - setenv("SERVER", buf, 1); - snprintf(buf, sizeof(buf), "%d.%d.%d.%d", - client[0], client[1], client[2], client[3]); - setenv("CLIENT", buf, 1); - snprintf(buf, sizeof(buf), "%d.%d.%d.%d", - mask[0], mask[1], mask[2], mask[3]); - setenv("MASK", buf, 1); - snprintf(buf, sizeof(buf), "%d.%d.%d.%d", - router[0], router[1], router[2], router[3]); - setenv("ROUTER", buf, 1); - snprintf(buf, sizeof(buf), "%d.%d.%d.%d", - dns[0], dns[1], dns[2], dns[3]); - setenv("DNS", buf, 1); - system(program); - } + char buf[128]; + + if (iflag) + setip(client, mask, router); + if (dflag) + setdns(dns); + if (*program) { + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + server[0], server[1], server[2], server[3]); + setenv("SERVER", buf, 1); + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + client[0], client[1], client[2], client[3]); + setenv("CLIENT", buf, 1); + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + mask[0], mask[1], mask[2], mask[3]); + setenv("MASK", buf, 1); + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + router[0], router[1], router[2], router[3]); + setenv("ROUTER", buf, 1); + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + dns[0], dns[1], dns[2], dns[3]); + setenv("DNS", buf, 1); + wsystem(program); + } } static void settimeout(int n, const struct itimerspec *ts) { - if (timerfd_settime(timers[n], 0, ts, NULL) < 0) - eprintf("timerfd_settime:"); + if (timerfd_settime(timers[n], 0, ts, NULL) < 0) + eprintf("timerfd_settime:"); } /* set ts to expire halfway to the remaining time on timer n, minimum 60s */ static void calctimeout(int n, struct itimerspec *ts) { - if (timerfd_gettime(timers[n], ts) < 0) - eprintf("timerfd_gettime:"); - ts->it_value.tv_nsec /= 2; - if (ts->it_value.tv_sec % 2) - ts->it_value.tv_nsec += 500000000; - ts->it_value.tv_sec /= 2; - if (ts->it_value.tv_sec < 60) { - ts->it_value.tv_sec = 60; - ts->it_value.tv_nsec = 0; - } + if (timerfd_gettime(timers[n], ts) < 0) + eprintf("timerfd_gettime:"); + ts->it_value.tv_nsec /= 2; + if (ts->it_value.tv_sec % 2) + ts->it_value.tv_nsec += 500000000; + ts->it_value.tv_sec /= 2; + if (ts->it_value.tv_sec < 60) { + ts->it_value.tv_sec = 60; + ts->it_value.tv_nsec = 0; + } } /* RFC 2131 DHCP state machine */ static void run(void) { - int forked = 0, t; - struct itimerspec timeout = { 0 }; - uint32_t renewaltime, rebindingtime, lease; + int forked = 0, t; + struct itimerspec timeout = { 0 }; + uint32_t renewaltime, rebindingtime, lease; Init: - dhcpsend(DHCP_DISCOVER, BROADCAST); - timeout.it_value.tv_sec = 1; - timeout.it_value.tv_nsec = 0; - settimeout(0, &timeout); - goto Selecting; + dhcpsend(DHCP_DISCOVER, BROADCAST); + timeout.it_value.tv_sec = 1; + timeout.it_value.tv_nsec = 0; + settimeout(0, &timeout); + goto Selecting; Selecting: - for (;;) { - switch (dhcprecv()) { - case DHCP_OFFER: - memcpy(client, bp.yiaddr, sizeof(client)); - optget(&bp, server, OD_SERVERID, sizeof(server)); - goto Requesting; - case TIMEOUT0: - goto Init; - } - } + for (;;) { + switch (dhcprecv()) { + case DHCP_OFFER: + memcpy(client, bp.yiaddr, sizeof(client)); + optget(&bp, server, OD_SERVERID, sizeof(server)); + goto Requesting; + case TIMEOUT0: + goto Init; + } + } Requesting: - for (t = 4; t <= 64; t *= 2) { - dhcpsend(DHCP_REQUEST, BROADCAST); - timeout.it_value.tv_sec = t; - settimeout(0, &timeout); - for (;;) { - switch (dhcprecv()) { - case DHCP_ACK: - goto Bound; - case DHCP_NAK: - goto Init; - case TIMEOUT0: - break; - default: - continue; - } - break; - } - } - /* no ACK after several DHCPREQUEST attempts */ - goto Init; + for (t = 4; t <= 64; t *= 2) { + dhcpsend(DHCP_REQUEST, BROADCAST); + timeout.it_value.tv_sec = t; + settimeout(0, &timeout); + for (;;) { + switch (dhcprecv()) { + case DHCP_ACK: + goto Bound; + case DHCP_NAK: + goto Init; + case TIMEOUT0: + break; + default: + continue; + } + break; + } + } + /* no ACK after several DHCPREQUEST attempts */ + goto Init; Bound: - optget(&bp, mask, OB_MASK, sizeof(mask)); - optget(&bp, router, OB_ROUTER, sizeof(router)); - optget(&bp, dns, OB_DNSSERVER, sizeof(dns)); - optget(&bp, &renewaltime, OD_RENEWALTIME, sizeof(renewaltime)); - optget(&bp, &rebindingtime, OD_REBINDINGTIME, sizeof(rebindingtime)); - optget(&bp, &lease, OD_LEASE, sizeof(lease)); - renewaltime = ntohl(renewaltime); - rebindingtime = ntohl(rebindingtime); - lease = ntohl(lease); - acceptlease(); - puts("Bound. Network configured."); - if (!fflag && !forked) { - if (fork()) - exit(0); - forked = 1; - } - timeout.it_value.tv_sec = renewaltime; - settimeout(0, &timeout); - timeout.it_value.tv_sec = rebindingtime; - settimeout(1, &timeout); - timeout.it_value.tv_sec = lease; - settimeout(2, &timeout); - for (;;) { - switch (dhcprecv()) { - case TIMEOUT0: /* t1: enter renewing */ - goto Renewing; - case TIMEOUT1: /* t2: enter rebinding */ - goto Rebinding; - case TIMEOUT2: /* lease expired */ - goto Init; - } - } + optget(&bp, mask, OB_MASK, sizeof(mask)); + optget(&bp, router, OB_ROUTER, sizeof(router)); + optget(&bp, dns, OB_DNSSERVER, sizeof(dns)); + optget(&bp, &renewaltime, OD_RENEWALTIME, sizeof(renewaltime)); + optget(&bp, &rebindingtime, OD_REBINDINGTIME, sizeof(rebindingtime)); + optget(&bp, &lease, OD_LEASE, sizeof(lease)); + renewaltime = ntohl(renewaltime); + rebindingtime = ntohl(rebindingtime); + lease = ntohl(lease); + acceptlease(); + puts("Bound. Network configured."); + if (!fflag && !forked) { + if (fork()) + exit(0); + forked = 1; + } + timeout.it_value.tv_sec = renewaltime; + settimeout(0, &timeout); + timeout.it_value.tv_sec = rebindingtime; + settimeout(1, &timeout); + timeout.it_value.tv_sec = lease; + settimeout(2, &timeout); + for (;;) { + switch (dhcprecv()) { + case TIMEOUT0: /* t1: enter renewing */ + goto Renewing; + case TIMEOUT1: /* t2: enter rebinding */ + goto Rebinding; + case TIMEOUT2: /* lease expired */ + goto Init; + } + } Renewing: - dhcpsend(DHCP_REQUEST, UNICAST); - calctimeout(1, &timeout); - settimeout(0, &timeout); - for (;;) { - switch (dhcprecv()) { - case DHCP_ACK: - goto Bound; - case TIMEOUT0: /* resend unicast */ - goto Renewing; - case TIMEOUT1: /* t2 elapsed */ - goto Rebinding; - case TIMEOUT2: - case DHCP_NAK: - goto Init; - } - } + dhcpsend(DHCP_REQUEST, UNICAST); + calctimeout(1, &timeout); + settimeout(0, &timeout); + for (;;) { + switch (dhcprecv()) { + case DHCP_ACK: + goto Bound; + case TIMEOUT0: /* resend unicast */ + goto Renewing; + case TIMEOUT1: /* t2 elapsed */ + goto Rebinding; + case TIMEOUT2: + case DHCP_NAK: + goto Init; + } + } Rebinding: - calctimeout(2, &timeout); - settimeout(0, &timeout); - dhcpsend(DHCP_REQUEST, BROADCAST); - for (;;) { - switch (dhcprecv()) { - case DHCP_ACK: - goto Bound; - case TIMEOUT0: /* resend broadcast */ - goto Rebinding; - case TIMEOUT2: /* lease expired */ - case DHCP_NAK: - goto Init; - } - } + calctimeout(2, &timeout); + settimeout(0, &timeout); + dhcpsend(DHCP_REQUEST, BROADCAST); + for (;;) { + switch (dhcprecv()) { + case DHCP_ACK: + goto Bound; + case TIMEOUT0: /* resend broadcast */ + goto Rebinding; + case TIMEOUT2: /* lease expired */ + case DHCP_NAK: + goto Init; + } + } } static void cleanexit(int unused) { - (void)unused; - dhcpsend(DHCP_RELEASE, UNICAST); - _exit(0); + (void)unused; + dhcpsend(DHCP_RELEASE, UNICAST); + _exit(0); } static void usage(void) { - eprintf("usage: %s [-d] [-e program] [-f] [-i] [ifname] [clientid]\n", argv0); + eprintf("usage: %s [-d] [-e program] [-f] [-i] [ifname] [clientid]\n", argv0); } +// ?man sdhcp: minimal DHCP client +// ?man arguments: [ifname] [clientid] +// ?man obtain an IPv4 lease via DHCP on the given interface int main(int argc, char *argv[]) { - struct ifreq ifreq; - struct sockaddr addr; - int bcast = 1; - int rnd; - size_t i; - - ARGBEGIN { - case 'd': /* don't update /etc/resolv.conf */ - dflag = 0; - break; - case 'e': /* exec program on each lease */ - program = EARGF(usage()); - break; - case 'f': /* stay in foreground */ - fflag = 1; - break; - case 'i': /* don't configure IP address */ - iflag = 0; - break; - default: - usage(); - break; - } ARGEND - - if (argc) - ifname = argv[0]; - if (argc >= 2) - strlcpy((char *)cid, argv[1], sizeof(cid)); - - memset(&ifreq, 0, sizeof(ifreq)); - signal(SIGTERM, cleanexit); - - if (gethostname(hostname, sizeof(hostname)) == -1) - eprintf("gethostname:"); - - if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) - eprintf("socket:"); - if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(bcast)) == -1) - eprintf("setsockopt SO_BROADCAST:"); - - strlcpy(ifreq.ifr_name, ifname, IF_NAMESIZE); - ioctl(sock, SIOCGIFINDEX, &ifreq); - if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifreq, sizeof(ifreq)) == -1) - eprintf("setsockopt SO_BINDTODEVICE:"); - iptoaddr(&addr, IP(255, 255, 255, 255), 68); - if (bind(sock, &addr, sizeof(addr)) != 0) - eprintf("bind:"); - ioctl(sock, SIOCGIFHWADDR, &ifreq); - memcpy(hwaddr, ifreq.ifr_hwaddr.sa_data, sizeof(ifreq.ifr_hwaddr.sa_data)); - if (!cid[0]) - memcpy(cid, hwaddr, sizeof(cid)); - - if ((rnd = open("/dev/urandom", O_RDONLY)) == -1) - eprintf("open /dev/urandom:"); - if (read(rnd, xid, sizeof(xid)) != (ssize_t)sizeof(xid)) - eprintf("read /dev/urandom:"); - close(rnd); - - for (i = 0; i < LEN(timers); ++i) { - timers[i] = timerfd_create(CLOCK_BOOTTIME, TFD_CLOEXEC); - if (timers[i] == -1) - eprintf("timerfd_create:"); - } - - starttime = time(NULL); - run(); - - return 0; + struct ifreq ifreq; + struct sockaddr addr; + int bcast = 1; + int rnd; + size_t i; + + ARGBEGIN { + case 'd': /* don't update /etc/resolv.conf */ + dflag = 0; + break; + case 'e': /* exec program on each lease */ + program = EARGF(usage()); + break; + case 'f': /* stay in foreground */ + fflag = 1; + break; + case 'i': /* don't configure IP address */ + iflag = 0; + break; + default: + usage(); + break; + } ARGEND + + if (argc) + ifname = argv[0]; + if (argc >= 2) + strlcpy((char *)cid, argv[1], sizeof(cid)); + + memset(&ifreq, 0, sizeof(ifreq)); + signal(SIGTERM, cleanexit); + + if (gethostname(hostname, sizeof(hostname)) == -1) + eprintf("gethostname:"); + + if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) + eprintf("socket:"); + if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(bcast)) == -1) + eprintf("setsockopt SO_BROADCAST:"); + + strlcpy(ifreq.ifr_name, ifname, IF_NAMESIZE); + ioctl(sock, SIOCGIFINDEX, &ifreq); + if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifreq, sizeof(ifreq)) == -1) + eprintf("setsockopt SO_BINDTODEVICE:"); + iptoaddr(&addr, IP(255, 255, 255, 255), 68); + if (bind(sock, &addr, sizeof(addr)) != 0) + eprintf("bind:"); + ioctl(sock, SIOCGIFHWADDR, &ifreq); + memcpy(hwaddr, ifreq.ifr_hwaddr.sa_data, sizeof(ifreq.ifr_hwaddr.sa_data)); + if (!cid[0]) + memcpy(cid, hwaddr, sizeof(cid)); + + if ((rnd = open("/dev/urandom", O_RDONLY)) == -1) + eprintf("open /dev/urandom:"); + if (read(rnd, xid, sizeof(xid)) != (ssize_t)sizeof(xid)) + eprintf("read /dev/urandom:"); + close(rnd); + + for (i = 0; i < LEN(timers); ++i) { + timers[i] = timerfd_create(CLOCK_BOOTTIME, TFD_CLOEXEC); + if (timers[i] == -1) + eprintf("timerfd_create:"); + } + + starttime = time(NULL); + run(); + + return 0; } diff --git a/cmd/posix/diff.c b/cmd/posix/diff.c @@ -1,19 +1,19 @@ /* See LICENSE file for copyright and license details. */ +#include "paths.h" #include "util.h" +#include "wexec.h" #include <sys/stat.h> #include <sys/wait.h> #include <ctype.h> #include <dirent.h> -#include <err.h> #include <errno.h> #include <fcntl.h> #include <fnmatch.h> #include <getopt.h> #include <limits.h> #include <math.h> -#include <paths.h> #include <poll.h> #include <regex.h> #include <signal.h> @@ -86,114 +86,113 @@ #define COLORFLAG_ALWAYS 2 #define FUNCTION_CONTEXT_SIZE 55 -#define _PATH_PR "/usr/bin/pr" #ifndef roundup #define roundup(x, y) ((((x) + ((y) - 1)) / (y)) * (y)) #endif struct Excludes { - char *pattern; - struct Excludes *next; + char *pattern; + struct Excludes *next; }; struct Cand { - int x; - int y; - int pred; + int x; + int y; + int pred; }; struct Line { - int serial; - int value; + int serial; + int value; }; struct ContextVec { - int a; - int b; - int c; - int d; + int a; + int b; + int c; + int d; }; struct Pr { - int ostdout; - pid_t cpid; + int ostdout; + pid_t cpid; }; struct Algorithm { - const char *name; - int id; + const char *name; + int id; }; static struct Algorithm algorithms[] = { - {"stone", D_DIFFSTONE}, - {"myers", D_DIFFMYERS}, - {"patience", D_DIFFPATIENCE}, - {NULL, D_DIFFNONE} + {"stone", D_DIFFSTONE}, + {"myers", D_DIFFMYERS}, + {"patience", D_DIFFPATIENCE}, + {NULL, D_DIFFNONE} }; /* options */ #define OPTIONS "0123456789A:aBbC:cdD:efF:HhI:iL:lnNPpqrS:sTtU:uwW:X:x:y" enum { - OPT_TSIZE = CHAR_MAX + 1, - OPT_STRIPCR, - OPT_IGN_FN_CASE, - OPT_NO_IGN_FN_CASE, - OPT_NORMAL, - OPT_HELP, - OPT_HORIZON_LINES, - OPT_CHANGED_GROUP_FORMAT, - OPT_SUPPRESS_COMMON, - OPT_COLOR, - OPT_NO_DEREFERENCE, - OPT_VERSION, + OPT_TSIZE = CHAR_MAX + 1, + OPT_STRIPCR, + OPT_IGN_FN_CASE, + OPT_NO_IGN_FN_CASE, + OPT_NORMAL, + OPT_HELP, + OPT_HORIZON_LINES, + OPT_CHANGED_GROUP_FORMAT, + OPT_SUPPRESS_COMMON, + OPT_COLOR, + OPT_NO_DEREFERENCE, + OPT_VERSION, }; static struct option longopts[] = { - { "algorithm", required_argument, 0, 'A' }, - { "text", no_argument, 0, 'a' }, - { "ignore-space-change", no_argument, 0, 'b' }, - { "context", optional_argument, 0, 'C' }, - { "ifdef", required_argument, 0, 'D' }, - { "minimal", no_argument, 0, 'd' }, - { "ed", no_argument, 0, 'e' }, - { "forward-ed", no_argument, 0, 'f' }, - { "show-function-line", required_argument, 0, 'F' }, - { "speed-large-files", no_argument, NULL, 'H' }, - { "ignore-blank-lines", no_argument, 0, 'B' }, - { "ignore-matching-lines", required_argument, 0, 'I' }, - { "ignore-case", no_argument, 0, 'i' }, - { "paginate", no_argument, NULL, 'l' }, - { "label", required_argument, 0, 'L' }, - { "new-file", no_argument, 0, 'N' }, - { "rcs", no_argument, 0, 'n' }, - { "unidirectional-new-file", no_argument, 0, 'P' }, - { "show-c-function", no_argument, 0, 'p' }, - { "brief", no_argument, 0, 'q' }, - { "recursive", no_argument, 0, 'r' }, - { "report-identical-files", no_argument, 0, 's' }, - { "starting-file", required_argument, 0, 'S' }, - { "expand-tabs", no_argument, 0, 't' }, - { "initial-tab", no_argument, 0, 'T' }, - { "unified", optional_argument, 0, 'U' }, - { "ignore-all-space", no_argument, 0, 'w' }, - { "width", required_argument, 0, 'W' }, - { "exclude", required_argument, 0, 'x' }, - { "exclude-from", required_argument, 0, 'X' }, - { "side-by-side", no_argument, NULL, 'y' }, - { "ignore-file-name-case", no_argument, NULL, OPT_IGN_FN_CASE }, - { "help", no_argument, NULL, OPT_HELP}, - { "horizon-lines", required_argument, NULL, OPT_HORIZON_LINES }, - { "no-dereference", no_argument, NULL, OPT_NO_DEREFERENCE}, - { "no-ignore-file-name-case", no_argument, NULL, OPT_NO_IGN_FN_CASE }, - { "normal", no_argument, NULL, OPT_NORMAL }, - { "strip-trailing-cr", no_argument, NULL, OPT_STRIPCR }, - { "tabsize", required_argument, NULL, OPT_TSIZE }, - { "changed-group-format", required_argument, NULL, OPT_CHANGED_GROUP_FORMAT}, - { "suppress-common-lines", no_argument, NULL, OPT_SUPPRESS_COMMON }, - { "color", optional_argument, NULL, OPT_COLOR }, - { "version", no_argument, NULL, OPT_VERSION}, - { NULL, 0, 0, '\0'} + { "algorithm", required_argument, 0, 'A' }, + { "text", no_argument, 0, 'a' }, + { "ignore-space-change", no_argument, 0, 'b' }, + { "context", optional_argument, 0, 'C' }, + { "ifdef", required_argument, 0, 'D' }, + { "minimal", no_argument, 0, 'd' }, + { "ed", no_argument, 0, 'e' }, + { "forward-ed", no_argument, 0, 'f' }, + { "show-function-line", required_argument, 0, 'F' }, + { "speed-large-files", no_argument, NULL, 'H' }, + { "ignore-blank-lines", no_argument, 0, 'B' }, + { "ignore-matching-lines", required_argument, 0, 'I' }, + { "ignore-case", no_argument, 0, 'i' }, + { "paginate", no_argument, NULL, 'l' }, + { "label", required_argument, 0, 'L' }, + { "new-file", no_argument, 0, 'N' }, + { "rcs", no_argument, 0, 'n' }, + { "unidirectional-new-file", no_argument, 0, 'P' }, + { "show-c-function", no_argument, 0, 'p' }, + { "brief", no_argument, 0, 'q' }, + { "recursive", no_argument, 0, 'r' }, + { "report-identical-files", no_argument, 0, 's' }, + { "starting-file", required_argument, 0, 'S' }, + { "expand-tabs", no_argument, 0, 't' }, + { "initial-tab", no_argument, 0, 'T' }, + { "unified", optional_argument, 0, 'U' }, + { "ignore-all-space", no_argument, 0, 'w' }, + { "width", required_argument, 0, 'W' }, + { "exclude", required_argument, 0, 'x' }, + { "exclude-from", required_argument, 0, 'X' }, + { "side-by-side", no_argument, NULL, 'y' }, + { "ignore-file-name-case", no_argument, NULL, OPT_IGN_FN_CASE }, + { "help", no_argument, NULL, OPT_HELP}, + { "horizon-lines", required_argument, NULL, OPT_HORIZON_LINES }, + { "no-dereference", no_argument, NULL, OPT_NO_DEREFERENCE}, + { "no-ignore-file-name-case", no_argument, NULL, OPT_NO_IGN_FN_CASE }, + { "normal", no_argument, NULL, OPT_NORMAL }, + { "strip-trailing-cr", no_argument, NULL, OPT_STRIPCR }, + { "tabsize", required_argument, NULL, OPT_TSIZE }, + { "changed-group-format", required_argument, NULL, OPT_CHANGED_GROUP_FORMAT}, + { "suppress-common-lines", no_argument, NULL, OPT_SUPPRESS_COMMON }, + { "color", optional_argument, NULL, OPT_COLOR }, + { "version", no_argument, NULL, OPT_VERSION}, + { NULL, 0, 0, '\0'} }; static const char diff_version[] = "FreeBSD diff 20240307"; @@ -213,9 +212,9 @@ struct Excludes *excludes_list; regex_t ignore_re, most_recent_re; enum Readhash { - RH_BINARY, - RH_OK, - RH_EOF + RH_BINARY, + RH_OK, + RH_EOF }; static struct Line *file[2]; @@ -305,101 +304,109 @@ void stop_pr(struct Pr *); static void handle_sig(int signo) { - write(sigpipe[1], &signo, sizeof(signo)); + write(sigpipe[1], &signo, sizeof(signo)); } struct Pr * start_pr(char *file1, char *file2) { - int pfd[2]; - pid_t pid; - char *header; - struct Pr *pr; - - pr = ecalloc(1, sizeof(*pr)); - xasprintf(&header, "%s %s %s", diffargs, file1, file2); - signal(SIGPIPE, SIG_IGN); - fflush(stdout); - if (pipe(pfd) == -1) - err(2, "pipe"); - if (sigpipe[0] < 0) { - if (pipe(sigpipe) == -1) - err(2, "pipe"); - if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC) == -1) - err(2, "fcntl"); - if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC) == -1) - err(2, "fcntl"); - if (signal(SIGCHLD, handle_sig) == SIG_ERR) - err(2, "signal"); - poll_fd.fd = sigpipe[0]; - poll_fd.events = POLLIN; - } - poll_fd.revents = 0; - switch ((pid = fork())) { - case -1: - status |= 2; - free(header); - err(2, "no more processes"); - case 0: - if (pfd[0] != STDIN_FILENO) { - dup2(pfd[0], STDIN_FILENO); - close(pfd[0]); - } - close(pfd[1]); - execl(_PATH_PR, _PATH_PR, "-h", header, (char *)0); - _exit(127); - default: - if (pfd[1] != STDOUT_FILENO) { - pr->ostdout = dup(STDOUT_FILENO); - dup2(pfd[1], STDOUT_FILENO); - close(pfd[1]); - } - close(pfd[0]); - free(header); - pr->cpid = pid; - } - return pr; + int pfd[2]; + pid_t pid; + char *header; + struct Pr *pr; + + pr = ecalloc(1, sizeof(*pr)); + xasprintf(&header, "%s %s %s", diffargs, file1, file2); + signal(SIGPIPE, SIG_IGN); + fflush(stdout); + if (pipe(pfd) == -1) + enprintf(2, "pipe"); + if (sigpipe[0] < 0) { + if (pipe(sigpipe) == -1) + enprintf(2, "pipe"); + if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC) == -1) + enprintf(2, "fcntl"); + if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC) == -1) + enprintf(2, "fcntl"); + if (signal(SIGCHLD, handle_sig) == SIG_ERR) + enprintf(2, "signal"); + poll_fd.fd = sigpipe[0]; + poll_fd.events = POLLIN; + } + poll_fd.revents = 0; + switch ((pid = fork())) { + case -1: + status |= 2; + free(header); + enprintf(2, "no more processes"); + /* fallthrough */ + case 0: + if (pfd[0] != STDIN_FILENO) { + dup2(pfd[0], STDIN_FILENO); + close(pfd[0]); + } + close(pfd[1]); + { + char *pr_argv[4]; + pr_argv[0] = "pr"; + pr_argv[1] = "-h"; + pr_argv[2] = header; + pr_argv[3] = NULL; + wexecvp_self("pr", pr_argv); + } + _exit(127); + default: + if (pfd[1] != STDOUT_FILENO) { + pr->ostdout = dup(STDOUT_FILENO); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); + } + close(pfd[0]); + free(header); + pr->cpid = pid; + } + return pr; } void stop_pr(struct Pr *pr) { - int wstatus; - int done = 0; - - if (!pr) - return; - - fflush(stdout); - if (pr->ostdout != STDOUT_FILENO) { - close(STDOUT_FILENO); - dup2(pr->ostdout, STDOUT_FILENO); - close(pr->ostdout); - } - while (!done) { - pid_t wpid; - int npe = poll(&poll_fd, 1, -1); - if (npe == -1) { - if (errno == EINTR) - continue; - err(2, "poll"); - } - if (poll_fd.revents != POLLIN) - continue; - if (read(poll_fd.fd, &npe, sizeof(npe)) < 0) - err(2, "read"); - while ((wpid = waitpid(-1, &wstatus, WNOHANG)) > 0) { - if (wpid != pr->cpid) - continue; - if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0) - errx(2, "pr exited abnormally"); - else if (WIFSIGNALED(wstatus)) - errx(2, "pr killed by signal %d", WTERMSIG(wstatus)); - done = 1; - break; - } - } - free(pr); + int wstatus; + int done = 0; + + if (!pr) + return; + + fflush(stdout); + if (pr->ostdout != STDOUT_FILENO) { + close(STDOUT_FILENO); + dup2(pr->ostdout, STDOUT_FILENO); + close(pr->ostdout); + } + while (!done) { + pid_t wpid; + int npe = poll(&poll_fd, 1, -1); + if (npe == -1) { + if (errno == EINTR) + continue; + enprintf(2, "poll"); + } + if (poll_fd.revents != POLLIN) + continue; + if (read(poll_fd.fd, &npe, sizeof(npe)) < 0) + enprintf(2, "read"); + while ((wpid = waitpid(-1, &wstatus, WNOHANG)) > 0) { + if (wpid != pr->cpid) + continue; + if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != 0) + enprintf(2, "pr exited abnormally"); + else if (WIFSIGNALED(wstatus)) + enprintf(2, "pr killed by signal %d", WTERMSIG(wstatus)); + done = 1; + break; + } + } + free(pr); } // ?man diff: differential file and directory comparator @@ -408,1823 +415,1823 @@ stop_pr(struct Pr *pr) int main(int argc, char **argv) { - const char *errstr = NULL; - char *ep, **oargv; - long l; - int ch, dflags, lastch, gotstdin, prevoptind, newarg; - - oargv = argv; - gotstdin = 0; - dflags = 0; - lastch = '\0'; - prevoptind = 1; - newarg = 1; - diff_context = 3; - diff_format = D_UNSET; - diff_algorithm = D_DIFFMYERS; - diff_algorithm_set = 0; + const char *errstr = NULL; + char *ep, **oargv; + long l; + int ch, dflags, lastch, gotstdin, prevoptind, newarg; + + oargv = argv; + gotstdin = 0; + dflags = 0; + lastch = '\0'; + prevoptind = 1; + newarg = 1; + diff_context = 3; + diff_format = D_UNSET; + diff_algorithm = D_DIFFMYERS; + diff_algorithm_set = 0; #define FORMAT_MISMATCHED(type) \ - (diff_format != D_UNSET && diff_format != (type)) - while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) { - // ?man -0: context length - // ?man -1: context length - // ?man -2: context length - // ?man -3: context length - // ?man -4: context length - // ?man -5: context length - // ?man -6: context length - // ?man -7: context length - // ?man -8: context length - // ?man -9: context length - switch (ch) { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - if (newarg) - usage(); - else if (lastch == 'c' || lastch == 'u') - diff_context = 0; - else if (!isdigit(lastch) || diff_context > INT_MAX / 10) - usage(); - diff_context = (diff_context * 10) + (ch - '0'); - break; - // ?man -A:algo: algorithm (stone, myers, patience) - case 'A': - diff_algorithm = D_DIFFNONE; - for (struct Algorithm *a = algorithms; a->name; a++) { - if (strcasecmp(optarg, a->name) == 0) { - diff_algorithm = a->id; - diff_algorithm_set = 1; - break; - } - } - if (diff_algorithm == D_DIFFNONE) { - printf("unknown algorithm: %s\n", optarg); - usage(); - } - break; - // ?man -a: force text mode - case 'a': - dflags |= D_FORCEASCII; - break; - // ?man -b: ignore space changes - case 'b': - dflags |= D_FOLDBLANKS; - break; - // ?man -C:lines: context format - case 'C': - // ?man -c: context format - case 'c': - if (FORMAT_MISMATCHED(D_CONTEXT)) - conflicting_format(); - cflag = 1; - diff_format = D_CONTEXT; - if (optarg != NULL) { - l = strtol(optarg, &ep, 10); - if (*ep != '\0' || l < 0 || l >= INT_MAX) - usage(); - diff_context = (int)l; - } - break; - // ?man -d: minimal diff search - case 'd': - dflags |= D_MINIMAL; - break; - // ?man -D:name: ifdef format - case 'D': - if (FORMAT_MISMATCHED(D_IFDEF)) - conflicting_format(); - diff_format = D_IFDEF; - ifdefname = optarg; - break; - // ?man -e: ed script format - case 'e': - if (FORMAT_MISMATCHED(D_EDIT)) - conflicting_format(); - diff_format = D_EDIT; - break; - // ?man -f: forward ed script format - case 'f': - if (FORMAT_MISMATCHED(D_REVERSE)) - conflicting_format(); - diff_format = D_REVERSE; - break; - // ?man -H: speed up large files (stub) - case 'H': - break; - // ?man -h: backward compatibility (stub) - case 'h': - break; - // ?man -B: ignore blank lines - case 'B': - dflags |= D_SKIPBLANKLINES; - break; - // ?man -F:pat: show function matching pattern - case 'F': - if (dflags & D_PROTOTYPE) - conflicting_format(); - dflags |= D_MATCHLAST; - most_recent_pat = estrdup(optarg); - break; - // ?man -I:pat: ignore pattern matching lines - case 'I': - push_ignore_pats(optarg); - break; - // ?man -i: ignore case - case 'i': - dflags |= D_IGNORECASE; - break; - // ?man -L:label: custom label - case 'L': - if (label[0] == NULL) - label[0] = optarg; - else if (label[1] == NULL) - label[1] = optarg; - else - usage(); - break; - // ?man -l: paginate output using pr - case 'l': - lflag = 1; - break; - // ?man -N: treat missing files as empty - case 'N': - Nflag = 1; - break; - // ?man -n: rcs format - case 'n': - if (FORMAT_MISMATCHED(D_NREVERSE)) - conflicting_format(); - diff_format = D_NREVERSE; - break; - // ?man -p: show C prototype context - case 'p': - if (dflags & D_MATCHLAST) - conflicting_format(); - dflags |= D_PROTOTYPE; - break; - // ?man -P: treat missing destination files as empty - case 'P': - Pflag = 1; - break; - // ?man -r: recursive directory comparison - case 'r': - rflag = 1; - break; - // ?man -q: brief output (differ / same only) - case 'q': - if (FORMAT_MISMATCHED(D_BRIEF)) - conflicting_format(); - diff_format = D_BRIEF; - break; - // ?man -S:name: starting file in directory comparison - case 'S': - start = optarg; - break; - // ?man -s: report identical files - case 's': - sflag = 1; - break; - // ?man -T: initial tab alignment - case 'T': - Tflag = 1; - break; - // ?man -t: expand tabs in output - case 't': - dflags |= D_EXPANDTABS; - break; - // ?man -U:lines: unified context format - case 'U': - // ?man -u: unified context format - case 'u': - if (FORMAT_MISMATCHED(D_UNIFIED)) - conflicting_format(); - diff_format = D_UNIFIED; - if (optarg != NULL) { - l = strtol(optarg, &ep, 10); - if (*ep != '\0' || l < 0 || l >= INT_MAX) - usage(); - diff_context = (int)l; - } - break; - // ?man -w: ignore all whitespace - case 'w': - dflags |= D_IGNOREBLANKS; - break; - // ?man -W:cols: column width for side-by-side - case 'W': - width = (int)strtonum(optarg, 1, INT_MAX, &errstr); - if (errstr) { - warnx("invalid width argument"); - usage(); - } - break; - // ?man -X:file: exclude patterns file - case 'X': - read_excludes_file(optarg); - break; - // ?man -x:pat: exclude pattern - case 'x': - push_excludes(optarg); - break; - // ?man -y: side by side format - case 'y': - if (FORMAT_MISMATCHED(D_SIDEBYSIDE)) - conflicting_format(); - diff_format = D_SIDEBYSIDE; - break; - case OPT_CHANGED_GROUP_FORMAT: - if (FORMAT_MISMATCHED(D_GFORMAT)) - conflicting_format(); - diff_format = D_GFORMAT; - group_format = optarg; - break; - case OPT_HELP: - help = 1; - usage(); - break; - case OPT_HORIZON_LINES: - break; - case OPT_IGN_FN_CASE: - ignore_file_case = 1; - break; - case OPT_NO_IGN_FN_CASE: - ignore_file_case = 0; - break; - case OPT_NORMAL: - if (FORMAT_MISMATCHED(D_NORMAL)) - conflicting_format(); - diff_format = D_NORMAL; - break; - case OPT_TSIZE: - tabsize = (int)strtonum(optarg, 1, INT_MAX, &errstr); - if (errstr) { - warnx("invalid tabsize argument"); - usage(); - } - break; - case OPT_STRIPCR: - dflags |= D_STRIPCR; - break; - case OPT_SUPPRESS_COMMON: - suppress_common = 1; - break; - case OPT_COLOR: - if (optarg == NULL || strncmp(optarg, "auto", 4) == 0) - colorflag = COLORFLAG_AUTO; - else if (strncmp(optarg, "always", 6) == 0) - colorflag = COLORFLAG_ALWAYS; - else if (strncmp(optarg, "never", 5) == 0) - colorflag = COLORFLAG_NEVER; - else - errx(2, "unsupported color option %s", optarg); - break; - case OPT_NO_DEREFERENCE: - noderef = 1; - break; - case OPT_VERSION: - printf("%s\n", diff_version); - exit(0); - default: - usage(); - break; - } - lastch = ch; - newarg = optind != prevoptind; - prevoptind = optind; - } - if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0) - diff_format = D_CONTEXT; - if (diff_format == D_UNSET) - diff_format = D_NORMAL; - argc -= optind; - argv += optind; - - if (do_color()) { - char *p; - const char *env; - - color = 1; - add_code = "32"; - del_code = "31"; - env = getenv("DIFFCOLORS"); - if (env != NULL && *env != '\0' && (p = estrdup(env))) { - add_code = p; - strsep(&p, ":"); - if (p != NULL) - del_code = p; - } - } - - if (argc != 2) - usage(); - checked_regcomp(ignore_pats, &ignore_re); - checked_regcomp(most_recent_pat, &most_recent_re); - if (strcmp(argv[0], "-") == 0) { - fstat(STDIN_FILENO, &stb1); - gotstdin = 1; - } else if (stat(argv[0], &stb1) != 0) { - if (!Nflag || errno != ENOENT) - err(2, "%s", argv[0]); - dflags |= D_EMPTY1; - memset(&stb1, 0, sizeof(struct stat)); - } - - if (strcmp(argv[1], "-") == 0) { - fstat(STDIN_FILENO, &stb2); - gotstdin = 1; - } else if (stat(argv[1], &stb2) != 0) { - if (!Nflag || errno != ENOENT) - err(2, "%s", argv[1]); - dflags |= D_EMPTY2; - memset(&stb2, 0, sizeof(stb2)); - stb2.st_mode = stb1.st_mode; - } - - if (dflags & D_EMPTY1 && dflags & D_EMPTY2){ - warn("%s", argv[0]); - warn("%s", argv[1]); - exit(2); - } - - if (stb1.st_mode == 0) - stb1.st_mode = stb2.st_mode; - - if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode))) - errx(2, "cant compare - to directory"); - set_argstr(oargv, argv); - if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) { - if (diff_format == D_IFDEF) - errx(2, "-D option not supported with directories"); - diffdir(argv[0], argv[1], dflags); - } else { - if (S_ISDIR(stb1.st_mode)) { - argv[0] = diff_splice(argv[0], argv[1]); - if (stat(argv[0], &stb1) == -1) - err(2, "%s", argv[0]); - } - if (S_ISDIR(stb2.st_mode)) { - argv[1] = diff_splice(argv[1], argv[0]); - if (stat(argv[1], &stb2) == -1) - err(2, "%s", argv[1]); - } - print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0], argv[1], ""); - } - if (fflush(stdout) != 0) - err(2, "stdout"); - exit(status); + (diff_format != D_UNSET && diff_format != (type)) + while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) { + // ?man -0: context length + // ?man -1: context length + // ?man -2: context length + // ?man -3: context length + // ?man -4: context length + // ?man -5: context length + // ?man -6: context length + // ?man -7: context length + // ?man -8: context length + // ?man -9: context length + switch (ch) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + if (newarg) + usage(); + else if (lastch == 'c' || lastch == 'u') + diff_context = 0; + else if (!isdigit(lastch) || diff_context > INT_MAX / 10) + usage(); + diff_context = (diff_context * 10) + (ch - '0'); + break; + // ?man -A:algo: algorithm (stone, myers, patience) + case 'A': + diff_algorithm = D_DIFFNONE; + for (struct Algorithm *a = algorithms; a->name; a++) { + if (strcasecmp(optarg, a->name) == 0) { + diff_algorithm = a->id; + diff_algorithm_set = 1; + break; + } + } + if (diff_algorithm == D_DIFFNONE) { + printf("unknown algorithm: %s\n", optarg); + usage(); + } + break; + // ?man -a: force text mode + case 'a': + dflags |= D_FORCEASCII; + break; + // ?man -b: ignore space changes + case 'b': + dflags |= D_FOLDBLANKS; + break; + // ?man -C:lines: context format + case 'C': + // ?man -c: context format + case 'c': + if (FORMAT_MISMATCHED(D_CONTEXT)) + conflicting_format(); + cflag = 1; + diff_format = D_CONTEXT; + if (optarg != NULL) { + l = strtol(optarg, &ep, 10); + if (*ep != '\0' || l < 0 || l >= INT_MAX) + usage(); + diff_context = (int)l; + } + break; + // ?man -d: minimal diff search + case 'd': + dflags |= D_MINIMAL; + break; + // ?man -D:name: ifdef format + case 'D': + if (FORMAT_MISMATCHED(D_IFDEF)) + conflicting_format(); + diff_format = D_IFDEF; + ifdefname = optarg; + break; + // ?man -e: ed script format + case 'e': + if (FORMAT_MISMATCHED(D_EDIT)) + conflicting_format(); + diff_format = D_EDIT; + break; + // ?man -f: forward ed script format + case 'f': + if (FORMAT_MISMATCHED(D_REVERSE)) + conflicting_format(); + diff_format = D_REVERSE; + break; + // ?man -H: speed up large files (stub) + case 'H': + break; + // ?man -h: backward compatibility (stub) + case 'h': + break; + // ?man -B: ignore blank lines + case 'B': + dflags |= D_SKIPBLANKLINES; + break; + // ?man -F:pat: show function matching pattern + case 'F': + if (dflags & D_PROTOTYPE) + conflicting_format(); + dflags |= D_MATCHLAST; + most_recent_pat = estrdup(optarg); + break; + // ?man -I:pat: ignore pattern matching lines + case 'I': + push_ignore_pats(optarg); + break; + // ?man -i: ignore case + case 'i': + dflags |= D_IGNORECASE; + break; + // ?man -L:label: custom label + case 'L': + if (label[0] == NULL) + label[0] = optarg; + else if (label[1] == NULL) + label[1] = optarg; + else + usage(); + break; + // ?man -l: paginate output using pr + case 'l': + lflag = 1; + break; + // ?man -N: treat missing files as empty + case 'N': + Nflag = 1; + break; + // ?man -n: rcs format + case 'n': + if (FORMAT_MISMATCHED(D_NREVERSE)) + conflicting_format(); + diff_format = D_NREVERSE; + break; + // ?man -p: show C prototype context + case 'p': + if (dflags & D_MATCHLAST) + conflicting_format(); + dflags |= D_PROTOTYPE; + break; + // ?man -P: treat missing destination files as empty + case 'P': + Pflag = 1; + break; + // ?man -r: recursive directory comparison + case 'r': + rflag = 1; + break; + // ?man -q: brief output (differ / same only) + case 'q': + if (FORMAT_MISMATCHED(D_BRIEF)) + conflicting_format(); + diff_format = D_BRIEF; + break; + // ?man -S:name: starting file in directory comparison + case 'S': + start = optarg; + break; + // ?man -s: report identical files + case 's': + sflag = 1; + break; + // ?man -T: initial tab alignment + case 'T': + Tflag = 1; + break; + // ?man -t: expand tabs in output + case 't': + dflags |= D_EXPANDTABS; + break; + // ?man -U:lines: unified context format + case 'U': + // ?man -u: unified context format + case 'u': + if (FORMAT_MISMATCHED(D_UNIFIED)) + conflicting_format(); + diff_format = D_UNIFIED; + if (optarg != NULL) { + l = strtol(optarg, &ep, 10); + if (*ep != '\0' || l < 0 || l >= INT_MAX) + usage(); + diff_context = (int)l; + } + break; + // ?man -w: ignore all whitespace + case 'w': + dflags |= D_IGNOREBLANKS; + break; + // ?man -W:cols: column width for side-by-side + case 'W': + width = (int)strtonum(optarg, 1, INT_MAX, &errstr); + if (errstr) { + weprintf("invalid width argument"); + usage(); + } + break; + // ?man -X:file: exclude patterns file + case 'X': + read_excludes_file(optarg); + break; + // ?man -x:pat: exclude pattern + case 'x': + push_excludes(optarg); + break; + // ?man -y: side by side format + case 'y': + if (FORMAT_MISMATCHED(D_SIDEBYSIDE)) + conflicting_format(); + diff_format = D_SIDEBYSIDE; + break; + case OPT_CHANGED_GROUP_FORMAT: + if (FORMAT_MISMATCHED(D_GFORMAT)) + conflicting_format(); + diff_format = D_GFORMAT; + group_format = optarg; + break; + case OPT_HELP: + help = 1; + usage(); + break; + case OPT_HORIZON_LINES: + break; + case OPT_IGN_FN_CASE: + ignore_file_case = 1; + break; + case OPT_NO_IGN_FN_CASE: + ignore_file_case = 0; + break; + case OPT_NORMAL: + if (FORMAT_MISMATCHED(D_NORMAL)) + conflicting_format(); + diff_format = D_NORMAL; + break; + case OPT_TSIZE: + tabsize = (int)strtonum(optarg, 1, INT_MAX, &errstr); + if (errstr) { + weprintf("invalid tabsize argument"); + usage(); + } + break; + case OPT_STRIPCR: + dflags |= D_STRIPCR; + break; + case OPT_SUPPRESS_COMMON: + suppress_common = 1; + break; + case OPT_COLOR: + if (optarg == NULL || strncmp(optarg, "auto", 4) == 0) + colorflag = COLORFLAG_AUTO; + else if (strncmp(optarg, "always", 6) == 0) + colorflag = COLORFLAG_ALWAYS; + else if (strncmp(optarg, "never", 5) == 0) + colorflag = COLORFLAG_NEVER; + else + enprintf(2, "unsupported color option %s", optarg); + break; + case OPT_NO_DEREFERENCE: + noderef = 1; + break; + case OPT_VERSION: + printf("%s\n", diff_version); + exit(0); + default: + usage(); + break; + } + lastch = ch; + newarg = optind != prevoptind; + prevoptind = optind; + } + if (diff_format == D_UNSET && (dflags & D_PROTOTYPE) != 0) + diff_format = D_CONTEXT; + if (diff_format == D_UNSET) + diff_format = D_NORMAL; + argc -= optind; + argv += optind; + + if (do_color()) { + char *p; + const char *env; + + color = 1; + add_code = "32"; + del_code = "31"; + env = getenv("DIFFCOLORS"); + if (env != NULL && *env != '\0' && (p = estrdup(env))) { + add_code = p; + strsep(&p, ":"); + if (p != NULL) + del_code = p; + } + } + + if (argc != 2) + usage(); + checked_regcomp(ignore_pats, &ignore_re); + checked_regcomp(most_recent_pat, &most_recent_re); + if (strcmp(argv[0], "-") == 0) { + fstat(STDIN_FILENO, &stb1); + gotstdin = 1; + } else if (stat(argv[0], &stb1) != 0) { + if (!Nflag || errno != ENOENT) + enprintf(2, "%s", argv[0]); + dflags |= D_EMPTY1; + memset(&stb1, 0, sizeof(struct stat)); + } + + if (strcmp(argv[1], "-") == 0) { + fstat(STDIN_FILENO, &stb2); + gotstdin = 1; + } else if (stat(argv[1], &stb2) != 0) { + if (!Nflag || errno != ENOENT) + enprintf(2, "%s", argv[1]); + dflags |= D_EMPTY2; + memset(&stb2, 0, sizeof(stb2)); + stb2.st_mode = stb1.st_mode; + } + + if (dflags & D_EMPTY1 && dflags & D_EMPTY2){ + weprintf("%s", argv[0]); + weprintf("%s", argv[1]); + exit(2); + } + + if (stb1.st_mode == 0) + stb1.st_mode = stb2.st_mode; + + if (gotstdin && (S_ISDIR(stb1.st_mode) || S_ISDIR(stb2.st_mode))) + enprintf(2, "cant compare - to directory"); + set_argstr(oargv, argv); + if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) { + if (diff_format == D_IFDEF) + enprintf(2, "-D option not supported with directories"); + diffdir(argv[0], argv[1], dflags); + } else { + if (S_ISDIR(stb1.st_mode)) { + argv[0] = diff_splice(argv[0], argv[1]); + if (stat(argv[0], &stb1) == -1) + enprintf(2, "%s", argv[0]); + } + if (S_ISDIR(stb2.st_mode)) { + argv[1] = diff_splice(argv[1], argv[0]); + if (stat(argv[1], &stb2) == -1) + enprintf(2, "%s", argv[1]); + } + print_status(diffreg(argv[0], argv[1], dflags, 1), argv[0], argv[1], ""); + } + if (fflush(stdout) != 0) + enprintf(2, "stdout"); + exit(status); } static void checked_regcomp(char const *pattern, regex_t *comp) { - char buf[BUFSIZ]; - int error; - - if (pattern == NULL) - return; - - error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED); - if (error != 0) { - regerror(error, comp, buf, sizeof(buf)); - if (*pattern != '\0') - errx(2, "%s: %s", pattern, buf); - else - errx(2, "%s", buf); - } + char buf[BUFSIZ]; + int error; + + if (pattern == NULL) + return; + + error = regcomp(comp, pattern, REG_NEWLINE | REG_EXTENDED); + if (error != 0) { + regerror(error, comp, buf, sizeof(buf)); + if (*pattern != '\0') + enprintf(2, "%s: %s", pattern, buf); + else + enprintf(2, "%s", buf); + } } static void set_argstr(char **av, char **ave) { - size_t argsize; - char **ap; - - argsize = strlen("diff") + 1; - for (ap = av + 1; ap < ave; ap++) { - if (strcmp(*ap, "--") != 0) - argsize += 1 + strlen(*ap); - } - diffargs = emalloc(argsize); - strlcpy(diffargs, "diff", argsize); - for (ap = av + 1; ap < ave; ap++) { - if (strcmp(*ap, "--") != 0) { - strlcat(diffargs, " ", argsize); - strlcat(diffargs, *ap, argsize); - } - } + size_t argsize; + char **ap; + + argsize = strlen("diff") + 1; + for (ap = av + 1; ap < ave; ap++) { + if (strcmp(*ap, "--") != 0) + argsize += 1 + strlen(*ap); + } + diffargs = emalloc(argsize); + strlcpy(diffargs, "diff", argsize); + for (ap = av + 1; ap < ave; ap++) { + if (strcmp(*ap, "--") != 0) { + strlcat(diffargs, " ", argsize); + strlcat(diffargs, *ap, argsize); + } + } } static void read_excludes_file(char *file) { - FILE *fp; - char *pattern = NULL; - size_t blen = 0; - ssize_t len; - - if (strcmp(file, "-") == 0) - fp = stdin; - else if ((fp = fopen(file, "r")) == NULL) - err(2, "%s", file); - while ((len = getline(&pattern, &blen, fp)) >= 0) { - if ((len > 0) && (pattern[len - 1] == '\n')) - pattern[len - 1] = '\0'; - push_excludes(pattern); - pattern = NULL; - blen = 0; - } - free(pattern); - if (strcmp(file, "-") != 0) - fclose(fp); + FILE *fp; + char *pattern = NULL; + size_t blen = 0; + ssize_t len; + + if (strcmp(file, "-") == 0) + fp = stdin; + else if ((fp = fopen(file, "r")) == NULL) + enprintf(2, "%s", file); + while ((len = getline(&pattern, &blen, fp)) >= 0) { + if ((len > 0) && (pattern[len - 1] == '\n')) + pattern[len - 1] = '\0'; + push_excludes(pattern); + pattern = NULL; + blen = 0; + } + free(pattern); + if (strcmp(file, "-") != 0) + fclose(fp); } static void push_excludes(char *pattern) { - struct Excludes *entry; + struct Excludes *entry; - entry = emalloc(sizeof(*entry)); - entry->pattern = pattern; - entry->next = excludes_list; - excludes_list = entry; + entry = emalloc(sizeof(*entry)); + entry->pattern = pattern; + entry->next = excludes_list; + excludes_list = entry; } static void push_ignore_pats(char *pattern) { - size_t len; - - if (ignore_pats == NULL) - ignore_pats = estrdup(pattern); - else { - len = strlen(ignore_pats) + strlen(pattern) + 2; - ignore_pats = ereallocarray(ignore_pats, 1, len); - strlcat(ignore_pats, "|", len); - strlcat(ignore_pats, pattern, len); - } + size_t len; + + if (ignore_pats == NULL) + ignore_pats = estrdup(pattern); + else { + len = strlen(ignore_pats) + strlen(pattern) + 2; + ignore_pats = ereallocarray(ignore_pats, 1, len); + strlcat(ignore_pats, "|", len); + strlcat(ignore_pats, pattern, len); + } } void print_status(int val, char *path1, char *path2, const char *entry) { - if (label[0] != NULL) - path1 = label[0]; - if (label[1] != NULL) - path2 = label[1]; - - switch (val) { - case D_BINARY: - printf("Binary files %s%s and %s%s differ\n", path1, entry, path2, entry); - break; - case D_DIFFER: - if (diff_format == D_BRIEF) - printf("Files %s%s and %s%s differ\n", path1, entry, path2, entry); - break; - case D_SAME: - if (sflag) - printf("Files %s%s and %s%s are identical\n", path1, entry, path2, entry); - break; - case D_MISMATCH1: - printf("File %s%s is directory, %s%s is file\n", path1, entry, path2, entry); - break; - case D_MISMATCH2: - printf("File %s%s is file, %s%s is directory\n", path1, entry, path2, entry); - break; - case D_SKIPPED1: - printf("File %s%s is not regular file or directory\n", path1, entry); - break; - case D_SKIPPED2: - printf("File %s%s is not regular file or directory\n", path2, entry); - break; - } + if (label[0] != NULL) + path1 = label[0]; + if (label[1] != NULL) + path2 = label[1]; + + switch (val) { + case D_BINARY: + printf("Binary files %s%s and %s%s differ\n", path1, entry, path2, entry); + break; + case D_DIFFER: + if (diff_format == D_BRIEF) + printf("Files %s%s and %s%s differ\n", path1, entry, path2, entry); + break; + case D_SAME: + if (sflag) + printf("Files %s%s and %s%s are identical\n", path1, entry, path2, entry); + break; + case D_MISMATCH1: + printf("File %s%s is directory, %s%s is file\n", path1, entry, path2, entry); + break; + case D_MISMATCH2: + printf("File %s%s is file, %s%s is directory\n", path1, entry, path2, entry); + break; + case D_SKIPPED1: + printf("File %s%s is not regular file or directory\n", path1, entry); + break; + case D_SKIPPED2: + printf("File %s%s is not regular file or directory\n", path2, entry); + break; + } } static void usage(void) { - fprintf(stderr, "usage: diff [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] " - "[-I pattern] [-F pattern] [-L label] file1 file2\n"); - exit(2); + fprintf(stderr, "usage: diff [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] " + "[-I pattern] [-F pattern] [-L label] file1 file2\n"); + exit(2); } static void conflicting_format(void) { - errx(2, "conflicting output format options"); + enprintf(2, "conflicting output format options"); } static char * diff_splice(char *dir, char *file) { - char *p, *res; + char *p, *res; - p = strrchr(file, '/'); - p = p ? p + 1 : file; - xasprintf(&res, "%s/%s", dir, p); - return res; + p = strrchr(file, '/'); + p = p ? p + 1 : file; + xasprintf(&res, "%s/%s", dir, p); + return res; } static void xasprintf(char **strp, const char *fmt, ...) { - va_list ap; - int r; - - va_start(ap, fmt); - r = vasprintf(strp, fmt, ap); - va_end(ap); - if (r == -1) - err(2, "asprintf"); + va_list ap; + int r; + + va_start(ap, fmt); + r = vasprintf(strp, fmt, ap); + va_end(ap); + if (r == -1) + enprintf(2, "asprintf"); } static int cup2low(int c) { - return tolower(c); + return tolower(c); } static int clow2low(int c) { - return c; + return c; } static int do_color(void) { - if (colorflag == COLORFLAG_ALWAYS) - return 1; - if (colorflag == COLORFLAG_NEVER) - return 0; - if (isatty(STDOUT_FILENO)) { - char *term = getenv("COLORTERM"); - if (term && *term != '\0') - return 1; - } - return 0; + if (colorflag == COLORFLAG_ALWAYS) + return 1; + if (colorflag == COLORFLAG_NEVER) + return 0; + if (isatty(STDOUT_FILENO)) { + char *term = getenv("COLORTERM"); + if (term && *term != '\0') + return 1; + } + return 0; } void diffdir(char *p1, char *p2, int flags) { - struct dirent *dent1, **dp1, **edp1, **dirp1 = NULL; - struct dirent *dent2, **dp2, **edp2, **dirp2 = NULL; - size_t dirlen1, dirlen2; - char path1[PATH_MAX], path2[PATH_MAX]; - int pos; - - edp1 = edp2 = NULL; - dirlen1 = strlcpy(path1, *p1 ? p1 : ".", sizeof(path1)); - if (dirlen1 >= sizeof(path1) - 1) { - errno = ENAMETOOLONG; - warn("%s", p1); - status |= 2; - return; - } - if (path1[dirlen1 - 1] != '/') { - path1[dirlen1++] = '/'; - path1[dirlen1] = '\0'; - } - dirlen2 = strlcpy(path2, *p2 ? p2 : ".", sizeof(path2)); - if (dirlen2 >= sizeof(path2) - 1) { - errno = ENAMETOOLONG; - warn("%s", p2); - status |= 2; - return; - } - if (path2[dirlen2 - 1] != '/') { - path2[dirlen2++] = '/'; - path2[dirlen2] = '\0'; - } - - pos = scandir(path1, &dirp1, selectfile, alphasort); - if (pos == -1) { - if (errno == ENOENT && (Nflag || Pflag)) - pos = 0; - else { - warn("%s", path1); - goto closem; - } - } - dp1 = dirp1; - edp1 = dirp1 + pos; - - pos = scandir(path2, &dirp2, selectfile, alphasort); - if (pos == -1) { - if (errno == ENOENT && Nflag) - pos = 0; - else { - warn("%s", path2); - goto closem; - } - } - dp2 = dirp2; - edp2 = dirp2 + pos; - - if (start != NULL) { - while (dp1 != edp1 && strcmp((*dp1)->d_name, start) < 0) - dp1++; - while (dp2 != edp2 && strcmp((*dp2)->d_name, start) < 0) - dp2++; - } - - while (dp1 != edp1 || dp2 != edp2) { - dent1 = dp1 != edp1 ? *dp1 : NULL; - dent2 = dp2 != edp2 ? *dp2 : NULL; - - pos = dent1 == NULL ? 1 : dent2 == NULL ? -1 : - ignore_file_case ? strcasecmp(dent1->d_name, dent2->d_name) : - strcmp(dent1->d_name, dent2->d_name); - if (pos == 0) { - diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags); - dp1++; - dp2++; - } else if (pos < 0) { - if (Nflag) - diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags); - else { - print_only(path1, dirlen1, dent1->d_name); - status |= 1; - } - dp1++; - } else { - if (Nflag || Pflag) - diffit(dent2, path1, dirlen1, dent1, path2, dirlen2, flags); - else { - print_only(path2, dirlen2, dent2->d_name); - status |= 1; - } - dp2++; - } - } + struct dirent *dent1, **dp1, **edp1, **dirp1 = NULL; + struct dirent *dent2, **dp2, **edp2, **dirp2 = NULL; + size_t dirlen1, dirlen2; + char path1[PATH_MAX], path2[PATH_MAX]; + int pos; + + edp1 = edp2 = NULL; + dirlen1 = strlcpy(path1, *p1 ? p1 : ".", sizeof(path1)); + if (dirlen1 >= sizeof(path1) - 1) { + errno = ENAMETOOLONG; + weprintf("%s", p1); + status |= 2; + return; + } + if (path1[dirlen1 - 1] != '/') { + path1[dirlen1++] = '/'; + path1[dirlen1] = '\0'; + } + dirlen2 = strlcpy(path2, *p2 ? p2 : ".", sizeof(path2)); + if (dirlen2 >= sizeof(path2) - 1) { + errno = ENAMETOOLONG; + weprintf("%s", p2); + status |= 2; + return; + } + if (path2[dirlen2 - 1] != '/') { + path2[dirlen2++] = '/'; + path2[dirlen2] = '\0'; + } + + pos = scandir(path1, &dirp1, selectfile, alphasort); + if (pos == -1) { + if (errno == ENOENT && (Nflag || Pflag)) + pos = 0; + else { + weprintf("%s", path1); + goto closem; + } + } + dp1 = dirp1; + edp1 = dirp1 + pos; + + pos = scandir(path2, &dirp2, selectfile, alphasort); + if (pos == -1) { + if (errno == ENOENT && Nflag) + pos = 0; + else { + weprintf("%s", path2); + goto closem; + } + } + dp2 = dirp2; + edp2 = dirp2 + pos; + + if (start != NULL) { + while (dp1 != edp1 && strcmp((*dp1)->d_name, start) < 0) + dp1++; + while (dp2 != edp2 && strcmp((*dp2)->d_name, start) < 0) + dp2++; + } + + while (dp1 != edp1 || dp2 != edp2) { + dent1 = dp1 != edp1 ? *dp1 : NULL; + dent2 = dp2 != edp2 ? *dp2 : NULL; + + pos = dent1 == NULL ? 1 : dent2 == NULL ? -1 : + ignore_file_case ? strcasecmp(dent1->d_name, dent2->d_name) : + strcmp(dent1->d_name, dent2->d_name); + if (pos == 0) { + diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags); + dp1++; + dp2++; + } else if (pos < 0) { + if (Nflag) + diffit(dent1, path1, dirlen1, dent2, path2, dirlen2, flags); + else { + print_only(path1, dirlen1, dent1->d_name); + status |= 1; + } + dp1++; + } else { + if (Nflag || Pflag) + diffit(dent2, path1, dirlen1, dent1, path2, dirlen2, flags); + else { + print_only(path2, dirlen2, dent2->d_name); + status |= 1; + } + dp2++; + } + } closem: - if (dirp1 != NULL) { - for (dp1 = dirp1; dp1 < edp1; dp1++) - free(*dp1); - free(dirp1); - } - if (dirp2 != NULL) { - for (dp2 = dirp2; dp2 < edp2; dp2++) - free(*dp2); - free(dirp2); - } + if (dirp1 != NULL) { + for (dp1 = dirp1; dp1 < edp1; dp1++) + free(*dp1); + free(dirp1); + } + if (dirp2 != NULL) { + for (dp2 = dirp2; dp2 < edp2; dp2++) + free(*dp2); + free(dirp2); + } } static void diffit(struct dirent *dp, char *path1, size_t plen1, struct dirent *dp2, char *path2, size_t plen2, int flags) { - flags |= D_HEADER; - strlcpy(path1 + plen1, dp->d_name, PATH_MAX - plen1); - - if (ignore_file_case && strcasecmp(dp->d_name, dp2->d_name) == 0) - strlcpy(path2 + plen2, dp2->d_name, PATH_MAX - plen2); - else - strlcpy(path2 + plen2, dp->d_name, PATH_MAX - plen2); - - if (noderef) { - if (lstat(path1, &stb1) != 0) { - if (!(Nflag || Pflag) || errno != ENOENT) { - warn("%s", path1); - return; - } - flags |= D_EMPTY1; - memset(&stb1, 0, sizeof(stb1)); - } - - if (lstat(path2, &stb2) != 0) { - if (!Nflag || errno != ENOENT) { - warn("%s", path2); - return; - } - flags |= D_EMPTY2; - memset(&stb2, 0, sizeof(stb2)); - stb2.st_mode = stb1.st_mode; - } - if (stb1.st_mode == 0) - stb1.st_mode = stb2.st_mode; - if (S_ISLNK(stb1.st_mode) || S_ISLNK(stb2.st_mode)) { - if (S_ISLNK(stb1.st_mode) && S_ISLNK(stb2.st_mode)) { - char buf1[PATH_MAX]; - char buf2[PATH_MAX]; - ssize_t len1; - ssize_t len2; - - len1 = readlink(path1, buf1, sizeof(buf1)); - len2 = readlink(path2, buf2, sizeof(buf2)); - if (len1 < 0 || len2 < 0) { - perror("reading links"); - return; - } - buf1[len1] = '\0'; - buf2[len2] = '\0'; - if (len1 != len2 || strncmp(buf1, buf2, len1) != 0) { - printf("Symbolic links %s and %s differ\n", path1, path2); - status |= 1; - } - return; - } - printf("File %s is a %s while file %s is a %s\n", - path1, S_ISLNK(stb1.st_mode) ? "symbolic link" : - S_ISDIR(stb1.st_mode) ? "directory" : "file", - path2, S_ISLNK(stb2.st_mode) ? "symbolic link" : - S_ISDIR(stb2.st_mode) ? "directory" : "file"); - status |= 1; - return; - } - } else { - if (stat(path1, &stb1) != 0) { - if (!(Nflag || Pflag) || errno != ENOENT) { - warn("%s", path1); - return; - } - flags |= D_EMPTY1; - memset(&stb1, 0, sizeof(stb1)); - } - - if (stat(path2, &stb2) != 0) { - if (!Nflag || errno != ENOENT) { - warn("%s", path2); - return; - } - flags |= D_EMPTY2; - memset(&stb2, 0, sizeof(stb2)); - stb2.st_mode = stb1.st_mode; - } - if (stb1.st_mode == 0) - stb1.st_mode = stb2.st_mode; - } - if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) { - if (rflag) - diffdir(path1, path2, flags); - else - printf("Common subdirectories: %s and %s\n", path1, path2); - return; - } - if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode)) - dp->d_status = D_SKIPPED1; - else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode)) - dp->d_status = D_SKIPPED2; - else - dp->d_status = diffreg(path1, path2, flags, 0); - print_status(dp->d_status, path1, path2, ""); + flags |= D_HEADER; + strlcpy(path1 + plen1, dp->d_name, PATH_MAX - plen1); + + if (ignore_file_case && strcasecmp(dp->d_name, dp2->d_name) == 0) + strlcpy(path2 + plen2, dp2->d_name, PATH_MAX - plen2); + else + strlcpy(path2 + plen2, dp->d_name, PATH_MAX - plen2); + + if (noderef) { + if (lstat(path1, &stb1) != 0) { + if (!(Nflag || Pflag) || errno != ENOENT) { + weprintf("%s", path1); + return; + } + flags |= D_EMPTY1; + memset(&stb1, 0, sizeof(stb1)); + } + + if (lstat(path2, &stb2) != 0) { + if (!Nflag || errno != ENOENT) { + weprintf("%s", path2); + return; + } + flags |= D_EMPTY2; + memset(&stb2, 0, sizeof(stb2)); + stb2.st_mode = stb1.st_mode; + } + if (stb1.st_mode == 0) + stb1.st_mode = stb2.st_mode; + if (S_ISLNK(stb1.st_mode) || S_ISLNK(stb2.st_mode)) { + if (S_ISLNK(stb1.st_mode) && S_ISLNK(stb2.st_mode)) { + char buf1[PATH_MAX]; + char buf2[PATH_MAX]; + ssize_t len1; + ssize_t len2; + + len1 = readlink(path1, buf1, sizeof(buf1)); + len2 = readlink(path2, buf2, sizeof(buf2)); + if (len1 < 0 || len2 < 0) { + perror("reading links"); + return; + } + buf1[len1] = '\0'; + buf2[len2] = '\0'; + if (len1 != len2 || strncmp(buf1, buf2, len1) != 0) { + printf("Symbolic links %s and %s differ\n", path1, path2); + status |= 1; + } + return; + } + printf("File %s is a %s while file %s is a %s\n", + path1, S_ISLNK(stb1.st_mode) ? "symbolic link" : + S_ISDIR(stb1.st_mode) ? "directory" : "file", + path2, S_ISLNK(stb2.st_mode) ? "symbolic link" : + S_ISDIR(stb2.st_mode) ? "directory" : "file"); + status |= 1; + return; + } + } else { + if (stat(path1, &stb1) != 0) { + if (!(Nflag || Pflag) || errno != ENOENT) { + weprintf("%s", path1); + return; + } + flags |= D_EMPTY1; + memset(&stb1, 0, sizeof(stb1)); + } + + if (stat(path2, &stb2) != 0) { + if (!Nflag || errno != ENOENT) { + weprintf("%s", path2); + return; + } + flags |= D_EMPTY2; + memset(&stb2, 0, sizeof(stb2)); + stb2.st_mode = stb1.st_mode; + } + if (stb1.st_mode == 0) + stb1.st_mode = stb2.st_mode; + } + if (S_ISDIR(stb1.st_mode) && S_ISDIR(stb2.st_mode)) { + if (rflag) + diffdir(path1, path2, flags); + else + printf("Common subdirectories: %s and %s\n", path1, path2); + return; + } + if (!S_ISREG(stb1.st_mode) && !S_ISDIR(stb1.st_mode)) + dp->d_status = D_SKIPPED1; + else if (!S_ISREG(stb2.st_mode) && !S_ISDIR(stb2.st_mode)) + dp->d_status = D_SKIPPED2; + else + dp->d_status = diffreg(path1, path2, flags, 0); + print_status(dp->d_status, path1, path2, ""); } static int selectfile(const struct dirent *dp) { - struct Excludes *excl; + struct Excludes *excl; - if (dp->d_fileno == 0) - return 0; + if (dp->d_fileno == 0) + return 0; - if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || - (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) - return 0; + if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || + (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) + return 0; - for (excl = excludes_list; excl != NULL; excl = excl->next) - if (fnmatch(excl->pattern, dp->d_name, FNM_PATHNAME) == 0) - return 0; + for (excl = excludes_list; excl != NULL; excl = excl->next) + if (fnmatch(excl->pattern, dp->d_name, FNM_PATHNAME) == 0) + return 0; - return 1; + return 1; } void print_only(const char *path, size_t dirlen, const char *entry) { - if (dirlen > 1) - dirlen--; - printf("Only in %.*s: %s\n", (int)dirlen, path, entry); + if (dirlen > 1) + dirlen--; + printf("Only in %.*s: %s\n", (int)dirlen, path, entry); } int diffreg(char *file1, char *file2, int flags, int capsicum) { - FILE *f1, *f2; - int i, rval; - struct Pr *pr = NULL; - - f1 = f2 = NULL; - rval = D_SAME; - anychange = 0; - lastline = 0; - lastmatchline = 0; - - if (diff_format == D_SIDEBYSIDE) { - if (flags & D_EXPANDTABS) { - if (width > 3) - hw = (width - 3) / 2; - else - hw = 0; - } else if (width <= 3 || width <= tabsize) { - hw = 0; - } else { - hw = (width - 3) / 2; - while (hw > 0 && roundup(hw + 3, tabsize) + hw > width) - hw--; - if (width - (roundup(hw + 3, tabsize) + hw) < tabsize) - width = roundup(hw + 3, tabsize) + hw; - } - lpad = (width - hw * 2 - 1) / 2; - rpad = (width - hw * 2 - 1) - lpad; - } - - if (flags & D_IGNORECASE) - chrtran = cup2low; - else - chrtran = clow2low; - if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode)) - return S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2; - if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0) - goto closem; - - if (flags & D_EMPTY1) - f1 = fopen(_PATH_DEVNULL, "r"); - else { - if (!S_ISREG(stb1.st_mode)) { - if ((f1 = opentemp(file1)) == NULL || fstat(fileno(f1), &stb1) == -1) { - warn("%s", file1); - rval = D_ERROR; - status |= 2; - goto closem; - } - } else if (strcmp(file1, "-") == 0) - f1 = stdin; - else - f1 = fopen(file1, "r"); - } - if (f1 == NULL) { - warn("%s", file1); - rval = D_ERROR; - status |= 2; - goto closem; - } - - if (flags & D_EMPTY2) - f2 = fopen(_PATH_DEVNULL, "r"); - else { - if (!S_ISREG(stb2.st_mode)) { - if ((f2 = opentemp(file2)) == NULL || fstat(fileno(f2), &stb2) == -1) { - warn("%s", file2); - rval = D_ERROR; - status |= 2; - goto closem; - } - } else if (strcmp(file2, "-") == 0) - f2 = stdin; - else - f2 = fopen(file2, "r"); - } - if (f2 == NULL) { - warn("%s", file2); - rval = D_ERROR; - status |= 2; - goto closem; - } - - if (lflag) - pr = start_pr(file1, file2); - - (void)capsicum; - - switch (files_differ(f1, f2, flags)) { - case 0: - goto closem; - case 1: - break; - default: - rval = D_ERROR; - status |= 2; - goto closem; - } - - if (diff_format == D_BRIEF && ignore_pats == NULL && - (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_SKIPBLANKLINES|D_STRIPCR)) == 0) - { - rval = D_DIFFER; - status |= 1; - goto closem; - } - if ((flags & D_FORCEASCII) != 0) { - prepare(0, f1, stb1.st_size, flags); - prepare(1, f2, stb2.st_size, flags); - } else if (!asciifile(f1) || !asciifile(f2) || - !prepare(0, f1, stb1.st_size, flags) || - !prepare(1, f2, stb2.st_size, flags)) { - rval = D_BINARY; - status |= 1; - goto closem; - } - if (len[0] > INT_MAX - 2) - errno = EFBIG, err(1, "%s", file1); - if (len[1] > INT_MAX - 2) - errno = EFBIG, err(1, "%s", file2); - - prune(); - sort(sfile[0], slen[0]); - sort(sfile[1], slen[1]); - - member = (int *)file[1]; - equiv(sfile[0], slen[0], sfile[1], slen[1], member); - member = ereallocarray(member, slen[1] + 2, sizeof(*member)); - - class = (int *)file[0]; - unsort(sfile[0], slen[0], class); - class = ereallocarray(class, slen[0] + 2, sizeof(*class)); - - klist = ecalloc(slen[0] + 2, sizeof(*klist)); - clen = 0; - clistlen = 100; - clist = ecalloc(clistlen, sizeof(*clist)); - i = stone(class, slen[0], member, klist, flags); - free(member); - free(class); - - J = ereallocarray(J, len[0] + 2, sizeof(*J)); - unravel(klist[i]); - free(clist); - free(klist); - - ixold = ereallocarray(ixold, len[0] + 2, sizeof(*ixold)); - ixnew = ereallocarray(ixnew, len[1] + 2, sizeof(*ixnew)); - check(f1, f2, flags); - output(file1, f1, file2, f2, flags); + FILE *f1, *f2; + int i, rval; + struct Pr *pr = NULL; + + f1 = f2 = NULL; + rval = D_SAME; + anychange = 0; + lastline = 0; + lastmatchline = 0; + + if (diff_format == D_SIDEBYSIDE) { + if (flags & D_EXPANDTABS) { + if (width > 3) + hw = (width - 3) / 2; + else + hw = 0; + } else if (width <= 3 || width <= tabsize) { + hw = 0; + } else { + hw = (width - 3) / 2; + while (hw > 0 && roundup(hw + 3, tabsize) + hw > width) + hw--; + if (width - (roundup(hw + 3, tabsize) + hw) < tabsize) + width = roundup(hw + 3, tabsize) + hw; + } + lpad = (width - hw * 2 - 1) / 2; + rpad = (width - hw * 2 - 1) - lpad; + } + + if (flags & D_IGNORECASE) + chrtran = cup2low; + else + chrtran = clow2low; + if (S_ISDIR(stb1.st_mode) != S_ISDIR(stb2.st_mode)) + return S_ISDIR(stb1.st_mode) ? D_MISMATCH1 : D_MISMATCH2; + if (strcmp(file1, "-") == 0 && strcmp(file2, "-") == 0) + goto closem; + + if (flags & D_EMPTY1) + f1 = fopen(ARUU_PATH_DEVNULL, "r"); + else { + if (!S_ISREG(stb1.st_mode)) { + if ((f1 = opentemp(file1)) == NULL || fstat(fileno(f1), &stb1) == -1) { + weprintf("%s", file1); + rval = D_ERROR; + status |= 2; + goto closem; + } + } else if (strcmp(file1, "-") == 0) + f1 = stdin; + else + f1 = fopen(file1, "r"); + } + if (f1 == NULL) { + weprintf("%s", file1); + rval = D_ERROR; + status |= 2; + goto closem; + } + + if (flags & D_EMPTY2) + f2 = fopen(ARUU_PATH_DEVNULL, "r"); + else { + if (!S_ISREG(stb2.st_mode)) { + if ((f2 = opentemp(file2)) == NULL || fstat(fileno(f2), &stb2) == -1) { + weprintf("%s", file2); + rval = D_ERROR; + status |= 2; + goto closem; + } + } else if (strcmp(file2, "-") == 0) + f2 = stdin; + else + f2 = fopen(file2, "r"); + } + if (f2 == NULL) { + weprintf("%s", file2); + rval = D_ERROR; + status |= 2; + goto closem; + } + + if (lflag) + pr = start_pr(file1, file2); + + (void)capsicum; + + switch (files_differ(f1, f2, flags)) { + case 0: + goto closem; + case 1: + break; + default: + rval = D_ERROR; + status |= 2; + goto closem; + } + + if (diff_format == D_BRIEF && ignore_pats == NULL && + (flags & (D_FOLDBLANKS|D_IGNOREBLANKS|D_IGNORECASE|D_SKIPBLANKLINES|D_STRIPCR)) == 0) + { + rval = D_DIFFER; + status |= 1; + goto closem; + } + if ((flags & D_FORCEASCII) != 0) { + prepare(0, f1, stb1.st_size, flags); + prepare(1, f2, stb2.st_size, flags); + } else if (!asciifile(f1) || !asciifile(f2) || + !prepare(0, f1, stb1.st_size, flags) || + !prepare(1, f2, stb2.st_size, flags)) { + rval = D_BINARY; + status |= 1; + goto closem; + } + if (len[0] > INT_MAX - 2) + errno = EFBIG, enprintf(1, "%s", file1); + if (len[1] > INT_MAX - 2) + errno = EFBIG, enprintf(1, "%s", file2); + + prune(); + sort(sfile[0], slen[0]); + sort(sfile[1], slen[1]); + + member = (int *)file[1]; + equiv(sfile[0], slen[0], sfile[1], slen[1], member); + member = ereallocarray(member, slen[1] + 2, sizeof(*member)); + + class = (int *)file[0]; + unsort(sfile[0], slen[0], class); + class = ereallocarray(class, slen[0] + 2, sizeof(*class)); + + klist = ecalloc(slen[0] + 2, sizeof(*klist)); + clen = 0; + clistlen = 100; + clist = ecalloc(clistlen, sizeof(*clist)); + i = stone(class, slen[0], member, klist, flags); + free(member); + free(class); + + J = ereallocarray(J, len[0] + 2, sizeof(*J)); + unravel(klist[i]); + free(clist); + free(klist); + + ixold = ereallocarray(ixold, len[0] + 2, sizeof(*ixold)); + ixnew = ereallocarray(ixnew, len[1] + 2, sizeof(*ixnew)); + check(f1, f2, flags); + output(file1, f1, file2, f2, flags); closem: - if (pr != NULL) - stop_pr(pr); - if (anychange) { - status |= 1; - if (rval == D_SAME) - rval = D_DIFFER; - } - if (f1 != NULL && f1 != stdin) - fclose(f1); - if (f2 != NULL && f2 != stdin) - fclose(f2); - - return rval; + if (pr != NULL) + stop_pr(pr); + if (anychange) { + status |= 1; + if (rval == D_SAME) + rval = D_DIFFER; + } + if (f1 != NULL && f1 != stdin) + fclose(f1); + if (f2 != NULL && f2 != stdin) + fclose(f2); + + return rval; } static int files_differ(FILE *f1, FILE *f2, int flags) { - char buf1[BUFSIZ], buf2[BUFSIZ]; - size_t i, j; - - if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size || - (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT)) - return 1; - - if (stb1.st_dev == stb2.st_dev && stb1.st_ino == stb2.st_ino) - return 0; - - for (;;) { - i = fread(buf1, 1, sizeof(buf1), f1); - j = fread(buf2, 1, sizeof(buf2), f2); - if ((!i && ferror(f1)) || (!j && ferror(f2))) - return -1; - if (i != j) - return 1; - if (i == 0) - return 0; - if (memcmp(buf1, buf2, i) != 0) - return 1; - } + char buf1[BUFSIZ], buf2[BUFSIZ]; + size_t i, j; + + if ((flags & (D_EMPTY1|D_EMPTY2)) || stb1.st_size != stb2.st_size || + (stb1.st_mode & S_IFMT) != (stb2.st_mode & S_IFMT)) + return 1; + + if (stb1.st_dev == stb2.st_dev && stb1.st_ino == stb2.st_ino) + return 0; + + for (;;) { + i = fread(buf1, 1, sizeof(buf1), f1); + j = fread(buf2, 1, sizeof(buf2), f2); + if ((!i && ferror(f1)) || (!j && ferror(f2))) + return -1; + if (i != j) + return 1; + if (i == 0) + return 0; + if (memcmp(buf1, buf2, i) != 0) + return 1; + } } static FILE * opentemp(const char *f) { - char buf[BUFSIZ], tempfile[PATH_MAX]; - ssize_t nread; - int ifd, ofd; - - if (strcmp(f, "-") == 0) - ifd = STDIN_FILENO; - else if ((ifd = open(f, O_RDONLY, 0644)) == -1) - return NULL; - - strlcpy(tempfile, _PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile)); - if ((ofd = mkstemp(tempfile)) == -1) { - close(ifd); - return NULL; - } - unlink(tempfile); - while ((nread = read(ifd, buf, BUFSIZ)) > 0) { - if (write(ofd, buf, nread) != nread) { - close(ifd); - close(ofd); - return NULL; - } - } - close(ifd); - lseek(ofd, (off_t)0, SEEK_SET); - return fdopen(ofd, "r"); + char buf[BUFSIZ], tempfile[PATH_MAX]; + ssize_t nread; + int ifd, ofd; + + if (strcmp(f, "-") == 0) + ifd = STDIN_FILENO; + else if ((ifd = open(f, O_RDONLY, 0644)) == -1) + return NULL; + + strlcpy(tempfile, ARUU_PATH_TMP "/diff.XXXXXXXX", sizeof(tempfile)); + if ((ofd = mkstemp(tempfile)) == -1) { + close(ifd); + return NULL; + } + unlink(tempfile); + while ((nread = read(ifd, buf, BUFSIZ)) > 0) { + if (write(ofd, buf, nread) != nread) { + close(ifd); + close(ofd); + return NULL; + } + } + close(ifd); + lseek(ofd, (off_t)0, SEEK_SET); + return fdopen(ofd, "r"); } static int prepare(int i, FILE *fd, size_t filesize, int flags) { - struct Line *p; - unsigned h; - size_t sz, j = 0; - enum Readhash r; - - rewind(fd); - sz = filesize / 25; - if (sz < 100) - sz = 100; - - p = ecalloc(sz + 3, sizeof(*p)); - while ((r = readhash(fd, flags, &h)) != RH_EOF) { - if (r == RH_BINARY) - return 0; - if (j == SIZE_MAX) - break; - if (j == sz) { - sz = sz * 3 / 2; - p = ereallocarray(p, sz + 3, sizeof(*p)); - } - p[++j].value = h; - } - len[i] = j; - file[i] = p; - return 1; + struct Line *p; + unsigned h; + size_t sz, j = 0; + enum Readhash r; + + rewind(fd); + sz = filesize / 25; + if (sz < 100) + sz = 100; + + p = ecalloc(sz + 3, sizeof(*p)); + while ((r = readhash(fd, flags, &h)) != RH_EOF) { + if (r == RH_BINARY) + return 0; + if (j == SIZE_MAX) + break; + if (j == sz) { + sz = sz * 3 / 2; + p = ereallocarray(p, sz + 3, sizeof(*p)); + } + p[++j].value = h; + } + len[i] = j; + file[i] = p; + return 1; } static void prune(void) { - size_t i, j; - - for (pref = 0; pref < len[0] && pref < len[1] && - file[0][pref + 1].value == file[1][pref + 1].value; - pref++) - ; - for (suff = 0; suff < len[0] - pref && suff < len[1] - pref && - file[0][len[0] - suff].value == file[1][len[1] - suff].value; - suff++) - ; - for (j = 0; j < 2; j++) { - sfile[j] = file[j] + pref; - slen[j] = len[j] - pref - suff; - for (i = 0; i <= slen[j]; i++) - sfile[j][i].serial = i; - } + size_t i, j; + + for (pref = 0; pref < len[0] && pref < len[1] && + file[0][pref + 1].value == file[1][pref + 1].value; + pref++) + ; + for (suff = 0; suff < len[0] - pref && suff < len[1] - pref && + file[0][len[0] - suff].value == file[1][len[1] - suff].value; + suff++) + ; + for (j = 0; j < 2; j++) { + sfile[j] = file[j] + pref; + slen[j] = len[j] - pref - suff; + for (i = 0; i <= slen[j]; i++) + sfile[j][i].serial = i; + } } static void equiv(struct Line *a, int n, struct Line *b, int m, int *c) { - int i, j; - - i = j = 1; - while (i <= n && j <= m) { - if (a[i].value < b[j].value) - a[i++].value = 0; - else if (a[i].value == b[j].value) - a[i++].value = j; - else - j++; - } - while (i <= n) - a[i++].value = 0; - b[m + 1].value = 0; - j = 0; - while (++j <= m) { - c[j] = -b[j].serial; - while (b[j + 1].value == b[j].value) { - j++; - c[j] = b[j].serial; - } - } - c[j] = -1; + int i, j; + + i = j = 1; + while (i <= n && j <= m) { + if (a[i].value < b[j].value) + a[i++].value = 0; + else if (a[i].value == b[j].value) + a[i++].value = j; + else + j++; + } + while (i <= n) + a[i++].value = 0; + b[m + 1].value = 0; + j = 0; + while (++j <= m) { + c[j] = -b[j].serial; + while (b[j + 1].value == b[j].value) { + j++; + c[j] = b[j].serial; + } + } + c[j] = -1; } static int stone(int *a, int n, int *b, int *c, int flags) { - int i, k, y, j, l; - int oldc, tc, oldl, sq; - unsigned numtries, bound; - - if (flags & D_MINIMAL) - bound = UINT_MAX; - else { - sq = sqrt(n); - bound = MAX(256, sq); - } - - k = 0; - c[0] = newcand(0, 0, 0); - for (i = 1; i <= n; i++) { - j = a[i]; - if (j == 0) - continue; - y = -b[j]; - oldl = 0; - oldc = c[0]; - numtries = 0; - do { - if (y <= clist[oldc].y) - continue; - l = search(c, k, y); - if (l != oldl + 1) - oldc = c[l - 1]; - if (l <= k) { - if (clist[c[l]].y <= y) - continue; - tc = c[l]; - c[l] = newcand(i, y, oldc); - oldc = tc; - oldl = l; - numtries++; - } else { - c[l] = newcand(i, y, oldc); - k++; - break; - } - } while ((y = b[++j]) > 0 && numtries < bound); - } - return k; + int i, k, y, j, l; + int oldc, tc, oldl, sq; + unsigned numtries, bound; + + if (flags & D_MINIMAL) + bound = UINT_MAX; + else { + sq = sqrt(n); + bound = MAX(256, sq); + } + + k = 0; + c[0] = newcand(0, 0, 0); + for (i = 1; i <= n; i++) { + j = a[i]; + if (j == 0) + continue; + y = -b[j]; + oldl = 0; + oldc = c[0]; + numtries = 0; + do { + if (y <= clist[oldc].y) + continue; + l = search(c, k, y); + if (l != oldl + 1) + oldc = c[l - 1]; + if (l <= k) { + if (clist[c[l]].y <= y) + continue; + tc = c[l]; + c[l] = newcand(i, y, oldc); + oldc = tc; + oldl = l; + numtries++; + } else { + c[l] = newcand(i, y, oldc); + k++; + break; + } + } while ((y = b[++j]) > 0 && numtries < bound); + } + return k; } static int newcand(int x, int y, int pred) { - struct Cand *q; - - if (clen == clistlen) { - clistlen = clistlen * 11 / 10; - clist = ereallocarray(clist, clistlen, sizeof(*clist)); - } - q = clist + clen; - q->x = x; - q->y = y; - q->pred = pred; - return clen++; + struct Cand *q; + + if (clen == clistlen) { + clistlen = clistlen * 11 / 10; + clist = ereallocarray(clist, clistlen, sizeof(*clist)); + } + q = clist + clen; + q->x = x; + q->y = y; + q->pred = pred; + return clen++; } static int search(int *c, int k, int y) { - int i, j, l, t; - - if (clist[c[k]].y < y) - return k + 1; - i = 0; - j = k + 1; - for (;;) { - l = (i + j) / 2; - if (l <= i) - break; - t = clist[c[l]].y; - if (t > y) - j = l; - else if (t < y) - i = l; - else - return l; - } - return l + 1; + int i, j, l, t; + + if (clist[c[k]].y < y) + return k + 1; + i = 0; + j = k + 1; + for (;;) { + l = (i + j) / 2; + if (l <= i) + break; + t = clist[c[l]].y; + if (t > y) + j = l; + else if (t < y) + i = l; + else + return l; + } + return l + 1; } static void unravel(int p) { - struct Cand *q; - size_t i; - - for (i = 0; i <= len[0]; i++) - J[i] = i <= pref ? i : - i > len[0] - suff ? i + len[1] - len[0] : 0; - for (q = clist + p; q->y != 0; q = clist + q->pred) - J[q->x + pref] = q->y + pref; + struct Cand *q; + size_t i; + + for (i = 0; i <= len[0]; i++) + J[i] = i <= pref ? i : + i > len[0] - suff ? i + len[1] - len[0] : 0; + for (q = clist + p; q->y != 0; q = clist + q->pred) + J[q->x + pref] = q->y + pref; } static void check(FILE *f1, FILE *f2, int flags) { - int i, j, c, d; - long ctold, ctnew; - - rewind(f1); - rewind(f2); - j = 1; - ixold[0] = ixnew[0] = 0; - ctold = ctnew = 0; - for (i = 1; i <= (int)len[0]; i++) { - if (J[i] == 0) { - ixold[i] = ctold += skipline(f1); - continue; - } - while (j < J[i]) { - ixnew[j] = ctnew += skipline(f2); - j++; - } - if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS | D_IGNORECASE | D_STRIPCR)) { - for (;;) { - c = getc(f1); - d = getc(f2); - if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS)) { - if (c == EOF && isspace(d)) { - ctnew++; - break; - } else if (isspace(c) && d == EOF) { - ctold++; - break; - } - } - ctold++; - ctnew++; - if (flags & D_STRIPCR && (c == '\r' || d == '\r')) { - if (c == '\r') { - if ((c = getc(f1)) == '\n') - ctold++; - else - ungetc(c, f1); - } - if (d == '\r') { - if ((d = getc(f2)) == '\n') - ctnew++; - else - ungetc(d, f2); - } - break; - } - if ((flags & D_FOLDBLANKS) && isspace(c) && isspace(d)) { - do { - if (c == '\n') - break; - ctold++; - } while (isspace(c = getc(f1))); - do { - if (d == '\n') - break; - ctnew++; - } while (isspace(d = getc(f2))); - } else if (flags & D_IGNOREBLANKS) { - while (isspace(c) && c != '\n') { - c = getc(f1); - ctold++; - } - while (isspace(d) && d != '\n') { - d = getc(f2); - ctnew++; - } - } - if (chrtran(c) != chrtran(d)) { - J[i] = 0; - if (c != '\n' && c != EOF) - ctold += skipline(f1); - if (d != '\n' && c != EOF) - ctnew += skipline(f2); - break; - } - if (c == '\n' || c == EOF) - break; - } - } else { - for (;;) { - ctold++; - ctnew++; - if ((c = getc(f1)) != (d = getc(f2))) { - J[i] = 0; - if (c != '\n' && c != EOF) - ctold += skipline(f1); - if (d != '\n' && c != EOF) - ctnew += skipline(f2); - break; - } - if (c == '\n' || c == EOF) - break; - } - } - ixold[i] = ctold; - ixnew[j] = ctnew; - j++; - } - for (; j <= (int)len[1]; j++) { - ixnew[j] = ctnew += skipline(f2); - } + int i, j, c, d; + long ctold, ctnew; + + rewind(f1); + rewind(f2); + j = 1; + ixold[0] = ixnew[0] = 0; + ctold = ctnew = 0; + for (i = 1; i <= (int)len[0]; i++) { + if (J[i] == 0) { + ixold[i] = ctold += skipline(f1); + continue; + } + while (j < J[i]) { + ixnew[j] = ctnew += skipline(f2); + j++; + } + if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS | D_IGNORECASE | D_STRIPCR)) { + for (;;) { + c = getc(f1); + d = getc(f2); + if (flags & (D_FOLDBLANKS | D_IGNOREBLANKS)) { + if (c == EOF && isspace(d)) { + ctnew++; + break; + } else if (isspace(c) && d == EOF) { + ctold++; + break; + } + } + ctold++; + ctnew++; + if (flags & D_STRIPCR && (c == '\r' || d == '\r')) { + if (c == '\r') { + if ((c = getc(f1)) == '\n') + ctold++; + else + ungetc(c, f1); + } + if (d == '\r') { + if ((d = getc(f2)) == '\n') + ctnew++; + else + ungetc(d, f2); + } + break; + } + if ((flags & D_FOLDBLANKS) && isspace(c) && isspace(d)) { + do { + if (c == '\n') + break; + ctold++; + } while (isspace(c = getc(f1))); + do { + if (d == '\n') + break; + ctnew++; + } while (isspace(d = getc(f2))); + } else if (flags & D_IGNOREBLANKS) { + while (isspace(c) && c != '\n') { + c = getc(f1); + ctold++; + } + while (isspace(d) && d != '\n') { + d = getc(f2); + ctnew++; + } + } + if (chrtran(c) != chrtran(d)) { + J[i] = 0; + if (c != '\n' && c != EOF) + ctold += skipline(f1); + if (d != '\n' && c != EOF) + ctnew += skipline(f2); + break; + } + if (c == '\n' || c == EOF) + break; + } + } else { + for (;;) { + ctold++; + ctnew++; + if ((c = getc(f1)) != (d = getc(f2))) { + J[i] = 0; + if (c != '\n' && c != EOF) + ctold += skipline(f1); + if (d != '\n' && c != EOF) + ctnew += skipline(f2); + break; + } + if (c == '\n' || c == EOF) + break; + } + } + ixold[i] = ctold; + ixnew[j] = ctnew; + j++; + } + for (; j <= (int)len[1]; j++) { + ixnew[j] = ctnew += skipline(f2); + } } static void sort(struct Line *a, int n) { - struct Line *ai, *aim, w; - int j, m = 0, k; - - if (n == 0) - return; - for (j = 1; j <= n; j *= 2) - m = 2 * j - 1; - for (m /= 2; m != 0; m /= 2) { - k = n - m; - for (j = 1; j <= k; j++) { - for (ai = &a[j]; ai > a; ai -= m) { - aim = &ai[m]; - if (aim < ai) - break; - if (aim->value > ai[0].value || - (aim->value == ai[0].value && aim->serial > ai[0].serial)) - break; - w.value = ai[0].value; - ai[0].value = aim->value; - aim->value = w.value; - w.serial = ai[0].serial; - ai[0].serial = aim->serial; - aim->serial = w.serial; - } - } - } + struct Line *ai, *aim, w; + int j, m = 0, k; + + if (n == 0) + return; + for (j = 1; j <= n; j *= 2) + m = 2 * j - 1; + for (m /= 2; m != 0; m /= 2) { + k = n - m; + for (j = 1; j <= k; j++) { + for (ai = &a[j]; ai > a; ai -= m) { + aim = &ai[m]; + if (aim < ai) + break; + if (aim->value > ai[0].value || + (aim->value == ai[0].value && aim->serial > ai[0].serial)) + break; + w.value = ai[0].value; + ai[0].value = aim->value; + aim->value = w.value; + w.serial = ai[0].serial; + ai[0].serial = aim->serial; + aim->serial = w.serial; + } + } + } } static void unsort(struct Line *f, int l, int *b) { - int *a, i; - - a = ecalloc(l + 1, sizeof(*a)); - for (i = 1; i <= l; i++) - a[f[i].serial] = f[i].value; - for (i = 1; i <= l; i++) - b[i] = a[i]; - free(a); + int *a, i; + + a = ecalloc(l + 1, sizeof(*a)); + for (i = 1; i <= l; i++) + a[f[i].serial] = f[i].value; + for (i = 1; i <= l; i++) + b[i] = a[i]; + free(a); } static int skipline(FILE *f) { - int i, c; + int i, c; - for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++) - continue; - return i; + for (i = 1; (c = getc(f)) != '\n' && c != EOF; i++) + continue; + return i; } static void output(char *file1, FILE *f1, char *file2, FILE *f2, int flags) { - int i, j, m, i0, i1, j0, j1, nc; - - rewind(f1); - rewind(f2); - m = len[0]; - J[0] = 0; - J[m + 1] = len[1] + 1; - if (diff_format != D_EDIT) { - for (i0 = 1; i0 <= m; i0 = i1 + 1) { - while (i0 <= m && J[i0] == J[i0 - 1] + 1) { - if (diff_format == D_SIDEBYSIDE && suppress_common != 1) { - nc = fetch(ixold, i0, i0, f1, '\0', 1, flags); - print_space(nc, hw - nc + lpad + 1 + rpad, flags); - fetch(ixnew, J[i0], J[i0], f2, '\0', 0, flags); - printf("\n"); - } - i0++; - } - j0 = J[i0 - 1] + 1; - i1 = i0 - 1; - while (i1 < m && J[i1 + 1] == 0) - i1++; - j1 = J[i1 + 1] - 1; - J[i1] = j1; - - if (diff_format == D_SIDEBYSIDE) { - for (i = i0, j = j0; i <= i1 && j <= j1; i++, j++) - change(file1, f1, file2, f2, i, i, j, j, &flags); - while (i <= i1) { - change(file1, f1, file2, f2, i, i, j + 1, j, &flags); - i++; - } - while (j <= j1) { - change(file1, f1, file2, f2, i + 1, i, j, j, &flags); - j++; - } - } else - change(file1, f1, file2, f2, i0, i1, j0, j1, &flags); - } - } else { - for (i0 = m; i0 >= 1; i0 = i1 - 1) { - while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0) - i0--; - j0 = J[i0 + 1] - 1; - i1 = i0 + 1; - while (i1 > 1 && J[i1 - 1] == 0) - i1--; - j1 = J[i1 - 1] + 1; - J[i1] = j1; - change(file1, f1, file2, f2, i1, i0, j1, j0, &flags); - } - } - if (m == 0) - change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags); - if (diff_format == D_IFDEF || diff_format == D_GFORMAT) { - for (;;) { + int i, j, m, i0, i1, j0, j1, nc; + + rewind(f1); + rewind(f2); + m = len[0]; + J[0] = 0; + J[m + 1] = len[1] + 1; + if (diff_format != D_EDIT) { + for (i0 = 1; i0 <= m; i0 = i1 + 1) { + while (i0 <= m && J[i0] == J[i0 - 1] + 1) { + if (diff_format == D_SIDEBYSIDE && suppress_common != 1) { + nc = fetch(ixold, i0, i0, f1, '\0', 1, flags); + print_space(nc, hw - nc + lpad + 1 + rpad, flags); + fetch(ixnew, J[i0], J[i0], f2, '\0', 0, flags); + printf("\n"); + } + i0++; + } + j0 = J[i0 - 1] + 1; + i1 = i0 - 1; + while (i1 < m && J[i1 + 1] == 0) + i1++; + j1 = J[i1 + 1] - 1; + J[i1] = j1; + + if (diff_format == D_SIDEBYSIDE) { + for (i = i0, j = j0; i <= i1 && j <= j1; i++, j++) + change(file1, f1, file2, f2, i, i, j, j, &flags); + while (i <= i1) { + change(file1, f1, file2, f2, i, i, j + 1, j, &flags); + i++; + } + while (j <= j1) { + change(file1, f1, file2, f2, i + 1, i, j, j, &flags); + j++; + } + } else + change(file1, f1, file2, f2, i0, i1, j0, j1, &flags); + } + } else { + for (i0 = m; i0 >= 1; i0 = i1 - 1) { + while (i0 >= 1 && J[i0] == J[i0 + 1] - 1 && J[i0] != 0) + i0--; + j0 = J[i0 + 1] - 1; + i1 = i0 + 1; + while (i1 > 1 && J[i1 - 1] == 0) + i1--; + j1 = J[i1 - 1] + 1; + J[i1] = j1; + change(file1, f1, file2, f2, i1, i0, j1, j0, &flags); + } + } + if (m == 0) + change(file1, f1, file2, f2, 1, 0, 1, len[1], &flags); + if (diff_format == D_IFDEF || diff_format == D_GFORMAT) { + for (;;) { #define c i0 - if ((c = getc(f1)) == EOF) - return; - printf("%c", c); - } + if ((c = getc(f1)) == EOF) + return; + printf("%c", c); + } #undef c - } - if (anychange != 0) { - if (diff_format == D_CONTEXT) - dump_context_vec(f1, f2, flags); - else if (diff_format == D_UNIFIED) - dump_unified_vec(f1, f2, flags); - } + } + if (anychange != 0) { + if (diff_format == D_CONTEXT) + dump_context_vec(f1, f2, flags); + else if (diff_format == D_UNIFIED) + dump_unified_vec(f1, f2, flags); + } } static void range(int a, int b, const char *separator) { - printf("%d", a > b ? b : a); - if (a < b) - printf("%s%d", separator, b); + printf("%d", a > b ? b : a); + if (a < b) + printf("%s%d", separator, b); } static void uni_range(int a, int b) { - if (a < b) - printf("%d,%d", a, b - a + 1); - else if (a == b) - printf("%d", b); - else - printf("%d,0", b); + if (a < b) + printf("%d,%d", a, b - a + 1); + else if (a == b) + printf("%d", b); + else + printf("%d,0", b); } static char * preadline(int fd, size_t rlen, off_t off) { - char *line; - ssize_t nr; - - line = emalloc(rlen + 1); - if ((nr = pread(fd, line, rlen, off)) == -1) - err(2, "preadline"); - if (nr > 0 && line[nr-1] == '\n') - nr--; - line[nr] = '\0'; - return line; + char *line; + ssize_t nr; + + line = emalloc(rlen + 1); + if ((nr = pread(fd, line, rlen, off)) == -1) + enprintf(2, "preadline"); + if (nr > 0 && line[nr-1] == '\n') + nr--; + line[nr] = '\0'; + return line; } static int ignoreline_pattern(char *line) { - int ret; + int ret; - ret = regexec(&ignore_re, line, 0, NULL, 0); - return ret == 0; + ret = regexec(&ignore_re, line, 0, NULL, 0); + return ret == 0; } static int ignoreline(char *line, int skip_blanks) { - if (skip_blanks && *line == '\0') - return 1; - if (ignore_pats != NULL && ignoreline_pattern(line)) - return 1; - return 0; + if (skip_blanks && *line == '\0') + return 1; + if (ignore_pats != NULL && ignoreline_pattern(line)) + return 1; + return 0; } static void change(char *file1, FILE *f1, char *file2, FILE *f2, int a, int b, int c, int d, int *pflags) { - static size_t max_context = 64; - long curpos; - int i, nc; - const char *walk; - int skip_blanks, ignore; + static size_t max_context = 64; + long curpos; + int i, nc; + const char *walk; + int skip_blanks, ignore; - skip_blanks = (*pflags & D_SKIPBLANKLINES); + skip_blanks = (*pflags & D_SKIPBLANKLINES); restart: - if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) && a > b && c > d) - return; - if (ignore_pats != NULL || skip_blanks) { - char *line; - if (a <= b) { - for (i = a; i <= b; i++) { - line = preadline(fileno(f1), ixold[i] - ixold[i - 1], ixold[i - 1]); - ignore = ignoreline(line, skip_blanks); - free(line); - if (!ignore) - goto proceed; - } - } - if (a > b || c <= d) { - for (i = c; i <= d; i++) { - line = preadline(fileno(f2), ixnew[i] - ixnew[i - 1], ixnew[i - 1]); - ignore = ignoreline(line, skip_blanks); - free(line); - if (!ignore) - goto proceed; - } - } - return; - } + if ((diff_format != D_IFDEF || diff_format == D_GFORMAT) && a > b && c > d) + return; + if (ignore_pats != NULL || skip_blanks) { + char *line; + if (a <= b) { + for (i = a; i <= b; i++) { + line = preadline(fileno(f1), ixold[i] - ixold[i - 1], ixold[i - 1]); + ignore = ignoreline(line, skip_blanks); + free(line); + if (!ignore) + goto proceed; + } + } + if (a > b || c <= d) { + for (i = c; i <= d; i++) { + line = preadline(fileno(f2), ixnew[i] - ixnew[i - 1], ixnew[i - 1]); + ignore = ignoreline(line, skip_blanks); + free(line); + if (!ignore) + goto proceed; + } + } + return; + } proceed: - if (*pflags & D_HEADER && diff_format != D_BRIEF) { - printf("%s %s %s\n", diffargs, file1, file2); - *pflags &= ~D_HEADER; - } - if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) { - if (context_vec_start == NULL || context_vec_ptr == context_vec_end - 1) { - ptrdiff_t offset = -1; - - if (context_vec_start != NULL) - offset = context_vec_ptr - context_vec_start; - max_context <<= 1; - context_vec_start = ereallocarray(context_vec_start, max_context, sizeof(*context_vec_start)); - context_vec_end = context_vec_start + max_context; - context_vec_ptr = context_vec_start + offset; - } - if (anychange == 0) { - print_header(file1, file2); - anychange = 1; - } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 && - c > context_vec_ptr->d + (2 * diff_context) + 1) { - if (diff_format == D_CONTEXT) - dump_context_vec(f1, f2, *pflags); - else - dump_unified_vec(f1, f2, *pflags); - } - context_vec_ptr++; - context_vec_ptr->a = a; - context_vec_ptr->b = b; - context_vec_ptr->c = c; - context_vec_ptr->d = d; - return; - } - if (anychange == 0) - anychange = 1; - switch (diff_format) { - case D_BRIEF: - return; - case D_NORMAL: - case D_EDIT: - range(a, b, ","); - printf("%c", a > b ? 'a' : c > d ? 'd' : 'c'); - if (diff_format == D_NORMAL) - range(c, d, ","); - printf("\n"); - break; - case D_REVERSE: - printf("%c", a > b ? 'a' : c > d ? 'd' : 'c'); - range(a, b, " "); - printf("\n"); - break; - case D_NREVERSE: - if (a > b) - printf("a%d %d\n", b, d - c + 1); - else { - printf("d%d %d\n", a, b - a + 1); - if (!(c > d)) - printf("a%d %d\n", b, d - c + 1); - } - break; - } - if (diff_format == D_GFORMAT) { - curpos = ftell(f1); - nc = ixold[a > b ? b : a - 1] - curpos; - for (i = 0; i < nc; i++) - printf("%c", getc(f1)); - for (walk = group_format; *walk != '\0'; walk++) { - if (*walk == '%') { - walk++; - switch (*walk) { - case '<': - fetch(ixold, a, b, f1, '<', 1, *pflags); - break; - case '>': - fetch(ixnew, c, d, f2, '>', 0, *pflags); - break; - default: - printf("%%%c", *walk); - break; - } - continue; - } - printf("%c", *walk); - } - } - if (diff_format == D_SIDEBYSIDE) { - if (color && a > b) - printf("\033[%sm", add_code); - else if (color && c > d) - printf("\033[%sm", del_code); - if (a > b) { - print_space(0, hw + lpad, *pflags); - } else { - nc = fetch(ixold, a, b, f1, '\0', 1, *pflags); - print_space(nc, hw - nc + lpad, *pflags); - } - if (color && a > b) - printf("\033[%sm", add_code); - else if (color && c > d) - printf("\033[%sm", del_code); - printf("%c", (a > b) ? '>' : ((c > d) ? '<' : '|')); - if (color && c > d) - printf("\033[m"); - print_space(hw + lpad + 1, rpad, *pflags); - fetch(ixnew, c, d, f2, '\0', 0, *pflags); - printf("\n"); - } - if (diff_format == D_NORMAL || diff_format == D_IFDEF) { - fetch(ixold, a, b, f1, '<', 1, *pflags); - if (a <= b && c <= d && diff_format == D_NORMAL) - printf("---\n"); - } - if (diff_format != D_GFORMAT && diff_format != D_SIDEBYSIDE) - fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags); - if (edoffset != 0 && diff_format == D_EDIT) { - printf(".\n"); - printf("%ds/.//\n", a + edoffset - 1); - b = a + edoffset - 1; - a = b + 1; - c += edoffset; - goto restart; - } - if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d) - printf(".\n"); - if (inifdef) { - printf("#endif /* %s */\n", ifdefname); - inifdef = 0; - } + if (*pflags & D_HEADER && diff_format != D_BRIEF) { + printf("%s %s %s\n", diffargs, file1, file2); + *pflags &= ~D_HEADER; + } + if (diff_format == D_CONTEXT || diff_format == D_UNIFIED) { + if (context_vec_start == NULL || context_vec_ptr == context_vec_end - 1) { + ptrdiff_t offset = -1; + + if (context_vec_start != NULL) + offset = context_vec_ptr - context_vec_start; + max_context <<= 1; + context_vec_start = ereallocarray(context_vec_start, max_context, sizeof(*context_vec_start)); + context_vec_end = context_vec_start + max_context; + context_vec_ptr = context_vec_start + offset; + } + if (anychange == 0) { + print_header(file1, file2); + anychange = 1; + } else if (a > context_vec_ptr->b + (2 * diff_context) + 1 && + c > context_vec_ptr->d + (2 * diff_context) + 1) { + if (diff_format == D_CONTEXT) + dump_context_vec(f1, f2, *pflags); + else + dump_unified_vec(f1, f2, *pflags); + } + context_vec_ptr++; + context_vec_ptr->a = a; + context_vec_ptr->b = b; + context_vec_ptr->c = c; + context_vec_ptr->d = d; + return; + } + if (anychange == 0) + anychange = 1; + switch (diff_format) { + case D_BRIEF: + return; + case D_NORMAL: + case D_EDIT: + range(a, b, ","); + printf("%c", a > b ? 'a' : c > d ? 'd' : 'c'); + if (diff_format == D_NORMAL) + range(c, d, ","); + printf("\n"); + break; + case D_REVERSE: + printf("%c", a > b ? 'a' : c > d ? 'd' : 'c'); + range(a, b, " "); + printf("\n"); + break; + case D_NREVERSE: + if (a > b) + printf("a%d %d\n", b, d - c + 1); + else { + printf("d%d %d\n", a, b - a + 1); + if (!(c > d)) + printf("a%d %d\n", b, d - c + 1); + } + break; + } + if (diff_format == D_GFORMAT) { + curpos = ftell(f1); + nc = ixold[a > b ? b : a - 1] - curpos; + for (i = 0; i < nc; i++) + printf("%c", getc(f1)); + for (walk = group_format; *walk != '\0'; walk++) { + if (*walk == '%') { + walk++; + switch (*walk) { + case '<': + fetch(ixold, a, b, f1, '<', 1, *pflags); + break; + case '>': + fetch(ixnew, c, d, f2, '>', 0, *pflags); + break; + default: + printf("%%%c", *walk); + break; + } + continue; + } + printf("%c", *walk); + } + } + if (diff_format == D_SIDEBYSIDE) { + if (color && a > b) + printf("\033[%sm", add_code); + else if (color && c > d) + printf("\033[%sm", del_code); + if (a > b) { + print_space(0, hw + lpad, *pflags); + } else { + nc = fetch(ixold, a, b, f1, '\0', 1, *pflags); + print_space(nc, hw - nc + lpad, *pflags); + } + if (color && a > b) + printf("\033[%sm", add_code); + else if (color && c > d) + printf("\033[%sm", del_code); + printf("%c", (a > b) ? '>' : ((c > d) ? '<' : '|')); + if (color && c > d) + printf("\033[m"); + print_space(hw + lpad + 1, rpad, *pflags); + fetch(ixnew, c, d, f2, '\0', 0, *pflags); + printf("\n"); + } + if (diff_format == D_NORMAL || diff_format == D_IFDEF) { + fetch(ixold, a, b, f1, '<', 1, *pflags); + if (a <= b && c <= d && diff_format == D_NORMAL) + printf("---\n"); + } + if (diff_format != D_GFORMAT && diff_format != D_SIDEBYSIDE) + fetch(ixnew, c, d, f2, diff_format == D_NORMAL ? '>' : '\0', 0, *pflags); + if (edoffset != 0 && diff_format == D_EDIT) { + printf(".\n"); + printf("%ds/.//\n", a + edoffset - 1); + b = a + edoffset - 1; + a = b + 1; + c += edoffset; + goto restart; + } + if ((diff_format == D_EDIT || diff_format == D_REVERSE) && c <= d) + printf(".\n"); + if (inifdef) { + printf("#endif /* %s */\n", ifdefname); + inifdef = 0; + } } static int fetch(long *f, int a, int b, FILE *lb, int ch, int oldfile, int flags) { - int i, j, c, lastc, col, nc, newcol; - - edoffset = 0; - nc = 0; - col = 0; - if ((diff_format == D_IFDEF) && oldfile) { - long curpos = ftell(lb); - nc = f[a > b ? b : a - 1] - curpos; - for (i = 0; i < nc; i++) - printf("%c", getc(lb)); - } - if (a > b) - return 0; - if (diff_format == D_IFDEF) { - if (inifdef) { - printf("#else /* %s%s */\n", - oldfile == 1 ? "!" : "", ifdefname); - } else { - if (oldfile) - printf("#ifndef %s\n", ifdefname); - else - printf("#ifdef %s\n", ifdefname); - } - inifdef = 1 + oldfile; - } - for (i = a; i <= b; i++) { - fseek(lb, f[i - 1], SEEK_SET); - nc = f[i] - f[i - 1]; - if (diff_format == D_SIDEBYSIDE && hw < nc) - nc = hw; - if (diff_format != D_IFDEF && diff_format != D_GFORMAT && ch != '\0') { - if (color && (ch == '>' || ch == '+')) - printf("\033[%sm", add_code); - else if (color && (ch == '<' || ch == '-')) - printf("\033[%sm", del_code); - printf("%c", ch); - if (Tflag && (diff_format == D_NORMAL || - diff_format == D_CONTEXT || - diff_format == D_UNIFIED)) - printf("\t"); - else if (diff_format != D_UNIFIED) - printf(" "); - } - col = j = 0; - lastc = '\0'; - while (j < nc && (hw == 0 || col < hw)) { - c = getc(lb); - if (flags & D_STRIPCR && c == '\r') { - if ((c = getc(lb)) == '\n') - j++; - else { - ungetc(c, lb); - c = '\r'; - } - } - if (c == EOF) { - if (diff_format == D_EDIT || - diff_format == D_REVERSE || - diff_format == D_NREVERSE) - warnx("No newline at end of file"); - else - printf("\n\\ No newline at end of file\n"); - return col; - } - if (c == '\t') { - newcol = roundup(col + 1, tabsize); - if ((flags & D_EXPANDTABS) == 0) { - if (hw > 0 && newcol >= hw) - return col; - printf("\t"); - } else { - if (hw > 0 && newcol > hw) - newcol = hw; - printf("%*s", newcol - col, ""); - } - col = newcol; - } else { - if (diff_format == D_EDIT && j == 1 && c == '\n' && lastc == '.') { - printf(".\n"); - edoffset = i - a + 1; - return edoffset; - } - if (diff_format != D_SIDEBYSIDE || c != '\n') { - if (color && c == '\n') - printf("\033[m%c", c); - else - printf("%c", c); - col++; - } - } - j++; - lastc = c; - } - } - if (color && diff_format == D_SIDEBYSIDE) - printf("\033[m"); - return col; + int i, j, c, lastc, col, nc, newcol; + + edoffset = 0; + nc = 0; + col = 0; + if ((diff_format == D_IFDEF) && oldfile) { + long curpos = ftell(lb); + nc = f[a > b ? b : a - 1] - curpos; + for (i = 0; i < nc; i++) + printf("%c", getc(lb)); + } + if (a > b) + return 0; + if (diff_format == D_IFDEF) { + if (inifdef) { + printf("#else /* %s%s */\n", + oldfile == 1 ? "!" : "", ifdefname); + } else { + if (oldfile) + printf("#ifndef %s\n", ifdefname); + else + printf("#ifdef %s\n", ifdefname); + } + inifdef = 1 + oldfile; + } + for (i = a; i <= b; i++) { + fseek(lb, f[i - 1], SEEK_SET); + nc = f[i] - f[i - 1]; + if (diff_format == D_SIDEBYSIDE && hw < nc) + nc = hw; + if (diff_format != D_IFDEF && diff_format != D_GFORMAT && ch != '\0') { + if (color && (ch == '>' || ch == '+')) + printf("\033[%sm", add_code); + else if (color && (ch == '<' || ch == '-')) + printf("\033[%sm", del_code); + printf("%c", ch); + if (Tflag && (diff_format == D_NORMAL || + diff_format == D_CONTEXT || + diff_format == D_UNIFIED)) + printf("\t"); + else if (diff_format != D_UNIFIED) + printf(" "); + } + col = j = 0; + lastc = '\0'; + while (j < nc && (hw == 0 || col < hw)) { + c = getc(lb); + if (flags & D_STRIPCR && c == '\r') { + if ((c = getc(lb)) == '\n') + j++; + else { + ungetc(c, lb); + c = '\r'; + } + } + if (c == EOF) { + if (diff_format == D_EDIT || + diff_format == D_REVERSE || + diff_format == D_NREVERSE) + weprintf("No newline at end of file"); + else + printf("\n\\ No newline at end of file\n"); + return col; + } + if (c == '\t') { + newcol = roundup(col + 1, tabsize); + if ((flags & D_EXPANDTABS) == 0) { + if (hw > 0 && newcol >= hw) + return col; + printf("\t"); + } else { + if (hw > 0 && newcol > hw) + newcol = hw; + printf("%*s", newcol - col, ""); + } + col = newcol; + } else { + if (diff_format == D_EDIT && j == 1 && c == '\n' && lastc == '.') { + printf(".\n"); + edoffset = i - a + 1; + return edoffset; + } + if (diff_format != D_SIDEBYSIDE || c != '\n') { + if (color && c == '\n') + printf("\033[m%c", c); + else + printf("%c", c); + col++; + } + } + j++; + lastc = c; + } + } + if (color && diff_format == D_SIDEBYSIDE) + printf("\033[m"); + return col; } static enum Readhash readhash(FILE *f, int flags, unsigned *hash) { - int i, t, space; - unsigned sum; - - sum = 1; - space = 0; - for (i = 0;;) { - switch (t = getc(f)) { - case '\0': - if ((flags & D_FORCEASCII) == 0) - return RH_BINARY; - goto hashchar; - case '\r': - if (flags & D_STRIPCR) { - t = getc(f); - if (t == '\n') - break; - ungetc(t, f); - } - /* FALLTHROUGH */ - case '\t': - case '\v': - case '\f': - case ' ': - if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) != 0) { - space++; - continue; - } - /* FALLTHROUGH */ - default: - hashchar: - if (space && (flags & D_IGNOREBLANKS) == 0) { - i++; - space = 0; - } - sum = sum * 127 + chrtran(t); - i++; - continue; - case EOF: - if (i == 0) - return RH_EOF; - /* FALLTHROUGH */ - case '\n': - break; - } - break; - } - *hash = sum; - return RH_OK; + int i, t, space; + unsigned sum; + + sum = 1; + space = 0; + for (i = 0;;) { + switch (t = getc(f)) { + case '\0': + if ((flags & D_FORCEASCII) == 0) + return RH_BINARY; + goto hashchar; + case '\r': + if (flags & D_STRIPCR) { + t = getc(f); + if (t == '\n') + break; + ungetc(t, f); + } + /* FALLTHROUGH */ + case '\t': + case '\v': + case '\f': + case ' ': + if ((flags & (D_FOLDBLANKS|D_IGNOREBLANKS)) != 0) { + space++; + continue; + } + /* FALLTHROUGH */ + default: + hashchar: + if (space && (flags & D_IGNOREBLANKS) == 0) { + i++; + space = 0; + } + sum = sum * 127 + chrtran(t); + i++; + continue; + case EOF: + if (i == 0) + return RH_EOF; + /* FALLTHROUGH */ + case '\n': + break; + } + break; + } + *hash = sum; + return RH_OK; } static int asciifile(FILE *f) { - unsigned char buf[BUFSIZ]; - size_t cnt; + unsigned char buf[BUFSIZ]; + size_t cnt; - if (f == NULL) - return 1; + if (f == NULL) + return 1; - rewind(f); - cnt = fread(buf, 1, sizeof(buf), f); - return memchr(buf, '\0', cnt) == NULL; + rewind(f); + cnt = fread(buf, 1, sizeof(buf), f); + return memchr(buf, '\0', cnt) == NULL; } #define begins_with(s, pre) (strncmp(s, pre, sizeof(pre) - 1) == 0) @@ -2232,258 +2239,258 @@ asciifile(FILE *f) static char * match_function(const long *f, int pos, FILE *fp) { - char buf[FUNCTION_CONTEXT_SIZE]; - size_t nc; - int last = lastline; - const char *state = NULL; - - lastline = pos; - for (; pos > last; pos--) { - fseek(fp, f[pos - 1], SEEK_SET); - nc = f[pos] - f[pos - 1]; - if (nc >= sizeof(buf)) - nc = sizeof(buf) - 1; - nc = fread(buf, 1, nc, fp); - if (nc == 0) - continue; - buf[nc] = '\0'; - buf[strcspn(buf, "\n")] = '\0'; - if (most_recent_pat != NULL) { - int ret = regexec(&most_recent_re, buf, 0, NULL, 0); - if (ret != 0) - continue; - strlcpy(lastbuf, buf, sizeof(lastbuf)); - lastmatchline = pos; - return lastbuf; - } else if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$' || buf[0] == '-' || buf[0] == '+') { - if (begins_with(buf, "private:")) { - if (!state) - state = " (private)"; - } else if (begins_with(buf, "protected:")) { - if (!state) - state = " (protected)"; - } else if (begins_with(buf, "public:")) { - if (!state) - state = " (public)"; - } else { - strlcpy(lastbuf, buf, sizeof(lastbuf)); - if (state) - strlcat(lastbuf, state, sizeof(lastbuf)); - lastmatchline = pos; - return lastbuf; - } - } - } - return lastmatchline > 0 ? lastbuf : NULL; + char buf[FUNCTION_CONTEXT_SIZE]; + size_t nc; + int last = lastline; + const char *state = NULL; + + lastline = pos; + for (; pos > last; pos--) { + fseek(fp, f[pos - 1], SEEK_SET); + nc = f[pos] - f[pos - 1]; + if (nc >= sizeof(buf)) + nc = sizeof(buf) - 1; + nc = fread(buf, 1, nc, fp); + if (nc == 0) + continue; + buf[nc] = '\0'; + buf[strcspn(buf, "\n")] = '\0'; + if (most_recent_pat != NULL) { + int ret = regexec(&most_recent_re, buf, 0, NULL, 0); + if (ret != 0) + continue; + strlcpy(lastbuf, buf, sizeof(lastbuf)); + lastmatchline = pos; + return lastbuf; + } else if (isalpha(buf[0]) || buf[0] == '_' || buf[0] == '$' || buf[0] == '-' || buf[0] == '+') { + if (begins_with(buf, "private:")) { + if (!state) + state = " (private)"; + } else if (begins_with(buf, "protected:")) { + if (!state) + state = " (protected)"; + } else if (begins_with(buf, "public:")) { + if (!state) + state = " (public)"; + } else { + strlcpy(lastbuf, buf, sizeof(lastbuf)); + if (state) + strlcat(lastbuf, state, sizeof(lastbuf)); + lastmatchline = pos; + return lastbuf; + } + } + } + return lastmatchline > 0 ? lastbuf : NULL; } static void dump_context_vec(FILE *f1, FILE *f2, int flags) { - struct ContextVec *cvp = context_vec_start; - int lowa, upb, lowc, upd, do_output; - int a, b, c, d; - char ch, *f; - - if (context_vec_start > context_vec_ptr) - return; - - b = d = 0; - lowa = MAX(1, cvp->a - diff_context); - upb = MIN((int)len[0], context_vec_ptr->b + diff_context); - lowc = MAX(1, cvp->c - diff_context); - upd = MIN((int)len[1], context_vec_ptr->d + diff_context); - - printf("***************"); - if (flags & (D_PROTOTYPE | D_MATCHLAST)) { - f = match_function(ixold, cvp->a - 1, f1); - if (f != NULL) - printf(" %s", f); - } - printf("\n*** "); - range(lowa, upb, ","); - printf(" ****\n"); - - do_output = 0; - for (; cvp <= context_vec_ptr; cvp++) - if (cvp->a <= cvp->b) { - cvp = context_vec_start; - do_output++; - break; - } - if (do_output) { - while (cvp <= context_vec_ptr) { - a = cvp->a; - b = cvp->b; - c = cvp->c; - d = cvp->d; - - if (a <= b && c <= d) - ch = 'c'; - else - ch = (a <= b) ? 'd' : 'a'; - - if (ch == 'a') - fetch(ixold, lowa, b, f1, ' ', 0, flags); - else { - fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); - fetch(ixold, a, b, f1, ch == 'c' ? '!' : '-', 0, flags); - } - lowa = b + 1; - cvp++; - } - fetch(ixold, b + 1, upb, f1, ' ', 0, flags); - } - - printf("--- "); - range(lowc, upd, ","); - printf(" ----\n"); - - do_output = 0; - for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++) - if (cvp->c <= cvp->d) { - cvp = context_vec_start; - do_output++; - break; - } - if (do_output) { - while (cvp <= context_vec_ptr) { - a = cvp->a; - b = cvp->b; - c = cvp->c; - d = cvp->d; - - if (a <= b && c <= d) - ch = 'c'; - else - ch = (a <= b) ? 'd' : 'a'; - - if (ch == 'd') - fetch(ixnew, lowc, d, f2, ' ', 0, flags); - else { - fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags); - fetch(ixnew, c, d, f2, ch == 'c' ? '!' : '+', 0, flags); - } - lowc = d + 1; - cvp++; - } - fetch(ixnew, d + 1, upd, f2, ' ', 0, flags); - } - context_vec_ptr = context_vec_start - 1; + struct ContextVec *cvp = context_vec_start; + int lowa, upb, lowc, upd, do_output; + int a, b, c, d; + char ch, *f; + + if (context_vec_start > context_vec_ptr) + return; + + b = d = 0; + lowa = MAX(1, cvp->a - diff_context); + upb = MIN((int)len[0], context_vec_ptr->b + diff_context); + lowc = MAX(1, cvp->c - diff_context); + upd = MIN((int)len[1], context_vec_ptr->d + diff_context); + + printf("***************"); + if (flags & (D_PROTOTYPE | D_MATCHLAST)) { + f = match_function(ixold, cvp->a - 1, f1); + if (f != NULL) + printf(" %s", f); + } + printf("\n*** "); + range(lowa, upb, ","); + printf(" ****\n"); + + do_output = 0; + for (; cvp <= context_vec_ptr; cvp++) + if (cvp->a <= cvp->b) { + cvp = context_vec_start; + do_output++; + break; + } + if (do_output) { + while (cvp <= context_vec_ptr) { + a = cvp->a; + b = cvp->b; + c = cvp->c; + d = cvp->d; + + if (a <= b && c <= d) + ch = 'c'; + else + ch = (a <= b) ? 'd' : 'a'; + + if (ch == 'a') + fetch(ixold, lowa, b, f1, ' ', 0, flags); + else { + fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); + fetch(ixold, a, b, f1, ch == 'c' ? '!' : '-', 0, flags); + } + lowa = b + 1; + cvp++; + } + fetch(ixold, b + 1, upb, f1, ' ', 0, flags); + } + + printf("--- "); + range(lowc, upd, ","); + printf(" ----\n"); + + do_output = 0; + for (cvp = context_vec_start; cvp <= context_vec_ptr; cvp++) + if (cvp->c <= cvp->d) { + cvp = context_vec_start; + do_output++; + break; + } + if (do_output) { + while (cvp <= context_vec_ptr) { + a = cvp->a; + b = cvp->b; + c = cvp->c; + d = cvp->d; + + if (a <= b && c <= d) + ch = 'c'; + else + ch = (a <= b) ? 'd' : 'a'; + + if (ch == 'd') + fetch(ixnew, lowc, d, f2, ' ', 0, flags); + else { + fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags); + fetch(ixnew, c, d, f2, ch == 'c' ? '!' : '+', 0, flags); + } + lowc = d + 1; + cvp++; + } + fetch(ixnew, d + 1, upd, f2, ' ', 0, flags); + } + context_vec_ptr = context_vec_start - 1; } static void dump_unified_vec(FILE *f1, FILE *f2, int flags) { - struct ContextVec *cvp = context_vec_start; - int lowa, upb, lowc, upd; - int a, b, c, d; - char ch, *f; - - if (context_vec_start > context_vec_ptr) - return; - - b = d = 0; - lowa = MAX(1, cvp->a - diff_context); - upb = MIN((int)len[0], context_vec_ptr->b + diff_context); - lowc = MAX(1, cvp->c - diff_context); - upd = MIN((int)len[1], context_vec_ptr->d + diff_context); - - printf("@@ -"); - uni_range(lowa, upb); - printf(" +"); - uni_range(lowc, upd); - printf(" @@"); - if (flags & (D_PROTOTYPE | D_MATCHLAST)) { - f = match_function(ixold, cvp->a - 1, f1); - if (f != NULL) - printf(" %s", f); - } - printf("\n"); - - for (; cvp <= context_vec_ptr; cvp++) { - a = cvp->a; - b = cvp->b; - c = cvp->c; - d = cvp->d; - - if (a <= b && c <= d) - ch = 'c'; - else - ch = (a <= b) ? 'd' : 'a'; - - switch (ch) { - case 'c': - fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); - fetch(ixold, a, b, f1, '-', 0, flags); - fetch(ixnew, c, d, f2, '+', 0, flags); - break; - case 'd': - fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); - fetch(ixold, a, b, f1, '-', 0, flags); - break; - case 'a': - fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags); - fetch(ixnew, c, d, f2, '+', 0, flags); - break; - } - lowa = b + 1; - lowc = d + 1; - } - fetch(ixnew, d + 1, upd, f2, ' ', 0, flags); - context_vec_ptr = context_vec_start - 1; + struct ContextVec *cvp = context_vec_start; + int lowa, upb, lowc, upd; + int a, b, c, d; + char ch, *f; + + if (context_vec_start > context_vec_ptr) + return; + + b = d = 0; + lowa = MAX(1, cvp->a - diff_context); + upb = MIN((int)len[0], context_vec_ptr->b + diff_context); + lowc = MAX(1, cvp->c - diff_context); + upd = MIN((int)len[1], context_vec_ptr->d + diff_context); + + printf("@@ -"); + uni_range(lowa, upb); + printf(" +"); + uni_range(lowc, upd); + printf(" @@"); + if (flags & (D_PROTOTYPE | D_MATCHLAST)) { + f = match_function(ixold, cvp->a - 1, f1); + if (f != NULL) + printf(" %s", f); + } + printf("\n"); + + for (; cvp <= context_vec_ptr; cvp++) { + a = cvp->a; + b = cvp->b; + c = cvp->c; + d = cvp->d; + + if (a <= b && c <= d) + ch = 'c'; + else + ch = (a <= b) ? 'd' : 'a'; + + switch (ch) { + case 'c': + fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); + fetch(ixold, a, b, f1, '-', 0, flags); + fetch(ixnew, c, d, f2, '+', 0, flags); + break; + case 'd': + fetch(ixold, lowa, a - 1, f1, ' ', 0, flags); + fetch(ixold, a, b, f1, '-', 0, flags); + break; + case 'a': + fetch(ixnew, lowc, c - 1, f2, ' ', 0, flags); + fetch(ixnew, c, d, f2, '+', 0, flags); + break; + } + lowa = b + 1; + lowc = d + 1; + } + fetch(ixnew, d + 1, upd, f2, ' ', 0, flags); + context_vec_ptr = context_vec_start - 1; } static void print_header(const char *file1, const char *file2) { - const char *time_format; - char buf[256]; - struct tm tm1, tm2, *tm_ptr1, *tm_ptr2; - int nsec1 = stb1.st_mtim.tv_nsec; - int nsec2 = stb2.st_mtim.tv_nsec; - - time_format = "%Y-%m-%d %H:%M:%S"; - if (cflag) - time_format = "%c"; - tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1); - tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2); - if (label[0] != NULL) - printf("%s %s\n", diff_format == D_CONTEXT ? "***" : "---", label[0]); - else { - strftime(buf, sizeof(buf), time_format, tm_ptr1); - printf("%s %s\t%s", diff_format == D_CONTEXT ? "***" : "---", file1, buf); - if (!cflag) { - strftime(buf, sizeof(buf), "%z", tm_ptr1); - printf(".%.9d %s", nsec1, buf); - } - printf("\n"); - } - if (label[1] != NULL) - printf("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++", label[1]); - else { - strftime(buf, sizeof(buf), time_format, tm_ptr2); - printf("%s %s\t%s", diff_format == D_CONTEXT ? "---" : "+++", file2, buf); - if (!cflag) { - strftime(buf, sizeof(buf), "%z", tm_ptr2); - printf(".%.9d %s", nsec2, buf); - } - printf("\n"); - } + const char *time_format; + char buf[256]; + struct tm tm1, tm2, *tm_ptr1, *tm_ptr2; + int nsec1 = stb1.st_mtim.tv_nsec; + int nsec2 = stb2.st_mtim.tv_nsec; + + time_format = "%Y-%m-%d %H:%M:%S"; + if (cflag) + time_format = "%c"; + tm_ptr1 = localtime_r(&stb1.st_mtime, &tm1); + tm_ptr2 = localtime_r(&stb2.st_mtime, &tm2); + if (label[0] != NULL) + printf("%s %s\n", diff_format == D_CONTEXT ? "***" : "---", label[0]); + else { + strftime(buf, sizeof(buf), time_format, tm_ptr1); + printf("%s %s\t%s", diff_format == D_CONTEXT ? "***" : "---", file1, buf); + if (!cflag) { + strftime(buf, sizeof(buf), "%z", tm_ptr1); + printf(".%.9d %s", nsec1, buf); + } + printf("\n"); + } + if (label[1] != NULL) + printf("%s %s\n", diff_format == D_CONTEXT ? "---" : "+++", label[1]); + else { + strftime(buf, sizeof(buf), time_format, tm_ptr2); + printf("%s %s\t%s", diff_format == D_CONTEXT ? "---" : "+++", file2, buf); + if (!cflag) { + strftime(buf, sizeof(buf), "%z", tm_ptr2); + printf(".%.9d %s", nsec2, buf); + } + printf("\n"); + } } static void print_space(int nc, int n, int flags) { - int col, newcol, tabstop; - - col = nc; - newcol = nc + n; - if ((flags & D_EXPANDTABS) == 0) { - while ((tabstop = roundup(col + 1, tabsize)) <= newcol) { - printf("\t"); - col = tabstop; - } - } - printf("%*s", newcol - col, ""); + int col, newcol, tabstop; + + col = nc; + newcol = nc + n; + if ((flags & D_EXPANDTABS) == 0) { + while ((tabstop = roundup(col + 1, tabsize)) <= newcol) { + printf("\t"); + col = tabstop; + } + } + printf("%*s", newcol - col, ""); } diff --git a/cmd/posix/diff3.c b/cmd/posix/diff3.c @@ -1,894 +1,502 @@ /* See LICENSE file for copyright and license details. */ +#include "config.h" +#include "diffutil.h" #include "util.h" -#include <sys/types.h> -#include <sys/wait.h> - #include <ctype.h> -#include <err.h> -#include <errno.h> -#include <fcntl.h> -#include <stdarg.h> -#include <getopt.h> -#include <inttypes.h> -#include <limits.h> -#include <poll.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> -struct Range { - int from; - int to; +struct region { + size_t from; + size_t to; }; -struct Diff { -#define DIFF_TYPE1 1 -#define DIFF_TYPE2 2 -#define DIFF_TYPE3 3 - int type; - - struct Range old; - struct Range new; +struct pair_hunk { + struct region old; + struct region new; }; -#define EFLAG_NONE 0 -#define EFLAG_OVERLAP 1 -#define EFLAG_NOOVERLAP 2 -#define EFLAG_UNMERGED 3 - -static size_t szchanges; - -static struct Diff *d13; -static struct Diff *d23; -static struct Diff *de; -static char *overlap; -static int overlapcnt; -static FILE *fp[3]; -static int cline[3]; -static int sigpipe[2]; -static int last[4]; -static int Aflag, eflag, iflag, mflag, Tflag; -static int oflag; -static int strip_cr; -static char *f1mark, *f2mark, *f3mark; -static const char *oldmark = "<<<<<<<"; -static const char *orgmark = "|||||||"; -static const char *newmark = ">>>>>>>"; -static const char *divider = "======="; - -static int duplicate(struct Range *, struct Range *); -static int edit(struct Diff *, int, int, int); -static char *getchange(FILE *); -static char *get_line(FILE *, size_t *); -static int readin(int, struct Diff **); -static int skip(int, int, const char *); -static void change(int, struct Range *, int); -static void keep(int, struct Range *); -static void merge(int, int); -static void prange(struct Range *, int); -static void repos(int); -static void separate(const char *); -static void edscript(int); -static void Ascript(int); -static void mergescript(int); -static void increase(void); -static void usage(void); -static void printrange(FILE *, struct Range *); -static void diffexec(const char *, char **, int *); -static int strtoi(char *, char **); -static void handle_sig(int); -static void xasprintf(char **, const char *, ...); - -static const char diff3_version[] = "FreeBSD diff3 20240925"; - -enum { - DIFFPROG_OPT, - STRIPCR_OPT, - HELP_OPT, - VERSION_OPT +enum hunk_kind { + HUNK_NONE, + HUNK_TYPE1, + HUNK_TYPE2, + HUNK_TYPE3, }; -#define DIFF_PATH "/usr/bin/diff" - -#define OPTIONS "3aAeEiL:mTxX" -static struct option longopts[] = { - { "ed", no_argument, NULL, 'e' }, - { "show-overlap", no_argument, NULL, 'E' }, - { "overlap-only", no_argument, NULL, 'x' }, - { "initial-tab", no_argument, NULL, 'T' }, - { "text", no_argument, NULL, 'a' }, - { "strip-trailing-cr", no_argument, NULL, STRIPCR_OPT }, - { "show-all", no_argument, NULL, 'A' }, - { "easy-only", no_argument, NULL, '3' }, - { "merge", no_argument, NULL, 'm' }, - { "label", required_argument, NULL, 'L' }, - { "diff-program", required_argument, NULL, DIFFPROG_OPT }, - { "help", no_argument, NULL, HELP_OPT}, - { "version", no_argument, NULL, VERSION_OPT} +struct three_hunk { + enum hunk_kind kind; + struct region r1; + struct region r2; + struct region r3; + int dup; }; -static void -usage(void) -{ - fprintf(stderr, "usage: diff3 [-3aAeEimTxX] [-L label1] [-L label2] " - "[-L label3] file1 file2 file3\n"); -} - -static int -strtoi(char *str, char **end) -{ - intmax_t num; - - errno = 0; - num = strtoimax(str, end, 10); - if ((end != NULL && *end == str) || - num < 0 || num > INT_MAX || - errno == EINVAL || errno == ERANGE) - err(1, "error in diff output"); - return (int)num; -} - -static int -readin(int fd, struct Diff **dd) -{ - int a, b, c, d; - int i; - char kind, *p; - FILE *f; - - f = fdopen(fd, "r"); - if (f == NULL) - err(2, "fdopen"); - for (i = 0; (p = getchange(f)) != NULL; i++) { - if ((size_t)i >= szchanges - 1) - increase(); - - a = b = strtoi(p, &p); - if (*p == ',') - b = strtoi(p + 1, &p); - kind = *p++; - c = d = strtoi(p, &p); - if (*p == ',') - d = strtoi(p + 1, &p); - if (*p != '\n') - errx(1, "error in diff output"); - if (kind == 'a') - a++; - else if (kind == 'c') - /* nothing */ ; - else if (kind == 'd') - c++; - else - errx(1, "error in diff output"); - b++; - d++; - if (b < a || d < c) - errx(1, "error in diff output"); - (*dd)[i].old.from = a; - (*dd)[i].old.to = b; - (*dd)[i].new.from = c; - (*dd)[i].new.to = d; - if (i > 0) { - if ((*dd)[i].old.from < (*dd)[i - 1].old.to || - (*dd)[i].new.from < (*dd)[i - 1].new.to) - errx(1, "diff output out of order"); - } - } - if (i > 0) { - (*dd)[i].old.from = (*dd)[i].old.to = (*dd)[i - 1].old.to; - (*dd)[i].new.from = (*dd)[i].new.to = (*dd)[i - 1].new.to; - } - fclose(f); - return i; -} +static int aflag; +static int Tflag; +static int eflag; +static int Eflag; +static int xflag; +static int Xflag; +static int Aflag; +static int mflag; +static int iflag; +static int strip_cr; +static char *labels[3]; +static int nlabels; static void -diffexec(const char *diffprog, char **diffargv, int fd[]) -{ - switch (fork()) { - case 0: - close(fd[0]); - if (dup2(fd[1], STDOUT_FILENO) == -1) - err(2, "child could not duplicate descriptor"); - close(fd[1]); - execvp(diffprog, diffargv); - err(2, "could not execute diff: %s", diffprog); - break; - case -1: - err(2, "could not fork"); - break; - } - close(fd[1]); -} - -static char * -getchange(FILE *b) -{ - char *line; - - while ((line = get_line(b, NULL)) != NULL) { - if (isdigit((unsigned char)line[0])) - return line; - } - return NULL; -} - -static char * -get_line(FILE *b, size_t *n) +usage(void) { - ssize_t len; - static char *buf = NULL; - static size_t bufsize = 0; - - if ((len = getline(&buf, &bufsize, b)) < 0) - return NULL; - - if (strip_cr && len >= 2 && strcmp("\r\n", &(buf[len - 2])) == 0) { - buf[len - 2] = '\n'; - buf[len - 1] = '\0'; - len--; - } - - if (n != NULL) - *n = len; - - return buf; + eprintf("usage: %s [-3aAeEimTxX] [-L label] file1 file2 file3\n", argv0); } static void -merge(int m1, int m2) +convert_hunks(const struct diffhunks *in, struct pair_hunk **out, size_t *outn) { - struct Diff *d1, *d2, *d3; - int j, t1, t2; - int dup = 0; - - d1 = d13; - d2 = d23; - j = 0; - - for (;;) { - t1 = (d1 < d13 + m1); - t2 = (d2 < d23 + m2); - if (!t1 && !t2) - break; - - if (!t2 || (t1 && d1->new.to < d2->new.from)) { - if (eflag == EFLAG_NONE) { - separate("1"); - change(1, &d1->old, 0); - keep(2, &d1->new); - change(3, &d1->new, 0); - } else if (eflag == EFLAG_OVERLAP) { - j = edit(d2, dup, j, DIFF_TYPE1); - } - d1++; - continue; - } - if (!t1 || (t2 && d2->new.to < d1->new.from)) { - if (eflag == EFLAG_NONE) { - separate("2"); - keep(1, &d2->new); - change(3, &d2->new, 0); - change(2, &d2->old, 0); - } else if (Aflag || mflag) { - if (eflag == EFLAG_UNMERGED) - j = edit(d2, dup, j, DIFF_TYPE2); - } - d2++; - continue; - } - if (d1 + 1 < d13 + m1 && d1->new.to >= d1[1].new.from) { - d1[1].old.from = d1->old.from; - d1[1].new.from = d1->new.from; - d1++; - continue; - } - if (d2 + 1 < d23 + m2 && d2->new.to >= d2[1].new.from) { - d2[1].old.from = d2->old.from; - d2[1].new.from = d2->new.from; - d2++; - continue; - } - if (d1->new.from == d2->new.from && d1->new.to == d2->new.to) { - dup = duplicate(&d1->old, &d2->old); - if (eflag == EFLAG_NONE) { - separate(dup ? "3" : ""); - change(1, &d1->old, dup); - change(2, &d2->old, 0); - d3 = d1->old.to > d1->old.from ? d1 : d2; - change(3, &d3->new, 0); - } else { - j = edit(d1, dup, j, DIFF_TYPE3); - } - dup = 0; - d1++; - d2++; - continue; - } - if (d1->new.from < d2->new.from) { - d2->old.from -= d2->new.from - d1->new.from; - d2->new.from = d1->new.from; - } else if (d2->new.from < d1->new.from) { - d1->old.from -= d1->new.from - d2->new.from; - d1->new.from = d2->new.from; - } - if (d1->new.to > d2->new.to) { - d2->old.to += d1->new.to - d2->new.to; - d2->new.to = d1->new.to; - } else if (d2->new.to > d1->new.to) { - d1->old.to += d2->new.to - d1->new.to; - d1->new.to = d2->new.to; - } - } - - if (mflag) - mergescript(j); - else if (Aflag) - Ascript(j); - else if (eflag) - edscript(j); + size_t i; + struct pair_hunk *p; + + p = ecalloc(in->n + 1, sizeof(*p)); + for (i = 0; i < in->n; i++) { + p[i].old.from = in->v[i].old.from; + p[i].old.to = in->v[i].old.to; + p[i].new.from = in->v[i].new.from; + p[i].new.to = in->v[i].new.to; + } + *out = p; + *outn = in->n; } -static void -separate(const char *s) +static int +region_same(const struct difffile *a, struct region *ra, + const struct difffile *b, struct region *rb) { - printf("====%s\n", s); + size_t i; + if (ra->to - ra->from != rb->to - rb->from) + return 0; + for (i = 0; i < ra->to - ra->from; i++) { + if (a->lines[ra->from + i].len != b->lines[rb->from + i].len) + return 0; + if (memcmp(a->lines[ra->from + i].data, + b->lines[rb->from + i].data, + a->lines[ra->from + i].len) != 0) + return 0; + } + return 1; } -static void -change(int i, struct Range *rold, int dup) +static int +merge_hunks(const struct difffile *f1, const struct difffile *f2, + const struct difffile *f3, + const struct pair_hunk *d13, size_t n13, + const struct pair_hunk *d23, size_t n23, + struct three_hunk **out, size_t *outn) { - printf("%d:", i); - last[i] = rold->to; - prange(rold, 0); - if (dup) - return; - i--; - skip(i, rold->from, NULL); - skip(i, rold->to, " "); + struct three_hunk *hs; + size_t i, j, k, cap; + int have1, have2; + size_t a1, a2, b1, b2; + + cap = n13 + n23 + 4; + hs = ecalloc(cap, sizeof(*hs)); + k = 0; + i = j = 0; + + while (i < n13 || j < n23) { + have1 = i < n13; + have2 = j < n23; + a1 = have1 ? d13[i].new.from : 0; + a2 = have1 ? d13[i].new.to : 0; + b1 = have2 ? d23[j].old.from : 0; + b2 = have2 ? d23[j].old.to : 0; + + if (have1 && (!have2 || a2 <= b1)) { + if (k + 1 >= cap) { + cap *= 2; + hs = erealloc(hs, cap * sizeof(*hs)); + } + hs[k].kind = HUNK_TYPE1; + hs[k].r1.from = d13[i].old.from; + hs[k].r1.to = d13[i].old.to; + hs[k].r2.from = d13[i].new.from; + hs[k].r2.to = d13[i].new.to; + hs[k].r3.from = d13[i].new.from; + hs[k].r3.to = d13[i].new.to; + hs[k].dup = 0; + k++; + i++; + continue; + } + if (have2 && (!have1 || b2 < a1)) { + if (k + 1 >= cap) { + cap *= 2; + hs = erealloc(hs, cap * sizeof(*hs)); + } + hs[k].kind = HUNK_TYPE2; + hs[k].r1.from = d23[j].old.from; + hs[k].r1.to = d23[j].old.to; + hs[k].r2.from = d23[j].old.from; + hs[k].r2.to = d23[j].old.to; + hs[k].r3.from = d23[j].new.from; + hs[k].r3.to = d23[j].new.to; + hs[k].dup = 0; + k++; + j++; + continue; + } + { + struct region r2; + size_t extra_pre, extra_post; + + r2.from = a1 < b1 ? a1 : b1; + r2.to = a2 > b2 ? a2 : b2; + extra_pre = (a1 > b1) ? (a1 - b1) : (b1 - a1); + extra_post = (a2 > b2) ? (a2 - b2) : (b2 - a2); + if (k + 1 >= cap) { + cap *= 2; + hs = erealloc(hs, cap * sizeof(*hs)); + } + hs[k].kind = HUNK_TYPE3; + hs[k].r2 = r2; + if (a1 >= b1) { + hs[k].r1.from = d13[i].old.from - extra_pre; + hs[k].r1.to = d13[i].old.to + extra_post; + } else { + hs[k].r1.from = d13[i].old.from; + hs[k].r1.to = d13[i].old.to + (extra_pre + extra_post); + } + if (b1 >= a1) { + hs[k].r3.from = d23[j].new.from - extra_pre; + hs[k].r3.to = d23[j].new.to + extra_post; + } else { + hs[k].r3.from = d23[j].new.from; + hs[k].r3.to = d23[j].new.to + (extra_pre + extra_post); + } + hs[k].dup = region_same(f1, &hs[k].r1, f3, &hs[k].r3); + k++; + i++; + j++; + } + } + *out = hs; + *outn = k; + (void)f1; (void)f2; (void)f3; + return 0; } static void -prange(struct Range *rold, int delete) +print_lines(const struct difffile *f, size_t from, size_t to) { - if (rold->to <= rold->from) - printf("%da\n", rold->from - 1); - else { - printf("%d", rold->from); - if (rold->to > rold->from + 1) - printf(",%d", rold->to - 1); - if (delete) - printf("d\n"); - else - printf("c\n"); - } + size_t i; + for (i = from; i < to; i++) { + fwrite(f->lines[i].data, 1, f->lines[i].len, stdout); + fputc('\n', stdout); + } } static void -keep(int i, struct Range *rnew) +print_range_cmd(FILE *out, size_t from, size_t to, char op) { - int delta; - struct Range trange; - - delta = last[3] - last[i]; - trange.from = rnew->from - delta; - trange.to = rnew->to - delta; - change(i, &trange, 1); + if (to <= from) { + fprintf(out, "%zua\n", from == 0 ? 0 : from); + } else { + fprintf(out, "%zu", from + 1); + if (to - from > 1) + fprintf(out, ",%zu", to); + fprintf(out, "%c\n", op); + } } static int -skip(int i, int from, const char *pr) +format_normal(const struct three_hunk *hs, size_t n, + const struct difffile *f1, const struct difffile *f2, + const struct difffile *f3) { - size_t j, n; - char *line; - - for (n = 0; cline[i] < from - 1; n += j) { - if ((line = get_line(fp[i], &j)) == NULL) - errx(EXIT_FAILURE, "logic error"); - if (pr != NULL) - printf("%s%s", Tflag == 1 ? "\t" : pr, line); - cline[i]++; - } - return (int)n; + size_t i; + for (i = 0; i < n; i++) { + const struct three_hunk *h = &hs[i]; + const char *tag = ""; + if (h->kind == HUNK_TYPE1) tag = "1"; + else if (h->kind == HUNK_TYPE2) tag = "2"; + else if (h->kind == HUNK_TYPE3) tag = h->dup ? "3" : ""; + printf("====%s\n", tag); + if (h->kind == HUNK_TYPE1) { + printf("1:%zu", h->r1.from + 1); + if (h->r1.to - h->r1.from > 1) + printf(",%zu", h->r1.to); + printf("a\n"); + printf("3:%zu", h->r3.from + 1); + if (h->r3.to - h->r3.from > 1) + printf(",%zu", h->r3.to); + printf("a\n"); + print_lines(f1, h->r1.from, h->r1.to); + } else if (h->kind == HUNK_TYPE2) { + printf("2:%zu", h->r2.from + 1); + if (h->r2.to - h->r2.from > 1) + printf(",%zu", h->r2.to); + printf("a\n"); + printf("3:%zu", h->r3.from + 1); + if (h->r3.to - h->r3.from > 1) + printf(",%zu", h->r3.to); + printf("a\n"); + print_lines(f3, h->r3.from, h->r3.to); + } else { + printf("1:%zu", h->r1.from + 1); + if (h->r1.to - h->r1.from > 1) + printf(",%zu", h->r1.to); + printf("c\n"); + printf("2:%zu", h->r2.from + 1); + if (h->r2.to - h->r2.from > 1) + printf(",%zu", h->r2.to); + printf("c\n"); + printf("3:%zu", h->r3.from + 1); + if (h->r3.to - h->r3.from > 1) + printf(",%zu", h->r3.to); + printf("c\n"); + print_lines(f1, h->r1.from, h->r1.to); + print_lines(f3, h->r3.from, h->r3.to); + } + } + (void)f2; + return 0; } static int -duplicate(struct Range *r1, struct Range *r2) +format_ed(const struct three_hunk *hs, size_t n, int overlap_only, + int show_all, const struct difffile *f2, const struct difffile *f3) { - int c, d; - int nchar; - int nline; - - if (r1->to-r1->from != r2->to-r2->from) - return 0; - skip(0, r1->from, NULL); - skip(1, r2->from, NULL); - nchar = 0; - for (nline = 0; nline < r1->to - r1->from; nline++) { - do { - c = getc(fp[0]); - d = getc(fp[1]); - if (c == -1 && d == -1) - break; - if (c == -1 || d == -1) - errx(EXIT_FAILURE, "logic error"); - nchar++; - if (c != d) { - repos(nchar); - return 0; - } - } while (c != '\n'); - } - repos(nchar); - return 1; -} - -static void -repos(int nchar) -{ - int i; - - for (i = 0; i < 2; i++) - (void)fseek(fp[i], (long)-nchar, SEEK_CUR); + size_t i; + for (i = n; i > 0; i--) { + const struct three_hunk *h = &hs[i - 1]; + + if (h->kind == HUNK_TYPE1) { + if (h->r1.to == h->r1.from) { + print_range_cmd(stdout, h->r2.from, h->r2.from, 'a'); + print_lines(f2, h->r2.from, h->r2.from); + printf(".\n"); + } else { + print_range_cmd(stdout, h->r2.from, h->r2.to, 'c'); + print_lines(f2, h->r1.from, h->r1.to); + printf(".\n"); + } + continue; + } + if (h->kind == HUNK_TYPE2) { + print_range_cmd(stdout, h->r2.from, h->r2.to, 'c'); + print_lines(f3, h->r3.from, h->r3.to); + printf(".\n"); + continue; + } + if (h->dup) { + print_range_cmd(stdout, h->r2.from, h->r2.to, 'c'); + print_lines(f2, h->r1.from, h->r1.to); + printf(".\n"); + continue; + } + if (overlap_only) + continue; + if (show_all) { + print_range_cmd(stdout, h->r2.from, h->r2.to, 'c'); + print_lines(f3, h->r3.from, h->r3.to); + printf(".\n"); + } + } + return 0; } +#if FEATURE_DIFF3_MERGE static int -edit(struct Diff *diff, int dup, int j, int difftype) -{ - if (!(eflag == EFLAG_UNMERGED || - (!dup && eflag == EFLAG_OVERLAP) || - (dup && eflag == EFLAG_NOOVERLAP))) { - return j; - } - j++; - overlap[j] = !dup; - if (!dup) - overlapcnt++; - - de[j].type = difftype; - de[j].old.from = diff->old.from; - de[j].old.to = diff->old.to; - de[j].new.from = diff->new.from; - de[j].new.to = diff->new.to; - return j; -} - -static void -printrange(FILE *p, struct Range *r) -{ - char *line = NULL; - size_t len = 0; - int i = 1; - - if (r->from == r->to) - return; - - if (r->from > r->to) - errx(EXIT_FAILURE, "invalid print range"); - - fseek(p, 0L, SEEK_SET); - while (getline(&line, &len, p) > 0) { - if (i >= r->from) - printf("%s", line); - if (++i > r->to - 1) - break; - } - free(line); -} - -static void -edscript(int n) -{ - int delete; - struct Range *new, *old; - - for (; n > 0; n--) { - new = &de[n].new; - old = &de[n].old; - - delete = (new->from == new->to); - if (de[n].type == DIFF_TYPE1) { - if (delete) - printf("%dd\n", new->from - 1); - else if (old->from == new->from && old->to == new->to) { - printf("%dc\n", old->from); - printrange(fp[2], old); - printf(".\n"); - } - continue; - } else { - if (!oflag || !overlap[n]) { - prange(old, delete); - } else { - printf("%da\n", old->to - 1); - printf("%s\n", divider); - } - printrange(fp[2], new); - if (!oflag || !overlap[n]) { - if (!delete) - printf(".\n"); - } else { - printf("%s %s\n.\n", newmark, f3mark); - printf("%da\n%s %s\n.\n", old->from - 1, oldmark, f1mark); - } - } - } - if (iflag) - printf("w\nq\n"); - - exit(eflag == EFLAG_NONE ? overlapcnt : 0); -} - -static void -Ascript(int n) -{ - int startmark; - int deletenew; - int deleteold; - struct Range *new, *old; - - for (; n > 0; n--) { - new = &de[n].new; - old = &de[n].old; - deletenew = (new->from == new->to); - deleteold = (old->from == old->to); - - if (de[n].type == DIFF_TYPE2) { - if (!oflag || !overlap[n]) { - prange(old, deletenew); - printrange(fp[2], new); - } else { - startmark = new->to - 1; - printf("%da\n", startmark); - printf("%s %s\n", newmark, f3mark); - printf(".\n"); - printf("%da\n", startmark - (new->to - new->from)); - printf("%s %s\n", oldmark, f2mark); - if (!deleteold) - printrange(fp[1], old); - printf("%s\n.\n", divider); - } - } else if (de[n].type == DIFF_TYPE3) { - startmark = old->to - 1; - if (!oflag || !overlap[n]) { - prange(old, deletenew); - printrange(fp[2], new); - } else { - printf("%da\n", startmark); - printf("%s %s\n", orgmark, f2mark); - if (deleteold) { - struct Range r; - r.from = old->from-1; - r.to = new->to; - printrange(fp[1], &r); - } else - printrange(fp[1], old); - printf("%s\n", divider); - printrange(fp[2], new); - } - if (!oflag || !overlap[n]) { - if (!deletenew) - printf(".\n"); - } else { - printf("%s %s\n.\n", newmark, f3mark); - printf("%da\n%s %s\n.\n", startmark - (old->to - old->from), oldmark, f1mark); - } - } - } - if (iflag) - printf("w\nq\n"); - - exit(overlapcnt > 0); -} - -static void -mergescript(int i) -{ - struct Range r, *new, *old; - int n; - int delete = 0; - - r.from = 1; - r.to = 1; - - for (n = 1; n <= i; n++) { - new = &de[n].new; - old = &de[n].old; - - delete = (new->from == new->to); - if (de[n].type == DIFF_TYPE1 && delete) - r.to = new->from - 1; - else if (de[n].type == DIFF_TYPE3 && (old->from == old->to)) { - r.from = old->from - 1; - r.to = new->from; - } else - r.to = old->from; - - printrange(fp[0], &r); - switch (de[n].type) { - case DIFF_TYPE1: - if (!delete) - printrange(fp[2], new); - break; - case DIFF_TYPE2: - printf("%s %s\n", oldmark, f2mark); - printrange(fp[1], old); - printf("%s\n", divider); - printrange(fp[2], new); - printf("%s %s\n", newmark, f3mark); - break; - case DIFF_TYPE3: - if (!oflag || !overlap[n]) { - printrange(fp[2], new); - } else { - printf("%s %s\n", oldmark, f1mark); - printrange(fp[0], old); - if (eflag != EFLAG_OVERLAP) { - printf("%s %s\n", orgmark, f2mark); - if (old->from == old->to) { - struct Range or; - or.from = old->from - 1; - or.to = new->to; - printrange(fp[1], &or); - } else { - printrange(fp[1], old); - } - } - printf("%s\n", divider); - printrange(fp[2], new); - printf("%s %s\n", newmark, f3mark); - } - break; - default: - printf("Error: Unhandled diff type - exiting\n"); - exit(EXIT_FAILURE); - } - - if (old->from == old->to) - r.from = new->to; - else - r.from = old->to; - } - - new = &de[n-1].new; - old = &de[n-1].old; - - if (old->from == new->from && old->to == new->to) - r.from--; - else if (new->from == new->to) - r.from = old->from; - - r.to = INT_MAX; - printrange(fp[2], &r); - exit(overlapcnt > 0); -} - -static void -increase(void) -{ - struct Diff *p; - char *q; - size_t newsz, incr; - - newsz = szchanges == 0 ? 64 : 2 * szchanges; - incr = newsz - szchanges; - - p = ereallocarray(d13, newsz, sizeof(*p)); - memset(p + szchanges, 0, incr * sizeof(*p)); - d13 = p; - - p = ereallocarray(d23, newsz, sizeof(*p)); - memset(p + szchanges, 0, incr * sizeof(*p)); - d23 = p; - - p = ereallocarray(de, newsz, sizeof(*p)); - memset(p + szchanges, 0, incr * sizeof(*p)); - de = p; - - q = ereallocarray(overlap, newsz, 1); - memset(q + szchanges, 0, incr * 1); - overlap = q; - szchanges = newsz; -} - -static void -handle_sig(int signo) -{ - write(sigpipe[1], &signo, sizeof(signo)); -} - -static void -xasprintf(char **strp, const char *fmt, ...) +format_merge(const struct three_hunk *hs, size_t n, + const struct difffile *f1, const struct difffile *f2, + const struct difffile *f3) { - va_list ap; - int r; - - va_start(ap, fmt); - r = vasprintf(strp, fmt, ap); - va_end(ap); - if (r == -1) - err(2, "asprintf"); + size_t i, j; + size_t cursor; + const char *l1, *l2, *l3; + + l1 = nlabels >= 1 ? labels[0] : "file1"; + l2 = nlabels >= 2 ? labels[1] : "file2"; + l3 = nlabels >= 3 ? labels[2] : "file3"; + cursor = 0; + for (i = 0; i < n; i++) { + const struct three_hunk *h = &hs[i]; + for (j = cursor; j < h->r2.from; j++) { + fwrite(f2->lines[j].data, 1, f2->lines[j].len, stdout); + fputc('\n', stdout); + } + cursor = h->r2.to; + if (h->kind == HUNK_TYPE1) { + print_lines(f1, h->r1.from, h->r1.to); + } else if (h->kind == HUNK_TYPE2) { + print_lines(f3, h->r3.from, h->r3.to); + } else if (h->dup) { + print_lines(f1, h->r1.from, h->r1.to); + } else { + printf("<<<<<<< %s\n", l1); + print_lines(f1, h->r1.from, h->r1.to); + printf("||||||| %s\n", l2); + print_lines(f2, h->r2.from, h->r2.to); + printf("=======\n"); + print_lines(f3, h->r3.from, h->r3.to); + printf(">>>>>>> %s\n", l3); + } + } + for (j = cursor; j < f2->nlines; j++) { + fwrite(f2->lines[j].data, 1, f2->lines[j].len, stdout); + fputc('\n', stdout); + } + return 0; } +#endif -// ?man diff3: 3-way differential file comparison +// ?man diff3: three-way file comparison // ?man arguments: file1 file2 file3 -// ?man synopsis: [-3aAeEiL:mTxX] [--diff-program program] [--strip-trailing-cr] [-L label1] [-L label2] [-L label3] file1 file2 file3 +// ?man compare three files line by line and show the differences int -main(int argc, char **argv) +main(int argc, char *argv[]) { - int ch, nblabels, status, m, n, npe, nleft; - char *labels[] = { NULL, NULL, NULL }; - const char *diffprog = DIFF_PATH; - char *file1, *file2, *file3; - char *diffargv[7]; - int diffargc = 0; - int fd13[2], fd23[2], signo; - pid_t wpid; - struct pollfd pfd; - - nblabels = 0; - eflag = EFLAG_NONE; - oflag = 0; - diffargv[diffargc++] = (char *)diffprog; - while ((ch = getopt_long(argc, argv, OPTIONS, longopts, NULL)) != -1) { - // ?man -3: output changes specific only to file3 - switch (ch) { - case '3': - eflag = EFLAG_NOOVERLAP; - break; - // ?man -a: treat files as text - case 'a': - diffargv[diffargc++] = "-a"; - break; - // ?man -A: output all changes bracketing conflicts - case 'A': - Aflag = 1; - break; - // ?man -e: output ed script - case 'e': - eflag = EFLAG_UNMERGED; - break; - // ?man -E: show overlapping changes - case 'E': - eflag = EFLAG_OVERLAP; - oflag = 1; - break; - // ?man -i: append w and q ed commands - case 'i': - iflag = 1; - break; - // ?man -L:label: define label - case 'L': - oflag = 1; - if (nblabels >= 3) - errx(2, "too many file label options"); - labels[nblabels++] = optarg; - break; - // ?man -m: merge output - case 'm': - Aflag = 1; - oflag = 1; - mflag = 1; - break; - // ?man -T: use tab prefix in normal listing - case 'T': - Tflag = 1; - break; - // ?man -x: output script with changes specific to all three - case 'x': - eflag = EFLAG_OVERLAP; - break; - // ?man -X: show overlapping changes - case 'X': - oflag = 1; - eflag = EFLAG_OVERLAP; - break; - case DIFFPROG_OPT: - diffprog = optarg; - break; - case STRIPCR_OPT: - strip_cr = 1; - diffargv[diffargc++] = "--strip-trailing-cr"; - break; - case HELP_OPT: - usage(); - exit(0); - case VERSION_OPT: - printf("%s\n", diff3_version); - exit(0); - } - } - argc -= optind; - argv += optind; - - if (Aflag) { - if (eflag == EFLAG_NONE) - eflag = EFLAG_UNMERGED; - oflag = 1; - } - - if (argc != 3) { - usage(); - exit(2); - } - - file1 = argv[0]; - file2 = argv[1]; - file3 = argv[2]; - - if (oflag) { - xasprintf(&f1mark, "%s", labels[0] != NULL ? labels[0] : file1); - xasprintf(&f2mark, "%s", labels[1] != NULL ? labels[1] : file2); - xasprintf(&f3mark, "%s", labels[2] != NULL ? labels[2] : file3); - } - fp[0] = fopen(file1, "r"); - if (fp[0] == NULL) - err(2, "Can't open %s", file1); - - fp[1] = fopen(file2, "r"); - if (fp[1] == NULL) - err(2, "Can't open %s", file2); - - fp[2] = fopen(file3, "r"); - if (fp[2] == NULL) - err(2, "Can't open %s", file3); - - if (pipe(fd13)) - err(2, "pipe"); - if (pipe(fd23)) - err(2, "pipe"); - if (pipe(sigpipe)) - err(2, "pipe"); - if (fcntl(sigpipe[0], F_SETFD, FD_CLOEXEC)) - err(2, "fcntl"); - if (fcntl(sigpipe[1], F_SETFD, FD_CLOEXEC)) - err(2, "fcntl"); - - pfd.fd = sigpipe[0]; - pfd.events = POLLIN; - pfd.revents = 0; - - if (signal(SIGCHLD, handle_sig) == SIG_ERR) - err(2, "signal"); - - diffargv[diffargc] = file1; - diffargv[diffargc + 1] = file3; - diffargv[diffargc + 2] = NULL; - - nleft = 0; - diffexec(diffprog, diffargv, fd13); - nleft++; - - diffargv[diffargc] = file2; - diffexec(diffprog, diffargv, fd23); - nleft++; - - increase(); - m = readin(fd13[0], &d13); - n = readin(fd23[0], &d23); - - while (nleft > 0) { - npe = poll(&pfd, 1, -1); - if (npe == -1) { - if (errno == EINTR) - continue; - err(2, "poll"); - } - if (pfd.revents != POLLIN) - continue; - if (read(pfd.fd, &signo, sizeof(signo)) < 0) - err(2, "read"); - while ((wpid = waitpid(-1, &status, WNOHANG)) > 0) { - if (WIFEXITED(status) && WEXITSTATUS(status) >= 2) - errx(2, "diff exited abnormally"); - else if (WIFSIGNALED(status)) - errx(2, "diff killed by signal %d", WTERMSIG(status)); - nleft--; - } - } - merge(m, n); - - return EXIT_SUCCESS; + struct difffile f1, f2, f3; + struct pair_hunk *d13, *d23; + size_t n13, n23; + struct three_hunk *hs; + size_t nhunks; + struct diffhunks raw13, raw23; + struct diffopts opts; + int ret, conflicts; + + ARGBEGIN { + case '3': + // ?man -3: like -A but skip overlapping changes + Aflag = 1; + break; + case 'a': + // ?man -a: treat all files as text + aflag = 1; + break; + case 'A': + // ?man -A: emit ed script with all changes including overlaps + Aflag = 1; + break; + case 'e': + // ?man -e: emit ed script to apply non-overlapping changes + eflag = 1; + break; + case 'E': + // ?man -E: like -e but include overlap markers + Eflag = 1; + break; +#if FEATURE_DIFF3_MERGE + case 'i': + // ?man -i: ignore case when comparing lines + iflag = 1; + break; + case 'L': + // ?man -L:label: use label in place of file name in merge output + if (nlabels >= 3) + usage(); + labels[nlabels++] = EARGF(usage()); + break; + case 'm': + // ?man -m: emit merged output with conflict markers + mflag = 1; + break; + case 'T': + // ?man -T: prefix output lines with a tab + Tflag = 1; + break; +#endif + case 'x': + // ?man -x: emit ed script for overlapping changes only + xflag = 1; + break; + case 'X': + // ?man -X: emit ed script for overlapping changes with markers + Xflag = 1; + break; + default: + usage(); + } ARGEND + + if (argc != 3) + usage(); + + if (diff_load(&f1, argv[0]) < 0) + return 2; + if (diff_load(&f2, argv[1]) < 0) { + diff_free(&f1); + return 2; + } + if (diff_load(&f3, argv[2]) < 0) { + diff_free(&f1); + diff_free(&f2); + return 2; + } + + memset(&opts, 0, sizeof(opts)); + opts.format = DIFF_NORMAL; + opts.ignore_case = iflag; + opts.strip_cr = strip_cr; + opts.context = 3; + + if (diff_compute(&raw13, &f1, &f2, &opts) < 0 || + diff_compute(&raw23, &f2, &f3, &opts) < 0) { + diff_free(&f1); diff_free(&f2); diff_free(&f3); + return 2; + } + convert_hunks(&raw13, &d13, &n13); + convert_hunks(&raw23, &d23, &n23); + + if (merge_hunks(&f1, &f2, &f3, d13, n13, d23, n23, &hs, &nhunks) < 0) { + diff_hunks_free(&raw13); + diff_hunks_free(&raw23); + free(d13); free(d23); + diff_free(&f1); diff_free(&f2); diff_free(&f3); + return 2; + } + + ret = 0; + conflicts = 0; + if (nhunks == 0) { + ret = 0; + } else { +#if FEATURE_DIFF3_MERGE + if (mflag) { + size_t i; + for (i = 0; i < nhunks; i++) + if (hs[i].kind == HUNK_TYPE3 && !hs[i].dup) + conflicts++; + format_merge(hs, nhunks, &f1, &f2, &f3); + ret = conflicts ? 1 : 0; + } else +#endif + if (eflag || Eflag) { + format_ed(hs, nhunks, Eflag && !eflag, 0, &f2, &f3); + ret = 1; + } else if (xflag) { + format_ed(hs, nhunks, 1, 0, &f2, &f3); + ret = 1; + } else if (Xflag) { + format_ed(hs, nhunks, 0, 1, &f2, &f3); + ret = 1; + } else if (Aflag) { + format_ed(hs, nhunks, 0, 1, &f2, &f3); + ret = 1; + } else { + format_normal(hs, nhunks, &f1, &f2, &f3); + ret = 1; + } + } + + if (fshut(stdout, "<stdout>")) + ret = 2; + + diff_hunks_free(&raw13); + diff_hunks_free(&raw23); + free(d13); free(d23); + free(hs); + diff_free(&f1); diff_free(&f2); diff_free(&f3); + return ret; } diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c @@ -15,6 +15,7 @@ #include <stdlib.h> #include <string.h> +#include "wexec.h" #include "util.h" #define REGEXSIZE 100 @@ -837,13 +838,13 @@ dowrite(const char *fname, int trunc) char *mode; if (fp) { - sh ? pclose(fp) : fclose(fp); + sh ? wpclose(fp) : fclose(fp); fp = NULL; } if (fname[0] == '!') { sh = 1; - if((fp = popen(expandcmd(), "w")) == NULL) + if((fp = wpopen(expandcmd(), NULL, "w")) == NULL) error("bad exec"); } else { sh = 0; @@ -865,7 +866,7 @@ dowrite(const char *fname, int trunc) aux = fp; fp = NULL; - r = sh ? pclose(aux) : fclose(aux); + r = sh ? wpclose(aux) : fclose(aux); if (r) error("input/output error"); strcpy(savfname, fname); @@ -890,13 +891,13 @@ doread(const char *fname) static FILE *fp; if (fp) { - sh ? pclose(fp) : fclose(fp); + sh ? wpclose(fp) : fclose(fp); fp = NULL; } if(fname[0] == '!') { sh = 1; - if((fp = popen(expandcmd(), "r")) == NULL) + if((fp = wpopen(expandcmd(), NULL, "r")) == NULL) error("bad exec"); } else if ((fp = fopen(fname, "r")) == NULL) { error("cannot open input file"); @@ -921,7 +922,7 @@ doread(const char *fname) aux = fp; fp = NULL; - r = sh ? pclose(aux) : fclose(aux); + r = sh ? wpclose(aux) : fclose(aux); if (r) error("input/output error"); } @@ -1153,7 +1154,7 @@ copy(int where) static void execsh(void) { - system(expandcmd()); + wsystem(expandcmd()); if (optdiag) puts("!"); } diff --git a/cmd/posix/env.c b/cmd/posix/env.c @@ -7,6 +7,7 @@ #include <string.h> #include <unistd.h> +#include "wexec.h" #include "util.h" extern char **environ; @@ -43,9 +44,9 @@ main(int argc, char *argv[]) putenv(*argv); if (*argv) { - execvp(*argv, argv); + wexecvp_self(*argv, argv); savederrno = errno; - weprintf("execvp %s:", *argv); + weprintf("wexecvp %s:", *argv); _exit(126 + (savederrno == ENOENT)); } diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -2,6 +2,7 @@ #include "config.h" +#include "wexec.h" #include "util.h" #include <dirent.h> @@ -344,7 +345,7 @@ spawn(char *argv[]) eprintf("fork:"); break; case 0: - execvp(*argv, argv); + wexecvp_self(*argv, argv); weprintf("exec %s failed:", *argv); _exit(1); } diff --git a/cmd/posix/make/main.c b/cmd/posix/make/main.c @@ -31,288 +31,268 @@ volatile sig_atomic_t stop; void debug(char *fmt, ...) { - va_list va; + va_list va; - if (!dflag) - return; + if (!dflag) + return; - va_start(va, fmt); - vfprintf(stdout, fmt, va); - fputc('\n', stdout); - va_end(va); + va_start(va, fmt); + vfprintf(stdout, fmt, va); + fputc('\n', stdout); + va_end(va); } int hash(char *name) { - int c; - unsigned h = 5381; + int c; + unsigned h = 5381; - while ((c = *name++)) - h = h*33 ^ c; + while ((c = *name++)) + h = h*33 ^ c; - return h; -} - -void * -emalloc(size_t siz) -{ - void *p; - - if ((p = malloc(siz)) == NULL) { - perror("make"); - exit(EXIT_FAILURE); - } - - return p; -} - -void * -erealloc(void *p, size_t siz) -{ - if ((p = realloc(p, siz)) == NULL) { - perror("make"); - exit(EXIT_FAILURE); - } - - return p; -} - -char * -estrdup(char *s) -{ - size_t len; - - len = strlen(s) + 1; - return memcpy(emalloc(len), s, len); + return h; } void sighandler(int signo) { - killchild(); - stop = signo; + killchild(); + stop = signo; } static void usage(void) { - fputs("usage: make [-eiknprSstd] [-f file] [-j jobs] " - "[macro=value ...] [target ...]\n", - stderr); - exit(EXIT_FAILURE); + fputs("usage: make [-eiknprSstd] [-f file] [-j jobs] " + "[macro=value ...] [target ...]\n", + stderr); + exit(EXIT_FAILURE); } static char * getarg(char **args, char ***argv) { - char *s; + char *s; - if ((*args)[1]) { - s = (*args) + 1; - *args += strlen(*args) - 1; - return s; - } + if ((*args)[1]) { + s = (*args) + 1; + *args += strlen(*args) - 1; + return s; + } - if (!argv) - usage(); + if (!argv) + usage(); - if ((*argv)[1] == NULL) - usage(); - (*argv)++; + if ((*argv)[1] == NULL) + usage(); + (*argv)++; - return **argv; + return **argv; } static void appendmakeflags(char *text) { - int n; - char *s, *t, *fmt; + int n; + char *s, *t, *fmt; - s = getmacro("MAKEFLAGS"); - fmt = *s ? "%s %s" : "%s%s"; - n = snprintf(NULL, 0, fmt, s, text); + s = getmacro("MAKEFLAGS"); + fmt = *s ? "%s %s" : "%s%s"; + n = snprintf(NULL, 0, fmt, s, text); - t = emalloc(n+1); - snprintf(t, n+1, fmt, s, text); - setmacro("MAKEFLAGS", t, MAKEFLAGS, EXPORT); + t = emalloc(n+1); + snprintf(t, n+1, fmt, s, text); + setmacro("MAKEFLAGS", t, MAKEFLAGS, EXPORT); - free(t); + free(t); } static int hasargs(int c) { - return c == 'f' || c == 'j'; + return c == 'f' || c == 'j'; } static void parseflag(int flag, char **args, char ***argv) { - if (hasargs(flag)) - getarg(args, argv); - - switch (flag) { - case 'j': - case 'f': - break; - case 'e': - eflag = 1; - appendmakeflags("-e"); - break; - case 'i': - iflag = 1; - appendmakeflags("-i"); - break; - case 'k': - kflag = 1; - appendmakeflags("-k"); - break; - case 'n': - nflag = 1; - appendmakeflags("-n"); - break; - case 'p': - pflag = 1; - break; - case 'q': - qflag = 1; - appendmakeflags("-q"); - break; - case 'r': - addtarget(".SUFFIXES", 0); - appendmakeflags("-r"); - break; - case 'S': - kflag = 0; - appendmakeflags("-S"); - break; - case 's': - sflag = 1; - appendmakeflags("-s"); - break; - case 't': - tflag = 1; - appendmakeflags("-t"); - break; - case 'd': - dflag = 1; - appendmakeflags("-d"); - break; - default: - usage(); - } + if (hasargs(flag)) + getarg(args, argv); + + switch (flag) { + case 'j': + /* ?man -j:jobs: number of parallel jobs (accepted, runs serially) */ + case 'f': + /* ?man -f:file: read rules from file instead of makefile or Makefile */ + break; + case 'e': + /* ?man -e: environment variables override makefile assignments */ + eflag = 1; + appendmakeflags("-e"); + break; + case 'i': + /* ?man -i: ignore errors from executed commands */ + iflag = 1; + appendmakeflags("-i"); + break; + case 'k': + /* ?man -k: continue building other targets after an error */ + kflag = 1; + appendmakeflags("-k"); + break; + case 'n': + /* ?man -n: print commands without executing them */ + nflag = 1; + appendmakeflags("-n"); + break; + case 'p': + /* ?man -p: print the rule and macro database then exit */ + pflag = 1; + break; + case 'q': + /* ?man -q: question mode, return zero if up to date, one otherwise */ + qflag = 1; + appendmakeflags("-q"); + break; + case 'r': + /* ?man -r: clear the built-in suffix rules and variables */ + addtarget(".SUFFIXES", 0); + appendmakeflags("-r"); + break; + case 'S': + /* ?man -S: cancel a previous -k, stop on first error */ + kflag = 0; + appendmakeflags("-S"); + break; + case 's': + /* ?man -s: silent, do not echo commands before running them */ + sflag = 1; + appendmakeflags("-s"); + break; + case 't': + /* ?man -t: touch targets instead of rebuilding them */ + tflag = 1; + appendmakeflags("-t"); + break; + case 'd': + /* ?man -d: enable debug output */ + dflag = 1; + appendmakeflags("-d"); + break; + default: + usage(); + } } static int assign(char *s, int where, int export) { - int pos; - char *t; + int pos; + char *t; - if ((t = strchr(s, '=')) == NULL) - return 0; + if ((t = strchr(s, '=')) == NULL) + return 0; - pos = t - s; + pos = t - s; - appendmakeflags(s); - t = estrdup(s); - t[pos] = '\0'; + appendmakeflags(s); + t = estrdup(s); + t[pos] = '\0'; - setmacro(t, t+pos+1, where, export); - free(t); - return 1; + setmacro(t, t+pos+1, where, export); + free(t); + return 1; } static void parseargv(char **argv, char ***targets, int where, int export) { - char *s; - char *hm = NULL; - - for ( ; *argv; ++argv) { - s = *argv; - if (hm == NULL && strcmp(s, "--") == 0) { - hm = *argv; - } else if (hm && s[0] == '-') { - break; - } else if (s[0] != '-') { - if (!assign(s, where, export)) - break; - continue; - } - while (hm == NULL && *++s) - parseflag(*s, &s, &argv); - } - - if (targets) - *targets = argv; + char *s; + char *hm = NULL; + + for ( ; *argv; ++argv) { + s = *argv; + if (hm == NULL && strcmp(s, "--") == 0) { + hm = *argv; + } else if (hm && s[0] == '-') { + break; + } else if (s[0] != '-') { + if (!assign(s, where, export)) + break; + continue; + } + while (hm == NULL && *++s) + parseflag(*s, &s, &argv); + } + + if (targets) + *targets = argv; } static void parsemakeflags(void) { - int n; - char *s, *flags, **arr; - - if ((flags = getenv("MAKEFLAGS")) == NULL) - return; - - setmacro("MAKEFLAGS", "", MAKEFLAGS, EXPORT); - - while (*flags == ' ' || *flags == '\t') - flags++; - - if (flags[0] != '-' && !strchr(flags, '=')) { - while (*flags) { - parseflag(*flags, &flags, NULL); - flags++; - } - } else { - n = 0; - arr = NULL; - for (s = strtok(flags, " \t"); s; s = strtok(NULL, " \t")) { - n++; - arr = erealloc(arr, sizeof(char *) * (n+1)); - arr[n-1] = s; - arr[n] = NULL; - } - - if (arr) - parseargv(arr, NULL, MAKEFLAGS, NOEXPORT); - free(arr); - } + int n; + char *s, *flags, **arr; + + if ((flags = getenv("MAKEFLAGS")) == NULL) + return; + + setmacro("MAKEFLAGS", "", MAKEFLAGS, EXPORT); + + while (*flags == ' ' || *flags == '\t') + flags++; + + if (flags[0] != '-' && !strchr(flags, '=')) { + while (*flags) { + parseflag(*flags, &flags, NULL); + flags++; + } + } else { + n = 0; + arr = NULL; + for (s = strtok(flags, " \t"); s; s = strtok(NULL, " \t")) { + n++; + arr = erealloc(arr, sizeof(char *) * (n+1)); + arr[n-1] = s; + arr[n] = NULL; + } + + if (arr) + parseargv(arr, NULL, MAKEFLAGS, NOEXPORT); + free(arr); + } } static void parsemakefiles(char **argv) { - char *s, *arg; - int c, hasmake; - - hasmake = 0; - for ( ; *argv && **argv == '-'; ++argv) { - for (s = *argv; (c = *s); ++s) { - if (hasargs(c)) - arg = getarg(&s, &argv); - - if (c == 'f') { - if (strcmp(arg, "-") == 0) - arg = NULL; - parse(arg); - hasmake = 1; - } - } - } - - if (hasmake) - return; - - if (parse("makefile")) - return; - if (parse("Makefile")) - return; + char *s, *arg; + int c, hasmake; + + hasmake = 0; + for ( ; *argv && **argv == '-'; ++argv) { + for (s = *argv; (c = *s); ++s) { + if (hasargs(c)) + arg = getarg(&s, &argv); + + if (c == 'f') { + if (strcmp(arg, "-") == 0) + arg = NULL; + parse(arg); + hasmake = 1; + } + } + } + + if (hasmake) + return; + + if (parse("makefile")) + return; + if (parse("Makefile")) + return; } /* @@ -323,57 +303,62 @@ parsemakefiles(char **argv) static void enadebug(char *argv[]) { - int c; - char *p; - - for ( ; *argv && **argv == '-'; ++argv) { - p = *argv; - for (++p; (c = *p); ++p) { - if (hasargs(c)) - getarg(&p, &argv); - if (c == 'd') - dflag = 1; - } - } + int c; + char *p; + + for ( ; *argv && **argv == '-'; ++argv) { + p = *argv; + for (++p; (c = *p); ++p) { + if (hasargs(c)) + getarg(&p, &argv); + if (c == 'd') + dflag = 1; + } + } } +// ?man make: maintain program dependencies +// ?man arguments: [name=value ...] [target ...] +// ?man update files based on dependency rules in a makefile. +// ?man if no -f is given, make tries makefile then Makefile. +// ?man if no target is given the first non-dot target in the makefile is built. int main(int argc, char *argv[]) { - char *arg0, **targets; + char *arg0, **targets; - (void)argc; + (void)argc; - signal(SIGINT, sighandler); - signal(SIGHUP, sighandler); - signal(SIGTERM, sighandler); - signal(SIGQUIT, sighandler); + signal(SIGINT, sighandler); + signal(SIGHUP, sighandler); + signal(SIGTERM, sighandler); + signal(SIGQUIT, sighandler); - targets = NULL; - arg0 = *argv++; + targets = NULL; + arg0 = *argv++; - enadebug(argv); - inject(defaults); - setmacro("MAKE", arg0, MAKEFILE, NOEXPORT); + enadebug(argv); + inject(defaults); + setmacro("MAKE", arg0, MAKEFILE, NOEXPORT); - parsemakeflags(); - parseargv(argv, &targets, CMDLINE, EXPORT); - parsemakefiles(argv); + parsemakeflags(); + parseargv(argv, &targets, CMDLINE, EXPORT); + parsemakefiles(argv); - if (pflag) { - dumpmacros(); - dumprules(); - exit(EXIT_SUCCESS); - } + if (pflag) { + dumpmacros(); + dumprules(); + exit(EXIT_SUCCESS); + } - if (!*targets) { - build(NULL); - } else { - while (*targets) - build(*targets++); - } + if (!*targets) { + build(NULL); + } else { + while (*targets) + build(*targets++); + } - exit(exitstatus); + exit(exitstatus); - return 0; + return 0; } diff --git a/cmd/posix/make/make.h b/cmd/posix/make/make.h @@ -1,52 +1,51 @@ #include <stddef.h> #include <time.h> +#include "util.h" +#include "wexec.h" + typedef struct target Target; enum { - NOEXPORT, - EXPORT, + NOEXPORT, + EXPORT, }; enum { - UNDEF, - ENVIRON, - CMDLINE, - INTERNAL, - MAKEFILE, - MAKEFLAGS, + UNDEF, + ENVIRON, + CMDLINE, + INTERNAL, + MAKEFILE, + MAKEFLAGS, }; struct loc { - char *fname; - int lineno; + char *fname; + int lineno; }; struct action { - char *line; - struct loc loc; + char *line; + struct loc loc; }; struct target { - char *name; - char *target; - char *req; - time_t stamp; - int defined; + char *name; + char *target; + char *req; + time_t stamp; + int defined; - int ndeps; - struct target **deps; + int ndeps; + struct target **deps; - int nactions; - struct action *actions; + int nactions; + struct action *actions; - struct target *next; + struct target *next; }; -void *emalloc(size_t); -void *erealloc(void *, size_t); -char *estrdup(char *); - void dumprules(void); void dumpmacros(void); @@ -57,7 +56,7 @@ int build(char *); int hash(char *); int parse(char *); void debug(char *, ...); -void error(char *, ...); +void error(char *, ...) __attribute__((noreturn)); void warning(char *, ...); void adddep(char *, char *); void addrule(char *, struct action *, int); diff --git a/cmd/posix/make/parser.c b/cmd/posix/make/parser.c @@ -17,37 +17,37 @@ typedef struct macro Macro; enum inputype { - FTFILE, - FTEXPAN, + FTFILE, + FTEXPAN, }; enum { - STBEGIN, - STINTERNAL, - STREPLACE, - STTO, - STEND, + STBEGIN, + STINTERNAL, + STREPLACE, + STTO, + STEND, }; struct input { - int siz; - int type; + int siz; + int type; - FILE *fp; - struct loc loc; + FILE *fp; + struct loc loc; - int pos; - char *buf; + int pos; + char *buf; - struct input *prev; + struct input *prev; }; struct macro { - char *name; - char *value; - int where; + char *name; + char *value; + int where; - struct macro *next; + struct macro *next; }; static struct input *input; @@ -58,352 +58,617 @@ static Macro *htab[TABSIZ]; void dumpmacros(void) { - Macro **pp, *p; + Macro **pp, *p; - for (pp = htab; pp < &htab[TABSIZ]; ++pp) { - for (p = *pp; p; p = p->next) - printf("%s = %s\n", p->name, getmacro(p->name)); - } + for (pp = htab; pp < &htab[TABSIZ]; ++pp) { + for (p = *pp; p; p = p->next) + printf("%s = %s\n", p->name, getmacro(p->name)); + } } static Macro * lookup(char *name) { - Macro *mp; - int h = hash(name) & (TABSIZ-1); + Macro *mp; + int h = hash(name) & (TABSIZ-1); - for (mp = htab[h]; mp && strcmp(mp->name, name); mp = mp->next) - ; + for (mp = htab[h]; mp && strcmp(mp->name, name); mp = mp->next) + ; - if (mp) - return mp; + if (mp) + return mp; - mp = emalloc(sizeof(*mp)); - mp->name = estrdup(name); - mp->value = estrdup(""); - mp->next = htab[h]; - mp->where = UNDEF; - htab[h] = mp; + mp = emalloc(sizeof(*mp)); + mp->name = estrdup(name); + mp->value = estrdup(""); + mp->next = htab[h]; + mp->where = UNDEF; + htab[h] = mp; - return mp; + return mp; } static char * macroinfo(char *name, int *pwhere, Macro **mpp) { - char *s, *t; - int hide, where; - Macro *mp = lookup(name); - - hide = 0; - if (!strcmp(name, "SHELL") || !strcmp(name, "MAKEFLAGS")) - hide = 1; - - s = mp->value; - where = mp->where; - - if (!hide && (where == UNDEF || where == INTERNAL || eflag)) { - t = getenv(name); - if (t) { - where = ENVIRON; - s = t; - } - } - - if (pwhere) - *pwhere = where; - if (mpp) - *mpp = mp; - - return s; + char *s, *t; + int hide, where; + Macro *mp = lookup(name); + + hide = 0; + if (!strcmp(name, "SHELL") || !strcmp(name, "MAKEFLAGS")) + hide = 1; + + s = mp->value; + where = mp->where; + + if (!hide && (where == UNDEF || where == INTERNAL || eflag)) { + t = getenv(name); + if (t) { + where = ENVIRON; + s = t; + } + } + + if (pwhere) + *pwhere = where; + if (mpp) + *mpp = mp; + + return s; } char * getmacro(char *name) { - return macroinfo(name, NULL, NULL); + return macroinfo(name, NULL, NULL); } void setmacro(char *name, char *val, int where, int export) { - int owhere, set; - char *s; - Macro *mp; - - assert(where != ENVIRON); - - s = macroinfo(name, &owhere, &mp); - - /* - * Default values are defined before anything else, and marked - * as INTERNAL because they are injected as parseable text, and - * MAKEFILE and INTERNAL variables are always overriden. ENVIRON - * macros are generated in macroinfo() and this is why this function - * should not receive a where == ENVIRON ever. - */ - switch (owhere) { - case UNDEF: - case INTERNAL: - case MAKEFILE: - set = 1; - break; - case ENVIRON: - set = (where == MAKEFLAGS || where == CMDLINE); - set |= (where == MAKEFILE && !eflag); - break; - case MAKEFLAGS: - set = (where == CMDLINE || where == MAKEFLAGS); - break; - case CMDLINE: - set = (where == CMDLINE); - break; - default: - abort(); - } - - if (!set) { - debug("hidding override of %s from '%s' to '%s'", name, s, val); - } else { - debug("override %s from '%s' to '%s'", name, s, val); - free(mp->value); - mp->value = estrdup(val); - mp->where = where; - - if (export && strcmp(name, "SHELL") != 0) { - debug("exporting macro %s", name); - exportvar(name, val); - } - } + int owhere, set; + char *s; + Macro *mp; + + assert(where != ENVIRON); + + s = macroinfo(name, &owhere, &mp); + + /* + * Default values are defined before anything else, and marked + * as INTERNAL because they are injected as parseable text, and + * MAKEFILE and INTERNAL variables are always overriden. ENVIRON + * macros are generated in macroinfo() and this is why this function + * should not receive a where == ENVIRON ever. + */ + switch (owhere) { + case UNDEF: + case INTERNAL: + case MAKEFILE: + set = 1; + break; + case ENVIRON: + set = (where == MAKEFLAGS || where == CMDLINE); + set |= (where == MAKEFILE && !eflag); + break; + case MAKEFLAGS: + set = (where == CMDLINE || where == MAKEFLAGS); + break; + case CMDLINE: + set = (where == CMDLINE); + break; + default: + abort(); + } + + if (!set) { + debug("hidding override of %s from '%s' to '%s'", name, s, val); + } else { + debug("override %s from '%s' to '%s'", name, s, val); + free(mp->value); + mp->value = estrdup(val); + mp->where = where; + + if (export && strcmp(name, "SHELL") != 0) { + debug("exporting macro %s", name); + exportvar(name, val); + } + } } void freeloc(struct loc *loc) { - free(loc->fname); + free(loc->fname); } static struct loc * getloc(void) { - struct input *ip; + struct input *ip; - for (ip = input; ip && ip->type != FTFILE; ip = ip->prev) - ; - if (!ip) - return NULL; + for (ip = input; ip && ip->type != FTFILE; ip = ip->prev) + ; + if (!ip) + return NULL; - return &ip->loc; + return &ip->loc; } void error(char *fmt, ...) { - va_list va; - struct loc *loc; + va_list va; + struct loc *loc; - fprintf(stderr, "make: error: "); - if ((loc = getloc()) != NULL) - fprintf(stderr, "%s:%d: ", loc->fname, loc->lineno); + fprintf(stderr, "make: error: "); + if ((loc = getloc()) != NULL) + fprintf(stderr, "%s:%d: ", loc->fname, loc->lineno); - va_start(va, fmt); - vfprintf(stderr, fmt, va); - va_end(va); - putc('\n', stderr); + va_start(va, fmt); + vfprintf(stderr, fmt, va); + va_end(va); + putc('\n', stderr); - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } void warning(char *fmt, ...) { - va_list va; - struct loc *loc; + va_list va; + struct loc *loc; - fprintf(stderr, "make: warning: "); - if ((loc = getloc()) != NULL) - fprintf(stderr, "%s:%d: ", loc->fname, loc->lineno); + fprintf(stderr, "make: warning: "); + if ((loc = getloc()) != NULL) + fprintf(stderr, "%s:%d: ", loc->fname, loc->lineno); - va_start(va, fmt); - vfprintf(stderr, fmt, va); - va_end(va); - putc('\n', stderr); + va_start(va, fmt); + vfprintf(stderr, fmt, va); + va_end(va); + putc('\n', stderr); } static void pop(void) { - struct input *ip = input->prev; + struct input *ip = input->prev; - if (input->type == FTFILE) { - if (input->fp) - fclose(input->fp); - freeloc(&input->loc); - } - free(input->buf); - free(input); + if (input->type == FTFILE) { + if (input->fp) + fclose(input->fp); + freeloc(&input->loc); + } + free(input->buf); + free(input); - input = ip; + input = ip; } static void push(int type, ...) { - int line, len, pos; - FILE *fp = NULL; - char *buf, *s, *fname = NULL; - va_list va; - struct input *ip; - - va_start(va, type); - switch (type) { - case FTFILE: - fp = va_arg(va, FILE *); - s = va_arg(va, char *); - line = va_arg(va, int); - fname = estrdup(s); - buf = emalloc(BUFSIZ); - pos = len = BUFSIZ; - break; - case FTEXPAN: - s = va_arg(va, char *); - buf = estrdup(s); - line = pos = 0; - len = strlen(s); - break; - } - va_end(va); - - ip = emalloc(sizeof(*ip)); - ip->siz = len; - ip->buf = buf; - ip->type = type; - ip->fp = fp; - ip->loc.fname = fname; - ip->loc.lineno = line; - ip->pos = pos; - ip->prev = input; - - input = ip; + int line, len, pos; + FILE *fp = NULL; + char *buf, *s, *fname = NULL; + va_list va; + struct input *ip; + + va_start(va, type); + switch (type) { + case FTFILE: + fp = va_arg(va, FILE *); + s = va_arg(va, char *); + line = va_arg(va, int); + fname = estrdup(s); + buf = emalloc(BUFSIZ); + pos = len = BUFSIZ; + break; + case FTEXPAN: + s = va_arg(va, char *); + buf = estrdup(s); + line = pos = 0; + len = strlen(s); + break; + } + va_end(va); + + ip = emalloc(sizeof(*ip)); + ip->siz = len; + ip->buf = buf; + ip->type = type; + ip->fp = fp; + ip->loc.fname = fname; + ip->loc.lineno = line; + ip->pos = pos; + ip->prev = input; + + input = ip; } static char * trim(char *s) { - size_t len; + size_t len; - while (isspace(*s)) - s++; + while (isspace(*s)) + s++; - for (len = strlen(s); len > 0 && isspace(s[len-1]); --len) - s[len-1] = '\0'; + for (len = strlen(s); len > 0 && isspace(s[len-1]); --len) + s[len-1] = '\0'; - return s; + return s; } static void include(char *s) { - FILE *fp; - char *fil, *t; + FILE *fp; + char *fil, *t, *end; + + s = trim(s); + if (*s == '<' || *s == '"') { + char delim = (*s == '<') ? '>' : '"'; + s++; + end = strchr(s, delim); + if (end) + *end = '\0'; + } + fil = expandstring(s, NULL, getloc()); + + t = trim(fil); + if (strlen(t) != 0) { + debug("including '%s'", t); + if ((fp = fopen(t, "r")) == NULL) + error("opening %s:%s", t, strerror(errno)); + push(FTFILE, fp, t, 0); + } + + free(fil); +} + +static void +sinclude(char *s) +{ + FILE *fp; + char *fil, *t, *end; + + s = trim(s); + if (*s == '<' || *s == '"') { + char delim = (*s == '<') ? '>' : '"'; + s++; + end = strchr(s, delim); + if (end) + *end = '\0'; + } + fil = expandstring(s, NULL, getloc()); + + t = trim(fil); + if (strlen(t) != 0) { + debug("trying to include '%s'", t); + if ((fp = fopen(t, "r")) != NULL) + push(FTFILE, fp, t, 0); + else + debug("skipping missing include %s", t); + } + + free(fil); +} + +#define MAXCOND 32 +static struct { + int active; + int matched; + int parent_active; +} condstack[MAXCOND]; +static int conddepth = 0; + +static int +cond_active(void) +{ + if (conddepth == 0) + return 1; + return condstack[conddepth].active && condstack[conddepth].parent_active; +} + +static void +cond_if(int truth) +{ + int parent; + if (conddepth >= MAXCOND) + error("too many nested .if directives"); + parent = cond_active(); + conddepth++; + condstack[conddepth].parent_active = parent; + condstack[conddepth].matched = truth; + condstack[conddepth].active = truth; +} + +static void +cond_elif(int truth) +{ + if (conddepth == 0) + error(".elif without .if"); + if (condstack[conddepth].matched) + condstack[conddepth].active = 0; + else { + condstack[conddepth].matched = condstack[conddepth].matched || truth; + condstack[conddepth].active = truth; + } +} - s = trim(s); - fil = expandstring(s, NULL, getloc()); +static void +cond_else(void) +{ + if (conddepth == 0) + error(".else without .if"); + condstack[conddepth].active = !condstack[conddepth].matched; + condstack[conddepth].matched = 1; +} - t = trim(fil); - if (strlen(t) != 0) { - debug("including '%s'", t); - if ((fp = fopen(t, "r")) == NULL) - error("opening %s:%s", t, strerror(errno)); - push(FTFILE, fp, t, 0); - } +static void +cond_endif(void) +{ + if (conddepth == 0) + error(".endif without .if"); + conddepth--; +} - free(fil); +static int +eval_if(char *expr) +{ + char *s, *p, *var, *val, *end; + int neg = 0, result; + + s = trim(expr); + if (!*s) + return 0; + + while (*s == '(') { + end = s + strlen(s); + if (end > s && end[-1] == ')') end[-1] = '\0'; + s++; + s = trim(s); + } + + if (*s == '!') { + neg = 1; + s++; + s = trim(s); + } + + if (strncmp(s, "defined", 7) == 0 && (s[7] == '(' || s[7] == ' ')) { + var = trim(s + 7); + if (*var == '(') var++; + end = var + strlen(var); + if (end > var && end[-1] == ')') end[-1] = '\0'; + var = trim(var); + result = getmacro(var)[0] != '\0'; + return neg ? !result : result; + } + + if (strncmp(s, "make", 4) == 0 && (s[4] == '(' || s[4] == ' ')) { + var = trim(s + 4); + if (*var == '(') var++; + end = var + strlen(var); + if (end > var && end[-1] == ')') end[-1] = '\0'; + var = trim(var); + result = getmacro(var)[0] != '\0'; + return neg ? !result : result; + } + + { + char *expanded = expandstring(s, NULL, getloc()); + s = expanded; + } + + p = strstr(s, "=="); + if (!p) p = strstr(s, "!="); + if (p) { + int eq = (p[1] == '='); + *p = '\0'; + val = trim(p + 2); + var = trim(s); + { + char *ev = expandstring(var, NULL, getloc()); + result = strcmp(ev, val) == 0; + free(ev); + } + if (!eq) result = !result; + free(s); + return neg ? !result : result; + } + + /* bare expression: true if non-empty after expansion */ + result = s[0] != '\0'; + free(s); + return neg ? !result : result; } static char * nextline(void) { - int c; - FILE *fp; - char *s, *lim; + int c; + FILE *fp; + char *s, *lim; - assert(input->type == FTFILE); + assert(input->type == FTFILE); repeat: - fp = input->fp; - if (!fp || feof(fp)) - return NULL; - - lim = &input->buf[input->siz]; - for (s = input->buf; s < lim; *s++ = c) { - c = getc(fp); - if (c == '\n' || c == EOF) { - input->loc.lineno++; - *s++ = '\n'; - break; - } - if (c > UCHAR_MAX || c < 0) - error("invalid character '%c' (%d)", c, c); - } - - - if (s == lim) - error("too long line"); - if (ferror(fp)) - error(strerror(errno)); - *s = '\0'; - - if (!strcmp(input->buf, "")) - goto repeat; - - if (!strncmp(input->buf, "include", 7) && isblank(input->buf[7])) { - input->pos = input->siz; - include(input->buf+7); - goto repeat; - } - - input->pos = 0; - - - return input->buf; + fp = input->fp; + if (!fp || feof(fp)) + return NULL; + + lim = &input->buf[input->siz]; + for (s = input->buf; s < lim; *s++ = c) { + c = getc(fp); + if (c == '\n' || c == EOF) { + input->loc.lineno++; + *s++ = '\n'; + break; + } + if (c > UCHAR_MAX || c < 0) + error("invalid character '%c' (%d)", c, c); + } + + + if (s == lim) + error("too long line"); + if (ferror(fp)) + error(strerror(errno)); + *s = '\0'; + + if (!strcmp(input->buf, "")) + goto repeat; + + /* bmake style .include / .sinclude / .-include */ + if (input->buf[0] == '.') { + char *d = input->buf + 1; + size_t dl; + /* strip trailing whitespace/newline so strcmp works */ + dl = strlen(d); + while (dl > 0 && isspace((unsigned char)d[dl-1])) + d[--dl] = '\0'; + if (strncmp(d, "include", 7) == 0 && isblank(d[7])) { + input->pos = input->siz; + if (cond_active()) include(d + 7); + goto repeat; + } + if (strncmp(d, "sinclude", 8) == 0 && isblank(d[8])) { + input->pos = input->siz; + if (cond_active()) sinclude(d + 8); + goto repeat; + } + if (strncmp(d, "-include", 8) == 0 && isblank(d[8])) { + input->pos = input->siz; + if (cond_active()) sinclude(d + 8); + goto repeat; + } + if (strncmp(d, "optinclude", 10) == 0 && isblank(d[10])) { + input->pos = input->siz; + if (cond_active()) sinclude(d + 10); + goto repeat; + } + /* conditionals */ + if (strncmp(d, "if", 2) == 0 && (isblank(d[2]) || d[2] == '\0')) { + if (cond_active()) { + if (d[2] == '\0') + cond_if(eval_if("")); + else + cond_if(eval_if(d + 3)); + } else { + cond_if(0); + } + goto repeat; + } + if (strncmp(d, "ifdef", 5) == 0 && (isblank(d[5]) || d[5] == '\0')) { + if (cond_active()) { + char *v = trim(d[5] ? d + 6 : ""); + cond_if(getmacro(v)[0] != '\0'); + } else { + cond_if(0); + } + goto repeat; + } + if (strncmp(d, "ifndef", 6) == 0 && (isblank(d[6]) || d[6] == '\0')) { + if (cond_active()) { + char *v = trim(d[6] ? d + 7 : ""); + cond_if(getmacro(v)[0] == '\0'); + } else { + cond_if(0); + } + goto repeat; + } + if (strncmp(d, "elif", 4) == 0 && (isblank(d[4]) || d[4] == '\0')) { + if (condstack[conddepth].parent_active) + cond_elif(eval_if(d[4] ? d + 5 : "")); + else + cond_elif(0); + goto repeat; + } + if (strcmp(d, "else") == 0) { + cond_else(); + goto repeat; + } + if (strcmp(d, "endif") == 0) { + cond_endif(); + goto repeat; + } + if (strncmp(d, "error", 5) == 0 && isblank(d[5])) { + if (cond_active()) + error("%s", trim(d + 6)); + goto repeat; + } + if (strncmp(d, "warning", 7) == 0 && isblank(d[7])) { + if (cond_active()) + warning("%s", trim(d + 8)); + goto repeat; + } + } + + /* POSIX include */ + if (!strncmp(input->buf, "include", 7) && isblank(input->buf[7])) { + input->pos = input->siz; + if (cond_active()) include(input->buf+7); + goto repeat; + } + + /* sinclude / -include (GNU/POSIX style without dot) */ + if ((!strncmp(input->buf, "sinclude", 8) && isblank(input->buf[8])) || + (!strncmp(input->buf, "-include", 8) && isblank(input->buf[8]))) { + input->pos = input->siz; + if (cond_active()) sinclude(input->buf + 8); + goto repeat; + } + + /* if we are inside an inactive conditional branch, skip this line */ + if (!cond_active()) { + input->pos = input->siz; + goto repeat; + } + + input->pos = 0; + + + return input->buf; } static int empty(struct input *ip) { - return ip->pos == ip->siz || ip->buf[ip->pos] == '\0'; + return ip->pos == ip->siz || ip->buf[ip->pos] == '\0'; } static int moreinput(void) { - while (input) { - if (!empty(input)) - break; - - switch (input->type) { - case FTEXPAN: - pop(); - break; - case FTFILE: - if (!nextline()) - pop(); - break; - } - } - - return input != NULL; + while (input) { + if (!empty(input)) + break; + + switch (input->type) { + case FTEXPAN: + pop(); + break; + case FTFILE: + if (!nextline()) + pop(); + break; + } + } + + return input != NULL; } static int nextc(void) { - if (!moreinput()) - return EOF; + if (!moreinput()) + return EOF; - return input->buf[input->pos++]; + return input->buf[input->pos++]; } /* @@ -415,284 +680,302 @@ nextc(void) static int ahead(void) { - return input->buf[input->pos]; + return input->buf[input->pos]; } static int back(int c) { - if (c == EOF) - return c; - assert(input->pos > 0); - return input->buf[--input->pos] = c; + if (c == EOF) + return c; + assert(input->pos > 0); + return input->buf[--input->pos] = c; } static void comment(void) { - int c; + int c; - while ((c = nextc()) != EOF && c != '\n') { - if (c == '\\' && nextc() == EOF) - break; - } + while ((c = nextc()) != EOF && c != '\n') { + if (c == '\\' && nextc() == EOF) + break; + } } static void skipspaces(void) { - int c; + int c; - for (c = nextc(); c == ' ' || c == '\t'; c = nextc()) - ; - back(c); + for (c = nextc(); c == ' ' || c == '\t'; c = nextc()) + ; + back(c); } static int validchar(int c) { - if (c == EOF) - return 0; - return c == '.' || c == '/' || c == '_' || c == '-' || isalnum(c); + if (c == EOF) + return 0; + return c == '.' || c == '/' || c == '_' || c == '-' || isalnum(c); } static char * expandmacro(char *name) { - char *s; + char *s; - s = expandstring(getmacro(name), NULL, getloc()); - debug("macro %s expanded to '%s'", name, s); + s = expandstring(getmacro(name), NULL, getloc()); + debug("macro %s expanded to '%s'", name, s); - return s; + return s; } static void replace(char *line, char *repl, char *to) { - int siz, at, len, replsiz, tosiz, pos; - char *oline, *cur, *buf; - - debug("replacing '%s', with '%s' to '%s'", line, repl, to); - oline = line; - tosiz = strlen(to); - replsiz = strlen(repl); - - buf = NULL; - for (pos = 0; *line; pos += siz) { - cur = NULL; - siz = 0; - - for (siz = 0; *line == ' ' || *line == '\t'; ++siz) { - cur = erealloc(cur, siz+1); - cur[siz] = *line++; - } - - len = strcspn(line, " \t"); - at = len - replsiz; - if (at < 0 || memcmp(line + at, repl, replsiz)) { - cur = erealloc(cur, siz + len); - memcpy(cur + siz, line, len); - siz += len; - } else { - cur = erealloc(cur, siz + at + tosiz); - memcpy(cur + siz, line, at); - memcpy(cur + siz + at, to, tosiz); - siz += at + tosiz; - } - - line += len; - buf = erealloc(buf, pos + siz); - memcpy(buf + pos, cur, siz); - free(cur); - } - - if (pos > 0) { - buf = erealloc(buf, pos + 1); - buf[pos] = '\0'; - debug("\treplace '%s' with '%s'", oline, buf); - push(FTEXPAN, buf); - } - - free(buf); + int siz, at, len, replsiz, tosiz, pos; + char *oline, *cur, *buf; + + debug("replacing '%s', with '%s' to '%s'", line, repl, to); + oline = line; + tosiz = strlen(to); + replsiz = strlen(repl); + + buf = NULL; + for (pos = 0; *line; pos += siz) { + cur = NULL; + siz = 0; + + for (siz = 0; *line == ' ' || *line == '\t'; ++siz) { + cur = erealloc(cur, siz+1); + cur[siz] = *line++; + } + + len = strcspn(line, " \t"); + at = len - replsiz; + if (at < 0 || memcmp(line + at, repl, replsiz)) { + cur = erealloc(cur, siz + len); + memcpy(cur + siz, line, len); + siz += len; + } else { + cur = erealloc(cur, siz + at + tosiz); + memcpy(cur + siz, line, at); + memcpy(cur + siz + at, to, tosiz); + siz += at + tosiz; + } + + line += len; + buf = erealloc(buf, pos + siz); + memcpy(buf + pos, cur, siz); + free(cur); + } + + if (pos > 0) { + buf = erealloc(buf, pos + 1); + buf[pos] = '\0'; + debug("\treplace '%s' with '%s'", oline, buf); + push(FTEXPAN, buf); + } + + free(buf); } static void expandsimple(Target *tp) { - char *s; - Target **p; - int len, c; - - switch (c = nextc()) { - case '@': - if (!tp || !tp->target) - return; - push(FTEXPAN, tp->target); - break; - case '<': - if (!tp || !tp->req) - return; - push(FTEXPAN, tp->req); - break; - case '*': - if (!tp || !tp->target) - return; - s = strrchr(tp->target, '.'); - if (!s) { - push(FTEXPAN, tp->target); - return; - } - - len = s - tp->target; - s = emalloc(len+1); - memcpy(s, tp->target, len); - s[len] = '\0'; - push(FTEXPAN, s); - free(s); - break; - case '?': - if (!tp) - return; - - if (tp->req && stamp(tp->req) > tp->stamp) { - push(FTEXPAN, " "); - push(FTEXPAN, tp->req); - } - - for (p = tp->deps; p && *p; ++p) { - if (stamp((*p)->name) > tp->stamp) { - push(FTEXPAN, " "); - push(FTEXPAN, (*p)->name); - } - } - break; - default: - token[0] = c; - token[1] = '\0'; - s = expandmacro(token); - push(FTEXPAN, s); - free(s); - break; - } + char *s; + Target **p; + int len, c, first; + + switch (c = nextc()) { + case '@': + if (!tp || !tp->target) + return; + push(FTEXPAN, tp->target); + break; + case '<': + if (!tp || !tp->req) + return; + push(FTEXPAN, tp->req); + break; + case '*': + if (!tp || !tp->target) + return; + s = strrchr(tp->target, '.'); + if (!s) { + push(FTEXPAN, tp->target); + return; + } + + len = s - tp->target; + s = emalloc(len+1); + memcpy(s, tp->target, len); + s[len] = '\0'; + push(FTEXPAN, s); + free(s); + break; + case '?': + if (!tp) + return; + + if (tp->req && stamp(tp->req) > tp->stamp) { + push(FTEXPAN, " "); + push(FTEXPAN, tp->req); + } + + for (p = tp->deps; p && *p; ++p) { + if (stamp((*p)->name) > tp->stamp) { + push(FTEXPAN, " "); + push(FTEXPAN, (*p)->name); + } + } + break; + case '>': + case '^': + if (!tp) + return; + first = 1; + if (tp->req) { + push(FTEXPAN, tp->req); + first = 0; + } + for (p = tp->deps; p && *p; ++p) { + if (!first) + push(FTEXPAN, " "); + push(FTEXPAN, (*p)->name); + first = 0; + } + break; + default: + token[0] = c; + token[1] = '\0'; + s = expandmacro(token); + push(FTEXPAN, s); + free(s); + break; + } } static int internal(int ch) { - switch (ch) { - case '@': - case '?': - case '*': - case '<': - return 1; - default: - return 0; - } + switch (ch) { + case '@': + case '?': + case '*': + case '<': + case '>': + case '^': + return 1; + default: + return 0; + } } static void expansion(Target *tp) { - int delim, c, repli, toi, namei, st; - char name[MAXTOKEN], repl[MAXREPL], to[MAXREPL]; - char *s, *erepl; - - c = nextc(); - if (c == '(') - delim = ')'; - else if (c == '{') - delim = '}'; - else - delim = 0; - - if (!delim) { - back(c); - expandsimple(tp); - return; - } - - s = NULL; - namei = repli = toi = 0; - st = STBEGIN; - - while (st != STEND && (c = nextc()) != EOF) { - switch (st) { - case STBEGIN: - if (c == ':') { - st = STREPLACE; - name[namei] = '\0'; - s = expandmacro(name); - break; - } - if (c == delim) { - name[namei] = '\0'; - s = expandmacro(name); - goto no_replace; - } - if (namei == MAXTOKEN-1) - error("expansion text too long"); - - if (namei == 0 && internal(c)) { - name[namei++] = '$'; - name[namei++] = c; - name[namei] = '\0'; - st = STINTERNAL; - s = expandstring(name, tp, getloc()); - break; - } - - if (!validchar(c)) - error("invalid macro name in expansion"); - name[namei++] = c; - break; - case STINTERNAL: - if (c == delim) - goto no_replace; - if (c != ':') - error("invalid internal macro in expansion"); - st = STREPLACE; - break; - case STREPLACE: - if (c == '=') { - st = STTO; - break; - } - if (c == delim) - error("invalid replacement pattern in expansion"); - if (repli == MAXREPL-1) - error("macro replacement too big"); - repl[repli++] = c; - break; - case STTO: - if (c == delim) { - st = STEND; - break; - } - - if (toi == MAXREPL-1) - error("macro substiturion too big"); - to[toi++] = c; - break; - } - } - - if (c == EOF) - error("found eof while parsing expansion"); - - repl[repli] = '\0'; - to[toi] = '\0'; - - erepl = expandstring(repl, tp, getloc()); - replace(s, erepl, to); - - free(erepl); - free(s); - return; + int delim, c, repli, toi, namei, st; + char name[MAXTOKEN], repl[MAXREPL], to[MAXREPL]; + char *s, *erepl; + + c = nextc(); + if (c == '(') + delim = ')'; + else if (c == '{') + delim = '}'; + else + delim = 0; + + if (!delim) { + back(c); + expandsimple(tp); + return; + } + + s = NULL; + namei = repli = toi = 0; + st = STBEGIN; + + while (st != STEND && (c = nextc()) != EOF) { + switch (st) { + case STBEGIN: + if (c == ':') { + st = STREPLACE; + name[namei] = '\0'; + s = expandmacro(name); + break; + } + if (c == delim) { + name[namei] = '\0'; + s = expandmacro(name); + goto no_replace; + } + if (namei == MAXTOKEN-1) + error("expansion text too long"); + + if (namei == 0 && internal(c)) { + name[namei++] = '$'; + name[namei++] = c; + name[namei] = '\0'; + st = STINTERNAL; + s = expandstring(name, tp, getloc()); + break; + } + + if (!validchar(c)) + error("invalid macro name in expansion"); + name[namei++] = c; + break; + case STINTERNAL: + if (c == delim) + goto no_replace; + if (c != ':') + error("invalid internal macro in expansion"); + st = STREPLACE; + break; + case STREPLACE: + if (c == '=') { + st = STTO; + break; + } + if (c == delim) + error("invalid replacement pattern in expansion"); + if (repli == MAXREPL-1) + error("macro replacement too big"); + repl[repli++] = c; + break; + case STTO: + if (c == delim) { + st = STEND; + break; + } + + if (toi == MAXREPL-1) + error("macro substiturion too big"); + to[toi++] = c; + break; + } + } + + if (c == EOF) + error("found eof while parsing expansion"); + + repl[repli] = '\0'; + to[toi] = '\0'; + + erepl = expandstring(repl, tp, getloc()); + replace(s, erepl, to); + + free(erepl); + free(s); + return; no_replace: - push(FTEXPAN, s); - free(s); + push(FTEXPAN, s); + free(s); } /* @@ -705,330 +988,420 @@ no_replace: char * expandstring(char *line, Target *tp, struct loc *loc) { - int c, n; - char *s; - struct input *ip = input; - - input = NULL; - push(FTFILE, NULL, loc->fname, loc->lineno); - push(FTEXPAN, line); - - n = 0; - s = NULL; - while ((c = nextc()) != EOF) { - if (c != '$') { - s = erealloc(s, ++n); - s[n-1] = c; - continue; - } - - if ((c = nextc()) == '$') { - s = erealloc(s, n += 2); - s[n-2] = '$'; - s[n-1] = '$'; - } else { - back(c); - expansion(tp); - } - } - - s = erealloc(s, n+1); - s[n] = '\0'; - input = ip; - - return s; + int c, n; + char *s; + struct input *ip = input; + + input = NULL; + push(FTFILE, NULL, loc->fname, loc->lineno); + push(FTEXPAN, line); + + n = 0; + s = NULL; + while ((c = nextc()) != EOF) { + if (c != '$') { + s = erealloc(s, ++n); + s[n-1] = c; + continue; + } + + if ((c = nextc()) == '$') { + s = erealloc(s, n += 2); + s[n-2] = '$'; + s[n-1] = '$'; + } else { + back(c); + expansion(tp); + } + } + + s = erealloc(s, n+1); + s[n] = '\0'; + input = ip; + + return s; } static int item(void) { - int c; - char *s; - char buf[MAXTOKEN]; - - for (s = buf; s < &buf[MAXTOKEN] - 1; ) { - c = nextc(); - if (c == '$' && ahead() != '$') - expansion(NULL); - else if (validchar(c)) - *s++ = c; - else - break; - } - back(c); - - if (s >= &buf[MAXTOKEN] - 1) - error("token too long"); - if (s == buf) - error("invalid empty token"); - *s++ = '\0'; - memcpy(token, buf, s - buf); - - return ITEM; + int c; + char *s; + char buf[MAXTOKEN]; + + for (s = buf; s < &buf[MAXTOKEN] - 1; ) { + c = nextc(); + if (c == '$' && ahead() != '$') + expansion(NULL); + else if (validchar(c)) + *s++ = c; + else + break; + } + back(c); + + if (s >= &buf[MAXTOKEN] - 1) + error("token too long"); + if (s == buf) + error("invalid empty token"); + *s++ = '\0'; + memcpy(token, buf, s - buf); + + return ITEM; } static int next(void) { - int c; + int c; repeat: - /* - * It is better to avoid skipspaces() here, because - * it can generate the need for 2 calls to back(), - * and we need the character anyway. - */ - c = nextc(); - if (c == ' ' || c == '\t') - goto repeat; - - if (c == '\\') { - if ((c = nextc()) == '\n') - goto repeat; - back(c); - c = '\\'; - } - - switch (c) { - case EOF: - strcpy(token, "<EOF>"); - tok = EOF; - break; - case '$': - if ((c = nextc()) == '$') - goto single; - back(c); - expansion(NULL); - goto repeat; - case '#': - comment(); - c = '\n'; - /* fallthrough */ - case ';': - case ':': - case '=': - case '\n': - single: - token[0] = c; - token[1] = '\0'; - tok = c; - break; - default: - if (!validchar(c)) - error("unexpected character '%c'", c); - back(c); - tok = item(); - break; - } - - return tok; + /* + * It is better to avoid skipspaces() here, because + * it can generate the need for 2 calls to back(), + * and we need the character anyway. + */ + c = nextc(); + if (c == ' ' || c == '\t') + goto repeat; + + if (c == '\\') { + if ((c = nextc()) == '\n') + goto repeat; + back(c); + c = '\\'; + } + + switch (c) { + case EOF: + strcpy(token, "<EOF>"); + tok = EOF; + break; + case '$': + if ((c = nextc()) == '$') + goto single; + back(c); + expansion(NULL); + goto repeat; + case '#': + comment(); + c = '\n'; + /* fallthrough */ + case ';': + case ':': + case '=': + case '\n': + single: + token[0] = c; + token[1] = '\0'; + tok = c; + break; + case '+': + if (nextc() == '=') { + token[0] = '+'; + token[1] = '='; + token[2] = '\0'; + tok = '+'; + break; + } + error("unexpected character '+'"); + case '!': + if (nextc() == '=') { + token[0] = '!'; + token[1] = '='; + token[2] = '\0'; + tok = '!'; + break; + } + error("unexpected character '!'"); + default: + if (!validchar(c)) + error("unexpected character '%c'", c); + back(c); + tok = item(); + break; + } + + return tok; } static char * readmacrodef(void) { - int n, c; - char *line; - - n = 0; - line = NULL; - while ((c = nextc()) != EOF) { - line = erealloc(line, n+1); - if (c == '\n') - break; - if (c == '#') { - comment(); - break; - } - if (c == '\\') { - if ((c = nextc()) != '\n') { - back(c); - c = '\\'; - } else { - skipspaces(); - c = ' '; - } - } - - line[n++] = c; - } - if (c == EOF) - error("EOF while looking for end of line"); - line[n] = '\0'; - - return line; + int n, c; + char *line; + + n = 0; + line = NULL; + while ((c = nextc()) != EOF) { + line = erealloc(line, n+1); + if (c == '\n') + break; + if (c == '#') { + comment(); + break; + } + if (c == '\\') { + if ((c = nextc()) != '\n') { + back(c); + c = '\\'; + } else { + skipspaces(); + c = ' '; + } + } + + line[n++] = c; + } + if (c == EOF) + error("EOF while looking for end of line"); + line[n] = '\0'; + + return line; } static struct action readcmd(void) { - int n, c; - struct loc *loc; - struct action act; - - skipspaces(); - - loc = getloc(); - act.loc.fname = estrdup(loc->fname); - act.loc.lineno = loc->lineno; - - n = 0; - act.line = NULL; - while ((c = nextc()) != EOF) { - act.line = erealloc(act.line, n+1); - if (c == '\n') - break; - if (c == '\\') { - if ((c = nextc()) == '\n') { - if ((c = nextc()) != '\t') - back(c); - continue; - } - back(c); - c = '\\'; - } - act.line[n++] = c; - } - if (c == EOF) - error("EOF while looking for end of command"); - act.line[n] = '\0'; - - return act; + int n, c; + struct loc *loc; + struct action act; + + skipspaces(); + + loc = getloc(); + act.loc.fname = estrdup(loc->fname); + act.loc.lineno = loc->lineno; + + n = 0; + act.line = NULL; + while ((c = nextc()) != EOF) { + act.line = erealloc(act.line, n+1); + if (c == '\n') + break; + if (c == '\\') { + if ((c = nextc()) == '\n') { + if ((c = nextc()) != '\t') + back(c); + continue; + } + back(c); + c = '\\'; + } + act.line[n++] = c; + } + if (c == EOF) + error("EOF while looking for end of command"); + act.line[n] = '\0'; + + return act; } static void rule(char *targets[], int ntargets) { - int c, i, j, ndeps, nactions; - struct action *acts; - char **deps = NULL; - - if (ntargets == 0) - error("missing target"); - - for (ndeps = 0; next() == ITEM; ++ndeps) { - deps = erealloc(deps, (ndeps+1) * sizeof(char *)); - deps[ndeps] = estrdup(token); - } - - if (tok != '\n' && tok != ';') - error("garbage at the end of the line"); - - nactions = 0; - acts = NULL; - if (tok == ';') { - nactions++; - acts = erealloc(acts, nactions * sizeof(*acts)); - acts[nactions-1] = readcmd(); - } - - for (;;) { - if ((c = nextc()) == '#') { - comment(); - continue; - } - if (c != '\t') - break; - nactions++; - acts = erealloc(acts, nactions * sizeof(*acts)); - acts[nactions-1] = readcmd(); - } - back(c); - - for (i = 0; i < ntargets; i++) { - addtarget(targets[i], ndeps); - for (j = 0; j < ndeps; j++) - adddep(targets[i], deps[j]); - if (nactions > 0) - addrule(targets[i], acts, nactions); - } - - for (i = 0; i < ndeps; i++) - free(deps[i]); - free(deps); - - for (i = 0; i < nactions; i++) { - free(acts[i].line); - freeloc(&acts[i].loc); - } - free(acts); + int c, i, j, ndeps, nactions; + struct action *acts; + char **deps = NULL; + + if (ntargets == 0) + error("missing target"); + + for (ndeps = 0; next() == ITEM; ++ndeps) { + deps = erealloc(deps, (ndeps+1) * sizeof(char *)); + deps[ndeps] = estrdup(token); + } + + if (tok != '\n' && tok != ';') + error("garbage at the end of the line"); + + nactions = 0; + acts = NULL; + if (tok == ';') { + nactions++; + acts = erealloc(acts, nactions * sizeof(*acts)); + acts[nactions-1] = readcmd(); + } + + for (;;) { + if ((c = nextc()) == '#') { + comment(); + continue; + } + if (c != '\t') + break; + nactions++; + acts = erealloc(acts, nactions * sizeof(*acts)); + acts[nactions-1] = readcmd(); + } + back(c); + + for (i = 0; i < ntargets; i++) { + addtarget(targets[i], ndeps); + for (j = 0; j < ndeps; j++) + adddep(targets[i], deps[j]); + if (nactions > 0) + addrule(targets[i], acts, nactions); + } + + for (i = 0; i < ndeps; i++) + free(deps[i]); + free(deps); + + for (i = 0; i < nactions; i++) { + free(acts[i].line); + freeloc(&acts[i].loc); + } + free(acts); } static void assign(char *macros[], int where, int n) { - char *defs; + char *defs; - if (n != 1) - error("invalid macro definition"); + if (n != 1) + error("invalid macro definition"); - skipspaces(); - defs = readmacrodef(); - setmacro(*macros, defs, where, NOEXPORT); - free(defs); + skipspaces(); + defs = readmacrodef(); + setmacro(*macros, defs, where, NOEXPORT); + free(defs); +} + +static void +assign_append(char *macros[], int where, int n) +{ + char *defs, *old, *new; + size_t olen, dlen; + + if (n != 1) + error("invalid macro definition"); + + skipspaces(); + defs = readmacrodef(); + old = getmacro(*macros); + olen = strlen(old); + dlen = strlen(defs); + /* old + " " + defs + '\0' */ + new = emalloc(olen + (olen > 0 ? 1 : 0) + dlen + 1); + memcpy(new, old, olen); + if (olen > 0) + new[olen++] = ' '; + memcpy(new + olen, defs, dlen); + new[olen + dlen] = '\0'; + setmacro(*macros, new, where, NOEXPORT); + free(new); + free(defs); +} + +static void +assign_shell(char *macros[], int where, int n) +{ + char *cmd, *out; + FILE *p; + size_t cap, len; + int c; + + if (n != 1) + error("invalid macro definition"); + + skipspaces(); + cmd = readmacrodef(); + { + char *expanded = expandstring(cmd, NULL, getloc()); + free(cmd); + cmd = expanded; + } + p = wpopen(cmd, NULL, "r"); + if (!p) + error("popen: %s", strerror(errno)); + cap = 64; + out = emalloc(cap); + len = 0; + while ((c = getc(p)) != EOF) { + if (len + 1 >= cap) { + cap *= 2; + out = erealloc(out, cap); + } + if (c == '\n') + break; + out[len++] = c; + } + out[len] = '\0'; + wpclose(p); + setmacro(*macros, out, where, NOEXPORT); + free(out); + free(cmd); } void parseinput(int where) { - int i, n; - char **targets; - - while (moreinput()) { - n = 0; - targets = NULL; - - next(); - if (tok == '\n') - continue; - - while (tok == ITEM) { - n++; - targets = erealloc(targets, n * sizeof(char *)); - targets[n-1] = estrdup(token); - next(); - } - - switch (tok) { - case ':': - rule(targets, n); - break; - case '=': - assign(targets, where, n); - break; - default: - error("unexpected token '%s'(%d)", token, tok); - } - - for (i = 0; i < n; i++) - free(targets[i]); - free(targets); - } + int i, n; + char **targets; + + while (moreinput()) { + n = 0; + targets = NULL; + + next(); + if (tok == '\n') + continue; + + while (tok == ITEM) { + n++; + targets = erealloc(targets, n * sizeof(char *)); + targets[n-1] = estrdup(token); + next(); + } + + switch (tok) { + case ':': + rule(targets, n); + break; + case '=': + assign(targets, where, n); + break; + case '+': + assign_append(targets, where, n); + break; + case '!': + assign_shell(targets, where, n); + break; + default: + error("unexpected token '%s'(%d)", token, tok); + } + + for (i = 0; i < n; i++) + free(targets[i]); + free(targets); + } } int parse(char *fname) { - FILE *fp; + FILE *fp; - if (!fname) { - fp = stdin; - fname = "<stdin>"; - } else if ((fp = fopen(fname, "r")) == NULL) { - return 0; - } + if (!fname) { + fp = stdin; + fname = "<stdin>"; + } else if ((fp = fopen(fname, "r")) == NULL) { + return 0; + } - debug("parsing %s", fname); - push(FTFILE, fp, fname, 0); - parseinput(MAKEFILE); + debug("parsing %s", fname); + push(FTFILE, fp, fname, 0); + parseinput(MAKEFILE); - return 1; + return 1; } void inject(char *s) { - push(FTFILE, NULL, "<internal>", 0); - push(FTEXPAN, s); - parseinput(INTERNAL); + push(FTFILE, NULL, "<internal>", 0); + push(FTEXPAN, s); + parseinput(INTERNAL); } diff --git a/cmd/posix/make/rules.c b/cmd/posix/make/rules.c @@ -14,554 +14,577 @@ static Target *htab[TABSIZ], *deftarget; void dumprules(void) { - int i; - Target **pp, **q, *p; - - for (pp = htab; pp < &htab[TABSIZ]; ++pp) { - for (p = *pp; p; p = p->next) { - if (!p->defined) - continue; - printf("%s:", p->name); - for (q = p->deps; q && *q; ++q) - printf(" %s", (*q)->name); - putchar('\n'); - for (i = 0; i < p->nactions; i++) - printf("\t%s\n", p->actions[i].line); - putchar('\n'); - } - } + int i; + Target **pp, **q, *p; + + for (pp = htab; pp < &htab[TABSIZ]; ++pp) { + for (p = *pp; p; p = p->next) { + if (!p->defined) + continue; + printf("%s:", p->name); + for (q = p->deps; q && *q; ++q) + printf(" %s", (*q)->name); + putchar('\n'); + for (i = 0; i < p->nactions; i++) + printf("\t%s\n", p->actions[i].line); + putchar('\n'); + } + } } static Target * lookup(char *name) { - Target *tp; - int h = hash(name) & (TABSIZ-1); - - for (tp = htab[h]; tp && strcmp(tp->name, name); tp = tp->next) - ; - - if (tp) - return tp; - - tp = emalloc(sizeof(*tp)); - tp->name = estrdup(name); - tp->target = tp->name; - tp->req = NULL; - tp->ndeps = 0; - tp->deps = NULL; - tp->actions = NULL; - tp->nactions = 0; - tp->next = htab[h]; - tp->defined = 0; - htab[h] = tp; - - return tp; + Target *tp; + int h = hash(name) & (TABSIZ-1); + + for (tp = htab[h]; tp && strcmp(tp->name, name); tp = tp->next) + ; + + if (tp) + return tp; + + tp = emalloc(sizeof(*tp)); + tp->name = estrdup(name); + tp->target = tp->name; + tp->req = NULL; + tp->ndeps = 0; + tp->deps = NULL; + tp->actions = NULL; + tp->nactions = 0; + tp->next = htab[h]; + tp->defined = 0; + htab[h] = tp; + + return tp; } static void cleanup(Target *tp) { - int sig, precious; - Target *p, **q; - - sig = stop; - printf("make: signal %d arrived\n", sig); - - precious = 0; - p = lookup(".PRECIOUS"); - for (q = p->deps; q && *q; q++) { - if (strcmp((*q)->name, tp->name) == 0) { - precious = 1; - break; - } - } - - if (!precious && !nflag && !qflag && !is_dir(tp->name)) { - printf("make: trying to remove target %s\n", tp->name); - remove(tp->name); - } - - signal(sig, SIG_DFL); - raise(sig); + int sig, precious; + Target *p, **q; + + sig = stop; + printf("make: signal %d arrived\n", sig); + + precious = 0; + p = lookup(".PRECIOUS"); + for (q = p->deps; q && *q; q++) { + if (strcmp((*q)->name, tp->name) == 0) { + precious = 1; + break; + } + } + + if (!precious && !nflag && !qflag && !is_dir(tp->name)) { + printf("make: trying to remove target %s\n", tp->name); + remove(tp->name); + } + + signal(sig, SIG_DFL); + raise(sig); } static int depends(char *target, char *dep) { - Target **p, *tp = lookup(target); + Target **p, *tp = lookup(target); - for (p = tp->deps; p && *p; ++p) { - if (strcmp((*p)->name, dep) == 0) - return 1; - } + for (p = tp->deps; p && *p; ++p) { + if (strcmp((*p)->name, dep) == 0) + return 1; + } - return 0; + return 0; } void addtarget(char *target, int ndeps) { - Target *tp = lookup(target); - - tp->defined = 1; - if (!deftarget && target[0] != '.') { - deftarget = tp; - return; - } - - if (strcmp(target, ".SUFFIXES") == 0 && ndeps == 0) { - free(tp->deps); - tp->deps = NULL; - tp->ndeps = 0; - return; - } - - if (strcmp(target, ".DEFAULT") == 0) { - if (ndeps > 0) - error("DEFAULT rule with prerequisites"); - return; - } - - if (strcmp(target, ".SILENT") == 0 && ndeps == 0) { - sflag = 1; - return; - } - - if (strcmp(target, ".IGNORE") == 0 && ndeps == 0) { - iflag = 1; - return; - } + Target *tp = lookup(target); + + tp->defined = 1; + if (!deftarget && target[0] != '.') { + deftarget = tp; + return; + } + + if (strcmp(target, ".SUFFIXES") == 0 && ndeps == 0) { + free(tp->deps); + tp->deps = NULL; + tp->ndeps = 0; + return; + } + + if (strcmp(target, ".DEFAULT") == 0) { + if (ndeps > 0) + error("DEFAULT rule with prerequisites"); + return; + } + + if (strcmp(target, ".SILENT") == 0 && ndeps == 0) { + sflag = 1; + return; + } + + if (strcmp(target, ".IGNORE") == 0 && ndeps == 0) { + iflag = 1; + return; + } + + /* .PHONY */ + if (strcmp(target, ".PHONY") == 0) { + if (ndeps == 0) { + free(tp->deps); + tp->deps = NULL; + tp->ndeps = 0; + } + return; + } } void adddep(char *target, char *dep) { - size_t siz; - Target **p, *tp = lookup(target); - - if (depends(dep, target)) { - warning("circular dependency %s <- %s dropped", target, dep); - return; - } - - for (p = tp->deps; p && *p; ++p) { - if (strcmp((*p)->name, dep) == 0) - return; - } - - tp->ndeps++; - siz = (tp->ndeps + 1) * sizeof(Target *); - tp->deps = erealloc(tp->deps, siz); - tp->deps[tp->ndeps-1] = lookup(dep); - tp->deps[tp->ndeps] = NULL; - - debug("adding dependency %s <- %s", target, dep); + size_t siz; + Target **p, *tp = lookup(target); + + if (depends(dep, target)) { + warning("circular dependency %s <- %s dropped", target, dep); + return; + } + + for (p = tp->deps; p && *p; ++p) { + if (strcmp((*p)->name, dep) == 0) + return; + } + + tp->ndeps++; + siz = (tp->ndeps + 1) * sizeof(Target *); + tp->deps = erealloc(tp->deps, siz); + tp->deps[tp->ndeps-1] = lookup(dep); + tp->deps[tp->ndeps] = NULL; + + debug("adding dependency %s <- %s", target, dep); } static void freeaction(struct action *act) { - free(act->line); - freeloc(&act->loc); + free(act->line); + freeloc(&act->loc); } void addrule(char *target, struct action *acts, int n) { - int i; - struct action *v; - Target *tp = lookup(target); - - debug("adding actions for target %s", target); - - if (tp->actions) { - debug("overring actions of target %s", target); - for (i = 0; i < tp->nactions; i++) - freeaction(&tp->actions[i]); - free(tp->actions); - } - - v = emalloc(n * sizeof(*v)); - for (i = 0; i < n; i++) { - v[i].line = estrdup(acts[i].line); - v[i].loc.lineno = acts[i].loc.lineno; - v[i].loc.fname = estrdup(acts[i].loc.fname); - } - - tp->nactions = n; - tp->actions = v; + int i; + struct action *v; + Target *tp = lookup(target); + + debug("adding actions for target %s", target); + + if (tp->actions) { + debug("overring actions of target %s", target); + for (i = 0; i < tp->nactions; i++) + freeaction(&tp->actions[i]); + free(tp->actions); + } + + v = emalloc(n * sizeof(*v)); + for (i = 0; i < n; i++) { + v[i].line = estrdup(acts[i].line); + v[i].loc.lineno = acts[i].loc.lineno; + v[i].loc.fname = estrdup(acts[i].loc.fname); + } + + tp->nactions = n; + tp->actions = v; } static int execline(Target *tp, char *line, int ignore, int silence) { - char *s, *t; - int r, at, plus, minus, l; - - (void)tp; - - debug("executing '%s'", line); - - at = plus = minus = 0; - for (s = line; ; s++) { - switch (*s) { - case '@': - at = 1; - break; - case '-': - minus = 1; - break; - case '+': - plus = 1; - break; - default: - goto out_loop; - } - } + char *s, *t; + int r, at, plus, minus, l; + + (void)tp; + + debug("executing '%s'", line); + + at = plus = minus = 0; + for (s = line; ; s++) { + switch (*s) { + case '@': + at = 1; + break; + case '-': + minus = 1; + break; + case '+': + plus = 1; + break; + default: + goto out_loop; + } + } out_loop: - /* unescape $$ */ - for (l = strlen(s)+1, t = s; *t; --l, ++t) { - if (t[0] == '$' && t[1] == '$') { - memmove(t+1, t+2, l-2); - l--; - } - } - - if (tflag && !plus) - return 0; - - if (sflag || silence || (qflag && !plus)) - at = 1; - if (nflag) - at = 0; - if (!at) { - puts(s); - fflush(stdout); - } - - if ((nflag || qflag) && !plus) { - if (qflag) - exitstatus = 1; - return 0; - } - - if (minus || iflag || ignore) - ignore = 1; - - r = launch(s, ignore); - if (ignore) - return 0; - - return r; + /* unescape $$ */ + for (l = strlen(s)+1, t = s; *t; --l, ++t) { + if (t[0] == '$' && t[1] == '$') { + memmove(t+1, t+2, l-2); + l--; + } + } + + if (tflag && !plus) + return 0; + + if (sflag || silence || (qflag && !plus)) + at = 1; + if (nflag) + at = 0; + if (!at) { + puts(s); + fflush(stdout); + } + + if ((nflag || qflag) && !plus) { + if (qflag) + exitstatus = 1; + return 0; + } + + if (minus || iflag || ignore) + ignore = 1; + + r = launch(s, ignore); + if (ignore) + return 0; + + return r; } static int touch(char *name, int ignore, int silence) { - char *cmd; - int r, n; + char *cmd; + int r, n; - n = snprintf(NULL, 0, "touch %s", name) + 1; - cmd = emalloc(n); - snprintf(cmd, n, "touch %s", name); + n = snprintf(NULL, 0, "touch %s", name) + 1; + cmd = emalloc(n); + snprintf(cmd, n, "touch %s", name); - if (!sflag && !silence) - puts(cmd); + if (!sflag && !silence) + puts(cmd); - r = system(cmd); - free(cmd); + r = wsystem(cmd); + free(cmd); - if (ignore || iflag) - return 0; + if (ignore || iflag) + return 0; - return r; + return r; } static int touchdeps(Target *tp, int ignore, int silent) { - int r; - Target **p; - - if (tp->req) { - r = touch(tp->req, silent, ignore); - if (r) - return r; - } - - for (p = tp->deps; p && *p; ++p) { - r = touch((*p)->name, silent, ignore); - if (r) - return r; - } - - return 0; + int r; + Target **p; + + if (tp->req) { + r = touch(tp->req, silent, ignore); + if (r) + return r; + } + + for (p = tp->deps; p && *p; ++p) { + r = touch((*p)->name, silent, ignore); + if (r) + return r; + } + + return 0; } static int run(Target *tp) { - int r, i, ignore, silent; - char *s; - Target *p, **q; - - silent = 0; - p = lookup(".SILENT"); - for (q = p->deps; q && *q; ++q) { - if (strcmp((*q)->name, tp->name) == 0) { - debug("target %s error silent by .SILENT", tp->name); - silent = 1; - } - } - - ignore = 0; - p = lookup(".IGNORE"); - for (q = p->deps; q && *q; ++q) { - if (strcmp((*q)->name, tp->name) == 0) { - debug("target %s error ignored by .IGNORE", tp->name); - ignore = 1; - } - } - - if (tflag) { - r = touchdeps(tp, ignore, silent); - if (r) - return r; - } - - for (i = 0; i < tp->nactions; i++) { - struct action *p; - - if (stop) - cleanup(tp); - - p = &tp->actions[i]; - debug("executing action '%s'", p->line); - s = expandstring(p->line, tp, &p->loc); - r = execline(tp, s, ignore, silent); - free(s); - - if (r) - return r; - } - - if (tflag) { - r = touch(tp->target, ignore, silent); - if (r) - return r; - } - - return 0; + int r, i, ignore, silent; + char *s; + Target *p, **q; + + silent = 0; + p = lookup(".SILENT"); + for (q = p->deps; q && *q; ++q) { + if (strcmp((*q)->name, tp->name) == 0) { + debug("target %s error silent by .SILENT", tp->name); + silent = 1; + } + } + + ignore = 0; + p = lookup(".IGNORE"); + for (q = p->deps; q && *q; ++q) { + if (strcmp((*q)->name, tp->name) == 0) { + debug("target %s error ignored by .IGNORE", tp->name); + ignore = 1; + } + } + + if (tflag) { + r = touchdeps(tp, ignore, silent); + if (r) + return r; + } + + for (i = 0; i < tp->nactions; i++) { + struct action *p; + + if (stop) + cleanup(tp); + + p = &tp->actions[i]; + debug("executing action '%s'", p->line); + s = expandstring(p->line, tp, &p->loc); + r = execline(tp, s, ignore, silent); + free(s); + + if (r) + return r; + } + + if (tflag) { + r = touch(tp->target, ignore, silent); + if (r) + return r; + } + + return 0; } static int enabled(char *suffix) { - Target **p, *tp = lookup(".SUFFIXES"); + Target **p, *tp = lookup(".SUFFIXES"); - for (p = tp->deps; p && *p; ++p) { - if (strcmp(suffix, (*p)->name) == 0) - return 1; - } + for (p = tp->deps; p && *p; ++p) { + if (strcmp(suffix, (*p)->name) == 0) + return 1; + } - return 0; + return 0; } static Target * inference(Target *tp, int force) { - time_t t; - int tolen, r; - char *to, *from; - Target *q, **p, *suffixes; - char buf[FILENAME_MAX], fname[FILENAME_MAX]; - - debug("searching an inference rule for %s", tp->name); - - to = strrchr(tp->name, '.'); - if (to && !enabled(to)) - return NULL; - tolen = to ? (int)(to - tp->name) : (int)strlen(tp->name); - - if (!to) - to = ""; - - suffixes = lookup(".SUFFIXES"); - for (p = suffixes->deps; p && *p; ++p) { - from = (*p)->name; - debug("trying suffix %s", from); - - r = snprintf(buf, - sizeof(buf), - "%s%s", - from, to); - - if (r < 0 || (size_t)r >= sizeof(buf)) - error("suffixes too long %s %s", from, to); - - q = lookup(buf); - if (!q->actions) - continue; - - r = snprintf(fname, - sizeof(fname), - "%*.*s%s", - tolen, tolen, tp->name, from); - - if (r < 0 || (size_t)r >= sizeof(fname)) { - error("prerequisite name too long %s %s", - tp->name, from); - } - - debug("\tsearching prerequisite %s", fname); - - t = stamp(fname); - if (t == -1) { - debug("\tprerequisite %s not found", fname); - continue; - } - - if (!force && t <= tp->stamp) { - debug("\tdiscarded because is newer"); - debug("\t%s: %s", tp->name, ctime(&tp->stamp)); - debug("\t%s: %s", fname, ctime(&t)); - continue; - } - - free(q->req); - q->req = estrdup(fname); - q->deps = tp->deps; - q->target = tp->name; - q->stamp = tp->stamp; - - debug("using inference rule %s with %s", q->name, fname); - return q; - } - - return NULL; + time_t t; + int tolen, r; + char *to, *from; + Target *q, **p, *suffixes; + char buf[FILENAME_MAX], fname[FILENAME_MAX]; + + debug("searching an inference rule for %s", tp->name); + + to = strrchr(tp->name, '.'); + if (to && !enabled(to)) + return NULL; + tolen = to ? (int)(to - tp->name) : (int)strlen(tp->name); + + if (!to) + to = ""; + + suffixes = lookup(".SUFFIXES"); + for (p = suffixes->deps; p && *p; ++p) { + from = (*p)->name; + debug("trying suffix %s", from); + + r = snprintf(buf, + sizeof(buf), + "%s%s", + from, to); + + if (r < 0 || (size_t)r >= sizeof(buf)) + error("suffixes too long %s %s", from, to); + + q = lookup(buf); + if (!q->actions) + continue; + + r = snprintf(fname, + sizeof(fname), + "%*.*s%s", + tolen, tolen, tp->name, from); + + if (r < 0 || (size_t)r >= sizeof(fname)) { + error("prerequisite name too long %s %s", + tp->name, from); + } + + debug("\tsearching prerequisite %s", fname); + + t = stamp(fname); + if (t == -1) { + debug("\tprerequisite %s not found", fname); + continue; + } + + if (!force && t <= tp->stamp) { + debug("\tdiscarded because is newer"); + debug("\t%s: %s", tp->name, ctime(&tp->stamp)); + debug("\t%s: %s", fname, ctime(&t)); + continue; + } + + free(q->req); + q->req = estrdup(fname); + q->deps = tp->deps; + q->target = tp->name; + q->stamp = tp->stamp; + + debug("using inference rule %s with %s", q->name, fname); + return q; + } + + return NULL; } static int update(Target *tp) { - Target *p; + Target *p; - debug("%s needs to be updated", tp->name); + debug("%s needs to be updated", tp->name); - if (tp->actions) { - debug("using target rule to build %s", tp->name); - return run(tp); - } + if (tp->actions) { + debug("using target rule to build %s", tp->name); + return run(tp); + } - if ((p = inference(tp, FORCE)) != NULL) { - debug("using inference rule %s", p->name); - return run(p); - } + if ((p = inference(tp, FORCE)) != NULL) { + debug("using inference rule %s", p->name); + return run(p); + } - p = lookup(".DEFAULT"); - if (p->defined) { - debug("using default rule"); - return run(p); - } + p = lookup(".DEFAULT"); + if (p->defined) { + debug("using default rule"); + return run(p); + } - debug("not rule found to update %s", tp->name); + debug("not rule found to update %s", tp->name); - if (!tp->defined) - error("don't know how to make %s", tp->name); + if (!tp->defined) + error("don't know how to make %s", tp->name); - return 0; + return 0; } -static int +static int +is_phony(Target *tp) +{ + Target **p, *ph = lookup(".PHONY"); + for (p = ph->deps; p && *p; ++p) + if (strcmp((*p)->name, tp->name) == 0) + return 1; + return 0; +} + +static int rebuild(Target *tp, int *buildp) { - Target **p, *q; - int r, need, build, err, def; - - debug("checking rebuild of %s", tp->name); - - tp->stamp = stamp(tp->name); - - def = err = need = 0; - for (p = tp->deps; p && *p; ++p) { - if (stop) - cleanup(tp); - - q = *p; - debug("checking dependency %s", q->name); - - if (strcmp(q->name, tp->name) == 0 && q->actions) - def = 1; - - build = 0; - if (rebuild(q, &build) != 0) { - err = 1; - continue; - } - - if (build) { - debug("rebuild of %s forces rebuild of %s", - q->name, tp->name); - need = 1; - } else if (q->stamp > tp->stamp) { - debug("dependency %s is newer than %s", - q->name, tp->name); - need = 1; - } - } - - if (tp->stamp == -1) { - need = 1; - } else if (!def) { - debug("no action found for %s, looking a inference rule", - tp->name); - if (inference(tp, NOFORCE)) - need = 1; - } - - if (err) { - warning("target %s not remade because of errors", tp->name); - return 1; - } else if (need) { - *buildp = 1; - - debug("target %s needs updating", tp->name); - r = update(tp); - if (r == 0) - return 0; - - if (stop) - cleanup(tp); - - exitstatus = 1; - - if (!kflag) - error("target %s: error %d", tp->name, r); - else - warning("target %s: error %d", tp->name, r); - return r; - } - - return 0; + Target **p, *q; + int r, need, build, err, def; + + debug("checking rebuild of %s", tp->name); + + if (is_phony(tp)) + tp->stamp = -1; + else + tp->stamp = stamp(tp->name); + + def = err = need = 0; + for (p = tp->deps; p && *p; ++p) { + if (stop) + cleanup(tp); + + q = *p; + debug("checking dependency %s", q->name); + + if (strcmp(q->name, tp->name) == 0 && q->actions) + def = 1; + + build = 0; + if (rebuild(q, &build) != 0) { + err = 1; + continue; + } + + if (build) { + debug("rebuild of %s forces rebuild of %s", + q->name, tp->name); + need = 1; + } else if (q->stamp > tp->stamp) { + debug("dependency %s is newer than %s", + q->name, tp->name); + need = 1; + } + } + + if (tp->stamp == -1) { + need = 1; + } else if (!def) { + debug("no action found for %s, looking a inference rule", + tp->name); + if (inference(tp, NOFORCE)) + need = 1; + } + + if (err) { + warning("target %s not remade because of errors", tp->name); + return 1; + } else if (need) { + *buildp = 1; + + debug("target %s needs updating", tp->name); + r = update(tp); + if (r == 0) + return 0; + + if (stop) + cleanup(tp); + + exitstatus = 1; + + if (!kflag) + error("target %s: error %d", tp->name, r); + else + warning("target %s: error %d", tp->name, r); + return r; + } + + return 0; } int build(char *name) { - int build; + int build; - if (!name) { - if (!deftarget) { - printf("make: no target to make\n"); - return 0; - } - name = deftarget->name; - } + if (!name) { + if (!deftarget) { + printf("make: no target to make\n"); + return 0; + } + name = deftarget->name; + } - debug("checking target %s", name); + debug("checking target %s", name); - build = 0; - return rebuild(lookup(name), &build); + build = 0; + return rebuild(lookup(name), &build); } diff --git a/cmd/posix/nice.c b/cmd/posix/nice.c @@ -7,6 +7,7 @@ #include <stdlib.h> #include <unistd.h> +#include "wexec.h" #include "util.h" #ifndef PRIO_MIN @@ -54,9 +55,9 @@ main(int argc, char *argv[]) if (setpriority(PRIO_PROCESS, 0, val) < 0) weprintf("setpriority:"); - execvp(argv[0], argv); + wexecvp_self(argv[0], argv); savederrno = errno; - weprintf("execvp %s:", argv[0]); + weprintf("wexecvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); } diff --git a/cmd/posix/nohup.c b/cmd/posix/nohup.c @@ -8,6 +8,7 @@ #include <signal.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -45,9 +46,9 @@ main(int argc, char *argv[]) if (isatty(STDERR_FILENO) && dup2(STDOUT_FILENO, STDERR_FILENO) < 0) enprintf(127, "dup2:"); - execvp(argv[0], argv); + wexecvp_self(argv[0], argv); savederrno = errno; - weprintf("execvp %s:", argv[0]); + weprintf("wexecvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); } diff --git a/cmd/posix/patch.c b/cmd/posix/patch.c @@ -1,4 +1,6 @@ /* See LICENSE file for copyright and license details. */ +#include "wexec.h" +#include "paths.h" #include "util.h" #include <sys/file.h> @@ -9,13 +11,11 @@ #include <ctype.h> #include <dirent.h> -#include <err.h> #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <libgen.h> #include <limits.h> -#include <paths.h> #include <stdarg.h> #include <stddef.h> #include <stdint.h> @@ -37,8 +37,8 @@ #define SCCSDIFF "get -p %s | diff - %s >/dev/null" #define RCSSUFFIX ",v" -#define CHECKOUT "/usr/bin/co" -#define RCSDIFF "/usr/bin/rcsdiff" +#define CHECKOUT "co" +#define RCSDIFF "rcsdiff" #define ORIGEXT ".orig" #define REJEXT ".rej" @@ -59,7 +59,7 @@ #define NEW_CONTEXT_DIFF 4 #define UNI_DIFF 5 -#define _PATH_ED "/bin/ed" +#define _PATH_ED "ed" #define ISDIGIT(c) (isascii((unsigned char)c) && isdigit((unsigned char)c)) @@ -74,16 +74,16 @@ typedef long LINENUM; enum BackupType { - BACKUP_UNDEFINED, - BACKUP_NONE, - BACKUP_SIMPLE, - BACKUP_NUMBERED_EXISTING, - BACKUP_NUMBERED + BACKUP_UNDEFINED, + BACKUP_NONE, + BACKUP_SIMPLE, + BACKUP_NUMBERED_EXISTING, + BACKUP_NUMBERED }; struct FileName { - char *path; - int exists; + char *path; + int exists; }; mode_t filemode = 0644; @@ -154,7 +154,6 @@ static void reinitialize_almost_everything(void); static void get_some_switches(void); static void reset_getopt_state(void); static LINENUM locate_hunk(LINENUM); -static void abort_context_hunk(void); static void rej_line(int, LINENUM); static void abort_hunk(void); static void apply_hunk(LINENUM); @@ -162,7 +161,6 @@ static void init_output(const char *); static void init_reject(const char *); static void copy_till(LINENUM, int); static int spew_output(void); -static void dump_patch_line(LINENUM, int); static void dump_input_line(LINENUM, int); static int patch_match(LINENUM, LINENUM, LINENUM); static int similar(const char *, const char *, ssize_t); @@ -268,11 +266,11 @@ static int argmatch(const char *, const char **); static void invalid_arg(const char *, const char *, int); static const char *backup_args[] = { - "none", "never", "simple", "nil", "existing", "t", "numbered", 0 + "none", "never", "simple", "nil", "existing", "t", "numbered", 0 }; static enum BackupType backup_types[] = { - BACKUP_NONE, BACKUP_SIMPLE, BACKUP_SIMPLE, BACKUP_NUMBERED_EXISTING, - BACKUP_NUMBERED_EXISTING, BACKUP_NUMBERED, BACKUP_NUMBERED + BACKUP_NONE, BACKUP_SIMPLE, BACKUP_SIMPLE, BACKUP_NUMBERED_EXISTING, + BACKUP_NUMBERED_EXISTING, BACKUP_NUMBERED, BACKUP_NUMBERED }; /* implementation */ @@ -281,675 +279,660 @@ static enum BackupType backup_types[] = { int main(int argc, char *argv[]) { - int error, hunk, failed, i, fd; - LINENUM where, newwhere, fuzz, mymaxfuzz; - const char *tmpdir; - char *v; - - error = 0; - where = 0; - bufsz = INITLINELEN; - if ((buf = malloc(bufsz)) == NULL) - pfatal("allocating input buffer"); - buf[0] = '\0'; - - setbuf(stderr, serrbuf); - for (i = 0; i < MAXFILEC; i++) - filearg[i] = NULL; - - if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0') - tmpdir = _PATH_TMP; - for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--) - ; - i++; - if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1) - fatal("cannot allocate memory"); - if ((fd = mkstemp(TMPOUTNAME)) < 0) - pfatal("cant create %s", TMPOUTNAME); - close(fd); - - if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1) - fatal("cannot allocate memory"); - if ((fd = mkstemp(TMPINNAME)) < 0) - pfatal("cant create %s", TMPINNAME); - close(fd); - - if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1) - fatal("cannot allocate memory"); - if ((fd = mkstemp(TMPREJNAME)) < 0) - pfatal("cant create %s", TMPREJNAME); - close(fd); - - if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1) - fatal("cannot allocate memory"); - if ((fd = mkstemp(TMPPATNAME)) < 0) - pfatal("cant create %s", TMPPATNAME); - close(fd); - - v = getenv("SIMPLE_BACKUP_SUFFIX"); - if (v) - simple_backup_suffix = v; - else - simple_backup_suffix = ORIGEXT; - - if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL) - v = getenv("VERSION_CONTROL"); - if (v != NULL) - backup_type = get_version(v); - - Argc = argc; - Argv = argv; - get_some_switches(); - - if (backup_type == BACKUP_UNDEFINED) - backup_type = posix ? BACKUP_NONE : BACKUP_NUMBERED_EXISTING; - - set_signals(0); - - for (open_patch_file(filearg[1]); there_is_another_patch(); reinitialize_almost_everything()) { - warn_on_invalid_line = 1; - if (outname == NULL) - outname = savestr(filearg[0]); - - if (diff_type == ED_DIFF) { - do_ed_script(); - continue; - } - if (!skip_rest_of_patch) - init_output(TMPOUTNAME); - - init_reject(TMPREJNAME); - - if (!skip_rest_of_patch) - scan_input(filearg[0]); - - hunk = 0; - failed = 0; - out_of_mem = 0; - while (another_hunk()) { - hunk++; - fuzz = 0; - mymaxfuzz = pch_context(); - if (maxfuzz < mymaxfuzz) - mymaxfuzz = maxfuzz; - if (!skip_rest_of_patch) { - do { - where = locate_hunk(fuzz); - if (hunk == 1 && where == 0 && !force) { - if (!pch_swap()) { - if (fuzz == 0) - say("Not enough memory to try swapped hunk! Assuming unswapped.\n"); - continue; - } - reverse = !reverse; - where = locate_hunk(fuzz); - if (where == 0) { - if (!pch_swap()) - fatal("lost hunk on alloc error!\n"); - reverse = !reverse; - } else if (noreverse) { - if (!pch_swap()) - fatal("lost hunk on alloc error!\n"); - reverse = !reverse; - say("Ignoring previously applied (or reversed) patch.\n"); - skip_rest_of_patch = 1; - } else if (batch) { - if (verbose) - say("%seversed (or %spreviously applied) patch detected! %s -R.", - reverse ? "R" : "Unr", - reverse ? "" : "not ", - reverse ? "Assuming" : "Ignoring"); - } else { - ask("%seversed (or %spreviously applied) patch detected! %s -R? [y] ", - reverse ? "R" : "Unr", - reverse ? "" : "not ", - reverse ? "Assume" : "Ignore"); - if (*buf == 'n') { - ask("Apply anyway? [n] "); - if (*buf != 'y') - skip_rest_of_patch = 1; - where = 0; - reverse = !reverse; - if (!pch_swap()) - fatal("lost hunk on alloc error!\n"); - } - } - } - } while (!skip_rest_of_patch && where == 0 && ++fuzz <= mymaxfuzz); - - if (skip_rest_of_patch) { - if (ferror(ofp) || fclose(ofp)) { - say("Error writing %s\n", TMPOUTNAME); - error = 1; - } - ofp = NULL; - } - } - newwhere = pch_newfirst() + last_offset; - if (skip_rest_of_patch) { - abort_hunk(); - failed++; - if (verbose) - say("Hunk #%d ignored at %ld.\n", hunk, newwhere); - } else if (where == 0) { - abort_hunk(); - failed++; - if (verbose) - say("Hunk #%d failed at %ld.\n", hunk, newwhere); - } else { - apply_hunk(where); - if (verbose) { - say("Hunk #%d succeeded at %ld", hunk, newwhere); - if (fuzz != 0) - say(" with fuzz %ld", fuzz); - if (last_offset) - say(" (offset %ld line%s)", last_offset, last_offset == 1L ? "" : "s"); - say(".\n"); - } - } - } - - if (out_of_mem && using_plan_a) { - Argc = Argc_last; - Argv = Argv_last; - say("\n\nRan out of memory using Plan A--trying again...\n\n"); - if (ofp) - fclose(ofp); - ofp = NULL; - if (rejfp) - fclose(rejfp); - rejfp = NULL; - continue; - } - if (hunk == 0) - fatal("internal error: hunk should not be 0\n"); - - if (!skip_rest_of_patch && !spew_output()) { - say("cant write %s\n", TMPOUTNAME); - error = 1; - } - - ignore_signals(); - if (!skip_rest_of_patch) { - struct stat statbuf; - char *realout = outname; - - if (!check_only) { - enum BackupType saved = backup_type; - if (failed > 0 && backup_if_mismatch > 0 && backup_type == BACKUP_NONE) - backup_type = BACKUP_SIMPLE; - if (move_file(TMPOUTNAME, outname) < 0) { - toutkeep = 1; - realout = TMPOUTNAME; - chmod(TMPOUTNAME, filemode); - } else - chmod(outname, filemode); - backup_type = saved; - - if (remove_empty_files && stat(realout, &statbuf) == 0 && statbuf.st_size == 0) { - if (verbose) - say("Removing %s (empty after patching).\n", realout); - unlink(realout); - } - } - } - if (ferror(rejfp) || fclose(rejfp)) { - say("Error writing %s\n", rejname); - error = 1; - } - rejfp = NULL; - if (failed) { - error = 1; - if (*rejname == '\0') { - if (strlcpy(rejname, outname, sizeof(rejname)) >= sizeof(rejname)) - fatal("filename %s is too long\n", outname); - if (strlcat(rejname, REJEXT, sizeof(rejname)) >= sizeof(rejname)) - fatal("filename %s is too long\n", outname); - } - if (skip_rest_of_patch) { - say("%d out of %d hunks ignored--saving rejects to %s\n", failed, hunk, rejname); - } else { - say("%d out of %d hunks FAILED -- saving rejects to %s\n", failed, hunk, rejname); - } - if (!check_only && move_file(TMPREJNAME, rejname) < 0) - trejkeep = 1; - } - set_signals(1); - } - my_exit(error); + int error, hunk, failed, i, fd; + LINENUM where, newwhere, fuzz, mymaxfuzz; + const char *tmpdir; + char *v; + + error = 0; + where = 0; + bufsz = INITLINELEN; + if ((buf = malloc(bufsz)) == NULL) + pfatal("allocating input buffer"); + buf[0] = '\0'; + + setbuf(stderr, serrbuf); + for (i = 0; i < MAXFILEC; i++) + filearg[i] = NULL; + + if ((tmpdir = getenv("TMPDIR")) == NULL || *tmpdir == '\0') + tmpdir = ARUU_PATH_TMP; + for (i = strlen(tmpdir) - 1; i > 0 && tmpdir[i] == '/'; i--) + ; + i++; + if (asprintf(&TMPOUTNAME, "%.*s/patchoXXXXXXXXXX", i, tmpdir) == -1) + fatal("cannot allocate memory"); + if ((fd = mkstemp(TMPOUTNAME)) < 0) + pfatal("cant create %s", TMPOUTNAME); + close(fd); + + if (asprintf(&TMPINNAME, "%.*s/patchiXXXXXXXXXX", i, tmpdir) == -1) + fatal("cannot allocate memory"); + if ((fd = mkstemp(TMPINNAME)) < 0) + pfatal("cant create %s", TMPINNAME); + close(fd); + + if (asprintf(&TMPREJNAME, "%.*s/patchrXXXXXXXXXX", i, tmpdir) == -1) + fatal("cannot allocate memory"); + if ((fd = mkstemp(TMPREJNAME)) < 0) + pfatal("cant create %s", TMPREJNAME); + close(fd); + + if (asprintf(&TMPPATNAME, "%.*s/patchpXXXXXXXXXX", i, tmpdir) == -1) + fatal("cannot allocate memory"); + if ((fd = mkstemp(TMPPATNAME)) < 0) + pfatal("cant create %s", TMPPATNAME); + close(fd); + + v = getenv("SIMPLE_BACKUP_SUFFIX"); + if (v) + simple_backup_suffix = v; + else + simple_backup_suffix = ORIGEXT; + + if ((v = getenv("PATCH_VERSION_CONTROL")) == NULL) + v = getenv("VERSION_CONTROL"); + if (v != NULL) + backup_type = get_version(v); + + Argc = argc; + Argv = argv; + get_some_switches(); + + if (backup_type == BACKUP_UNDEFINED) + backup_type = posix ? BACKUP_NONE : BACKUP_NUMBERED_EXISTING; + + set_signals(0); + + for (open_patch_file(filearg[1]); there_is_another_patch(); reinitialize_almost_everything()) { + warn_on_invalid_line = 1; + if (outname == NULL) + outname = savestr(filearg[0]); + + if (diff_type == ED_DIFF) { + do_ed_script(); + continue; + } + if (!skip_rest_of_patch) + init_output(TMPOUTNAME); + + init_reject(TMPREJNAME); + + if (!skip_rest_of_patch) + scan_input(filearg[0]); + + hunk = 0; + failed = 0; + out_of_mem = 0; + while (another_hunk()) { + hunk++; + fuzz = 0; + mymaxfuzz = pch_context(); + if (maxfuzz < mymaxfuzz) + mymaxfuzz = maxfuzz; + if (!skip_rest_of_patch) { + do { + where = locate_hunk(fuzz); + if (hunk == 1 && where == 0 && !force) { + if (!pch_swap()) { + if (fuzz == 0) + say("Not enough memory to try swapped hunk! Assuming unswapped.\n"); + continue; + } + reverse = !reverse; + where = locate_hunk(fuzz); + if (where == 0) { + if (!pch_swap()) + fatal("lost hunk on alloc error!\n"); + reverse = !reverse; + } else if (noreverse) { + if (!pch_swap()) + fatal("lost hunk on alloc error!\n"); + reverse = !reverse; + say("Ignoring previously applied (or reversed) patch.\n"); + skip_rest_of_patch = 1; + } else if (batch) { + if (verbose) + say("%seversed (or %spreviously applied) patch detected! %s -R.", + reverse ? "R" : "Unr", + reverse ? "" : "not ", + reverse ? "Assuming" : "Ignoring"); + } else { + ask("%seversed (or %spreviously applied) patch detected! %s -R? [y] ", + reverse ? "R" : "Unr", + reverse ? "" : "not ", + reverse ? "Assume" : "Ignore"); + if (*buf == 'n') { + ask("Apply anyway? [n] "); + if (*buf != 'y') + skip_rest_of_patch = 1; + where = 0; + reverse = !reverse; + if (!pch_swap()) + fatal("lost hunk on alloc error!\n"); + } + } + } + } while (!skip_rest_of_patch && where == 0 && ++fuzz <= mymaxfuzz); + + if (skip_rest_of_patch) { + if (ferror(ofp) || fclose(ofp)) { + say("Error writing %s\n", TMPOUTNAME); + error = 1; + } + ofp = NULL; + } + } + newwhere = pch_newfirst() + last_offset; + if (skip_rest_of_patch) { + abort_hunk(); + failed++; + if (verbose) + say("Hunk #%d ignored at %ld.\n", hunk, newwhere); + } else if (where == 0) { + abort_hunk(); + failed++; + if (verbose) + say("Hunk #%d failed at %ld.\n", hunk, newwhere); + } else { + apply_hunk(where); + if (verbose) { + say("Hunk #%d succeeded at %ld", hunk, newwhere); + if (fuzz != 0) + say(" with fuzz %ld", fuzz); + if (last_offset) + say(" (offset %ld line%s)", last_offset, last_offset == 1L ? "" : "s"); + say(".\n"); + } + } + } + + if (out_of_mem && using_plan_a) { + Argc = Argc_last; + Argv = Argv_last; + say("\n\nRan out of memory using Plan A--trying again...\n\n"); + if (ofp) + fclose(ofp); + ofp = NULL; + if (rejfp) + fclose(rejfp); + rejfp = NULL; + continue; + } + if (hunk == 0) + fatal("internal error: hunk should not be 0\n"); + + if (!skip_rest_of_patch && !spew_output()) { + say("cant write %s\n", TMPOUTNAME); + error = 1; + } + + ignore_signals(); + if (!skip_rest_of_patch) { + struct stat statbuf; + char *realout = outname; + + if (!check_only) { + enum BackupType saved = backup_type; + if (failed > 0 && backup_if_mismatch > 0 && backup_type == BACKUP_NONE) + backup_type = BACKUP_SIMPLE; + if (move_file(TMPOUTNAME, outname) < 0) { + toutkeep = 1; + realout = TMPOUTNAME; + chmod(TMPOUTNAME, filemode); + } else + chmod(outname, filemode); + backup_type = saved; + + if (remove_empty_files && stat(realout, &statbuf) == 0 && statbuf.st_size == 0) { + if (verbose) + say("Removing %s (empty after patching).\n", realout); + unlink(realout); + } + } + } + if (ferror(rejfp) || fclose(rejfp)) { + say("Error writing %s\n", rejname); + error = 1; + } + rejfp = NULL; + if (failed) { + error = 1; + if (*rejname == '\0') { + if (strlcpy(rejname, outname, sizeof(rejname)) >= sizeof(rejname)) + fatal("filename %s is too long\n", outname); + if (strlcat(rejname, REJEXT, sizeof(rejname)) >= sizeof(rejname)) + fatal("filename %s is too long\n", outname); + } + if (skip_rest_of_patch) { + say("%d out of %d hunks ignored--saving rejects to %s\n", failed, hunk, rejname); + } else { + say("%d out of %d hunks FAILED -- saving rejects to %s\n", failed, hunk, rejname); + } + if (!check_only && move_file(TMPREJNAME, rejname) < 0) + trejkeep = 1; + } + set_signals(1); + } + my_exit(error); } static void reset_getopt_state(void) { #if defined(__GLIBC__) || defined(__linux__) - optind = 0; + optind = 0; #else - optreset = 1; - optind = 1; + optreset = 1; + optind = 1; #endif } static void reinitialize_almost_everything(void) { - re_patch(); - re_input(); - - input_lines = 0; - last_frozen_line = 0; - filec = 0; - if (!out_of_mem) { - free(filearg[0]); - filearg[0] = NULL; - } - free(outname); - outname = NULL; - last_offset = 0; - diff_type = 0; - free(revision); - revision = NULL; - reverse = reverse_flag_specified; - skip_rest_of_patch = 0; - get_some_switches(); + re_patch(); + re_input(); + + input_lines = 0; + last_frozen_line = 0; + filec = 0; + if (!out_of_mem) { + free(filearg[0]); + filearg[0] = NULL; + } + free(outname); + outname = NULL; + last_offset = 0; + diff_type = 0; + free(revision); + revision = NULL; + reverse = reverse_flag_specified; + skip_rest_of_patch = 0; + get_some_switches(); } static void get_some_switches(void) { - const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:"; - static struct option longopts[] = { - {"backup", no_argument, 0, 'b'}, - {"backup-if-mismatch", no_argument, &backup_if_mismatch, 1}, - {"batch", no_argument, 0, 't'}, - {"check", no_argument, 0, 'C'}, - {"context", no_argument, 0, 'c'}, - {"debug", required_argument, 0, 'x'}, - {"directory", required_argument, 0, 'd'}, - {"ed", no_argument, 0, 'e'}, - {"force", no_argument, 0, 'f'}, - {"forward", no_argument, 0, 'N'}, - {"fuzz", required_argument, 0, 'F'}, - {"ifdef", required_argument, 0, 'D'}, - {"input", required_argument, 0, 'i'}, - {"ignore-whitespace", no_argument, 0, 'l'}, - {"no-backup-if-mismatch", no_argument, &backup_if_mismatch, 0}, - {"normal", no_argument, 0, 'n'}, - {"output", required_argument, 0, 'o'}, - {"prefix", required_argument, 0, 'B'}, - {"quiet", no_argument, 0, 's'}, - {"reject-file", required_argument, 0, 'r'}, - {"remove-empty-files", no_argument, 0, 'E'}, - {"reverse", no_argument, 0, 'R'}, - {"silent", no_argument, 0, 's'}, - {"strip", required_argument, 0, 'p'}, - {"suffix", required_argument, 0, 'z'}, - {"unified", no_argument, 0, 'u'}, - {"version", no_argument, 0, 'v'}, - {"version-control", required_argument, 0, 'V'}, - {"posix", no_argument, &posix, 1}, - {NULL, 0, 0, 0} - }; - int ch; - - rejname[0] = '\0'; - Argc_last = Argc; - Argv_last = Argv; - if (!Argc) - return; - reset_getopt_state(); - while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) { - switch (ch) { - case 'b': - if (backup_type == BACKUP_UNDEFINED) - backup_type = BACKUP_NUMBERED_EXISTING; - if (optarg == NULL) - break; - if (verbose) - say("Warning, the -b suffix option has been obsoleted by the -z option\n"); - /* FALLTHROUGH */ - case 'z': - simple_backup_suffix = savestr(optarg); - break; - case 'B': - origprae = savestr(optarg); - break; - case 'c': - diff_type = CONTEXT_DIFF; - break; - case 'C': - check_only = 1; - break; - case 'd': - if (chdir(optarg) < 0) - pfatal("cant cd to %s", optarg); - break; - case 'D': - do_defines = 1; - if (!isalpha((unsigned char)*optarg) && *optarg != '_') - fatal("argument to -D is not an identifier\n"); - snprintf(if_defined, sizeof if_defined, "#ifdef %s\n", optarg); - snprintf(not_defined, sizeof not_defined, "#ifndef %s\n", optarg); - snprintf(end_defined, sizeof end_defined, "#endif /* %s */\n", optarg); - break; - case 'e': - diff_type = ED_DIFF; - break; - case 'E': - remove_empty_files = 1; - break; - case 'f': - force = 1; - break; - case 'F': - maxfuzz = strtolinenum(optarg, NULL); - break; - case 'i': - free(filearg[1]); - filearg[1] = fetchname(optarg, &warn_on_invalid_line, 0); - break; - case 'l': - canonicalize = 1; - break; - case 'n': - diff_type = NORMAL_DIFF; - break; - case 'N': - noreverse = 1; - break; - case 'o': - outname = savestr(optarg); - break; - case 'p': - strippath = (int)strtolinenum(optarg, NULL); - break; - case 'r': - if (strlcpy(rejname, optarg, sizeof(rejname)) >= sizeof(rejname)) - fatal("reject filename %s too long\n", optarg); - break; - case 'R': - reverse = 1; - reverse_flag_specified = 1; - break; - case 's': - verbose = 0; - break; - case 't': - batch = 1; - break; - case 'u': - diff_type = UNI_DIFF; - break; - case 'v': - version(); - break; - case 'V': - backup_type = get_version(optarg); - break; - case 'x': + const char *options = "b::B:cCd:D:eEfF:i:lnNo:p:r:RstuvV:x:z:"; + static struct option longopts[] = { + {"backup", no_argument, 0, 'b'}, + {"backup-if-mismatch", no_argument, &backup_if_mismatch, 1}, + {"batch", no_argument, 0, 't'}, + {"check", no_argument, 0, 'C'}, + {"context", no_argument, 0, 'c'}, + {"debug", required_argument, 0, 'x'}, + {"directory", required_argument, 0, 'd'}, + {"ed", no_argument, 0, 'e'}, + {"force", no_argument, 0, 'f'}, + {"forward", no_argument, 0, 'N'}, + {"fuzz", required_argument, 0, 'F'}, + {"ifdef", required_argument, 0, 'D'}, + {"input", required_argument, 0, 'i'}, + {"ignore-whitespace", no_argument, 0, 'l'}, + {"no-backup-if-mismatch", no_argument, &backup_if_mismatch, 0}, + {"normal", no_argument, 0, 'n'}, + {"output", required_argument, 0, 'o'}, + {"prefix", required_argument, 0, 'B'}, + {"quiet", no_argument, 0, 's'}, + {"reject-file", required_argument, 0, 'r'}, + {"remove-empty-files", no_argument, 0, 'E'}, + {"reverse", no_argument, 0, 'R'}, + {"silent", no_argument, 0, 's'}, + {"strip", required_argument, 0, 'p'}, + {"suffix", required_argument, 0, 'z'}, + {"unified", no_argument, 0, 'u'}, + {"version", no_argument, 0, 'v'}, + {"version-control", required_argument, 0, 'V'}, + {"posix", no_argument, &posix, 1}, + {NULL, 0, 0, 0} + }; + int ch; + + rejname[0] = '\0'; + Argc_last = Argc; + Argv_last = Argv; + if (!Argc) + return; + reset_getopt_state(); + while ((ch = getopt_long(Argc, Argv, options, longopts, NULL)) != -1) { + switch (ch) { + case 'b': + if (backup_type == BACKUP_UNDEFINED) + backup_type = BACKUP_NUMBERED_EXISTING; + if (optarg == NULL) + break; + if (verbose) + say("Warning, the -b suffix option has been obsoleted by the -z option\n"); + /* FALLTHROUGH */ + case 'z': + simple_backup_suffix = savestr(optarg); + break; + case 'B': + origprae = savestr(optarg); + break; + case 'c': + diff_type = CONTEXT_DIFF; + break; + case 'C': + check_only = 1; + break; + case 'd': + if (chdir(optarg) < 0) + pfatal("cant cd to %s", optarg); + break; + case 'D': + do_defines = 1; + if (!isalpha((unsigned char)*optarg) && *optarg != '_') + fatal("argument to -D is not an identifier\n"); + snprintf(if_defined, sizeof if_defined, "#ifdef %s\n", optarg); + snprintf(not_defined, sizeof not_defined, "#ifndef %s\n", optarg); + snprintf(end_defined, sizeof end_defined, "#endif /* %s */\n", optarg); + break; + case 'e': + diff_type = ED_DIFF; + break; + case 'E': + remove_empty_files = 1; + break; + case 'f': + force = 1; + break; + case 'F': + maxfuzz = strtolinenum(optarg, NULL); + break; + case 'i': + free(filearg[1]); + filearg[1] = fetchname(optarg, &warn_on_invalid_line, 0); + break; + case 'l': + canonicalize = 1; + break; + case 'n': + diff_type = NORMAL_DIFF; + break; + case 'N': + noreverse = 1; + break; + case 'o': + outname = savestr(optarg); + break; + case 'p': + strippath = (int)strtolinenum(optarg, NULL); + break; + case 'r': + if (strlcpy(rejname, optarg, sizeof(rejname)) >= sizeof(rejname)) + fatal("reject filename %s too long\n", optarg); + break; + case 'R': + reverse = 1; + reverse_flag_specified = 1; + break; + case 's': + verbose = 0; + break; + case 't': + batch = 1; + break; + case 'u': + diff_type = UNI_DIFF; + break; + case 'v': + version(); + break; + case 'V': + backup_type = get_version(optarg); + break; + case 'x': #ifdef DEBUGGING - debug = (int)strtolinenum(optarg, NULL); + debug = (int)strtolinenum(optarg, NULL); #endif - break; - default: - if (ch == 0) - break; - usage(); - } - } - Argc -= optind; - Argv += optind; - - for (ch = 0; ch < Argc; ch++) { - if (filec >= MAXFILEC) - usage(); - filearg[filec++] = savestr(Argv[ch]); - } + break; + default: + if (ch == 0) + break; + usage(); + } + } + Argc -= optind; + Argv += optind; + + for (ch = 0; ch < Argc; ch++) { + if (filec >= MAXFILEC) + usage(); + filearg[filec++] = savestr(Argv[ch]); + } } static void usage(void) { - fprintf(stderr, "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] " - "[-d directory] [-F max-fuzz] [-i patchfile] [-o out-file] " - "[-p strip-count] [-r rej-name] [-V method] [-x number] " - "[-z backup-ext] [origfile [patchfile]]\n"); - my_exit(2); + fprintf(stderr, "usage: patch [-bCcEeflNnRstuv] [-B backup-prefix] [-D symbol] " + "[-d directory] [-F max-fuzz] [-i patchfile] [-o out-file] " + "[-p strip-count] [-r rej-name] [-V method] [-x number] " + "[-z backup-ext] [origfile [patchfile]]\n"); + my_exit(2); } static LINENUM locate_hunk(LINENUM fuzz) { - LINENUM first_hunk_line = pch_first(); - LINENUM count = pch_ptrn_lines(); - LINENUM max_line = input_lines - count + 1; - LINENUM line; - LINENUM offset; - - if (!count) - return first_hunk_line + last_offset; - - if (first_hunk_line + last_offset <= 0) - offset = 1 - first_hunk_line; - else if (first_hunk_line + last_offset > max_line) - offset = max_line - first_hunk_line; - else - offset = last_offset; - - for (line = first_hunk_line + offset; line <= max_line; line++) { - if (patch_match(line, count, fuzz)) { - last_offset = line - first_hunk_line; - return line; - } - } - for (line = first_hunk_line + offset - 1; line >= 1; line--) { - if (patch_match(line, count, fuzz)) { - last_offset = line - first_hunk_line; - return line; - } - } - return 0; + LINENUM first_hunk_line = pch_first(); + LINENUM count = pch_ptrn_lines(); + LINENUM max_line = input_lines - count + 1; + LINENUM line; + LINENUM offset; + + if (!count) + return first_hunk_line + last_offset; + + if (first_hunk_line + last_offset <= 0) + offset = 1 - first_hunk_line; + else if (first_hunk_line + last_offset > max_line) + offset = max_line - first_hunk_line; + else + offset = last_offset; + + for (line = first_hunk_line + offset; line <= max_line; line++) { + if (patch_match(line, count, fuzz)) { + last_offset = line - first_hunk_line; + return line; + } + } + for (line = first_hunk_line + offset - 1; line >= 1; line--) { + if (patch_match(line, count, fuzz)) { + last_offset = line - first_hunk_line; + return line; + } + } + return 0; } static int patch_match(LINENUM line, LINENUM count, LINENUM fuzz) { - LINENUM i; - LINENUM pat_line; - char *str; - char *pat; - ssize_t len; - - for (i = 1; i <= count; i++) { - pat_line = i; - if (i <= fuzz) - continue; - if (i > count - fuzz) - continue; - str = ifetch(line + i - 1 - fuzz, 0); - if (str == NULL) - return 0; - pat = pfetch(pat_line); - len = pch_line_len(pat_line); - if (canonicalize) { - if (!similar(str, pat, len)) - return 0; - } else if (strncmp(str, pat, len) != 0) - return 0; - } - return 1; + LINENUM i; + LINENUM pat_line; + char *str; + char *pat; + ssize_t len; + + for (i = 1; i <= count; i++) { + pat_line = i; + if (i <= fuzz) + continue; + if (i > count - fuzz) + continue; + str = ifetch(line + i - 1 - fuzz, 0); + if (str == NULL) + return 0; + pat = pfetch(pat_line); + len = pch_line_len(pat_line); + if (canonicalize) { + if (!similar(str, pat, len)) + return 0; + } else if (strncmp(str, pat, len) != 0) + return 0; + } + return 1; } static int similar(const char *a, const char *b, ssize_t len) { - while (len > 0) { - if (isspace((unsigned char)*b)) { - if (!isspace((unsigned char)*a)) - return 0; - while (len > 0 && isspace((unsigned char)*b)) { - b++; - len--; - } - while (isspace((unsigned char)*a) && *a != '\n') - a++; - } else { - if (*a != *b) - return 0; - a++; - b++; - len--; - } - } - if (*a == '\n' || *a == '\r') { - while (*a == '\n' || *a == '\r') - a++; - return *a == '\0'; - } - return *a == '\0' || isspace((unsigned char)*a); + while (len > 0) { + if (isspace((unsigned char)*b)) { + if (!isspace((unsigned char)*a)) + return 0; + while (len > 0 && isspace((unsigned char)*b)) { + b++; + len--; + } + while (isspace((unsigned char)*a) && *a != '\n') + a++; + } else { + if (*a != *b) + return 0; + a++; + b++; + len--; + } + } + if (*a == '\n' || *a == '\r') { + while (*a == '\n' || *a == '\r') + a++; + return *a == '\0'; + } + return *a == '\0' || isspace((unsigned char)*a); } static void abort_hunk(void) { - LINENUM i; - LINENUM pat_line; - char *str; - ssize_t len; + LINENUM i; - for (i = 1; i <= pch_end(); i++) { - pat_line = i; - str = pfetch(pat_line); - len = pch_line_len(pat_line); - rej_line(pat_line, i); - } + for (i = 1; i <= pch_end(); i++) + rej_line(i, i); } static void rej_line(int pat_line, LINENUM i) { - char *str = pfetch(pat_line); - char ch = pch_char(pat_line); - if (rejfp != NULL) { - if (ch == ' ') - fprintf(rejfp, " %s", str); - else - fprintf(rejfp, "%c%s", ch, str); - } -} - -static void -abort_context_hunk(void) -{ - LINENUM i; - for (i = 0; i <= pch_end(); i++) { - rej_line(i, i); - } + char *str = pfetch(pat_line); + char ch = pch_char(pat_line); + (void)i; + if (rejfp != NULL) { + if (ch == ' ') + fprintf(rejfp, " %s", str); + else + fprintf(rejfp, "%c%s", ch, str); + } } static void apply_hunk(LINENUM where) { - LINENUM old = 1; - const LINENUM lastline = pch_ptrn_lines(); - LINENUM new = lastline + 1; + LINENUM old = 1; + const LINENUM lastline = pch_ptrn_lines(); + LINENUM new = lastline + 1; #define OUTSIDE 0 #define IN_IFNDEF 1 #define IN_IFDEF 2 #define IN_ELSE 3 - int def_state = OUTSIDE; - const LINENUM pat_end = pch_end(); - - where--; - while (pch_char(new) == '=' || pch_char(new) == '\n') - new++; - - while (old <= lastline) { - if (pch_char(old) == '-') { - copy_till(where + old - 1, 0); - if (do_defines) { - if (def_state == OUTSIDE) { - fputs(not_defined, ofp); - def_state = IN_IFNDEF; - } else if (def_state == IN_IFDEF) { - fputs(else_defined, ofp); - def_state = IN_ELSE; - } - fputs(pfetch(old), ofp); - } - last_frozen_line++; - old++; - } else if (new > pat_end) { - break; - } else if (pch_char(new) == '+') { - copy_till(where + old - 1, 0); - if (do_defines) { - if (def_state == IN_IFNDEF) { - fputs(else_defined, ofp); - def_state = IN_ELSE; - } else if (def_state == OUTSIDE) { - fputs(if_defined, ofp); - def_state = IN_IFDEF; - } - } - fputs(pfetch(new), ofp); - new++; - } else if (pch_char(new) != pch_char(old)) { - say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n", - pch_hunk_beg() + old, - pch_hunk_beg() + new); - my_exit(2); - } else if (pch_char(new) == '!') { - copy_till(where + old - 1, 0); - if (do_defines) { - fputs(not_defined, ofp); - def_state = IN_IFNDEF; - } - while (pch_char(old) == '!') { - if (do_defines) { - fputs(pfetch(old), ofp); - } - last_frozen_line++; - old++; - } - if (do_defines) { - fputs(else_defined, ofp); - def_state = IN_ELSE; - } - while (pch_char(new) == '!') { - fputs(pfetch(new), ofp); - new++; - } - } else { - if (pch_char(new) != ' ') - fatal("Internal error: expected ' '\n"); - old++; - new++; - if (do_defines && def_state != OUTSIDE) { - fputs(end_defined, ofp); - def_state = OUTSIDE; - } - } - } - if (new <= pat_end && pch_char(new) == '+') { - copy_till(where + old - 1, 0); - if (do_defines) { - if (def_state == OUTSIDE) { - fputs(if_defined, ofp); - def_state = IN_IFDEF; - } else if (def_state == IN_IFNDEF) { - fputs(else_defined, ofp); - def_state = IN_ELSE; - } - } - while (new <= pat_end && pch_char(new) == '+') { - fputs(pfetch(new), ofp); - new++; - } - } - if (do_defines && def_state != OUTSIDE) { - fputs(end_defined, ofp); - } + int def_state = OUTSIDE; + const LINENUM pat_end = pch_end(); + + where--; + while (pch_char(new) == '=' || pch_char(new) == '\n') + new++; + + while (old <= lastline) { + if (pch_char(old) == '-') { + copy_till(where + old - 1, 0); + if (do_defines) { + if (def_state == OUTSIDE) { + fputs(not_defined, ofp); + def_state = IN_IFNDEF; + } else if (def_state == IN_IFDEF) { + fputs(else_defined, ofp); + def_state = IN_ELSE; + } + fputs(pfetch(old), ofp); + } + last_frozen_line++; + old++; + } else if (new > pat_end) { + break; + } else if (pch_char(new) == '+') { + copy_till(where + old - 1, 0); + if (do_defines) { + if (def_state == IN_IFNDEF) { + fputs(else_defined, ofp); + def_state = IN_ELSE; + } else if (def_state == OUTSIDE) { + fputs(if_defined, ofp); + def_state = IN_IFDEF; + } + } + fputs(pfetch(new), ofp); + new++; + } else if (pch_char(new) != pch_char(old)) { + say("Out-of-sync patch, lines %ld,%ld--mangled text or line numbers, maybe?\n", + pch_hunk_beg() + old, + pch_hunk_beg() + new); + my_exit(2); + } else if (pch_char(new) == '!') { + copy_till(where + old - 1, 0); + if (do_defines) { + fputs(not_defined, ofp); + def_state = IN_IFNDEF; + } + while (pch_char(old) == '!') { + if (do_defines) { + fputs(pfetch(old), ofp); + } + last_frozen_line++; + old++; + } + if (do_defines) { + fputs(else_defined, ofp); + def_state = IN_ELSE; + } + while (pch_char(new) == '!') { + fputs(pfetch(new), ofp); + new++; + } + } else { + if (pch_char(new) != ' ') + fatal("Internal error: expected ' '\n"); + old++; + new++; + if (do_defines && def_state != OUTSIDE) { + fputs(end_defined, ofp); + def_state = OUTSIDE; + } + } + } + if (new <= pat_end && pch_char(new) == '+') { + copy_till(where + old - 1, 0); + if (do_defines) { + if (def_state == OUTSIDE) { + fputs(if_defined, ofp); + def_state = IN_IFDEF; + } else if (def_state == IN_IFNDEF) { + fputs(else_defined, ofp); + def_state = IN_ELSE; + } + } + while (new <= pat_end && pch_char(new) == '+') { + fputs(pfetch(new), ofp); + new++; + } + } + if (do_defines && def_state != OUTSIDE) { + fputs(end_defined, ofp); + } #undef OUTSIDE #undef IN_IFNDEF #undef IN_IFDEF @@ -959,2192 +942,2178 @@ apply_hunk(LINENUM where) static void dump_input_line(LINENUM line, int write_newline) { - char *s = ifetch(line, 0); - if (s == NULL) - return; - for (; *s != '\n' && *s != '\0'; s++) - putc(*s, ofp); - if (write_newline) - putc('\n', ofp); + char *s = ifetch(line, 0); + if (s == NULL) + return; + for (; *s != '\n' && *s != '\0'; s++) + putc(*s, ofp); + if (write_newline) + putc('\n', ofp); } static void copy_till(LINENUM line, int end) { - if (last_frozen_line > line) - fatal("misordered hunks! output would be garbled\n"); - while (last_frozen_line < line) { - if (++last_frozen_line == line && end) - dump_input_line(last_frozen_line, !last_line_missing_eol); - else - dump_input_line(last_frozen_line, 1); - } + if (last_frozen_line > line) + fatal("misordered hunks! output would be garbled\n"); + while (last_frozen_line < line) { + if (++last_frozen_line == line && end) + dump_input_line(last_frozen_line, !last_line_missing_eol); + else + dump_input_line(last_frozen_line, 1); + } } static int spew_output(void) { - if (input_lines) - copy_till(input_lines, 1); - if (ferror(ofp) || fclose(ofp)) - return 0; - ofp = NULL; - return 1; + if (input_lines) + copy_till(input_lines, 1); + if (ferror(ofp) || fclose(ofp)) + return 0; + ofp = NULL; + return 1; } static void init_output(const char *name) { - ofp = fopen(name, "w"); - if (ofp == NULL) - pfatal("cant create %s", name); + ofp = fopen(name, "w"); + if (ofp == NULL) + pfatal("cant create %s", name); } static void init_reject(const char *name) { - rejfp = fopen(name, "w"); - if (rejfp == NULL) - pfatal("cant create %s", name); + rejfp = fopen(name, "w"); + if (rejfp == NULL) + pfatal("cant create %s", name); } void re_input(void) { - if (using_plan_a) { - i_size = 0; - free(i_ptr); - i_ptr = NULL; - if (i_womp != NULL) { - munmap(i_womp, i_size); - i_womp = NULL; - } - } else { - using_plan_a = 1; - close(tifd); - tifd = -1; - free(tibuf[0]); - free(tibuf[1]); - tibuf[0] = tibuf[1] = NULL; - tiline[0] = tiline[1] = -1; - tireclen = 0; - } + if (using_plan_a) { + i_size = 0; + free(i_ptr); + i_ptr = NULL; + if (i_womp != NULL) { + munmap(i_womp, i_size); + i_womp = NULL; + } + } else { + using_plan_a = 1; + close(tifd); + tifd = -1; + free(tibuf[0]); + free(tibuf[1]); + tibuf[0] = tibuf[1] = NULL; + tiline[0] = tiline[1] = -1; + tireclen = 0; + } } void scan_input(const char *filename) { - if (!plan_a(filename)) - plan_b(filename); - if (verbose) { - say("Patching file %s using Plan %s...\n", filename, (using_plan_a ? "A" : "B")); - } + if (!plan_a(filename)) + plan_b(filename); + if (verbose) { + say("Patching file %s using Plan %s...\n", filename, (using_plan_a ? "A" : "B")); + } } static int reallocate_lines(size_t *lines_allocated) { - char **p; - size_t new_size; + char **p; + size_t new_size; - new_size = *lines_allocated * 3 / 2; - p = pch_realloc(i_ptr, new_size + 2, sizeof(char *)); - if (p == NULL) { - munmap(i_womp, i_size); - i_womp = NULL; - free(i_ptr); - i_ptr = NULL; - *lines_allocated = 0; - return 0; - } - *lines_allocated = new_size; - i_ptr = p; - return 1; + new_size = *lines_allocated * 3 / 2; + p = pch_realloc(i_ptr, new_size + 2, sizeof(char *)); + if (p == NULL) { + munmap(i_womp, i_size); + i_womp = NULL; + free(i_ptr); + i_ptr = NULL; + *lines_allocated = 0; + return 0; + } + *lines_allocated = new_size; + i_ptr = p; + return 1; } static int plan_a(const char *filename) { - int ifd, statfailed, devnull, pstat; - char *p, *s, *lbuf; - struct stat filestat; - off_t i; - ptrdiff_t sz; - size_t iline, lines_allocated, lbufsz; - pid_t pid; - char *argp[4] = {NULL}; + int ifd, statfailed; + char *p, *s, *lbuf; + struct stat filestat; + off_t i; + ptrdiff_t sz; + size_t iline, lines_allocated, lbufsz; #ifdef DEBUGGING - if (debug & 8) - return 0; + if (debug & 8) + return 0; #endif - if (filename == NULL || *filename == '\0') - return 0; - - statfailed = stat(filename, &filestat); - if (statfailed && ok_to_create_file) { - if (verbose) - say("(Creating file %s...)\n", filename); - if (check_only) - return 1; - makedirs(filename, 1); - close(creat(filename, 0666)); - statfailed = stat(filename, &filestat); - } - if (statfailed && check_only) - fatal("%s not found, -C mode, cant probe further\n", filename); - - if (statfailed || (filestat.st_mode & 0222) == 0 || - ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) { - char *filebase, *filedir; - struct stat cstat; - char *tmp_filename1, *tmp_filename2; - - tmp_filename1 = strdup(filename); - tmp_filename2 = strdup(filename); - if (tmp_filename1 == NULL || tmp_filename2 == NULL) - fatal("strdupping filename"); - filebase = basename(tmp_filename1); - filedir = dirname(tmp_filename2); - - lbufsz = INITLINELEN; - if ((lbuf = malloc(bufsz)) == NULL) - pfatal("allocating line buffer"); - lbuf[0] = '\0'; + if (filename == NULL || *filename == '\0') + return 0; + + statfailed = stat(filename, &filestat); + if (statfailed && ok_to_create_file) { + if (verbose) + say("(Creating file %s...)\n", filename); + if (check_only) + return 1; + makedirs(filename, 1); + close(creat(filename, 0666)); + statfailed = stat(filename, &filestat); + } + if (statfailed && check_only) + fatal("%s not found, -C mode, cant probe further\n", filename); + + if (statfailed || (filestat.st_mode & 0222) == 0 || + ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) { + char *filebase, *filedir; + struct stat cstat; + char *tmp_filename1, *tmp_filename2; + + tmp_filename1 = strdup(filename); + tmp_filename2 = strdup(filename); + if (tmp_filename1 == NULL || tmp_filename2 == NULL) + fatal("strdupping filename"); + filebase = basename(tmp_filename1); + filedir = dirname(tmp_filename2); + + lbufsz = INITLINELEN; + if ((lbuf = malloc(bufsz)) == NULL) + pfatal("allocating line buffer"); + lbuf[0] = '\0'; #define try(f, a1, a2, a3) \ - (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &cstat) == 0) - - if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) || - try("%s/RCS/%s%s", filedir, filebase, "") || - try("%s/%s%s", filedir, filebase, RCSSUFFIX)) { - if (!statfailed) { - if ((filestat.st_mode & 0222) != 0) - fatal("file %s seems to be locked by somebody else under RCS\n", filename); - if (verbose) - say("Comparing file %s to default RCS version...\n", filename); - switch (pid = fork()) { - case -1: - fatal("cant fork: %s\n", strerror(errno)); - case 0: - devnull = open("/dev/null", O_RDONLY); - if (devnull == -1) - fatal("cant open /dev/null: %s", strerror(errno)); - dup2(devnull, STDOUT_FILENO); - argp[0] = __UNCONST(RCSDIFF); - argp[1] = __UNCONST(filename); - execv(RCSDIFF, argp); - exit(127); - } - pid = waitpid(pid, &pstat, 0); - if (pid == -1 || WEXITSTATUS(pstat) != 0) - fatal("cant check out file %s: differs from default RCS version\n", filename); - } - if (verbose) - say("Checking out file %s from RCS...\n", filename); - switch (pid = fork()) { - case -1: - fatal("cant fork: %s\n", strerror(errno)); - case 0: - argp[0] = __UNCONST(CHECKOUT); - argp[1] = __UNCONST("-l"); - argp[2] = __UNCONST(filename); - execv(CHECKOUT, argp); - exit(127); - } - pid = waitpid(pid, &pstat, 0); - if (pid == -1 || WEXITSTATUS(pstat) != 0 || stat(filename, &filestat)) - fatal("cant check out file %s from RCS\n", filename); - } else if (statfailed) { - fatal("cant find %s\n", filename); - } + (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &cstat) == 0) + + if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) || + try("%s/RCS/%s%s", filedir, filebase, "") || + try("%s/%s%s", filedir, filebase, RCSSUFFIX)) { + if (!statfailed) { + if ((filestat.st_mode & 0222) != 0) + fatal("file %s seems to be locked by somebody else under RCS\n", filename); + if (verbose) + say("Comparing file %s to default RCS version...\n", filename); + { + char *rcsdiff_argv[3]; + rcsdiff_argv[0] = __UNCONST(RCSDIFF); + rcsdiff_argv[1] = __UNCONST(filename); + rcsdiff_argv[2] = NULL; + if (wexecvp(RCSDIFF, rcsdiff_argv) != 0) + fatal("cant check out file %s: differs from default RCS version\n", filename); + } + } + if (verbose) + say("Checking out file %s from RCS...\n", filename); + { + char *co_argv[4]; + co_argv[0] = __UNCONST(CHECKOUT); + co_argv[1] = __UNCONST("-l"); + co_argv[2] = __UNCONST(filename); + co_argv[3] = NULL; + if (wexecvp(CHECKOUT, co_argv) != 0 || stat(filename, &filestat)) + fatal("cant check out file %s from RCS\n", filename); + } + } else if (statfailed) { + fatal("cant find %s\n", filename); + } #undef try - free(lbuf); - free(tmp_filename1); - free(tmp_filename2); - } - - filemode = filestat.st_mode; - if (!S_ISREG(filemode)) - fatal("%s is not a normal file--cant patch\n", filename); - i_size = filestat.st_size; - if (out_of_mem) { - set_hunkmax(); - out_of_mem = 0; - return 0; - } - if ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) { - say("block too large to mmap\n"); - return 0; - } - if ((ifd = open(filename, O_RDONLY)) < 0) - pfatal("cant open file %s", filename); - - if (i_size) { - i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0); - if (i_womp == MAP_FAILED) { - perror("mmap failed"); - i_womp = NULL; - close(ifd); - return 0; - } - } else - i_womp = NULL; - - close(ifd); - if (i_size) - madvise(i_womp, i_size, MADV_SEQUENTIAL); - - lines_allocated = i_size / 25; - if (lines_allocated < 100) - lines_allocated = 100; - - if (!reallocate_lines(&lines_allocated)) - return 0; - - iline = 1; - i_ptr[iline] = i_womp; - for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) { - if (*s == '\n') { - if (iline == lines_allocated) { - if (!reallocate_lines(&lines_allocated)) - return 0; - } - i_ptr[++iline] = s + 1; - } - } - if (i_size > 0 && i_womp[i_size - 1] != '\n') { - last_line_missing_eol = 1; - sz = s - i_ptr[iline]; - p = malloc(sz + 1); - if (p == NULL) { - free(i_ptr); - i_ptr = NULL; - munmap(i_womp, i_size); - i_womp = NULL; - return 0; - } - memcpy(p, i_ptr[iline], sz); - p[sz] = '\n'; - i_ptr[iline] = p; - i_ptr[++iline] = empty_line; - } else - last_line_missing_eol = 0; - - input_lines = iline - 1; - - if (revision != NULL) { - if (!rev_in_string(i_womp)) { - if (force) { - if (verbose) - say("Warning: this file doesnt appear to be the %s version--patching anyway\n", revision); - } else if (batch) { - fatal("this file doesnt appear to be the %s version--aborting\n", revision); - } else { - ask("This file doesnt appear to be the %s version--patch anyway? [n] ", revision); - if (*buf != 'y') - fatal("aborted\n"); - } - } else if (verbose) - say("Good. This file appears to be the %s version.\n", revision); - } - return 1; + free(lbuf); + free(tmp_filename1); + free(tmp_filename2); + } + + filemode = filestat.st_mode; + if (!S_ISREG(filemode)) + fatal("%s is not a normal file--cant patch\n", filename); + i_size = filestat.st_size; + if (out_of_mem) { + set_hunkmax(); + out_of_mem = 0; + return 0; + } + if ((uintmax_t)i_size > (uintmax_t)SIZE_MAX) { + say("block too large to mmap\n"); + return 0; + } + if ((ifd = open(filename, O_RDONLY)) < 0) + pfatal("cant open file %s", filename); + + if (i_size) { + i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0); + if (i_womp == MAP_FAILED) { + perror("mmap failed"); + i_womp = NULL; + close(ifd); + return 0; + } + } else + i_womp = NULL; + + close(ifd); + if (i_size) + madvise(i_womp, i_size, MADV_SEQUENTIAL); + + lines_allocated = i_size / 25; + if (lines_allocated < 100) + lines_allocated = 100; + + if (!reallocate_lines(&lines_allocated)) + return 0; + + iline = 1; + i_ptr[iline] = i_womp; + for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) { + if (*s == '\n') { + if (iline == lines_allocated) { + if (!reallocate_lines(&lines_allocated)) + return 0; + } + i_ptr[++iline] = s + 1; + } + } + if (i_size > 0 && i_womp[i_size - 1] != '\n') { + last_line_missing_eol = 1; + sz = s - i_ptr[iline]; + p = malloc(sz + 1); + if (p == NULL) { + free(i_ptr); + i_ptr = NULL; + munmap(i_womp, i_size); + i_womp = NULL; + return 0; + } + memcpy(p, i_ptr[iline], sz); + p[sz] = '\n'; + i_ptr[iline] = p; + i_ptr[++iline] = empty_line; + } else + last_line_missing_eol = 0; + + input_lines = iline - 1; + + if (revision != NULL) { + if (!rev_in_string(i_womp)) { + if (force) { + if (verbose) + say("Warning: this file doesnt appear to be the %s version--patching anyway\n", revision); + } else if (batch) { + fatal("this file doesnt appear to be the %s version--aborting\n", revision); + } else { + ask("This file doesnt appear to be the %s version--patch anyway? [n] ", revision); + if (*buf != 'y') + fatal("aborted\n"); + } + } else if (verbose) + say("Good. This file appears to be the %s version.\n", revision); + } + return 1; } static void plan_b(const char *filename) { - FILE *ifp; - size_t i = 0, j, maxlen = 1; - char *p; - int found_revision = (revision == NULL); - - using_plan_a = 0; - if ((ifp = fopen(filename, "r")) == NULL) - pfatal("cant open file %s", filename); - unlink(TMPINNAME); - if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0) - pfatal("cant open file %s", TMPINNAME); - while (getline(&buf, &bufsz, ifp) != -1) { - if (revision != NULL && !found_revision && rev_in_string(buf)) - found_revision = 1; - if ((i = strlen(buf)) > maxlen) - maxlen = i; - } - last_line_missing_eol = i > 0 && buf[i - 1] != '\n'; - if (last_line_missing_eol && maxlen == i) - maxlen++; - - if (revision != NULL) { - if (!found_revision) { - if (force) { - if (verbose) - say("Warning: this file doesnt appear to be the %s version--patching anyway\n", revision); - } else if (batch) { - fatal("this file doesnt appear to be the %s version--aborting\n", revision); - } else { - ask("This file doesnt appear to be the %s version--patch anyway? [n] ", revision); - if (*buf != 'y') - fatal("aborted\n"); - } - } else if (verbose) - say("Good. This file appears to be the %s version.\n", revision); - } - fseek(ifp, 0L, SEEK_SET); - lines_per_buf = BUFFERSIZE / maxlen; - tireclen = maxlen; - tibuf[0] = malloc(BUFFERSIZE + 1); - if (tibuf[0] == NULL) - fatal("out of memory\n"); - tibuf[1] = malloc(BUFFERSIZE + 1); - if (tibuf[1] == NULL) - fatal("out of memory\n"); - for (i = 1;; i++) { - p = tibuf[0] + maxlen * (i % lines_per_buf); - if (i % lines_per_buf == 0) { - if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE) - pfatal("cant write temp file"); - } - if (fgets(p, maxlen + 1, ifp) == NULL) { - input_lines = i - 1; - if (i % lines_per_buf != 0) { - if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE) - pfatal("cant write temp file"); - } - break; - } - j = strlen(p); - if (j == 0 || p[j - 1] != '\n') - p[j] = '\n'; - } - fclose(ifp); - close(tifd); - if ((tifd = open(TMPINNAME, O_RDONLY)) < 0) - pfatal("cant reopen file %s", TMPINNAME); + FILE *ifp; + size_t i = 0, j, maxlen = 1; + char *p; + int found_revision = (revision == NULL); + + using_plan_a = 0; + if ((ifp = fopen(filename, "r")) == NULL) + pfatal("cant open file %s", filename); + unlink(TMPINNAME); + if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0) + pfatal("cant open file %s", TMPINNAME); + while (getline(&buf, &bufsz, ifp) != -1) { + if (revision != NULL && !found_revision && rev_in_string(buf)) + found_revision = 1; + if ((i = strlen(buf)) > maxlen) + maxlen = i; + } + last_line_missing_eol = i > 0 && buf[i - 1] != '\n'; + if (last_line_missing_eol && maxlen == i) + maxlen++; + + if (revision != NULL) { + if (!found_revision) { + if (force) { + if (verbose) + say("Warning: this file doesnt appear to be the %s version--patching anyway\n", revision); + } else if (batch) { + fatal("this file doesnt appear to be the %s version--aborting\n", revision); + } else { + ask("This file doesnt appear to be the %s version--patch anyway? [n] ", revision); + if (*buf != 'y') + fatal("aborted\n"); + } + } else if (verbose) + say("Good. This file appears to be the %s version.\n", revision); + } + fseek(ifp, 0L, SEEK_SET); + lines_per_buf = BUFFERSIZE / maxlen; + tireclen = maxlen; + tibuf[0] = malloc(BUFFERSIZE + 1); + if (tibuf[0] == NULL) + fatal("out of memory\n"); + tibuf[1] = malloc(BUFFERSIZE + 1); + if (tibuf[1] == NULL) + fatal("out of memory\n"); + for (i = 1;; i++) { + p = tibuf[0] + maxlen * (i % lines_per_buf); + if (i % lines_per_buf == 0) { + if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE) + pfatal("cant write temp file"); + } + if (fgets(p, maxlen + 1, ifp) == NULL) { + input_lines = i - 1; + if (i % lines_per_buf != 0) { + if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE) + pfatal("cant write temp file"); + } + break; + } + j = strlen(p); + if (j == 0 || p[j - 1] != '\n') + p[j] = '\n'; + } + fclose(ifp); + close(tifd); + if ((tifd = open(TMPINNAME, O_RDONLY)) < 0) + pfatal("cant reopen file %s", TMPINNAME); } char * ifetch(LINENUM line, int whichbuf) { - if (line < 1 || line > input_lines) { - if (warn_on_invalid_line) { - say("No such line %ld in input file, ignoring\n", line); - warn_on_invalid_line = 0; - } - return NULL; - } - if (using_plan_a) - return i_ptr[line]; - else { - LINENUM offline = line % lines_per_buf; - LINENUM baseline = line - offline; - - if (tiline[0] == baseline) - whichbuf = 0; - else if (tiline[1] == baseline) - whichbuf = 1; - else { - tiline[whichbuf] = baseline; - if (lseek(tifd, (off_t)(baseline / lines_per_buf * BUFFERSIZE), SEEK_SET) < 0) - pfatal("cannot seek in the temporary input file"); - if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0) - pfatal("error reading tmp file %s", TMPINNAME); - } - return tibuf[whichbuf] + (tireclen * offline); - } + if (line < 1 || line > input_lines) { + if (warn_on_invalid_line) { + say("No such line %ld in input file, ignoring\n", line); + warn_on_invalid_line = 0; + } + return NULL; + } + if (using_plan_a) + return i_ptr[line]; + else { + LINENUM offline = line % lines_per_buf; + LINENUM baseline = line - offline; + + if (tiline[0] == baseline) + whichbuf = 0; + else if (tiline[1] == baseline) + whichbuf = 1; + else { + tiline[whichbuf] = baseline; + if (lseek(tifd, (off_t)(baseline / lines_per_buf * BUFFERSIZE), SEEK_SET) < 0) + pfatal("cannot seek in the temporary input file"); + if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0) + pfatal("error reading tmp file %s", TMPINNAME); + } + return tibuf[whichbuf] + (tireclen * offline); + } } static int rev_in_string(const char *string) { - const char *s; - size_t patlen; + const char *s; + size_t patlen; - if (revision == NULL) - return 1; - patlen = strlen(revision); - if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen])) - return 1; - for (s = string; *s; s++) { - if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) && - isspace((unsigned char)s[patlen + 1])) - return 1; - } - return 0; + if (revision == NULL) + return 1; + patlen = strlen(revision); + if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen])) + return 1; + for (s = string; *s; s++) { + if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) && + isspace((unsigned char)s[patlen + 1])) + return 1; + } + return 0; } void re_patch(void) { - p_first = 0; - p_newfirst = 0; - p_ptrn_lines = 0; - p_repl_lines = 0; - p_end = (LINENUM)-1; - p_max = 0; - p_indent = 0; + p_first = 0; + p_newfirst = 0; + p_ptrn_lines = 0; + p_repl_lines = 0; + p_end = (LINENUM)-1; + p_max = 0; + p_indent = 0; } void open_patch_file(const char *filename) { - struct stat filestat; - - if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) { - pfp = fopen(TMPPATNAME, "w"); - if (pfp == NULL) - pfatal("cant create %s", TMPPATNAME); - while (getline(&buf, &bufsz, stdin) != -1) - fprintf(pfp, "%s", buf); - if (ferror(pfp) || fclose(pfp)) - pfatal("cant write %s", TMPPATNAME); - filename = TMPPATNAME; - } - pfp = fopen(filename, "r"); - if (pfp == NULL) - pfatal("patch file %s not found", filename); - fstat(fileno(pfp), &filestat); - p_filesize = filestat.st_size; - next_intuit_at(0L, 1L); - set_hunkmax(); + struct stat filestat; + + if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) { + pfp = fopen(TMPPATNAME, "w"); + if (pfp == NULL) + pfatal("cant create %s", TMPPATNAME); + while (getline(&buf, &bufsz, stdin) != -1) + fprintf(pfp, "%s", buf); + if (ferror(pfp) || fclose(pfp)) + pfatal("cant write %s", TMPPATNAME); + filename = TMPPATNAME; + } + pfp = fopen(filename, "r"); + if (pfp == NULL) + pfatal("patch file %s not found", filename); + fstat(fileno(pfp), &filestat); + p_filesize = filestat.st_size; + next_intuit_at(0L, 1L); + set_hunkmax(); } void set_hunkmax(void) { - if (p_line == NULL) - p_line = calloc((size_t)hunkmax, sizeof(char *)); - if (p_len == NULL) - p_len = calloc((size_t)hunkmax, sizeof(ssize_t)); - if (p_char == NULL) - p_char = calloc((size_t)hunkmax, sizeof(char)); + if (p_line == NULL) + p_line = calloc((size_t)hunkmax, sizeof(char *)); + if (p_len == NULL) + p_len = calloc((size_t)hunkmax, sizeof(ssize_t)); + if (p_char == NULL) + p_char = calloc((size_t)hunkmax, sizeof(char)); } static void grow_hunkmax(void) { - int new_hunkmax; - char **new_p_line; - ssize_t *new_p_len; - char *new_p_char; + int new_hunkmax; + char **new_p_line; + ssize_t *new_p_len; + char *new_p_char; - new_hunkmax = hunkmax * 2; - if (p_line == NULL || p_len == NULL || p_char == NULL) - fatal("Internal memory allocation error\n"); + new_hunkmax = hunkmax * 2; + if (p_line == NULL || p_len == NULL || p_char == NULL) + fatal("Internal memory allocation error\n"); - new_p_line = pch_realloc(p_line, new_hunkmax, sizeof(char *)); - if (new_p_line == NULL) - free(p_line); - new_p_len = pch_realloc(p_len, new_hunkmax, sizeof(ssize_t)); - if (new_p_len == NULL) - free(p_len); - new_p_char = pch_realloc(p_char, new_hunkmax, sizeof(char)); - if (new_p_char == NULL) - free(p_char); + new_p_line = pch_realloc(p_line, new_hunkmax, sizeof(char *)); + if (new_p_line == NULL) + free(p_line); + new_p_len = pch_realloc(p_len, new_hunkmax, sizeof(ssize_t)); + if (new_p_len == NULL) + free(p_len); + new_p_char = pch_realloc(p_char, new_hunkmax, sizeof(char)); + if (new_p_char == NULL) + free(p_char); - p_char = new_p_char; - p_len = new_p_len; - p_line = new_p_line; + p_char = new_p_char; + p_len = new_p_len; + p_line = new_p_line; - if (p_line != NULL && p_len != NULL && p_char != NULL) { - hunkmax = new_hunkmax; - return; - } + if (p_line != NULL && p_len != NULL && p_char != NULL) { + hunkmax = new_hunkmax; + return; + } - if (!using_plan_a) - fatal("out of memory\n"); - out_of_mem = 1; + if (!using_plan_a) + fatal("out of memory\n"); + out_of_mem = 1; } int there_is_another_patch(void) { - int exists = 0; - - if (p_base != 0L && p_base >= p_filesize) { - if (verbose) - say("done\n"); - return 0; - } - if (verbose) - say("Hmm..."); - diff_type = intuit_diff_type(); - if (!diff_type) { - if (p_base != 0L) { - if (verbose) - say(" Ignoring the trailing garbage.\ndone\n"); - } else - say(" I cant seem to find a patch in there anywhere\n"); - return 0; - } - if (verbose) { - say(" %sooks like %s to me...\n", - (p_base == 0L ? "L" : "The next patch l"), - diff_type == UNI_DIFF ? "a unified diff" : - diff_type == CONTEXT_DIFF ? "a context diff" : - diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" : - diff_type == NORMAL_DIFF ? "a normal diff" : "an ed script"); - } - if (p_indent && verbose) - say("(Patch is indented %d space%s.)\n", p_indent, p_indent == 1 ? "" : "s"); - skip_to(p_start, p_sline); - while (filearg[0] == NULL) { - if (force || batch) { - say("No file to patch. Skipping...\n"); - filearg[0] = savestr(bestguess); - skip_rest_of_patch = 1; - return 1; - } - ask("File to patch: "); - if (*buf != '\n') { - free(bestguess); - bestguess = savestr(buf); - filearg[0] = fetchname(buf, &exists, 0); - } - if (!exists) { - ask("No file found--skip this patch? [n] "); - if (*buf != 'y') - continue; - if (verbose) - say("Skipping patch...\n"); - free(filearg[0]); - filearg[0] = fetchname(bestguess, &exists, 0); - skip_rest_of_patch = 1; - return 1; - } - } - return 1; + int exists = 0; + + if (p_base != 0L && p_base >= p_filesize) { + if (verbose) + say("done\n"); + return 0; + } + if (verbose) + say("Hmm..."); + diff_type = intuit_diff_type(); + if (!diff_type) { + if (p_base != 0L) { + if (verbose) + say(" Ignoring the trailing garbage.\ndone\n"); + } else + say(" I cant seem to find a patch in there anywhere\n"); + return 0; + } + if (verbose) { + say(" %sooks like %s to me...\n", + (p_base == 0L ? "L" : "The next patch l"), + diff_type == UNI_DIFF ? "a unified diff" : + diff_type == CONTEXT_DIFF ? "a context diff" : + diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" : + diff_type == NORMAL_DIFF ? "a normal diff" : "an ed script"); + } + if (p_indent && verbose) + say("(Patch is indented %d space%s.)\n", p_indent, p_indent == 1 ? "" : "s"); + skip_to(p_start, p_sline); + while (filearg[0] == NULL) { + if (force || batch) { + say("No file to patch. Skipping...\n"); + filearg[0] = savestr(bestguess); + skip_rest_of_patch = 1; + return 1; + } + ask("File to patch: "); + if (*buf != '\n') { + free(bestguess); + bestguess = savestr(buf); + filearg[0] = fetchname(buf, &exists, 0); + } + if (!exists) { + ask("No file found--skip this patch? [n] "); + if (*buf != 'y') + continue; + if (verbose) + say("Skipping patch...\n"); + free(filearg[0]); + filearg[0] = fetchname(bestguess, &exists, 0); + skip_rest_of_patch = 1; + return 1; + } + } + return 1; } static int intuit_diff_type(void) { - long this_line = 0, previous_line; - long first_command_line = -1; - LINENUM fcl_line = -1; - int last_line_was_command = 0, this_is_a_command = 0; - int stars_last_line = 0, stars_this_line = 0; - char *s, *t; - int indent, retval; - struct FileName names[MAX_FILE]; - - memset(names, 0, sizeof(names)); - ok_to_create_file = 0; - fseek(pfp, p_base, SEEK_SET); - p_input_line = p_bline - 1; - for (;;) { - previous_line = this_line; - last_line_was_command = this_is_a_command; - stars_last_line = stars_this_line; - this_line = ftell(pfp); - indent = 0; - p_input_line++; - if (getline(&buf, &bufsz, pfp) == -1) { - if (first_command_line >= 0L) { - p_start = first_command_line; - p_sline = fcl_line; - retval = ED_DIFF; - goto scan_exit; - } else { - p_start = this_line; - p_sline = p_input_line; - retval = 0; - goto scan_exit; - } - } - for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { - if (*s == '\t') - indent += 8 - (indent % 8); - else - indent++; - } - for (t = s; isdigit((unsigned char)*t) || *t == ','; t++) - ; - this_is_a_command = (isdigit((unsigned char)*s) && (*t == 'd' || *t == 'c' || *t == 'a')); - if (first_command_line < 0L && this_is_a_command) { - first_command_line = this_line; - fcl_line = p_input_line; - p_indent = indent; - } - if (!stars_last_line && strnEQ(s, "*** ", 4)) { - names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath); - } else if (strnEQ(s, "--- ", 4)) { - names[NEW_FILE].path = fetchname(s + 4, &names[NEW_FILE].exists, strippath); - } else if (strnEQ(s, "+++ ", 4)) { - names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath); - } else if (strnEQ(s, "Index:", 6)) { - names[INDEX_FILE].path = fetchname(s + 6, &names[INDEX_FILE].exists, strippath); - } else if (strnEQ(s, "Prereq:", 7)) { - for (t = s + 7; isspace((unsigned char)*t); t++) - ; - revision = savestr(t); - for (t = revision; *t && !isspace((unsigned char)*t); t++) - ; - *t = '\0'; - if (*revision == '\0') { - free(revision); - revision = NULL; - } - } - if ((!diff_type || diff_type == ED_DIFF) && first_command_line >= 0L && strEQ(s, ".\n")) { - p_indent = indent; - p_start = first_command_line; - p_sline = fcl_line; - retval = ED_DIFF; - goto scan_exit; - } - if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { - if (strnEQ(s + 4, "0,0", 3)) - ok_to_create_file = 1; - p_indent = indent; - p_start = this_line; - p_sline = p_input_line; - retval = UNI_DIFF; - goto scan_exit; - } - stars_this_line = strnEQ(s, "********", 8); - if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line && strnEQ(s, "*** ", 4)) { - if (atol(s + 4) == 0) - ok_to_create_file = 1; - while (*s != '\n') - s++; - p_indent = indent; - p_start = previous_line; - p_sline = p_input_line - 1; - retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); - goto scan_exit; - } - if ((!diff_type || diff_type == NORMAL_DIFF) && last_line_was_command && - (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) { - p_start = previous_line; - p_sline = p_input_line - 1; - p_indent = indent; - retval = NORMAL_DIFF; - goto scan_exit; - } - } + long this_line = 0, previous_line; + long first_command_line = -1; + LINENUM fcl_line = -1; + int last_line_was_command = 0, this_is_a_command = 0; + int stars_last_line = 0, stars_this_line = 0; + char *s, *t; + int indent, retval; + struct FileName names[MAX_FILE]; + + memset(names, 0, sizeof(names)); + ok_to_create_file = 0; + fseek(pfp, p_base, SEEK_SET); + p_input_line = p_bline - 1; + for (;;) { + previous_line = this_line; + last_line_was_command = this_is_a_command; + stars_last_line = stars_this_line; + this_line = ftell(pfp); + indent = 0; + p_input_line++; + if (getline(&buf, &bufsz, pfp) == -1) { + if (first_command_line >= 0L) { + p_start = first_command_line; + p_sline = fcl_line; + retval = ED_DIFF; + goto scan_exit; + } else { + p_start = this_line; + p_sline = p_input_line; + retval = 0; + goto scan_exit; + } + } + for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) { + if (*s == '\t') + indent += 8 - (indent % 8); + else + indent++; + } + for (t = s; isdigit((unsigned char)*t) || *t == ','; t++) + ; + this_is_a_command = (isdigit((unsigned char)*s) && (*t == 'd' || *t == 'c' || *t == 'a')); + if (first_command_line < 0L && this_is_a_command) { + first_command_line = this_line; + fcl_line = p_input_line; + p_indent = indent; + } + if (!stars_last_line && strnEQ(s, "*** ", 4)) { + names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath); + } else if (strnEQ(s, "--- ", 4)) { + names[NEW_FILE].path = fetchname(s + 4, &names[NEW_FILE].exists, strippath); + } else if (strnEQ(s, "+++ ", 4)) { + names[OLD_FILE].path = fetchname(s + 4, &names[OLD_FILE].exists, strippath); + } else if (strnEQ(s, "Index:", 6)) { + names[INDEX_FILE].path = fetchname(s + 6, &names[INDEX_FILE].exists, strippath); + } else if (strnEQ(s, "Prereq:", 7)) { + for (t = s + 7; isspace((unsigned char)*t); t++) + ; + revision = savestr(t); + for (t = revision; *t && !isspace((unsigned char)*t); t++) + ; + *t = '\0'; + if (*revision == '\0') { + free(revision); + revision = NULL; + } + } + if ((!diff_type || diff_type == ED_DIFF) && first_command_line >= 0L && strEQ(s, ".\n")) { + p_indent = indent; + p_start = first_command_line; + p_sline = fcl_line; + retval = ED_DIFF; + goto scan_exit; + } + if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) { + if (strnEQ(s + 4, "0,0", 3)) + ok_to_create_file = 1; + p_indent = indent; + p_start = this_line; + p_sline = p_input_line; + retval = UNI_DIFF; + goto scan_exit; + } + stars_this_line = strnEQ(s, "********", 8); + if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line && strnEQ(s, "*** ", 4)) { + if (atol(s + 4) == 0) + ok_to_create_file = 1; + while (*s != '\n') + s++; + p_indent = indent; + p_start = previous_line; + p_sline = p_input_line - 1; + retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF); + goto scan_exit; + } + if ((!diff_type || diff_type == NORMAL_DIFF) && last_line_was_command && + (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) { + p_start = previous_line; + p_sline = p_input_line - 1; + p_indent = indent; + retval = NORMAL_DIFF; + goto scan_exit; + } + } scan_exit: - if (retval == UNI_DIFF) { - struct FileName tmp = names[OLD_FILE]; - names[OLD_FILE] = names[NEW_FILE]; - names[NEW_FILE] = tmp; - } - if (filearg[0] == NULL) { - if (posix) - filearg[0] = posix_name(names, ok_to_create_file); - else { - if (names[OLD_FILE].path != NULL || names[NEW_FILE].path != NULL) { - free(names[INDEX_FILE].path); - names[INDEX_FILE].path = NULL; - } - filearg[0] = best_name(names, ok_to_create_file); - } - } - free(bestguess); - bestguess = NULL; - if (filearg[0] != NULL) - bestguess = savestr(filearg[0]); - else if (!ok_to_create_file) { - if (posix) - bestguess = posix_name(names, 1); - else - bestguess = best_name(names, 1); - } - free(names[OLD_FILE].path); - free(names[NEW_FILE].path); - free(names[INDEX_FILE].path); - return retval; + if (retval == UNI_DIFF) { + struct FileName tmp = names[OLD_FILE]; + names[OLD_FILE] = names[NEW_FILE]; + names[NEW_FILE] = tmp; + } + if (filearg[0] == NULL) { + if (posix) + filearg[0] = posix_name(names, ok_to_create_file); + else { + if (names[OLD_FILE].path != NULL || names[NEW_FILE].path != NULL) { + free(names[INDEX_FILE].path); + names[INDEX_FILE].path = NULL; + } + filearg[0] = best_name(names, ok_to_create_file); + } + } + free(bestguess); + bestguess = NULL; + if (filearg[0] != NULL) + bestguess = savestr(filearg[0]); + else if (!ok_to_create_file) { + if (posix) + bestguess = posix_name(names, 1); + else + bestguess = best_name(names, 1); + } + free(names[OLD_FILE].path); + free(names[NEW_FILE].path); + free(names[INDEX_FILE].path); + return retval; } static void next_intuit_at(LINENUM file_pos, LINENUM file_line) { - p_base = file_pos; - p_bline = file_line; + p_base = file_pos; + p_bline = file_line; } static void skip_to(LINENUM file_pos, LINENUM file_line) { - int ret; - - if (p_base > file_pos) - fatal("Internal error: seek %ld>%ld\n", p_base, file_pos); - if (verbose && p_base < file_pos) { - fseek(pfp, p_base, SEEK_SET); - say("The text leading up to this was:\n--------------------------\n"); - while (ftell(pfp) < file_pos) { - ret = getline(&buf, &bufsz, pfp); - if (ret == -1) - fatal("Unexpected end of file\n"); - say("|%s", buf); - } - say("--------------------------\n"); - } else - fseek(pfp, file_pos, SEEK_SET); - p_input_line = file_line - 1; + int ret; + + if (p_base > file_pos) + fatal("Internal error: seek %ld>%ld\n", p_base, file_pos); + if (verbose && p_base < file_pos) { + fseek(pfp, p_base, SEEK_SET); + say("The text leading up to this was:\n--------------------------\n"); + while (ftell(pfp) < file_pos) { + ret = getline(&buf, &bufsz, pfp); + if (ret == -1) + fatal("Unexpected end of file\n"); + say("|%s", buf); + } + say("--------------------------\n"); + } else + fseek(pfp, file_pos, SEEK_SET); + p_input_line = file_line - 1; } __dead static void malformed(void) { - fatal("malformed patch at line %ld: %s", p_input_line, buf); + fatal("malformed patch at line %ld: %s", p_input_line, buf); } static LINENUM getlinenum(const char *s) { - LINENUM l = (LINENUM)atol(s); - if (l < 0) { - l = 0; - malformed(); - } - return l; + LINENUM l = (LINENUM)atol(s); + if (l < 0) { + l = 0; + malformed(); + } + return l; } static LINENUM getskiplinenum(char **p) { - char *s = *p; - LINENUM l = getlinenum(s); - while (isdigit((unsigned char)*s)) - s++; - *p = s; - return l; + char *s = *p; + LINENUM l = getlinenum(s); + while (isdigit((unsigned char)*s)) + s++; + *p = s; + return l; } static int remove_special_line(void) { - int c; + int c; - c = fgetc(pfp); - if (c == '\\') { - do { - c = fgetc(pfp); - } while (c != EOF && c != '\n'); - return 1; - } - if (c != EOF) - fseek(pfp, -1L, SEEK_CUR); - return 0; + c = fgetc(pfp); + if (c == '\\') { + do { + c = fgetc(pfp); + } while (c != EOF && c != '\n'); + return 1; + } + if (c != EOF) + fseek(pfp, -1L, SEEK_CUR); + return 0; } int another_hunk(void) { - long line_beginning; - LINENUM repl_beginning; - LINENUM fillcnt; - LINENUM fillsrc; - LINENUM filldst; - int ptrn_spaces_eaten; - int repl_could_be_missing; - int repl_missing; - long repl_backtrack_position; - LINENUM repl_patch_line; - LINENUM ptrn_copiable; - char *s; - int context = 0; - int ret; - - while (p_end >= 0) { - if (p_end == p_efake) - p_end = p_bfake; - else - free(p_line[p_end]); - p_end--; - } - p_efake = -1; - p_max = hunkmax; - - if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) { - line_beginning = ftell(pfp); - repl_beginning = 0; - fillcnt = 0; - fillsrc = 0; - filldst = 0; - ptrn_spaces_eaten = 0; - repl_could_be_missing = 1; - repl_missing = 0; - repl_backtrack_position = 0; - repl_patch_line = 0; - ptrn_copiable = 0; - - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1 || strnNE(buf, "********", 8)) { - next_intuit_at(line_beginning, p_input_line); - return 0; - } - p_context = 100; - p_hunk_beg = p_input_line + 1; - while (p_end < p_max) { - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1) { - if (repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - fatal("unexpected end of file in patch\n"); - } - p_end++; - if (p_end >= hunkmax) - fatal("Internal error: hunk larger than hunk buffer size"); - p_char[p_end] = *buf; - p_line[p_end] = NULL; - switch (*buf) { - case '*': - if (strnEQ(buf, "********", 8)) { - if (repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } else - fatal("unexpected end of hunk at line %ld\n", p_input_line); - } - if (p_end != 0) { - if (repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - fatal("unexpected *** at line %ld: %s", p_input_line, buf); - } - context = 0; - p_line[p_end] = savestr(buf); - if (out_of_mem) { - p_end--; - return 0; - } - for (s = buf; *s && !isdigit((unsigned char)*s); s++) - ; - if (!*s) - malformed(); - if (strnEQ(s, "0,0", 3)) - memmove(s, s + 2, strlen(s + 2) + 1); - p_first = getskiplinenum(&s); - if (*s == ',') { - for (; *s && !isdigit((unsigned char)*s); s++) - ; - if (!*s) - malformed(); - p_ptrn_lines = (getlinenum(s)) - p_first + 1; - if (p_ptrn_lines < 0) - malformed(); - } else if (p_first) - p_ptrn_lines = 1; - else { - p_ptrn_lines = 0; - p_first = 1; - } - if (p_first >= LINENUM_MAX - p_ptrn_lines || p_ptrn_lines >= LINENUM_MAX - 6) - malformed(); - p_max = p_ptrn_lines + 6; - while (p_max >= hunkmax) - grow_hunkmax(); - p_max = hunkmax; - break; - case '-': - if (buf[1] == '-') { - if (repl_beginning || (p_end != p_ptrn_lines + 1 + (p_char[p_end - 1] == '\n'))) { - if (p_end == 1) { - p_end = p_ptrn_lines + 1; - fillsrc = p_end + 1; - filldst = 1; - fillcnt = p_ptrn_lines; - } else { - if (repl_beginning) { - if (repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - fatal("duplicate \"---\" at line %ld\n", p_input_line); - } else { - fatal("premature/overdue \"---\" at line %ld\n", p_input_line); - } - } - } - repl_beginning = p_end; - repl_backtrack_position = ftell(pfp); - repl_patch_line = p_input_line; - p_line[p_end] = savestr(buf); - if (out_of_mem) { - p_end--; - return 0; - } - p_char[p_end] = '='; - for (s = buf; *s && !isdigit((unsigned char)*s); s++) - ; - if (!*s) - malformed(); - p_newfirst = getskiplinenum(&s); - if (*s == ',') { - for (; *s && !isdigit((unsigned char)*s); s++) - ; - if (!*s) - malformed(); - p_repl_lines = (getlinenum(s)) - p_newfirst + 1; - if (p_repl_lines < 0) - malformed(); - } else if (p_newfirst) - p_repl_lines = 1; - else { - p_repl_lines = 0; - p_newfirst = 1; - } - if (p_newfirst >= LINENUM_MAX - p_repl_lines || p_repl_lines >= LINENUM_MAX - p_end) - malformed(); - p_max = p_repl_lines + p_end; - if (p_max > MAXHUNKSIZE) - fatal("hunk too large at line %ld\n", p_input_line); - while (p_max >= hunkmax) - grow_hunkmax(); - if (p_repl_lines != ptrn_copiable && (p_context != 0 || p_repl_lines != 1)) - repl_could_be_missing = 0; - break; - } - goto change_line; - case '+': - case '!': - repl_could_be_missing = 0; - change_line: - if (buf[1] == '\n' && canonicalize) - strlcpy(buf + 1, " \n", bufsz - 1); - if (!isspace((unsigned char)buf[1]) && buf[1] != '>' && buf[1] != '<' && - repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - if (context >= 0) { - if (context < p_context) - p_context = context; - context = -1000; - } - p_line[p_end] = savestr(buf + 2); - if (out_of_mem) { - p_end--; - return 0; - } - if (p_end == p_ptrn_lines) { - if (remove_special_line()) { - int length = strlen(p_line[p_end]) - 1; - (p_line[p_end])[length] = 0; - } - } - break; - case '\t': - case '\n': - if (repl_beginning && repl_could_be_missing && - (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF)) { - repl_missing = 1; - goto hunk_done; - } - p_line[p_end] = savestr(buf); - if (out_of_mem) { - p_end--; - return 0; - } - if (p_end != p_ptrn_lines + 1) { - ptrn_spaces_eaten |= (repl_beginning != 0); - context++; - if (!repl_beginning) - ptrn_copiable++; - p_char[p_end] = ' '; - } - break; - case ' ': - if (!isspace((unsigned char)buf[1]) && repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - context++; - if (!repl_beginning) - ptrn_copiable++; - p_line[p_end] = savestr(buf + 2); - if (out_of_mem) { - p_end--; - return 0; - } - break; - default: - if (repl_beginning && repl_could_be_missing) { - repl_missing = 1; - goto hunk_done; - } - malformed(); - } - if (p_line[p_end]) - p_len[p_end] = strlen(p_line[p_end]); - else - p_len[p_end] = 0; - } + long line_beginning; + LINENUM repl_beginning; + LINENUM fillcnt; + LINENUM fillsrc; + LINENUM filldst; + int ptrn_spaces_eaten; + int repl_could_be_missing; + int repl_missing; + long repl_backtrack_position; + LINENUM repl_patch_line; + LINENUM ptrn_copiable; + char *s; + int context = 0; + int ret; + + while (p_end >= 0) { + if (p_end == p_efake) + p_end = p_bfake; + else + free(p_line[p_end]); + p_end--; + } + p_efake = -1; + p_max = hunkmax; + + if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) { + line_beginning = ftell(pfp); + repl_beginning = 0; + fillcnt = 0; + fillsrc = 0; + filldst = 0; + ptrn_spaces_eaten = 0; + repl_could_be_missing = 1; + repl_missing = 0; + repl_backtrack_position = 0; + repl_patch_line = 0; + ptrn_copiable = 0; + + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1 || strnNE(buf, "********", 8)) { + next_intuit_at(line_beginning, p_input_line); + return 0; + } + p_context = 100; + p_hunk_beg = p_input_line + 1; + while (p_end < p_max) { + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1) { + if (repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + fatal("unexpected end of file in patch\n"); + } + p_end++; + if (p_end >= hunkmax) + fatal("Internal error: hunk larger than hunk buffer size"); + p_char[p_end] = *buf; + p_line[p_end] = NULL; + switch (*buf) { + case '*': + if (strnEQ(buf, "********", 8)) { + if (repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } else + fatal("unexpected end of hunk at line %ld\n", p_input_line); + } + if (p_end != 0) { + if (repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + fatal("unexpected *** at line %ld: %s", p_input_line, buf); + } + context = 0; + p_line[p_end] = savestr(buf); + if (out_of_mem) { + p_end--; + return 0; + } + for (s = buf; *s && !isdigit((unsigned char)*s); s++) + ; + if (!*s) + malformed(); + if (strnEQ(s, "0,0", 3)) + memmove(s, s + 2, strlen(s + 2) + 1); + p_first = getskiplinenum(&s); + if (*s == ',') { + for (; *s && !isdigit((unsigned char)*s); s++) + ; + if (!*s) + malformed(); + p_ptrn_lines = (getlinenum(s)) - p_first + 1; + if (p_ptrn_lines < 0) + malformed(); + } else if (p_first) + p_ptrn_lines = 1; + else { + p_ptrn_lines = 0; + p_first = 1; + } + if (p_first >= LINENUM_MAX - p_ptrn_lines || p_ptrn_lines >= LINENUM_MAX - 6) + malformed(); + p_max = p_ptrn_lines + 6; + while (p_max >= hunkmax) + grow_hunkmax(); + p_max = hunkmax; + break; + case '-': + if (buf[1] == '-') { + if (repl_beginning || (p_end != p_ptrn_lines + 1 + (p_char[p_end - 1] == '\n'))) { + if (p_end == 1) { + p_end = p_ptrn_lines + 1; + fillsrc = p_end + 1; + filldst = 1; + fillcnt = p_ptrn_lines; + } else { + if (repl_beginning) { + if (repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + fatal("duplicate \"---\" at line %ld\n", p_input_line); + } else { + fatal("premature/overdue \"---\" at line %ld\n", p_input_line); + } + } + } + repl_beginning = p_end; + repl_backtrack_position = ftell(pfp); + repl_patch_line = p_input_line; + p_line[p_end] = savestr(buf); + if (out_of_mem) { + p_end--; + return 0; + } + p_char[p_end] = '='; + for (s = buf; *s && !isdigit((unsigned char)*s); s++) + ; + if (!*s) + malformed(); + p_newfirst = getskiplinenum(&s); + if (*s == ',') { + for (; *s && !isdigit((unsigned char)*s); s++) + ; + if (!*s) + malformed(); + p_repl_lines = (getlinenum(s)) - p_newfirst + 1; + if (p_repl_lines < 0) + malformed(); + } else if (p_newfirst) + p_repl_lines = 1; + else { + p_repl_lines = 0; + p_newfirst = 1; + } + if (p_newfirst >= LINENUM_MAX - p_repl_lines || p_repl_lines >= LINENUM_MAX - p_end) + malformed(); + p_max = p_repl_lines + p_end; + if (p_max > MAXHUNKSIZE) + fatal("hunk too large at line %ld\n", p_input_line); + while (p_max >= hunkmax) + grow_hunkmax(); + if (p_repl_lines != ptrn_copiable && (p_context != 0 || p_repl_lines != 1)) + repl_could_be_missing = 0; + break; + } + goto change_line; + case '+': + case '!': + repl_could_be_missing = 0; + change_line: + if (buf[1] == '\n' && canonicalize) + strlcpy(buf + 1, " \n", bufsz - 1); + if (!isspace((unsigned char)buf[1]) && buf[1] != '>' && buf[1] != '<' && + repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + if (context >= 0) { + if (context < p_context) + p_context = context; + context = -1000; + } + p_line[p_end] = savestr(buf + 2); + if (out_of_mem) { + p_end--; + return 0; + } + if (p_end == p_ptrn_lines) { + if (remove_special_line()) { + int length = strlen(p_line[p_end]) - 1; + (p_line[p_end])[length] = 0; + } + } + break; + case '\t': + case '\n': + if (repl_beginning && repl_could_be_missing && + (!ptrn_spaces_eaten || diff_type == NEW_CONTEXT_DIFF)) { + repl_missing = 1; + goto hunk_done; + } + p_line[p_end] = savestr(buf); + if (out_of_mem) { + p_end--; + return 0; + } + if (p_end != p_ptrn_lines + 1) { + ptrn_spaces_eaten |= (repl_beginning != 0); + context++; + if (!repl_beginning) + ptrn_copiable++; + p_char[p_end] = ' '; + } + break; + case ' ': + if (!isspace((unsigned char)buf[1]) && repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + context++; + if (!repl_beginning) + ptrn_copiable++; + p_line[p_end] = savestr(buf + 2); + if (out_of_mem) { + p_end--; + return 0; + } + break; + default: + if (repl_beginning && repl_could_be_missing) { + repl_missing = 1; + goto hunk_done; + } + malformed(); + } + if (p_line[p_end]) + p_len[p_end] = strlen(p_line[p_end]); + else + p_len[p_end] = 0; + } hunk_done: - if (p_end >= 0 && !repl_beginning) - fatal("no --- found in patch at line %ld\n", pch_hunk_beg()); - - if (repl_missing) { - p_input_line = repl_patch_line; - for (p_end--; p_end > repl_beginning; p_end--) - free(p_line[p_end]); - fseek(pfp, repl_backtrack_position, SEEK_SET); - - if (!p_context && p_repl_lines == 1) { - p_repl_lines = 0; - p_max--; - } - fillsrc = 1; - filldst = repl_beginning + 1; - fillcnt = p_repl_lines; - p_end = p_max; - } else if (!p_context && fillcnt == 1) { - while (filldst < p_end) { - p_line[filldst] = p_line[filldst + 1]; - p_char[filldst] = p_char[filldst + 1]; - p_len[filldst] = p_len[filldst + 1]; - filldst++; - } - p_end--; - p_first++; - fillcnt = 0; - p_ptrn_lines = 0; - } - if (diff_type == CONTEXT_DIFF && (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) { - diff_type = NEW_CONTEXT_DIFF; - } - if (fillcnt) { - p_bfake = filldst; - p_efake = filldst + fillcnt - 1; - while (fillcnt-- > 0) { - while (fillsrc <= p_end && p_char[fillsrc] != ' ') - fillsrc++; - if (fillsrc > p_end) - fatal("replacement text mangled in hunk at line %ld\n", p_hunk_beg); - p_line[filldst] = p_line[fillsrc]; - p_char[filldst] = p_char[fillsrc]; - p_len[filldst] = p_len[fillsrc]; - fillsrc++; - filldst++; - } - while (fillsrc <= p_end && fillsrc != repl_beginning && p_char[fillsrc] != ' ') - fillsrc++; - if (fillsrc != p_end + 1 && fillsrc != repl_beginning) - malformed(); - if (filldst != p_end + 1 && filldst != repl_beginning) - malformed(); - } - if (p_line[p_end] != NULL) { - if (remove_special_line()) { - p_len[p_end] -= 1; - (p_line[p_end])[p_len[p_end]] = 0; - } - } - } else if (diff_type == UNI_DIFF) { - LINENUM fillold; - LINENUM fillnew; - char ch; - - line_beginning = ftell(pfp); - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1 || strnNE(buf, "@@ -", 4)) { - next_intuit_at(line_beginning, p_input_line); - return 0; - } - s = buf + 4; - if (!*s) - malformed(); - p_first = getskiplinenum(&s); - if (*s == ',') { - s++; - p_ptrn_lines = getskiplinenum(&s); - } else - p_ptrn_lines = 1; - if (p_first >= LINENUM_MAX - p_ptrn_lines) - malformed(); - if (*s == ' ') - s++; - if (*s != '+' || !*++s) - malformed(); - p_newfirst = getskiplinenum(&s); - if (*s == ',') { - s++; - p_repl_lines = getskiplinenum(&s); - } else - p_repl_lines = 1; - if (*s == ' ') - s++; - if (*s != '@') - malformed(); - if (p_first >= LINENUM_MAX - p_ptrn_lines || - p_newfirst > LINENUM_MAX - p_repl_lines || - p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1) - malformed(); - if (!p_ptrn_lines) - p_first++; - p_max = p_ptrn_lines + p_repl_lines + 1; - while (p_max >= hunkmax) - grow_hunkmax(); - fillold = 1; - fillnew = fillold + p_ptrn_lines; - p_end = fillnew + p_repl_lines; - snprintf(buf, bufsz, "*** %ld,%ld ****\n", p_first, p_first + p_ptrn_lines - 1); - p_line[0] = savestr(buf); - if (out_of_mem) { - p_end = -1; - return 0; - } - p_char[0] = '*'; - snprintf(buf, bufsz, "--- %ld,%ld ----\n", p_newfirst, p_newfirst + p_repl_lines - 1); - p_line[fillnew] = savestr(buf); - if (out_of_mem) { - p_end = 0; - return 0; - } - p_char[fillnew++] = '='; - p_context = 100; - context = 0; - p_hunk_beg = p_input_line + 1; - while (fillold <= p_ptrn_lines || fillnew <= p_end) { - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1) { - if (p_max - fillnew < 3) - strlcpy(buf, " \n", bufsz); - else - fatal("unexpected end of file in patch\n"); - } - if (*buf == '\t' || *buf == '\n') { - ch = ' '; - s = savestr(buf); - } else { - ch = *buf; - s = savestr(buf + 1); - } - if (out_of_mem) { - while (--fillnew > p_ptrn_lines) - free(p_line[fillnew]); - p_end = fillold - 1; - return 0; - } - switch (ch) { - case '-': - if (fillold > p_ptrn_lines) { - free(s); - p_end = fillnew - 1; - malformed(); - } - p_char[fillold] = ch; - p_line[fillold] = s; - p_len[fillold++] = strlen(s); - if (fillold > p_ptrn_lines) { - if (remove_special_line()) { - p_len[fillold - 1] -= 1; - s[p_len[fillold - 1]] = 0; - } - } - break; - case '=': - ch = ' '; - /* FALL THROUGH */ - case ' ': - if (fillold > p_ptrn_lines) { - free(s); - while (--fillnew > p_ptrn_lines) - free(p_line[fillnew]); - p_end = fillold - 1; - malformed(); - } - context++; - p_char[fillold] = ch; - p_line[fillold] = s; - p_len[fillold++] = strlen(s); - s = savestr(s); - if (out_of_mem) { - while (--fillnew > p_ptrn_lines) - free(p_line[fillnew]); - p_end = fillold - 1; - return 0; - } - if (fillold > p_ptrn_lines) { - if (remove_special_line()) { - p_len[fillold - 1] -= 1; - s[p_len[fillold - 1]] = 0; - } - } - /* FALL THROUGH */ - case '+': - if (fillnew > p_end) { - free(s); - while (--fillnew > p_ptrn_lines) - free(p_line[fillnew]); - p_end = fillold - 1; - malformed(); - } - p_char[fillnew] = ch; - p_line[fillnew] = s; - p_len[fillnew++] = strlen(s); - if (fillold > p_ptrn_lines) { - if (remove_special_line()) { - p_len[fillnew - 1] -= 1; - s[p_len[fillnew - 1]] = 0; - } - } - break; - default: - p_end = fillnew; - malformed(); - } - if (ch != ' ' && context > 0) { - if (context < p_context) - p_context = context; - context = -1000; - } - } - } else { - char hunk_type; - int i; - LINENUM min, max; - - line_beginning = ftell(pfp); - p_context = 0; - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1 || !isdigit((unsigned char)*buf)) { - next_intuit_at(line_beginning, p_input_line); - return 0; - } - s = buf; - p_first = getskiplinenum(&s); - if (*s == ',') { - s++; - p_ptrn_lines = getskiplinenum(&s) - p_first + 1; - } else - p_ptrn_lines = (*s != 'a'); - if (p_first >= LINENUM_MAX - p_ptrn_lines) - malformed(); - hunk_type = *s++; - if (hunk_type == 'a') - p_first++; - min = getskiplinenum(&s); - if (*s == ',') - max = getlinenum(++s); - else - max = min; - if (min < 0 || min > max || max - min == LINENUM_MAX) - malformed(); - if (hunk_type == 'd') - min++; - p_end = p_ptrn_lines + p_repl_lines + 1; - p_newfirst = min; - p_repl_lines = max - min + 1; - if (p_newfirst > LINENUM_MAX - p_repl_lines || p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1) - malformed(); - p_end = p_ptrn_lines + p_repl_lines + 1; - if (p_end > MAXHUNKSIZE) - fatal("hunk too large at line %ld\n", p_input_line); - while (p_end >= hunkmax) - grow_hunkmax(); - snprintf(buf, bufsz, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1); - p_line[0] = savestr(buf); - if (out_of_mem) { - p_end = -1; - return 0; - } - p_char[0] = '*'; - for (i = 1; i <= p_ptrn_lines; i++) { - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1) - fatal("unexpected end of file in patch at line %ld\n", p_input_line); - if (*buf != '<') - fatal("< expected at line %ld of patch\n", p_input_line); - p_line[i] = savestr(buf + 2); - if (out_of_mem) { - p_end = i - 1; - return 0; - } - p_len[i] = strlen(p_line[i]); - p_char[i] = '-'; - } - if (remove_special_line()) { - p_len[i - 1] -= 1; - (p_line[i - 1])[p_len[i - 1]] = 0; - } - if (hunk_type == 'c') { - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1) - fatal("unexpected end of file in patch at line %ld\n", p_input_line); - if (*buf != '-') - fatal("--- expected at line %ld of patch\n", p_input_line); - } - snprintf(buf, bufsz, "--- %ld,%ld\n", min, max); - p_line[i] = savestr(buf); - if (out_of_mem) { - p_end = i - 1; - return 0; - } - p_char[i] = '='; - for (i++; i <= p_end; i++) { - ret = pgetline(&buf, &bufsz, pfp); - p_input_line++; - if (ret == -1) - fatal("unexpected end of file in patch at line %ld\n", p_input_line); - if (*buf != '>') - fatal("> expected at line %ld of patch\n", p_input_line); - p_line[i] = savestr(buf + 2); - if (out_of_mem) { - p_end = i - 1; - return 0; - } - p_len[i] = strlen(p_line[i]); - p_char[i] = '+'; - } - if (remove_special_line()) { - p_len[i - 1] -= 1; - (p_line[i - 1])[p_len[i - 1]] = 0; - } - } - if (reverse) { - if (!pch_swap()) - say("Not enough memory to swap next hunk!\n"); - } - if (p_end + 1 < hunkmax) - p_char[p_end + 1] = '^'; - return 1; + if (p_end >= 0 && !repl_beginning) + fatal("no --- found in patch at line %ld\n", pch_hunk_beg()); + + if (repl_missing) { + p_input_line = repl_patch_line; + for (p_end--; p_end > repl_beginning; p_end--) + free(p_line[p_end]); + fseek(pfp, repl_backtrack_position, SEEK_SET); + + if (!p_context && p_repl_lines == 1) { + p_repl_lines = 0; + p_max--; + } + fillsrc = 1; + filldst = repl_beginning + 1; + fillcnt = p_repl_lines; + p_end = p_max; + } else if (!p_context && fillcnt == 1) { + while (filldst < p_end) { + p_line[filldst] = p_line[filldst + 1]; + p_char[filldst] = p_char[filldst + 1]; + p_len[filldst] = p_len[filldst + 1]; + filldst++; + } + p_end--; + p_first++; + fillcnt = 0; + p_ptrn_lines = 0; + } + if (diff_type == CONTEXT_DIFF && (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) { + diff_type = NEW_CONTEXT_DIFF; + } + if (fillcnt) { + p_bfake = filldst; + p_efake = filldst + fillcnt - 1; + while (fillcnt-- > 0) { + while (fillsrc <= p_end && p_char[fillsrc] != ' ') + fillsrc++; + if (fillsrc > p_end) + fatal("replacement text mangled in hunk at line %ld\n", p_hunk_beg); + p_line[filldst] = p_line[fillsrc]; + p_char[filldst] = p_char[fillsrc]; + p_len[filldst] = p_len[fillsrc]; + fillsrc++; + filldst++; + } + while (fillsrc <= p_end && fillsrc != repl_beginning && p_char[fillsrc] != ' ') + fillsrc++; + if (fillsrc != p_end + 1 && fillsrc != repl_beginning) + malformed(); + if (filldst != p_end + 1 && filldst != repl_beginning) + malformed(); + } + if (p_line[p_end] != NULL) { + if (remove_special_line()) { + p_len[p_end] -= 1; + (p_line[p_end])[p_len[p_end]] = 0; + } + } + } else if (diff_type == UNI_DIFF) { + LINENUM fillold; + LINENUM fillnew; + char ch; + + line_beginning = ftell(pfp); + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1 || strnNE(buf, "@@ -", 4)) { + next_intuit_at(line_beginning, p_input_line); + return 0; + } + s = buf + 4; + if (!*s) + malformed(); + p_first = getskiplinenum(&s); + if (*s == ',') { + s++; + p_ptrn_lines = getskiplinenum(&s); + } else + p_ptrn_lines = 1; + if (p_first >= LINENUM_MAX - p_ptrn_lines) + malformed(); + if (*s == ' ') + s++; + if (*s != '+' || !*++s) + malformed(); + p_newfirst = getskiplinenum(&s); + if (*s == ',') { + s++; + p_repl_lines = getskiplinenum(&s); + } else + p_repl_lines = 1; + if (*s == ' ') + s++; + if (*s != '@') + malformed(); + if (p_first >= LINENUM_MAX - p_ptrn_lines || + p_newfirst > LINENUM_MAX - p_repl_lines || + p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1) + malformed(); + if (!p_ptrn_lines) + p_first++; + p_max = p_ptrn_lines + p_repl_lines + 1; + while (p_max >= hunkmax) + grow_hunkmax(); + fillold = 1; + fillnew = fillold + p_ptrn_lines; + p_end = fillnew + p_repl_lines; + snprintf(buf, bufsz, "*** %ld,%ld ****\n", p_first, p_first + p_ptrn_lines - 1); + p_line[0] = savestr(buf); + if (out_of_mem) { + p_end = -1; + return 0; + } + p_char[0] = '*'; + snprintf(buf, bufsz, "--- %ld,%ld ----\n", p_newfirst, p_newfirst + p_repl_lines - 1); + p_line[fillnew] = savestr(buf); + if (out_of_mem) { + p_end = 0; + return 0; + } + p_char[fillnew++] = '='; + p_context = 100; + context = 0; + p_hunk_beg = p_input_line + 1; + while (fillold <= p_ptrn_lines || fillnew <= p_end) { + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1) { + if (p_max - fillnew < 3) + strlcpy(buf, " \n", bufsz); + else + fatal("unexpected end of file in patch\n"); + } + if (*buf == '\t' || *buf == '\n') { + ch = ' '; + s = savestr(buf); + } else { + ch = *buf; + s = savestr(buf + 1); + } + if (out_of_mem) { + while (--fillnew > p_ptrn_lines) + free(p_line[fillnew]); + p_end = fillold - 1; + return 0; + } + switch (ch) { + case '-': + if (fillold > p_ptrn_lines) { + free(s); + p_end = fillnew - 1; + malformed(); + } + p_char[fillold] = ch; + p_line[fillold] = s; + p_len[fillold++] = strlen(s); + if (fillold > p_ptrn_lines) { + if (remove_special_line()) { + p_len[fillold - 1] -= 1; + s[p_len[fillold - 1]] = 0; + } + } + break; + case '=': + ch = ' '; + /* FALL THROUGH */ + case ' ': + if (fillold > p_ptrn_lines) { + free(s); + while (--fillnew > p_ptrn_lines) + free(p_line[fillnew]); + p_end = fillold - 1; + malformed(); + } + context++; + p_char[fillold] = ch; + p_line[fillold] = s; + p_len[fillold++] = strlen(s); + s = savestr(s); + if (out_of_mem) { + while (--fillnew > p_ptrn_lines) + free(p_line[fillnew]); + p_end = fillold - 1; + return 0; + } + if (fillold > p_ptrn_lines) { + if (remove_special_line()) { + p_len[fillold - 1] -= 1; + s[p_len[fillold - 1]] = 0; + } + } + /* FALL THROUGH */ + case '+': + if (fillnew > p_end) { + free(s); + while (--fillnew > p_ptrn_lines) + free(p_line[fillnew]); + p_end = fillold - 1; + malformed(); + } + p_char[fillnew] = ch; + p_line[fillnew] = s; + p_len[fillnew++] = strlen(s); + if (fillold > p_ptrn_lines) { + if (remove_special_line()) { + p_len[fillnew - 1] -= 1; + s[p_len[fillnew - 1]] = 0; + } + } + break; + default: + p_end = fillnew; + malformed(); + } + if (ch != ' ' && context > 0) { + if (context < p_context) + p_context = context; + context = -1000; + } + } + } else { + char hunk_type; + int i; + LINENUM min, max; + + line_beginning = ftell(pfp); + p_context = 0; + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1 || !isdigit((unsigned char)*buf)) { + next_intuit_at(line_beginning, p_input_line); + return 0; + } + s = buf; + p_first = getskiplinenum(&s); + if (*s == ',') { + s++; + p_ptrn_lines = getskiplinenum(&s) - p_first + 1; + } else + p_ptrn_lines = (*s != 'a'); + if (p_first >= LINENUM_MAX - p_ptrn_lines) + malformed(); + hunk_type = *s++; + if (hunk_type == 'a') + p_first++; + min = getskiplinenum(&s); + if (*s == ',') + max = getlinenum(++s); + else + max = min; + if (min < 0 || min > max || max - min == LINENUM_MAX) + malformed(); + if (hunk_type == 'd') + min++; + p_end = p_ptrn_lines + p_repl_lines + 1; + p_newfirst = min; + p_repl_lines = max - min + 1; + if (p_newfirst > LINENUM_MAX - p_repl_lines || p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1) + malformed(); + p_end = p_ptrn_lines + p_repl_lines + 1; + if (p_end > MAXHUNKSIZE) + fatal("hunk too large at line %ld\n", p_input_line); + while (p_end >= hunkmax) + grow_hunkmax(); + snprintf(buf, bufsz, "*** %ld,%ld\n", p_first, p_first + p_ptrn_lines - 1); + p_line[0] = savestr(buf); + if (out_of_mem) { + p_end = -1; + return 0; + } + p_char[0] = '*'; + for (i = 1; i <= p_ptrn_lines; i++) { + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1) + fatal("unexpected end of file in patch at line %ld\n", p_input_line); + if (*buf != '<') + fatal("< expected at line %ld of patch\n", p_input_line); + p_line[i] = savestr(buf + 2); + if (out_of_mem) { + p_end = i - 1; + return 0; + } + p_len[i] = strlen(p_line[i]); + p_char[i] = '-'; + } + if (remove_special_line()) { + p_len[i - 1] -= 1; + (p_line[i - 1])[p_len[i - 1]] = 0; + } + if (hunk_type == 'c') { + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1) + fatal("unexpected end of file in patch at line %ld\n", p_input_line); + if (*buf != '-') + fatal("--- expected at line %ld of patch\n", p_input_line); + } + snprintf(buf, bufsz, "--- %ld,%ld\n", min, max); + p_line[i] = savestr(buf); + if (out_of_mem) { + p_end = i - 1; + return 0; + } + p_char[i] = '='; + for (i++; i <= p_end; i++) { + ret = pgetline(&buf, &bufsz, pfp); + p_input_line++; + if (ret == -1) + fatal("unexpected end of file in patch at line %ld\n", p_input_line); + if (*buf != '>') + fatal("> expected at line %ld of patch\n", p_input_line); + p_line[i] = savestr(buf + 2); + if (out_of_mem) { + p_end = i - 1; + return 0; + } + p_len[i] = strlen(p_line[i]); + p_char[i] = '+'; + } + if (remove_special_line()) { + p_len[i - 1] -= 1; + (p_line[i - 1])[p_len[i - 1]] = 0; + } + } + if (reverse) { + if (!pch_swap()) + say("Not enough memory to swap next hunk!\n"); + } + if (p_end + 1 < hunkmax) + p_char[p_end + 1] = '^'; + return 1; } int pgetline(char **bf, size_t *sz, FILE *fp) { - char *s; - int indent = 0; - int ret; + char *s; + int indent = 0; + int ret; - ret = getline(bf, sz, fp); - if (p_indent && ret != -1) { - for (s = buf; indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X'); s++) { - if (*s == '\t') - indent += 8 - (indent % 7); - else - indent++; - } - if (buf != s && strlcpy(buf, s, bufsz) >= bufsz) - fatal("buffer too small in pgetline()\n"); - } - return ret; + ret = getline(bf, sz, fp); + if (p_indent && ret != -1) { + for (s = buf; indent < p_indent && (*s == ' ' || *s == '\t' || *s == 'X'); s++) { + if (*s == '\t') + indent += 8 - (indent % 7); + else + indent++; + } + if (buf != s && strlcpy(buf, s, bufsz) >= bufsz) + fatal("buffer too small in pgetline()\n"); + } + return ret; } int pch_swap(void) { - char **tp_line; - ssize_t *tp_len; - char *tp_char; - LINENUM i; - LINENUM n; - int blankline = 0; - char *s; - - i = p_first; - p_first = p_newfirst; - p_newfirst = i; - - tp_line = p_line; - tp_len = p_len; - tp_char = p_char; - p_line = NULL; - p_len = NULL; - p_char = NULL; - set_hunkmax(); - if (p_line == NULL || p_len == NULL || p_char == NULL) { - free(p_line); - p_line = tp_line; - free(p_len); - p_len = tp_len; - free(p_char); - p_char = tp_char; - return 0; - } - - i = p_ptrn_lines + 1; - if (tp_char[i] == '\n') { - blankline = 1; - i++; - } - if (p_efake >= 0) { - if (p_efake <= i) - n = p_end - i + 1; - else - n = -i; - p_efake += n; - p_bfake += n; - } - for (n = 0; i <= p_end; i++, n++) { - p_line[n] = tp_line[i]; - p_char[n] = tp_char[i]; - if (p_char[n] == '+') - p_char[n] = '-'; - p_len[n] = tp_len[i]; - } - if (blankline) { - i = p_ptrn_lines + 1; - p_line[n] = tp_line[i]; - p_char[n] = tp_char[i]; - p_len[n] = tp_len[i]; - n++; - } - if (p_char[0] != '=') - fatal("expected '=' found '%c'\n", p_char[0]); - p_char[0] = '*'; - for (s = p_line[0]; *s; s++) - if (*s == '-') - *s = '*'; - - if (p_char[0] != '*') - fatal("expected '*' found '%c'\n", p_char[0]); - tp_char[0] = '='; - for (s = tp_line[0]; *s; s++) - if (*s == '*') - *s = '-'; - for (i = 0; n <= p_end; i++, n++) { - p_line[n] = tp_line[i]; - p_char[n] = tp_char[i]; - if (p_char[n] == '-') - p_char[n] = '+'; - p_len[n] = tp_len[i]; - } - if (i != p_ptrn_lines + 1) - fatal("expected %ld lines, got %ld\n", p_ptrn_lines + 1, i); - - i = p_ptrn_lines; - p_ptrn_lines = p_repl_lines; - p_repl_lines = i; - - free(tp_line); - free(tp_len); - free(tp_char); - return 1; + char **tp_line; + ssize_t *tp_len; + char *tp_char; + LINENUM i; + LINENUM n; + int blankline = 0; + char *s; + + i = p_first; + p_first = p_newfirst; + p_newfirst = i; + + tp_line = p_line; + tp_len = p_len; + tp_char = p_char; + p_line = NULL; + p_len = NULL; + p_char = NULL; + set_hunkmax(); + if (p_line == NULL || p_len == NULL || p_char == NULL) { + free(p_line); + p_line = tp_line; + free(p_len); + p_len = tp_len; + free(p_char); + p_char = tp_char; + return 0; + } + + i = p_ptrn_lines + 1; + if (tp_char[i] == '\n') { + blankline = 1; + i++; + } + if (p_efake >= 0) { + if (p_efake <= i) + n = p_end - i + 1; + else + n = -i; + p_efake += n; + p_bfake += n; + } + for (n = 0; i <= p_end; i++, n++) { + p_line[n] = tp_line[i]; + p_char[n] = tp_char[i]; + if (p_char[n] == '+') + p_char[n] = '-'; + p_len[n] = tp_len[i]; + } + if (blankline) { + i = p_ptrn_lines + 1; + p_line[n] = tp_line[i]; + p_char[n] = tp_char[i]; + p_len[n] = tp_len[i]; + n++; + } + if (p_char[0] != '=') + fatal("expected '=' found '%c'\n", p_char[0]); + p_char[0] = '*'; + for (s = p_line[0]; *s; s++) + if (*s == '-') + *s = '*'; + + if (p_char[0] != '*') + fatal("expected '*' found '%c'\n", p_char[0]); + tp_char[0] = '='; + for (s = tp_line[0]; *s; s++) + if (*s == '*') + *s = '-'; + for (i = 0; n <= p_end; i++, n++) { + p_line[n] = tp_line[i]; + p_char[n] = tp_char[i]; + if (p_char[n] == '-') + p_char[n] = '+'; + p_len[n] = tp_len[i]; + } + if (i != p_ptrn_lines + 1) + fatal("expected %ld lines, got %ld\n", p_ptrn_lines + 1, i); + + i = p_ptrn_lines; + p_ptrn_lines = p_repl_lines; + p_repl_lines = i; + + free(tp_line); + free(tp_len); + free(tp_char); + return 1; } LINENUM pch_first(void) { - return p_first; + return p_first; } LINENUM pch_ptrn_lines(void) { - return p_ptrn_lines; + return p_ptrn_lines; } LINENUM pch_newfirst(void) { - return p_newfirst; + return p_newfirst; } LINENUM pch_repl_lines(void) { - return p_repl_lines; + return p_repl_lines; } LINENUM pch_end(void) { - return p_end; + return p_end; } LINENUM pch_context(void) { - return p_context; + return p_context; } ssize_t pch_line_len(LINENUM line) { - return p_len[line]; + return p_len[line]; } char pch_char(LINENUM line) { - return p_char[line]; + return p_char[line]; } char * pfetch(LINENUM line) { - return p_line[line]; + return p_line[line]; } LINENUM pch_hunk_beg(void) { - return p_hunk_beg; + return p_hunk_beg; } void do_ed_script(void) { - char *t; - long beginning_of_this_line; - FILE *pipefp = NULL; - int continuation; - - if (!skip_rest_of_patch) { - if (copy_file(filearg[0], TMPOUTNAME) < 0) { - unlink(TMPOUTNAME); - fatal("cant create temp file %s", TMPOUTNAME); - } - snprintf(buf, bufsz, "%s -S%s %s", _PATH_ED, verbose ? "" : "s", TMPOUTNAME); - pipefp = popen(buf, "w"); - } - for (;;) { - beginning_of_this_line = ftell(pfp); - if (pgetline(&buf, &bufsz, pfp) == -1) { - next_intuit_at(beginning_of_this_line, p_input_line); - break; - } - p_input_line++; - for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++) - ; - if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) { - if (pipefp != NULL) - fprintf(pipefp, "%s", buf); - if (*t == 's') { - for (;;) { - continuation = 0; - t = strchr(buf, '\0') - 1; - while (--t >= buf && *t == '\\') - continuation = !continuation; - if (!continuation || pgetline(&buf, &bufsz, pfp) == -1) - break; - if (pipefp != NULL) - fprintf(pipefp, "%s", buf); - } - } else if (*t != 'd') { - while (pgetline(&buf, &bufsz, pfp) != -1) { - p_input_line++; - if (pipefp != NULL) - fprintf(pipefp, "%s", buf); - if (strEQ(buf, ".\n")) - break; - } - } - } else { - next_intuit_at(beginning_of_this_line, p_input_line); - break; - } - } - if (pipefp == NULL) - return; - fprintf(pipefp, "w\n"); - fprintf(pipefp, "q\n"); - fflush(pipefp); - pclose(pipefp); - ignore_signals(); - if (!check_only) { - if (move_file(TMPOUTNAME, outname) < 0) { - toutkeep = 1; - chmod(TMPOUTNAME, filemode); - } else - chmod(outname, filemode); - } - set_signals(1); + char *t; + long beginning_of_this_line; + FILE *pipefp = NULL; + int continuation; + + if (!skip_rest_of_patch) { + if (copy_file(filearg[0], TMPOUTNAME) < 0) { + unlink(TMPOUTNAME); + fatal("cant create temp file %s", TMPOUTNAME); + } + snprintf(buf, bufsz, "%s -S%s %s", _PATH_ED, verbose ? "" : "s", TMPOUTNAME); + pipefp = wpopen(buf, NULL, "w"); + } + for (;;) { + beginning_of_this_line = ftell(pfp); + if (pgetline(&buf, &bufsz, pfp) == -1) { + next_intuit_at(beginning_of_this_line, p_input_line); + break; + } + p_input_line++; + for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++) + ; + if (isdigit((unsigned char)*buf) && (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) { + if (pipefp != NULL) + fprintf(pipefp, "%s", buf); + if (*t == 's') { + for (;;) { + continuation = 0; + t = strchr(buf, '\0') - 1; + while (--t >= buf && *t == '\\') + continuation = !continuation; + if (!continuation || pgetline(&buf, &bufsz, pfp) == -1) + break; + if (pipefp != NULL) + fprintf(pipefp, "%s", buf); + } + } else if (*t != 'd') { + while (pgetline(&buf, &bufsz, pfp) != -1) { + p_input_line++; + if (pipefp != NULL) + fprintf(pipefp, "%s", buf); + if (strEQ(buf, ".\n")) + break; + } + } + } else { + next_intuit_at(beginning_of_this_line, p_input_line); + break; + } + } + if (pipefp == NULL) + return; + fprintf(pipefp, "w\n"); + fprintf(pipefp, "q\n"); + fflush(pipefp); + wpclose(pipefp); + ignore_signals(); + if (!check_only) { + if (move_file(TMPOUTNAME, outname) < 0) { + toutkeep = 1; + chmod(TMPOUTNAME, filemode); + } else + chmod(outname, filemode); + } + set_signals(1); } static char * posix_name(const struct FileName *names, int assume_exists) { - char *path = NULL; - int i; - - for (i = 0; i < MAX_FILE; i++) { - if (names[i].path != NULL && names[i].exists) { - path = names[i].path; - break; - } - } - if (path == NULL && !assume_exists) { - for (i = 0; i < MAX_FILE; i++) { - if (names[i].path != NULL && (path = checked_in(names[i].path)) != NULL) - break; - } - if (path == NULL && ok_to_create_file && names[NEW_FILE].path != NULL) - path = names[NEW_FILE].path; - } - return path ? savestr(path) : NULL; + char *path = NULL; + int i; + + for (i = 0; i < MAX_FILE; i++) { + if (names[i].path != NULL && names[i].exists) { + path = names[i].path; + break; + } + } + if (path == NULL && !assume_exists) { + for (i = 0; i < MAX_FILE; i++) { + if (names[i].path != NULL && (path = checked_in(names[i].path)) != NULL) + break; + } + if (path == NULL && ok_to_create_file && names[NEW_FILE].path != NULL) + path = names[NEW_FILE].path; + } + return path ? savestr(path) : NULL; } static char * best_name(const struct FileName *names, int assume_exists) { - size_t min_components, min_baselen, min_len, tmp; - char *best = NULL; - int i; - - min_components = min_baselen = min_len = SIZE_MAX; - for (i = INDEX_FILE; i >= OLD_FILE; i--) { - if (names[i].path == NULL || (!names[i].exists && !assume_exists)) - continue; - if ((tmp = num_components(names[i].path)) > min_components) - continue; - min_components = tmp; - if ((tmp = strlen(basename(names[i].path))) > min_baselen) - continue; - min_baselen = tmp; - if ((tmp = strlen(names[i].path)) > min_len) - continue; - min_len = tmp; - best = names[i].path; - } - if (best == NULL) { - min_components = min_baselen = min_len = SIZE_MAX; - for (i = INDEX_FILE; i >= OLD_FILE; i--) { - if (names[i].path == NULL || checked_in(names[i].path) == NULL) - continue; - if ((tmp = num_components(names[i].path)) > min_components) - continue; - min_components = tmp; - if ((tmp = strlen(basename(names[i].path))) > min_baselen) - continue; - min_baselen = tmp; - if ((tmp = strlen(names[i].path)) > min_len) - continue; - min_len = tmp; - best = names[i].path; - } - if (best == NULL && ok_to_create_file && names[NEW_FILE].path != NULL) - best = names[NEW_FILE].path; - } - return best ? savestr(best) : NULL; + size_t min_components, min_baselen, min_len, tmp; + char *best = NULL; + int i; + + min_components = min_baselen = min_len = SIZE_MAX; + for (i = INDEX_FILE; i >= OLD_FILE; i--) { + if (names[i].path == NULL || (!names[i].exists && !assume_exists)) + continue; + if ((tmp = num_components(names[i].path)) > min_components) + continue; + min_components = tmp; + if ((tmp = strlen(basename(names[i].path))) > min_baselen) + continue; + min_baselen = tmp; + if ((tmp = strlen(names[i].path)) > min_len) + continue; + min_len = tmp; + best = names[i].path; + } + if (best == NULL) { + min_components = min_baselen = min_len = SIZE_MAX; + for (i = INDEX_FILE; i >= OLD_FILE; i--) { + if (names[i].path == NULL || checked_in(names[i].path) == NULL) + continue; + if ((tmp = num_components(names[i].path)) > min_components) + continue; + min_components = tmp; + if ((tmp = strlen(basename(names[i].path))) > min_baselen) + continue; + min_baselen = tmp; + if ((tmp = strlen(names[i].path)) > min_len) + continue; + min_len = tmp; + best = names[i].path; + } + if (best == NULL && ok_to_create_file && names[NEW_FILE].path != NULL) + best = names[NEW_FILE].path; + } + return best ? savestr(best) : NULL; } static size_t num_components(const char *path) { - size_t n; - const char *cp; + size_t n; + const char *cp; - for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) { - while (*cp == '/') - cp++; - } - return n; + for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) { + while (*cp == '/') + cp++; + } + return n; } LINENUM strtolinenum(char *nptr, char **endptr) { - LINENUM rv; - char c; - char *p; - const char *errstr; + LINENUM rv; + char c; + char *p; + const char *errstr; - for (p = nptr; isdigit((unsigned char)*p); p++) - ; + for (p = nptr; isdigit((unsigned char)*p); p++) + ; - if (p == nptr) - malformed(); + if (p == nptr) + malformed(); - c = *p; - *p = '\0'; + c = *p; + *p = '\0'; - rv = strtonum(nptr, 0, LINENUM_MAX, &errstr); - if (errstr != NULL) - fatal("invalid line number at line %ld: `%s' is %s\n", - p_input_line, nptr, errstr); + rv = strtonum(nptr, 0, LINENUM_MAX, &errstr); + if (errstr != NULL) + fatal("invalid line number at line %ld: `%s' is %s\n", + p_input_line, nptr, errstr); - *p = c; - *endptr = p; + *p = c; + *endptr = p; - return rv; + return rv; } int move_file(const char *from, const char *to) { - int fromfd; - ssize_t i; - - if (strEQ(to, "-")) { - fromfd = open(from, O_RDONLY); - if (fromfd < 0) - pfatal("internal error, cant reopen %s", from); - while ((i = read(fromfd, buf, bufsz)) > 0) { - if (write(STDOUT_FILENO, buf, i) != i) - pfatal("write failed"); - } - close(fromfd); - return 0; - } - if (backup_file(to) < 0) { - say("Cant backup %s, output is in %s: %s\n", to, from, strerror(errno)); - return -1; - } - if (rename(from, to) < 0) { - if (errno != EXDEV || copy_file(from, to) < 0) { - say("Cant create %s, output is in %s: %s\n", to, from, strerror(errno)); - return -1; - } - } - return 0; + int fromfd; + ssize_t i; + + if (strEQ(to, "-")) { + fromfd = open(from, O_RDONLY); + if (fromfd < 0) + pfatal("internal error, cant reopen %s", from); + while ((i = read(fromfd, buf, bufsz)) > 0) { + if (write(STDOUT_FILENO, buf, i) != i) + pfatal("write failed"); + } + close(fromfd); + return 0; + } + if (backup_file(to) < 0) { + say("Cant backup %s, output is in %s: %s\n", to, from, strerror(errno)); + return -1; + } + if (rename(from, to) < 0) { + if (errno != EXDEV || copy_file(from, to) < 0) { + say("Cant create %s, output is in %s: %s\n", to, from, strerror(errno)); + return -1; + } + } + return 0; } int backup_file(const char *orig) { - struct stat filestat; - char bakname[PATH_MAX], *s, *simplename; - dev_t orig_device; - ino_t orig_inode; - - if (backup_type == BACKUP_NONE || stat(orig, &filestat) != 0) - return 0; - if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) { - unlink(orig); - return 0; - } - orig_device = filestat.st_dev; - orig_inode = filestat.st_ino; - - if (origprae) { - if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) || - strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname)) - fatal("filename too long\n"); - } else { - if ((s = find_backup_file_name(orig)) == NULL) - fatal("out of memory\n"); - if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname)) - fatal("filename too long\n"); - free(s); - } - - if ((simplename = strrchr(bakname, '/')) != NULL) - simplename = simplename + 1; - else - simplename = bakname; - - while (stat(bakname, &filestat) == 0 && orig_device == filestat.st_dev && orig_inode == filestat.st_ino) { - for (s = simplename; *s && !islower((unsigned char)*s); s++) - ; - if (*s) - *s = toupper((unsigned char)*s); - else - memmove(simplename, simplename + 1, strlen(simplename + 1) + 1); - } - if (rename(orig, bakname) < 0) { - if (errno != EXDEV || copy_file(orig, bakname) < 0) - return -1; - } - return 0; + struct stat filestat; + char bakname[PATH_MAX], *s, *simplename; + dev_t orig_device; + ino_t orig_inode; + + if (backup_type == BACKUP_NONE || stat(orig, &filestat) != 0) + return 0; + if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) { + unlink(orig); + return 0; + } + orig_device = filestat.st_dev; + orig_inode = filestat.st_ino; + + if (origprae) { + if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) || + strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname)) + fatal("filename too long\n"); + } else { + if ((s = find_backup_file_name(orig)) == NULL) + fatal("out of memory\n"); + if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname)) + fatal("filename too long\n"); + free(s); + } + + if ((simplename = strrchr(bakname, '/')) != NULL) + simplename = simplename + 1; + else + simplename = bakname; + + while (stat(bakname, &filestat) == 0 && orig_device == filestat.st_dev && orig_inode == filestat.st_ino) { + for (s = simplename; *s && !islower((unsigned char)*s); s++) + ; + if (*s) + *s = toupper((unsigned char)*s); + else + memmove(simplename, simplename + 1, strlen(simplename + 1) + 1); + } + if (rename(orig, bakname) < 0) { + if (errno != EXDEV || copy_file(orig, bakname) < 0) + return -1; + } + return 0; } int copy_file(const char *from, const char *to) { - int tofd, fromfd; - ssize_t i; + int tofd, fromfd; + ssize_t i; - tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666); - if (tofd < 0) - return -1; - fromfd = open(from, O_RDONLY, 0); - if (fromfd < 0) - pfatal("internal error, cant reopen %s", from); - while ((i = read(fromfd, buf, bufsz)) > 0) { - if (write(tofd, buf, i) != i) - pfatal("write to %s failed", to); - } - close(fromfd); - close(tofd); - return 0; + tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666); + if (tofd < 0) + return -1; + fromfd = open(from, O_RDONLY, 0); + if (fromfd < 0) + pfatal("internal error, cant reopen %s", from); + while ((i = read(fromfd, buf, bufsz)) > 0) { + if (write(tofd, buf, i) != i) + pfatal("write to %s failed", to); + } + close(fromfd); + close(tofd); + return 0; } char * savestr(const char *s) { - char *rv; + char *rv; - if (!s) - s = "Oops"; - rv = strdup(s); - if (rv == NULL) { - if (using_plan_a) - out_of_mem = 1; - else - fatal("out of memory\n"); - } - return rv; + if (!s) + s = "Oops"; + rv = strdup(s); + if (rv == NULL) { + if (using_plan_a) + out_of_mem = 1; + else + fatal("out of memory\n"); + } + return rv; } void say(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); - fflush(stderr); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fflush(stderr); } __dead void fatal(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - fprintf(stderr, "patch: **** "); - vfprintf(stderr, fmt, ap); - va_end(ap); - my_exit(2); + va_start(ap, fmt); + fprintf(stderr, "patch: **** "); + vfprintf(stderr, fmt, ap); + va_end(ap); + my_exit(2); } __dead void pfatal(const char *fmt, ...) { - va_list ap; - int errnum = errno; + va_list ap; + int errnum = errno; - fprintf(stderr, "patch: **** "); - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); - fprintf(stderr, ": %s\n", strerror(errnum)); - my_exit(2); + fprintf(stderr, "patch: **** "); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fprintf(stderr, ": %s\n", strerror(errnum)); + my_exit(2); } void ask(const char *fmt, ...) { - va_list ap; - ssize_t nr = 0; - static int ttyfd = -1; - - va_start(ap, fmt); - vfprintf(stdout, fmt, ap); - va_end(ap); - fflush(stdout); - if (ttyfd < 0) - ttyfd = open(_PATH_TTY, O_RDONLY); - if (ttyfd >= 0) { - if ((nr = read(ttyfd, buf, bufsz)) > 0 && buf[nr - 1] == '\n') - buf[nr - 1] = '\0'; - } - if (ttyfd < 0 || nr <= 0) { - putchar('\n'); - buf[0] = '\0'; - } + va_list ap; + ssize_t nr = 0; + static int ttyfd = -1; + + va_start(ap, fmt); + vfprintf(stdout, fmt, ap); + va_end(ap); + fflush(stdout); + if (ttyfd < 0) + ttyfd = open(ARUU_PATH_DEVTTY, O_RDONLY); + if (ttyfd >= 0) { + if ((nr = read(ttyfd, buf, bufsz)) > 0 && buf[nr - 1] == '\n') + buf[nr - 1] = '\0'; + } + if (ttyfd < 0 || nr <= 0) { + putchar('\n'); + buf[0] = '\0'; + } } void set_signals(int reset) { - static sig_t hupval, intval; + static sig_t hupval, intval; - if (!reset) { - hupval = signal(SIGHUP, SIG_IGN); - if (hupval != SIG_IGN) - hupval = (sig_t)my_exit; - intval = signal(SIGINT, SIG_IGN); - if (intval != SIG_IGN) - intval = (sig_t)my_exit; - } - signal(SIGHUP, hupval); - signal(SIGINT, intval); + if (!reset) { + hupval = signal(SIGHUP, SIG_IGN); + if (hupval != SIG_IGN) + hupval = (sig_t)my_exit; + intval = signal(SIGINT, SIG_IGN); + if (intval != SIG_IGN) + intval = (sig_t)my_exit; + } + signal(SIGHUP, hupval); + signal(SIGINT, intval); } void ignore_signals(void) { - signal(SIGHUP, SIG_IGN); - signal(SIGINT, SIG_IGN); + signal(SIGHUP, SIG_IGN); + signal(SIGINT, SIG_IGN); } void makedirs(const char *filename, int striplast) { - char *tmpbuf; + char *tmpbuf; - if ((tmpbuf = strdup(filename)) == NULL) - fatal("out of memory\n"); + if ((tmpbuf = strdup(filename)) == NULL) + fatal("out of memory\n"); - if (striplast) { - char *s = strrchr(tmpbuf, '/'); - if (s == NULL) { - free(tmpbuf); - return; - } - *s = '\0'; - } - if (mkpath(tmpbuf) != 0) - pfatal("creation of %s failed", tmpbuf); - free(tmpbuf); + if (striplast) { + char *s = strrchr(tmpbuf, '/'); + if (s == NULL) { + free(tmpbuf); + return; + } + *s = '\0'; + } + if (mkpath(tmpbuf) != 0) + pfatal("creation of %s failed", tmpbuf); + free(tmpbuf); } char * fetchname(const char *at, int *exists, int strip_leading) { - char *fullname, *name, *t; - int sleading, tab; - struct stat filestat; - - if (at == NULL || *at == '\0') - return NULL; - while (isspace((unsigned char)*at)) - at++; - if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1)) - return NULL; - name = fullname = t = savestr(at); - tab = strchr(t, '\t') != NULL; - for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') || !isspace((unsigned char)*t)); t++) { - if (t[0] == '/' && t[1] != '/' && t[1] != '\0') { - if (--sleading >= 0) - name = t + 1; - } - } - *t = '\0'; - - if (strip_leading == 957 && name != fullname && *fullname != '/') { - name[-1] = '\0'; - if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) { - name[-1] = '/'; - name = fullname; - } - } - name = savestr(name); - free(fullname); - - *exists = stat(name, &filestat) == 0; - return name; + char *fullname, *name, *t; + int sleading, tab; + struct stat filestat; + + if (at == NULL || *at == '\0') + return NULL; + while (isspace((unsigned char)*at)) + at++; + if (strnEQ(at, ARUU_PATH_DEVNULL, sizeof(ARUU_PATH_DEVNULL) - 1)) + return NULL; + name = fullname = t = savestr(at); + tab = strchr(t, '\t') != NULL; + for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') || !isspace((unsigned char)*t)); t++) { + if (t[0] == '/' && t[1] != '/' && t[1] != '\0') { + if (--sleading >= 0) + name = t + 1; + } + } + *t = '\0'; + + if (strip_leading == 957 && name != fullname && *fullname != '/') { + name[-1] = '\0'; + if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) { + name[-1] = '/'; + name = fullname; + } + } + name = savestr(name); + free(fullname); + + *exists = stat(name, &filestat) == 0; + return name; } char * checked_in(char *file) { - char *filebase, *filedir, tmpbuf[PATH_MAX]; - struct stat filestat; + char *filebase, *filedir, tmpbuf[PATH_MAX]; + struct stat filestat; - filebase = basename(file); - filedir = dirname(file); + filebase = basename(file); + filedir = dirname(file); #define try(f, a1, a2, a3) \ (snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0) - if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) || - try("%s/RCS/%s%s", filedir, filebase, "") || - try("%s/%s%s", filedir, filebase, RCSSUFFIX) || - try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) || - try("%s/%s%s", filedir, SCCSPREFIX, filebase)) - return file; + if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) || + try("%s/RCS/%s%s", filedir, filebase, "") || + try("%s/%s%s", filedir, filebase, RCSSUFFIX) || + try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) || + try("%s/%s%s", filedir, SCCSPREFIX, filebase)) + return file; - return NULL; + return NULL; } __dead void version(void) { - printf("Patch version 2.0-12u9-NetBSD\n"); - my_exit(EXIT_SUCCESS); + printf("Patch version 2.0-12u9-NetBSD\n"); + my_exit(EXIT_SUCCESS); } __dead void my_exit(int status) { - unlink(TMPINNAME); - if (!toutkeep) - unlink(TMPOUTNAME); - if (!trejkeep) - unlink(TMPREJNAME); - unlink(TMPPATNAME); - exit(status); + unlink(TMPINNAME); + if (!toutkeep) + unlink(TMPOUTNAME); + if (!trejkeep) + unlink(TMPREJNAME); + unlink(TMPPATNAME); + exit(status); } static void * pch_realloc(void *ptr, size_t number, size_t size) { - if (number > SIZE_MAX / size) { - errno = EOVERFLOW; - return NULL; - } - return realloc(ptr, number * size); + if (number > SIZE_MAX / size) { + errno = EOVERFLOW; + return NULL; + } + return realloc(ptr, number * size); } int mkpath(char *path) { - struct stat sb; - char *slash; - int done = 0; - - slash = path; - while (!done) { - slash += strspn(slash, "/"); - slash += strcspn(slash, "/"); - done = (*slash == '\0'); - *slash = '\0'; - if (stat(path, &sb)) { - if (errno != ENOENT || (mkdir(path, 0777) && errno != EEXIST)) { - warn("%s", path); - return -1; - } - } else if (!S_ISDIR(sb.st_mode)) { - warnx("%s: %s", path, strerror(ENOTDIR)); - return -1; - } - *slash = '/'; - } - return 0; + struct stat sb; + char *slash; + int done = 0; + + slash = path; + while (!done) { + slash += strspn(slash, "/"); + slash += strcspn(slash, "/"); + done = (*slash == '\0'); + *slash = '\0'; + if (stat(path, &sb)) { + if (errno != ENOENT || (mkdir(path, 0777) && errno != EEXIST)) { + weprintf("%s", path); + return -1; + } + } else if (!S_ISDIR(sb.st_mode)) { + weprintf("%s: %s", path, strerror(ENOTDIR)); + return -1; + } + *slash = '/'; + } + return 0; } char * find_backup_file_name(const char *file) { - char *dir, *base_versions, *tmp_file; - int highest_backup; - - if (backup_type == BACKUP_SIMPLE) - return patch_concat(file, simple_backup_suffix); - tmp_file = strdup(file); - if (tmp_file == NULL) - return NULL; - base_versions = patch_concat(basename(tmp_file), ".~"); - free(tmp_file); - if (base_versions == NULL) - return NULL; - tmp_file = strdup(file); - if (tmp_file == NULL) { - free(base_versions); - return NULL; - } - dir = dirname(tmp_file); - if (dir == NULL) { - free(base_versions); - free(tmp_file); - return NULL; - } - highest_backup = max_backup_version(base_versions, dir); - free(base_versions); - free(tmp_file); - if (backup_type == BACKUP_NUMBERED_EXISTING && highest_backup == 0) - return patch_concat(file, simple_backup_suffix); - return make_version_name(file, highest_backup + 1); + char *dir, *base_versions, *tmp_file; + int highest_backup; + + if (backup_type == BACKUP_SIMPLE) + return patch_concat(file, simple_backup_suffix); + tmp_file = strdup(file); + if (tmp_file == NULL) + return NULL; + base_versions = patch_concat(basename(tmp_file), ".~"); + free(tmp_file); + if (base_versions == NULL) + return NULL; + tmp_file = strdup(file); + if (tmp_file == NULL) { + free(base_versions); + return NULL; + } + dir = dirname(tmp_file); + if (dir == NULL) { + free(base_versions); + free(tmp_file); + return NULL; + } + highest_backup = max_backup_version(base_versions, dir); + free(base_versions); + free(tmp_file); + if (backup_type == BACKUP_NUMBERED_EXISTING && highest_backup == 0) + return patch_concat(file, simple_backup_suffix); + return make_version_name(file, highest_backup + 1); } static int max_backup_version(const char *file, const char *dir) { - DIR *dirp; - struct dirent *dp; - int highest_version, this_version; - size_t file_name_length; + DIR *dirp; + struct dirent *dp; + int highest_version, this_version; + size_t file_name_length; - dirp = opendir(dir); - if (dirp == NULL) - return 0; + dirp = opendir(dir); + if (dirp == NULL) + return 0; - highest_version = 0; - file_name_length = strlen(file); - while ((dp = readdir(dirp)) != NULL) { - if (strlen(dp->d_name) <= file_name_length) - continue; - this_version = version_number(file, dp->d_name, file_name_length); - if (this_version > highest_version) - highest_version = this_version; - } - closedir(dirp); - return highest_version; + highest_version = 0; + file_name_length = strlen(file); + while ((dp = readdir(dirp)) != NULL) { + if (strlen(dp->d_name) <= file_name_length) + continue; + this_version = version_number(file, dp->d_name, file_name_length); + if (this_version > highest_version) + highest_version = this_version; + } + closedir(dirp); + return highest_version; } static char * make_version_name(const char *file, int version_num) { - char *backup_name; + char *backup_name; - if (asprintf(&backup_name, "%s.~%d~", file, version_num) == -1) - return NULL; - return backup_name; + if (asprintf(&backup_name, "%s.~%d~", file, version_num) == -1) + return NULL; + return backup_name; } static int version_number(const char *base, const char *backup, size_t base_length) { - int version_num; - const char *p; + int version_num; + const char *p; - version_num = 0; - if (!strncmp(base, backup, base_length) && ISDIGIT(backup[base_length])) { - for (p = &backup[base_length]; ISDIGIT(*p); ++p) - version_num = version_num * 10 + *p - '0'; - if (p[0] != '~' || p[1]) - version_num = 0; - } - return version_num; + version_num = 0; + if (!strncmp(base, backup, base_length) && ISDIGIT(backup[base_length])) { + for (p = &backup[base_length]; ISDIGIT(*p); ++p) + version_num = version_num * 10 + *p - '0'; + if (p[0] != '~' || p[1]) + version_num = 0; + } + return version_num; } static char * patch_concat(const char *str1, const char *str2) { - char *newstr; + char *newstr; - if (asprintf(&newstr, "%s%s", str1, str2) == -1) - return NULL; - return newstr; + if (asprintf(&newstr, "%s%s", str1, str2) == -1) + return NULL; + return newstr; } static int argmatch(const char *arg, const char **optlist) { - int i; - size_t arglen; - int matchind = -1; - int ambiguous = 0; - - arglen = strlen(arg); - for (i = 0; optlist[i]; i++) { - if (!strncmp(optlist[i], arg, arglen)) { - if (strlen(optlist[i]) == arglen) - return i; - else if (matchind == -1) - matchind = i; - else - ambiguous = 1; - } - } - if (ambiguous) - return -2; - else - return matchind; + int i; + size_t arglen; + int matchind = -1; + int ambiguous = 0; + + arglen = strlen(arg); + for (i = 0; optlist[i]; i++) { + if (!strncmp(optlist[i], arg, arglen)) { + if (strlen(optlist[i]) == arglen) + return i; + else if (matchind == -1) + matchind = i; + else + ambiguous = 1; + } + } + if (ambiguous) + return -2; + else + return matchind; } static void invalid_arg(const char *kind, const char *value, int problem) { - fprintf(stderr, "patch: "); - if (problem == -1) - fprintf(stderr, "invalid"); - else - fprintf(stderr, "ambiguous"); - fprintf(stderr, " %s `%s'\n", kind, value); + fprintf(stderr, "patch: "); + if (problem == -1) + fprintf(stderr, "invalid"); + else + fprintf(stderr, "ambiguous"); + fprintf(stderr, " %s `%s'\n", kind, value); } enum BackupType get_version(const char *version_str) { - int i; + int i; - if (version_str == NULL || *version_str == '\0') - return BACKUP_NUMBERED_EXISTING; - i = argmatch(version_str, backup_args); - if (i >= 0) - return backup_types[i]; - invalid_arg("version control type", version_str, i); - exit(2); + if (version_str == NULL || *version_str == '\0') + return BACKUP_NUMBERED_EXISTING; + i = argmatch(version_str, backup_args); + if (i >= 0) + return backup_types[i]; + invalid_arg("version control type", version_str, i); + exit(2); } diff --git a/cmd/posix/sh/eval.c b/cmd/posix/sh/eval.c @@ -32,7 +32,6 @@ * SUCH DAMAGE. */ -#include <paths.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> @@ -43,6 +42,7 @@ * Evaluate a command. */ +#include "../../../shared/paths.h" #include "shell.h" #include "nodes.h" #include "syntax.h" @@ -989,7 +989,7 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) argv += 2; argc -= 2; } - path = _PATH_STDPATH; + path = ARUU_PATH_STDPATH; clearcmdentry(); do_clearcmdentry = 1; } else if (!strcmp(argv[1], "--")) { @@ -1318,7 +1318,7 @@ commandcmd(int argc __unused, char **argv __unused) while ((ch = nextopt("pvV")) != '\0') { switch (ch) { case 'p': - path = _PATH_STDPATH; + path = ARUU_PATH_STDPATH; break; case 'v': cmd = TYPECMD_SMALLV; diff --git a/cmd/posix/sh/exec.c b/cmd/posix/sh/exec.c @@ -37,7 +37,6 @@ #include <unistd.h> #include <fcntl.h> #include <errno.h> -#include <paths.h> #include <stdlib.h> /* @@ -49,6 +48,7 @@ * would make the command name "hash" a misnomer. */ +#include "../../../shared/paths.h" #include "shell.h" #include "main.h" #include "nodes.h" @@ -186,8 +186,8 @@ tryexec(char *cmd, char **argv, char **envp) } } *argv = cmd; - *--argv = __DECONST(char *, _PATH_BSHELL); - execve(_PATH_BSHELL, argv, envp); + *--argv = __DECONST(char *, ARUU_PATH_BSHELL); + execve(ARUU_PATH_BSHELL, argv, envp); } errno = e; } diff --git a/cmd/posix/sh/jobs.c b/cmd/posix/sh/jobs.c @@ -39,12 +39,12 @@ #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 "../../../shared/paths.h" #include "shell.h" #if JOBS #include <termios.h> @@ -179,7 +179,7 @@ setjobctl(int on) if (on) { if (ttyfd != -1) close(ttyfd); - if ((ttyfd = open(_PATH_TTY, O_RDWR | O_CLOEXEC)) < 0) { + if ((ttyfd = open(ARUU_PATH_DEVTTY, O_RDWR | O_CLOEXEC)) < 0) { i = 0; while (i <= 2 && !isatty(i)) i++; @@ -942,9 +942,9 @@ forkshell(struct job *jp, union node *n, int mode) if ((jp == NULL || jp->nprocs == 0) && ! fd0_redirected_p ()) { close(0); - if (open(_PATH_DEVNULL, O_RDONLY) != 0) + if (open(ARUU_PATH_DEVNULL, O_RDONLY) != 0) error("cannot open %s: %s", - _PATH_DEVNULL, strerror(errno)); + ARUU_PATH_DEVNULL, strerror(errno)); } } #else @@ -954,9 +954,9 @@ forkshell(struct job *jp, union node *n, int mode) if ((jp == NULL || jp->nprocs == 0) && ! fd0_redirected_p ()) { close(0); - if (open(_PATH_DEVNULL, O_RDONLY) != 0) + if (open(ARUU_PATH_DEVNULL, O_RDONLY) != 0) error("cannot open %s: %s", - _PATH_DEVNULL, strerror(errno)); + ARUU_PATH_DEVNULL, strerror(errno)); } } #endif diff --git a/cmd/posix/sh/lineedit.c b/cmd/posix/sh/lineedit.c @@ -39,6 +39,7 @@ #endif #include "util.h" +#include "../../../shared/paths.h" #include "shell.h" #include "alias.h" #include "builtins.h" @@ -63,7 +64,6 @@ #include <errno.h> #include <fcntl.h> #include <limits.h> -#include <paths.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> @@ -693,7 +693,7 @@ operands: if (editor) { int fd; INTOFF; - sprintf(editfilestr, "%s/_shXXXXXX", _PATH_TMP); + sprintf(editfilestr, "%s/_shXXXXXX", ARUU_PATH_TMP); if ((fd = mkstemp(editfilestr)) < 0) error("can't create temporary file %s", editfile); editfile = editfilestr; diff --git a/cmd/posix/sh/main.c b/cmd/posix/sh/main.c @@ -40,9 +40,9 @@ #include <locale.h> #include <errno.h> #include <termios.h> -#include <paths.h> #include <unistd.h> +#include "../../../shared/paths.h" #include "shell.h" #include "main.h" #include "mail.h" @@ -134,7 +134,7 @@ main(int argc, char *argv[]) * 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)open(ARUU_PATH_DEVCONSOLE, O_RDWR); (void)setsid(); (void)tcsetsid(STDIN_FILENO, rootpid); } diff --git a/cmd/posix/sh/var.c b/cmd/posix/sh/var.c @@ -32,6 +32,7 @@ * SUCH DAMAGE. */ +#include "../../../shared/paths.h" #include "shell.h" #include "output.h" #include "expand.h" @@ -53,7 +54,6 @@ #include <langinfo.h> #include <locale.h> -#include <paths.h> #include <stdlib.h> #include <unistd.h> @@ -102,7 +102,7 @@ static const struct varinit varinit[] = { NULL }, { &vmpath, VUNSET, "MAILPATH=", NULL }, - { &vpath, 0, "PATH=" _PATH_DEFPATH, + { &vpath, 0, "PATH=" ARUU_PATH_DEFPATH, changepath }, /* * vps1 depends on uid diff --git a/cmd/posix/time.c b/cmd/posix/time.c @@ -8,6 +8,7 @@ #include <stdio.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -50,9 +51,9 @@ main(int argc, char *argv[]) eprintf("fork:"); /* fallthrough */ case 0: - execvp(argv[0], argv); + wexecvp_self(argv[0], argv); savederrno = errno; - weprintf("execvp %s:", argv[0]); + weprintf("wexecvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); default: break; diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c @@ -11,6 +11,7 @@ #include <string.h> #include <unistd.h> +#include "wexec.h" #include "util.h" #define NARGS 10000 @@ -245,9 +246,9 @@ dospawn: eprintf("fork:"); /* fallthrough */ case 0: - execvp(*cmd, cmd); + wexecvp_self(*cmd, cmd); savederrno = errno; - weprintf("execvp %s:", *cmd); + weprintf("wexecvp %s:", *cmd); _exit(126 + (savederrno == ENOENT)); } curprocs++; diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c @@ -5,6 +5,7 @@ #include <stdlib.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -41,14 +42,14 @@ main(int argc, char *argv[]) if (argc == 1) { cmd = *shell; - execvp(cmd, shell); + wexecvp_self(cmd, shell); } else { cmd = argv[1]; - execvp(cmd, argv + 1); + wexecvp_self(cmd, argv + 1); } savederrno = errno; - weprintf("execvp %s:", cmd); + weprintf("wexecvp %s:", cmd); _exit(126 + (savederrno == ENOENT)); } diff --git a/cmd/pseudo/cron.c b/cmd/pseudo/cron.c @@ -17,6 +17,8 @@ #include <unistd.h> #include "queue.h" +#include "paths.h" +#include "wexec.h" #include "util.h" struct field { @@ -121,7 +123,7 @@ runjob(char *cmd) setsid(); loginfo("run: %s pid: %d at %s", cmd, getpid(), ctime(&t)); - execl("/bin/sh", "/bin/sh", "-c", cmd, (char *)NULL); + wexecv_self(ARUU_PATH_BIN "/sh", (char *const[]){"sh", "-c", cmd, NULL}); logerr("error: failed to execute job: %s time: %s", cmd, ctime(&t)); _exit(1); diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c @@ -9,6 +9,7 @@ #include <stdio.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -71,9 +72,9 @@ main(int argc, char *argv[]) if (oflag && close(fd) < 0) eprintf("close:"); argv++; - execvp(*argv, argv); + wexecvp_self(*argv, argv); savederrno = errno; - weprintf("execvp %s:", *argv); + weprintf("wexecvp %s:", *argv); _exit(126 + (savederrno == ENOENT)); default: break; diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c @@ -15,6 +15,7 @@ #include <utmp.h> #include "config.h" +#include "wexec.h" #include "util.h" static char *tty = "/dev/tty1"; @@ -23,7 +24,7 @@ static char *defaultterm = "linux"; static void usage(void) { - eprintf("usage: %s [tty] [term] [cmd] [args...]\n", argv0); + eprintf("usage: %s [tty] [term] [cmd] [args...]\n", argv0); } // ?man getty: set terminal mode @@ -32,117 +33,119 @@ usage(void) int main(int argc, char *argv[]) { - char term[128], logname[LOGIN_NAME_MAX], c; - char hostname[HOST_NAME_MAX + 1]; - char ut_line_buf[UT_LINESIZE + 1]; - struct utmp usr; - struct sigaction sa; - FILE *fp; - int fd; - unsigned int i = 0; - ssize_t n; - long pos; - - ARGBEGIN { - default: - usage(); - } ARGEND; - - strlcpy(term, defaultterm, sizeof(term)); - if (argc > 0) { - tty = argv[0]; - if (argc > 1) - strlcpy(term, argv[1], sizeof(term)); - } - - sa.sa_handler = SIG_IGN; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGHUP, &sa, NULL); - - setenv("TERM", term, 1); - - setsid(); - - fd = open(tty, O_RDWR); - if (fd < 0) - eprintf("open %s:", tty); - if (isatty(fd) == 0) - eprintf("%s is not a tty\n", tty); - - /* steal the controlling terminal if necessary */ - if (ioctl(fd, TIOCSCTTY, (void *)1) != 0) - weprintf("TIOCSCTTY: could not set controlling tty\n"); - vhangup(); - close(fd); - - fd = open(tty, O_RDWR); - if (fd < 0) - eprintf("open %s:", tty); - dup2(fd, 0); - dup2(fd, 1); - dup2(fd, 2); - if (fchown(fd, 0, 0) < 0) - weprintf("fchown %s:", tty); - if (fchmod(fd, 0600) < 0) - weprintf("fchmod %s:", tty); - if (fd > 2) - close(fd); - - sa.sa_handler = SIG_DFL; - sa.sa_flags = 0; - sigemptyset(&sa.sa_mask); - sigaction(SIGHUP, &sa, NULL); - - /* Clear all utmp entries for this tty */ - fp = fopen(UTMP_PATH, "r+"); - if (fp) { - do { - pos = ftell(fp); - if (fread(&usr, sizeof(usr), 1, fp) != 1) - break; - if (usr.ut_line[0] == '\0') - continue; - memcpy(ut_line_buf, usr.ut_line, UT_LINESIZE); - ut_line_buf[UT_LINESIZE] = '\0'; - if (strcmp(ut_line_buf, tty) != 0) - continue; - memset(&usr, 0, sizeof(usr)); - fseek(fp, pos, SEEK_SET); - if (fwrite(&usr, sizeof(usr), 1, fp) != 1) - break; - } while (1); - if (ferror(fp)) - weprintf("%s: I/O error:", UTMP_PATH); - fclose(fp); - } - - if (argc > 2) - return execvp(argv[2], argv + 2); - - if (gethostname(hostname, sizeof(hostname)) == 0) - printf("%s ", hostname); - printf("login: "); - fflush(stdout); - - /* Flush pending input */ - ioctl(0, TCFLSH, (void *)0); - memset(logname, 0, sizeof(logname)); - while (1) { - n = read(0, &c, 1); - if (n < 0) - eprintf("read:"); - if (n == 0) - return 1; - if (i >= sizeof(logname) - 1) - eprintf("login name too long\n"); - if (c == '\n' || c == '\r') - break; - logname[i++] = c; - } - if (logname[0] == '-') - eprintf("login name cannot start with '-'\n"); - if (logname[0] == '\0') - return 1; - return execlp("/bin/login", "login", "-p", logname, NULL); + char term[128], logname[LOGIN_NAME_MAX], c; + char hostname[HOST_NAME_MAX + 1]; + char ut_line_buf[UT_LINESIZE + 1]; + struct utmp usr; + struct sigaction sa; + FILE *fp; + int fd; + unsigned int i = 0; + ssize_t n; + long pos; + + ARGBEGIN { + default: + usage(); + } ARGEND; + + strlcpy(term, defaultterm, sizeof(term)); + if (argc > 0) { + tty = argv[0]; + if (argc > 1) + strlcpy(term, argv[1], sizeof(term)); + } + + sa.sa_handler = SIG_IGN; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sigaction(SIGHUP, &sa, NULL); + + setenv("TERM", term, 1); + + setsid(); + + fd = open(tty, O_RDWR); + if (fd < 0) + eprintf("open %s:", tty); + if (isatty(fd) == 0) + eprintf("%s is not a tty\n", tty); + + /* steal the controlling terminal if necessary */ + if (ioctl(fd, TIOCSCTTY, (void *)1) != 0) + weprintf("TIOCSCTTY: could not set controlling tty\n"); + vhangup(); + close(fd); + + fd = open(tty, O_RDWR); + if (fd < 0) + eprintf("open %s:", tty); + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + if (fchown(fd, 0, 0) < 0) + weprintf("fchown %s:", tty); + if (fchmod(fd, 0600) < 0) + weprintf("fchmod %s:", tty); + if (fd > 2) + close(fd); + + sa.sa_handler = SIG_DFL; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sigaction(SIGHUP, &sa, NULL); + + /* Clear all utmp entries for this tty */ + fp = fopen(UTMP_PATH, "r+"); + if (fp) { + do { + pos = ftell(fp); + if (fread(&usr, sizeof(usr), 1, fp) != 1) + break; + if (usr.ut_line[0] == '\0') + continue; + memcpy(ut_line_buf, usr.ut_line, UT_LINESIZE); + ut_line_buf[UT_LINESIZE] = '\0'; + if (strcmp(ut_line_buf, tty) != 0) + continue; + memset(&usr, 0, sizeof(usr)); + fseek(fp, pos, SEEK_SET); + if (fwrite(&usr, sizeof(usr), 1, fp) != 1) + break; + } while (1); + if (ferror(fp)) + weprintf("%s: I/O error:", UTMP_PATH); + fclose(fp); + } + + if (argc > 2) { + wexecvp_self(argv[2], argv + 2); + return 0; + } + + if (gethostname(hostname, sizeof(hostname)) == 0) + printf("%s ", hostname); + printf("login: "); + fflush(stdout); + + /* Flush pending input */ + ioctl(0, TCFLSH, (void *)0); + memset(logname, 0, sizeof(logname)); + while (1) { + n = read(0, &c, 1); + if (n < 0) + eprintf("read:"); + if (n == 0) + return 1; + if (i >= sizeof(logname) - 1) + eprintf("login name too long\n"); + if (c == '\n' || c == '\r') + break; + logname[i++] = c; + } + if (logname[0] == '-') + eprintf("login name cannot start with '-'\n"); + if (logname[0] == '\0') + return 1; + wexecvp_self("login", (char *const[]){"login", "-p", logname, NULL}); return 0; } diff --git a/cmd/pseudo/last.c b/cmd/pseudo/last.c @@ -3,7 +3,6 @@ #include <errno.h> #include <libgen.h> -#include <paths.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> @@ -13,6 +12,7 @@ #include <unistd.h> #include "config.h" +#include "paths.h" #include "util.h" static void diff --git a/cmd/pseudo/lastlog.c b/cmd/pseudo/lastlog.c @@ -2,7 +2,6 @@ #include <errno.h> -#include <paths.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> @@ -11,6 +10,7 @@ #include <utmp.h> #include "text.h" +#include "paths.h" #include "util.h" #define PASSWD "/etc/passwd" @@ -37,7 +37,7 @@ lastlog(char *user) fread(&ll, sizeof(struct lastlog), 1, last); if (ferror(last)) - eprintf("%s: read error:", _PATH_LASTLOG); + eprintf("%s: read error:", ARUU_PATH_LASTLOG); /* on glibc `ll_time' can be an int32_t with compat32 * avoid compiler warning when calling ctime() */ @@ -55,8 +55,8 @@ main(int argc, char **argv) char *line = NULL, *p; size_t sz = 0; - if ((last = fopen(_PATH_LASTLOG, "r")) == NULL) - eprintf("fopen %s:", _PATH_LASTLOG); + if ((last = fopen(ARUU_PATH_LASTLOG, "r")) == NULL) + eprintf("fopen %s:", ARUU_PATH_LASTLOG); if (argc > 1) { while (*++argv) @@ -76,7 +76,7 @@ main(int argc, char **argv) } if (fclose(last)) - eprintf("fclose %s:", _PATH_LASTLOG); + eprintf("fclose %s:", ARUU_PATH_LASTLOG); return 0; } diff --git a/cmd/pseudo/login.c b/cmd/pseudo/login.c @@ -16,6 +16,7 @@ #include "config.h" #include "passwd.h" +#include "wexec.h" #include "util.h" /* Write utmp entry */ @@ -58,8 +59,8 @@ dologin(struct passwd *pw, int preserve) setenv("PATH", ENV_PATH, 1); if (chdir(pw->pw_dir) < 0) eprintf("chdir %s:", pw->pw_dir); - execlp(shell, shell, "-l", NULL); - weprintf("execlp %s:", shell); + wexecvp_self(shell, (char *const[]){shell, "-l", NULL}); + weprintf("wexecvp %s:", shell); return (errno == ENOENT) ? 127 : 126; } diff --git a/cmd/pseudo/mkpasswd.c b/cmd/pseudo/mkpasswd.c @@ -1,8 +1,9 @@ /* See LICENSE file for copyright and license details. */ +#include "passwd.h" +#include "paths.h" #include "util.h" #include <ctype.h> -#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -11,7 +12,7 @@ static void usage(void) { - eprintf("usage: %s [-P fd] [-m type] [-S salt] [password] [salt]\n", argv0); + eprintf("usage: %s [-P fd] [-m type] [-S salt] [password] [salt]\n", argv0); } // ?man mkpasswd: encrypt the given password using salt @@ -20,145 +21,116 @@ usage(void) int main(int argc, char *argv[]) { - char *mflag; - char *sflag; - char *parg; - char *password; - char *cryptpass; - int pfd; - int fd; - int r; - int i; - int len; - int id; - char salt[128]; - char rand_bytes[32]; - char passbuf[1024]; - static const char saltchars[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - - mflag = NULL; - sflag = NULL; - parg = NULL; - password = NULL; - cryptpass = NULL; - pfd = -1; - - ARGBEGIN { - // ?man -P:fd: read password from file descriptor - case 'P': - parg = EARGF(usage()); - pfd = estrtonum(parg, 0, INT_MAX); - break; - // ?man -m:type: encryption method (des, md5, sha256, sha512) - case 'm': - mflag = EARGF(usage()); - break; - // ?man -S:salt: salt to use - case 'S': - sflag = EARGF(usage()); - break; - default: - usage(); - } ARGEND - - if (argc > 2) - usage(); - - if (argc == 2) { - if (sflag) - eprintf("duplicate salt\n"); - sflag = argv[1]; - } - - if (argc >= 1) - password = argv[0]; - - /* default type is des */ - if (!mflag) - mflag = "des"; - - if (strcasecmp(mflag, "des") == 0) { - id = 0; - len = 2; - } else if (strcasecmp(mflag, "md5") == 0) { - id = 1; - len = 8; - } else if (strcasecmp(mflag, "sha256") == 0) { - id = 5; - len = 16; - } else if (strcasecmp(mflag, "sha512") == 0) { - id = 6; - len = 16; - } else { - eprintf("bad method: %s\n", mflag); - } - - if (sflag) { - /* validate provided salt */ - char *s = sflag; - while (*s) { - if (!isalnum((unsigned char)*s) && *s != '.' && *s != '/') - eprintf("bad SALT (need [a-zA-Z0-9./])\n"); - s++; - } - if (id > 0) - snprintf(salt, sizeof(salt), "$%d$%s", id, sflag); - else - estrlcpy(salt, sflag, sizeof(salt)); - } else { - /* generate random salt */ - fd = open("/dev/urandom", O_RDONLY); - if (fd < 0) - eprintf("open /dev/urandom:"); - r = read(fd, rand_bytes, len); - if (r < len) - eprintf("read /dev/urandom:"); - close(fd); - - if (id > 0) { - snprintf(salt, sizeof(salt), "$%d$", id); - for (i = 0; i < len; i++) - salt[3 + i] = saltchars[(unsigned char)rand_bytes[i] % 64]; - salt[3 + len] = '\0'; - } else { - for (i = 0; i < len; i++) - salt[i] = saltchars[(unsigned char)rand_bytes[i] % 64]; - salt[len] = '\0'; - } - } - - if (pfd >= 0) { - if (dup2(pfd, 0) == -1) - eprintf("dup2:"); - close(pfd); - } - - if (!password) { - if (isatty(0)) { - char *p = getpass("Password: "); - if (!p) - eprintf("getpass failed\n"); - estrlcpy(passbuf, p, sizeof(passbuf)); - password = passbuf; - } else { - /* read from stdin */ - int bytes = read(0, passbuf, sizeof(passbuf) - 1); - if (bytes < 0) - eprintf("read stdin:"); - /* strip trailing newline or cr */ - while (bytes > 0 && (passbuf[bytes - 1] == '\n' || passbuf[bytes - 1] == '\r')) - bytes--; - passbuf[bytes] = '\0'; - password = passbuf; - } - } - - cryptpass = crypt(password, salt); - if (!cryptpass) - eprintf("crypt:"); - printf("%s\n", cryptpass); - - if (fshut(stdout, "<stdout>")) - return 2; - return 0; + char *mflag, *sflag, *parg, *password, *cryptpass; + char *prefix; + char salt[128]; + char passbuf[1024]; + int pfd, len; + + mflag = NULL; + sflag = NULL; + parg = NULL; + password = NULL; + cryptpass = NULL; + pfd = -1; + len = 2; + prefix = NULL; + + ARGBEGIN { + case 'P': + // ?man -P:fd: read password from file descriptor + parg = EARGF(usage()); + pfd = estrtonum(parg, 0, INT_MAX); + break; + case 'm': + // ?man -m:type: encryption method (des, md5, sha256, sha512) + mflag = EARGF(usage()); + break; + case 'S': + // ?man -S:salt: salt to use + sflag = EARGF(usage()); + break; + default: + usage(); + } ARGEND + + if (argc > 2) + usage(); + + if (argc == 2) { + if (sflag) + eprintf("duplicate salt\n"); + sflag = argv[1]; + } + + if (argc >= 1) + password = argv[0]; + + if (!mflag) + mflag = "des"; + + if (strcasecmp(mflag, "des") == 0) { + len = 2; + prefix = NULL; + } else if (strcasecmp(mflag, "md5") == 0) { + len = 8; + prefix = "$1$"; + } else if (strcasecmp(mflag, "sha256") == 0) { + len = 16; + prefix = "$5$"; + } else if (strcasecmp(mflag, "sha512") == 0) { + len = 16; + prefix = "$6$"; + } else { + eprintf("bad method: %s\n", mflag); + } + + if (sflag) { + char *s = sflag; + while (*s) { + if (!isalnum((unsigned char)*s) && *s != '.' && *s != '/') + eprintf("bad SALT (need [a-zA-Z0-9./])\n"); + s++; + } + if (prefix) + snprintf(salt, sizeof(salt), "%s%s", prefix, sflag); + else + estrlcpy(salt, sflag, sizeof(salt)); + } else { + if (pw_gensalt_cipher(salt, sizeof(salt), prefix, len) < 0) + eprintf("pw_gensalt_cipher:"); + } + + if (pfd >= 0) { + if (dup2(pfd, 0) == -1) + eprintf("dup2:"); + close(pfd); + } + + if (!password) { + if (isatty(0)) { + char *p = getpass("Password: "); + if (!p) + eprintf("getpass failed\n"); + estrlcpy(passbuf, p, sizeof(passbuf)); + password = passbuf; + } else { + int bytes = read(0, passbuf, sizeof(passbuf) - 1); + if (bytes < 0) + eprintf("read stdin:"); + while (bytes > 0 && (passbuf[bytes - 1] == '\n' || passbuf[bytes - 1] == '\r')) + bytes--; + passbuf[bytes] = '\0'; + password = passbuf; + } + } + + cryptpass = crypt(password, salt); + if (!cryptpass) + eprintf("crypt:"); + printf("%s\n", cryptpass); + + if (fshut(stdout, "<stdout>")) + return 2; + return 0; } diff --git a/cmd/pseudo/respawn.c b/cmd/pseudo/respawn.c @@ -14,6 +14,7 @@ #include <stdlib.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -103,9 +104,9 @@ main(int argc, char *argv[]) eprintf("fork:"); switch (pid) { case 0: - execvp(argv[0], argv); + wexecvp_self(argv[0], argv); savederrno = errno; - weprintf("execvp %s:", argv[0]); + weprintf("wexecvp %s:", argv[0]); _exit(savederrno == ENOENT ? 127 : 126); break; default: diff --git a/cmd/pseudo/setsid.c b/cmd/pseudo/setsid.c @@ -4,6 +4,7 @@ #include <errno.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static int fflag = 0; @@ -46,9 +47,9 @@ main(int argc, char *argv[]) } if (setsid() < 0) eprintf("setsid:"); - execvp(argv[0], argv); + wexecvp_self(argv[0], argv); savederrno = errno; - weprintf("execvp %s:", argv[0]); + weprintf("wexecvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); } diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -3,6 +3,7 @@ #include "config.h" #include "fs.h" #include "utf.h" +#include "wexec.h" #include "util.h" #include <assert.h> @@ -25,27 +26,27 @@ static void safe_puts(const char *s) { - Rune r; - int n; - - if (isatty(1)) { - while (*s) { - n = chartorune(&r, s); - if (r == Runeerror) { - putchar('?'); - s++; - } else if (isprintrune(r)) { - fputrune(&r, stdout); - s += n; - } else { - putchar('?'); - s += n; - } - } - putchar('\n'); - } else { - puts(s); - } + Rune r; + int n; + + if (isatty(1)) { + while (*s) { + n = chartorune(&r, s); + if (r == Runeerror) { + putchar('?'); + s++; + } else if (isprintrune(r)) { + fputrune(&r, stdout); + s += n; + } else { + putchar('?'); + s += n; + } + } + putchar('\n'); + } else { + puts(s); + } } #else #define safe_puts(s) puts(s) @@ -54,40 +55,40 @@ safe_puts(const char *s) #define BLKSIZ (sizeof (struct header)) /* must equal 512 bytes */ enum Type { - REG = '0', - AREG = '\0', - HARDLINK = '1', - SYMLINK = '2', - CHARDEV = '3', - BLOCKDEV = '4', - DIRECTORY = '5', - FIFO = '6', - RESERVED = '7' + REG = '0', + AREG = '\0', + HARDLINK = '1', + SYMLINK = '2', + CHARDEV = '3', + BLOCKDEV = '4', + DIRECTORY = '5', + FIFO = '6', + RESERVED = '7' }; struct header { - char name[100]; - char mode[8]; - char uid[8]; - char gid[8]; - char size[12]; - char mtime[12]; - char chksum[8]; - char type; - char linkname[100]; - char magic[6]; - char version[2]; - char uname[32]; - char gname[32]; - char major[8]; - char minor[8]; - char prefix[155]; - char padding[12]; + char name[100]; + char mode[8]; + char uid[8]; + char gid[8]; + char size[12]; + char mtime[12]; + char chksum[8]; + char type; + char linkname[100]; + char magic[6]; + char version[2]; + char uname[32]; + char gname[32]; + char major[8]; + char minor[8]; + char prefix[155]; + char padding[12]; }; static struct dirtime { - char *name; - time_t mtime; + char *name; + time_t mtime; } *dirtimes; static size_t dirtimeslen; @@ -106,33 +107,33 @@ 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); + 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; + 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[] = { - ['J'] = "xz", - ['Z'] = "compress", - ['a'] = "lzma", - ['j'] = "bzip2", - ['z'] = "gzip", + ['J'] = "xz", + ['Z'] = "compress", + ['a'] = "lzma", + ['j'] = "bzip2", + ['z'] = "gzip", }; #if FEATURE_TAR_TO_STDOUT @@ -153,17 +154,17 @@ static int strip_components_count = 0; static char * strip_components(char *path, int count) { - char *p = path; - int i; - - for (i = 0; i < count; i++) { - p = strchr(p, '/'); - if (!p) - return NULL; - while (*p == '/') - p++; - } - return p; + char *p = path; + int i; + + for (i = 0; i < count; i++) { + p = strchr(p, '/'); + if (!p) + return NULL; + while (*p == '/') + p++; + } + return p; } #else #define strip_components_count 0 @@ -176,27 +177,27 @@ static size_t files_from_cnt = 0; static void add_files_from(const char *path) { - files_from = ereallocarray(files_from, files_from_cnt + 1, sizeof(*files_from)); - files_from[files_from_cnt++] = estrdup(path); + files_from = ereallocarray(files_from, files_from_cnt + 1, sizeof(*files_from)); + files_from[files_from_cnt++] = estrdup(path); } static void load_files_from_file(const char *path) { - FILE *fp = fopen(path, "r"); - char line[PATH_MAX]; - - if (!fp) - eprintf("open %s:", path); - while (fgets(line, sizeof(line), fp)) { - size_t len = strlen(line); - while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) - len--; - line[len] = '\0'; - if (len > 0) - add_files_from(line); - } - fclose(fp); + FILE *fp = fopen(path, "r"); + char line[PATH_MAX]; + + if (!fp) + eprintf("open %s:", path); + while (fgets(line, sizeof(line), fp)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) + len--; + line[len] = '\0'; + if (len > 0) + add_files_from(line); + } + fclose(fp); } #else #define files_from_cnt 0 @@ -206,581 +207,593 @@ load_files_from_file(const char *path) static void load_excludes_from_file(const char *path) { - FILE *fp = fopen(path, "r"); - char line[PATH_MAX]; - - if (!fp) - eprintf("open %s:", path); - while (fgets(line, sizeof(line), fp)) { - size_t len = strlen(line); - while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) - len--; - line[len] = '\0'; - if (len > 0) { + FILE *fp = fopen(path, "r"); + char line[PATH_MAX]; + + if (!fp) + eprintf("open %s:", path); + while (fgets(line, sizeof(line), fp)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) + len--; + line[len] = '\0'; + if (len > 0) { #if FEATURE_TAR_EXCLUDE - add_exclude(line); + add_exclude(line); #else - (void)line; + (void)line; #endif - } - } - fclose(fp); + } + } + fclose(fp); } #endif static void pushdirtime(char *name, time_t mtime) { - dirtimes = ereallocarray(dirtimes, dirtimeslen + 1, sizeof(*dirtimes)); - dirtimes[dirtimeslen].name = estrdup(name); - dirtimes[dirtimeslen].mtime = mtime; - dirtimeslen++; + dirtimes = ereallocarray(dirtimes, dirtimeslen + 1, sizeof(*dirtimes)); + dirtimes[dirtimeslen].name = estrdup(name); + dirtimes[dirtimeslen].mtime = mtime; + dirtimeslen++; } static struct dirtime * popdirtime(void) { - if (dirtimeslen) { - dirtimeslen--; - return &dirtimes[dirtimeslen]; - } - return NULL; + if (dirtimeslen) { + dirtimeslen--; + return &dirtimes[dirtimeslen]; + } + return NULL; } static int comp(int fd, const char *tool, const char *flags) { - int fds[2]; - - if (pipe(fds) < 0) - eprintf("pipe:"); - - switch (fork()) { - case -1: - eprintf("fork:"); - /* fallthrough */ - case 0: - dup2(fd, 1); - dup2(fds[0], 0); - close(fds[0]); - close(fds[1]); - - execlp(tool, tool, flags, NULL); - weprintf("execlp %s:", tool); - _exit(1); - } - close(fds[0]); - return fds[1]; + int fds[2]; + + if (pipe(fds) < 0) + eprintf("pipe:"); + + switch (fork()) { + case -1: + eprintf("fork:"); + /* fallthrough */ + case 0: + dup2(fd, 1); + dup2(fds[0], 0); + close(fds[0]); + close(fds[1]); + + { + char *tar_argv[3]; + tar_argv[0] = (char *)tool; + tar_argv[1] = (char *)flags; + tar_argv[2] = NULL; + wexecvp_self(tool, tar_argv); + } + weprintf("wexecvp %s:", tool); + _exit(1); + } + close(fds[0]); + return fds[1]; } static int decomp(int fd, const char *tool, const char *flags) { - int fds[2]; - - if (pipe(fds) < 0) - eprintf("pipe:"); - - switch (fork()) { - case -1: - eprintf("fork:"); - /* fallthrough */ - case 0: - dup2(fd, 0); - dup2(fds[1], 1); - close(fds[0]); - close(fds[1]); - - execlp(tool, tool, flags, NULL); - weprintf("execlp %s:", tool); - _exit(1); - } - close(fds[1]); - return fds[0]; + int fds[2]; + + if (pipe(fds) < 0) + eprintf("pipe:"); + + switch (fork()) { + case -1: + eprintf("fork:"); + /* fallthrough */ + case 0: + dup2(fd, 0); + dup2(fds[1], 1); + close(fds[0]); + close(fds[1]); + + { + char *tar_argv[3]; + tar_argv[0] = (char *)tool; + tar_argv[1] = (char *)flags; + tar_argv[2] = NULL; + wexecvp_self(tool, tar_argv); + } + weprintf("wexecvp %s:", tool); + _exit(1); + } + close(fds[1]); + return fds[0]; } static ssize_t eread(int fd, void *buf, size_t n) { - ssize_t r; + ssize_t r; again: - r = read(fd, buf, n); - if (r < 0) { - if (errno == EINTR) - goto again; - eprintf("read:"); - } - return r; + r = read(fd, buf, n); + if (r < 0) { + if (errno == EINTR) + goto again; + eprintf("read:"); + } + return r; } static ssize_t ewrite(int fd, const void *buf, size_t n) { - ssize_t r; + ssize_t r; - if ((r = write(fd, buf, n)) < 0 || (size_t)r != n) - eprintf("write:"); - return r; + if ((r = write(fd, buf, n)) < 0 || (size_t)r != n) + eprintf("write:"); + return r; } static unsigned chksum(struct header *h) { - unsigned sum, i; + unsigned sum, i; - memset(h->chksum, ' ', sizeof(h->chksum)); - for (i = 0, sum = 0, assert(BLKSIZ == 512); i < BLKSIZ; i++) - sum += *((unsigned char *)h + i); - return sum; + memset(h->chksum, ' ', sizeof(h->chksum)); + for (i = 0, sum = 0, assert(BLKSIZ == 512); i < BLKSIZ; i++) + sum += *((unsigned char *)h + i); + return sum; } #if FEATURE_TAR_CREATE static void putoctal(char *dst, unsigned num, int size) { - if (snprintf(dst, size, "%.*o", size - 1, num) >= size) - eprintf("putoctal: input number '%o' too large\n", num); + if (snprintf(dst, size, "%.*o", size - 1, num) >= size) + eprintf("putoctal: input number '%o' too large\n", num); } static int archive(const char *path) { - static const struct header blank = { - .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; - struct group *gr; - struct passwd *pw; - struct stat st; - ssize_t l, n, r; - int fd = -1; - - if (lstat(path, &st) < 0) { - weprintf("lstat %s:", path); - return 0; - } else if (st.st_ino == tarinode && st.st_dev == tardev) { - weprintf("ignoring %s\n", path); - return 0; - } - pw = getpwuid(st.st_uid); - gr = getgrgid(st.st_gid); - - *h = blank; - n = strlcpy(h->name, path, sizeof(h->name)); - if ((size_t)n >= sizeof(h->name)) { - *++h = blank; - h->type = 'L'; - putoctal(h->size, n, sizeof(h->size)); - putoctal(h->chksum, chksum(h), sizeof(h->chksum)); - ewrite(tarfd, (char *)h, BLKSIZ); - - for (p = (char *)path; n > 0; n -= BLKSIZ, p += BLKSIZ) { - if ((size_t)n < BLKSIZ) { - p = memcpy(h--, p, n); - memset(p + n, 0, BLKSIZ - (size_t)n); - } - ewrite(tarfd, p, BLKSIZ); - } - } - - putoctal(h->mode, (unsigned)st.st_mode & 0777, sizeof(h->mode)); - putoctal(h->uid, (unsigned)st.st_uid, sizeof(h->uid)); - putoctal(h->gid, (unsigned)st.st_gid, sizeof(h->gid)); - putoctal(h->mtime, (unsigned)st.st_mtime, sizeof(h->mtime)); - estrlcpy(h->uname, pw ? pw->pw_name : "", sizeof(h->uname)); - estrlcpy(h->gname, gr ? gr->gr_name : "", sizeof(h->gname)); - - if (S_ISREG(st.st_mode)) { - h->type = REG; - putoctal(h->size, st.st_size, sizeof(h->size)); - fd = open(path, O_RDONLY); - if (fd < 0) - eprintf("open %s:", path); - } else if (S_ISDIR(st.st_mode)) { - h->type = DIRECTORY; - } else if (S_ISLNK(st.st_mode)) { - h->type = SYMLINK; - if ((r = readlink(path, h->linkname, sizeof(h->linkname) - 1)) < 0) - eprintf("readlink %s:", path); - h->linkname[r] = '\0'; - } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) { - h->type = S_ISCHR(st.st_mode) ? CHARDEV : BLOCKDEV; - putoctal(h->major, (unsigned)major(st.st_dev), sizeof(h->major)); - putoctal(h->minor, (unsigned)minor(st.st_dev), sizeof(h->minor)); - } else if (S_ISFIFO(st.st_mode)) { - h->type = FIFO; - } - - putoctal(h->chksum, chksum(h), sizeof(h->chksum)); - ewrite(tarfd, b, BLKSIZ); - - if (fd != -1) { - while ((l = eread(fd, b, BLKSIZ)) > 0) { - if ((size_t)l < BLKSIZ) - memset(b + l, 0, BLKSIZ - (size_t)l); - ewrite(tarfd, b, BLKSIZ); - } - close(fd); - } - - return 0; + static const struct header blank = { + .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; + struct group *gr; + struct passwd *pw; + struct stat st; + ssize_t l, n, r; + int fd = -1; + + if (lstat(path, &st) < 0) { + weprintf("lstat %s:", path); + return 0; + } else if (st.st_ino == tarinode && st.st_dev == tardev) { + weprintf("ignoring %s\n", path); + return 0; + } + pw = getpwuid(st.st_uid); + gr = getgrgid(st.st_gid); + + *h = blank; + n = strlcpy(h->name, path, sizeof(h->name)); + if ((size_t)n >= sizeof(h->name)) { + *++h = blank; + h->type = 'L'; + putoctal(h->size, n, sizeof(h->size)); + putoctal(h->chksum, chksum(h), sizeof(h->chksum)); + ewrite(tarfd, (char *)h, BLKSIZ); + + for (p = (char *)path; n > 0; n -= BLKSIZ, p += BLKSIZ) { + if ((size_t)n < BLKSIZ) { + p = memcpy(h--, p, n); + memset(p + n, 0, BLKSIZ - (size_t)n); + } + ewrite(tarfd, p, BLKSIZ); + } + } + + putoctal(h->mode, (unsigned)st.st_mode & 0777, sizeof(h->mode)); + putoctal(h->uid, (unsigned)st.st_uid, sizeof(h->uid)); + putoctal(h->gid, (unsigned)st.st_gid, sizeof(h->gid)); + putoctal(h->mtime, (unsigned)st.st_mtime, sizeof(h->mtime)); + estrlcpy(h->uname, pw ? pw->pw_name : "", sizeof(h->uname)); + estrlcpy(h->gname, gr ? gr->gr_name : "", sizeof(h->gname)); + + if (S_ISREG(st.st_mode)) { + h->type = REG; + putoctal(h->size, st.st_size, sizeof(h->size)); + fd = open(path, O_RDONLY); + if (fd < 0) + eprintf("open %s:", path); + } else if (S_ISDIR(st.st_mode)) { + h->type = DIRECTORY; + } else if (S_ISLNK(st.st_mode)) { + h->type = SYMLINK; + if ((r = readlink(path, h->linkname, sizeof(h->linkname) - 1)) < 0) + eprintf("readlink %s:", path); + h->linkname[r] = '\0'; + } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) { + h->type = S_ISCHR(st.st_mode) ? CHARDEV : BLOCKDEV; + putoctal(h->major, (unsigned)major(st.st_dev), sizeof(h->major)); + putoctal(h->minor, (unsigned)minor(st.st_dev), sizeof(h->minor)); + } else if (S_ISFIFO(st.st_mode)) { + h->type = FIFO; + } + + putoctal(h->chksum, chksum(h), sizeof(h->chksum)); + ewrite(tarfd, b, BLKSIZ); + + if (fd != -1) { + while ((l = eread(fd, b, BLKSIZ)) > 0) { + if ((size_t)l < BLKSIZ) + memset(b + l, 0, BLKSIZ - (size_t)l); + ewrite(tarfd, b, BLKSIZ); + } + close(fd); + } + + return 0; } #endif static void skipblk(ssize_t l) { - char b[BLKSIZ]; + char b[BLKSIZ]; - for (; l > 0; l -= BLKSIZ) - if (!eread(tarfd, b, BLKSIZ)) - break; + for (; l > 0; l -= BLKSIZ) + if (!eread(tarfd, b, BLKSIZ)) + break; } static int unarchive(char *fname, ssize_t l, char b[BLKSIZ]) { - struct header *h = (struct header *)b; - struct timespec times[2]; - struct stat st; - char lname[101], *tmp, *p; - long mode, major, minor, type, mtime, uid, gid; - int fd = -1, lnk = h->type == SYMLINK; - - if (kflag_keep && !Oflag_stdout) { - if (lstat(fname, &st) == 0) { - skipblk(l); - return 0; - } - } - - if (!mflag && ((mtime = strtol(h->mtime, &p, 8)) < 0 || *p != '\0')) - eprintf("strtol %s: invalid mtime\n", h->mtime); - - if (Oflag_stdout) { - if (h->type == REG || h->type == AREG || h->type == RESERVED) { - fd = 1; - } else { - return 0; - } - } else { - if (strcmp(fname, ".") && strcmp(fname, "./") && remove(fname) < 0) - if (errno != ENOENT) weprintf("remove %s:", fname); - - tmp = estrdup(fname); - mkdirp(dirname(tmp), 0777, 0777); - free(tmp); - - switch (h->type) { - case REG: - case AREG: - case RESERVED: - if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid mode\n", h->mode); + struct header *h = (struct header *)b; + struct timespec times[2]; + struct stat st; + char lname[101], *tmp, *p; + long mode, major, minor, type, mtime, uid, gid; + int fd = -1, lnk = h->type == SYMLINK; + + if (kflag_keep && !Oflag_stdout) { + if (lstat(fname, &st) == 0) { + skipblk(l); + return 0; + } + } + + if (!mflag && ((mtime = strtol(h->mtime, &p, 8)) < 0 || *p != '\0')) + eprintf("strtol %s: invalid mtime\n", h->mtime); + + if (Oflag_stdout) { + if (h->type == REG || h->type == AREG || h->type == RESERVED) { + fd = 1; + } else { + return 0; + } + } else { + if (strcmp(fname, ".") && strcmp(fname, "./") && remove(fname) < 0) + if (errno != ENOENT) weprintf("remove %s:", fname); + + tmp = estrdup(fname); + mkdirp(dirname(tmp), 0777, 0777); + free(tmp); + + switch (h->type) { + case REG: + case AREG: + case RESERVED: + if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid mode\n", h->mode); #if FEATURE_TAR_NOFOLLOW - fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, 0600); + fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT | O_NOFOLLOW, 0600); #else - fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT, 0600); + fd = open(fname, O_WRONLY | O_TRUNC | O_CREAT, 0600); #endif - if (fd < 0) - eprintf("open %s:", fname); - break; - case HARDLINK: - case SYMLINK: - snprintf(lname, sizeof(lname), "%.*s", (int)sizeof(h->linkname), - h->linkname); - if ((lnk ? symlink:link)(lname, fname) < 0) - eprintf("%s %s -> %s:", lnk ? "symlink":"link", fname, lname); - lnk++; - break; - case DIRECTORY: - if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid mode\n", h->mode); - if (mkdir(fname, (mode_t)mode) < 0 && errno != EEXIST) - eprintf("mkdir %s:", fname); - pushdirtime(fname, mtime); - break; - case CHARDEV: - case BLOCKDEV: - if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid mode\n", h->mode); - if ((major = strtol(h->major, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid major device\n", h->major); - if ((minor = strtol(h->minor, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid minor device\n", h->minor); - type = (h->type == CHARDEV) ? S_IFCHR : S_IFBLK; - if (mknod(fname, type | mode, makedev(major, minor)) < 0) - eprintf("mknod %s:", fname); - break; - case FIFO: - if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid mode\n", h->mode); - if (mknod(fname, S_IFIFO | mode, 0) < 0) - eprintf("mknod %s:", fname); - break; - default: - eprintf("unsupported tar-filetype %c\n", h->type); - } - } - - if (!Oflag_stdout) { - if ((uid = strtol(h->uid, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid uid\n", h->uid); - if ((gid = strtol(h->gid, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid gid\n", h->gid); - } - - if (fd != -1) { - for (; l > 0; l -= BLKSIZ) - if (eread(tarfd, b, BLKSIZ) > 0) - ewrite(fd, b, MIN(l, (ssize_t)BLKSIZ)); - if (fd != 1) - close(fd); - } - - if (Oflag_stdout) - return 0; - - if (lnk == 1) - return 0; - - times[0].tv_sec = times[1].tv_sec = mtime; - times[0].tv_nsec = times[1].tv_nsec = 0; - if (!mflag && utimensat(AT_FDCWD, fname, times, AT_SYMLINK_NOFOLLOW) < 0) - weprintf("utimensat %s:", fname); - if (lnk) { - if (!getuid() && lchown(fname, uid, gid)) - weprintf("lchown %s:", fname); - } else { - if (!getuid() && chown(fname, uid, gid)) - weprintf("chown %s:", fname); - if (chmod(fname, mode) < 0) - eprintf("fchmod %s:", fname); - } - - return 0; + if (fd < 0) + eprintf("open %s:", fname); + break; + case HARDLINK: + case SYMLINK: + snprintf(lname, sizeof(lname), "%.*s", (int)sizeof(h->linkname), + h->linkname); + if ((lnk ? symlink:link)(lname, fname) < 0) + eprintf("%s %s -> %s:", lnk ? "symlink":"link", fname, lname); + lnk++; + break; + case DIRECTORY: + if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid mode\n", h->mode); + if (mkdir(fname, (mode_t)mode) < 0 && errno != EEXIST) + eprintf("mkdir %s:", fname); + pushdirtime(fname, mtime); + break; + case CHARDEV: + case BLOCKDEV: + if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid mode\n", h->mode); + if ((major = strtol(h->major, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid major device\n", h->major); + if ((minor = strtol(h->minor, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid minor device\n", h->minor); + type = (h->type == CHARDEV) ? S_IFCHR : S_IFBLK; + if (mknod(fname, type | mode, makedev(major, minor)) < 0) + eprintf("mknod %s:", fname); + break; + case FIFO: + if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid mode\n", h->mode); + if (mknod(fname, S_IFIFO | mode, 0) < 0) + eprintf("mknod %s:", fname); + break; + default: + eprintf("unsupported tar-filetype %c\n", h->type); + } + } + + if (!Oflag_stdout) { + if ((uid = strtol(h->uid, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid uid\n", h->uid); + if ((gid = strtol(h->gid, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid gid\n", h->gid); + } + + if (fd != -1) { + for (; l > 0; l -= BLKSIZ) + if (eread(tarfd, b, BLKSIZ) > 0) + ewrite(fd, b, MIN(l, (ssize_t)BLKSIZ)); + if (fd != 1) + close(fd); + } + + if (Oflag_stdout) + return 0; + + if (lnk == 1) + return 0; + + times[0].tv_sec = times[1].tv_sec = mtime; + times[0].tv_nsec = times[1].tv_nsec = 0; + if (!mflag && utimensat(AT_FDCWD, fname, times, AT_SYMLINK_NOFOLLOW) < 0) + weprintf("utimensat %s:", fname); + if (lnk) { + if (!getuid() && lchown(fname, uid, gid)) + weprintf("lchown %s:", fname); + } else { + if (!getuid() && chown(fname, uid, gid)) + weprintf("chown %s:", fname); + if (chmod(fname, mode) < 0) + eprintf("fchmod %s:", fname); + } + + return 0; } static int print(char *fname, ssize_t l, char b[BLKSIZ]) { - (void)b; - safe_puts(fname); - skipblk(l); - return 0; + (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; + (void)data; #if FEATURE_TAR_EXCLUDE - if (is_excluded(r->path)) - return; + if (is_excluded(r->path)) + return; #endif - archive(r->path); - if (vflag) - safe_puts(r->path); + archive(r->path); + if (vflag) + safe_puts(r->path); - if (S_ISDIR(st->st_mode)) - recurse(dirfd, name, NULL, r); + if (S_ISDIR(st->st_mode)) + recurse(dirfd, name, NULL, r); } #endif static void sanitize(struct header *h) { - size_t i, j, l; - struct { - char *f; - size_t l; - } fields[] = { - { h->mode, sizeof(h->mode) }, - { h->uid, sizeof(h->uid) }, - { h->gid, sizeof(h->gid) }, - { h->size, sizeof(h->size) }, - { h->mtime, sizeof(h->mtime) }, - { h->chksum, sizeof(h->chksum) }, - { h->major, sizeof(h->major) }, - { h->minor, sizeof(h->minor) } - }; - - /* Numeric fields can be terminated with spaces instead of - * NULs as per the ustar specification. Patch all of them to - * use NULs so we can perform string operations on them. */ - for (i = 0; i < LEN(fields); i++){ - j = 0, l = fields[i].l - 1; - for (; j < l && fields[i].f[j] == ' '; j++); - for (; j <= l; j++) - if (fields[i].f[j] == ' ') - fields[i].f[j] = '\0'; - if (fields[i].f[l]) - eprintf("numeric field #%d (%.*s) is not null or space terminated\n", - i, l+1, fields[i].f); - } + size_t i, j, l; + struct { + char *f; + size_t l; + } fields[] = { + { h->mode, sizeof(h->mode) }, + { h->uid, sizeof(h->uid) }, + { h->gid, sizeof(h->gid) }, + { h->size, sizeof(h->size) }, + { h->mtime, sizeof(h->mtime) }, + { h->chksum, sizeof(h->chksum) }, + { h->major, sizeof(h->major) }, + { h->minor, sizeof(h->minor) } + }; + + /* Numeric fields can be terminated with spaces instead of + * NULs as per the ustar specification. Patch all of them to + * use NULs so we can perform string operations on them. */ + for (i = 0; i < LEN(fields); i++){ + j = 0, l = fields[i].l - 1; + for (; j < l && fields[i].f[j] == ' '; j++); + for (; j <= l; j++) + if (fields[i].f[j] == ' ') + fields[i].f[j] = '\0'; + if (fields[i].f[l]) + eprintf("numeric field #%d (%.*s) is not null or space terminated\n", + i, l+1, fields[i].f); + } } static void chktar(struct header *h) { - const char *reason; - char tmp[sizeof h->chksum], *err; - long sum, i; - - if (h->prefix[0] == '\0' && h->name[0] == '\0') { - reason = "empty filename"; - goto bad; - } - if (h->magic[0] && strncmp("ustar", h->magic, 5)) { - reason = "not ustar format"; - goto bad; - } - memcpy(tmp, h->chksum, sizeof(tmp)); - for (i = sizeof(tmp)-1; i > 0 && tmp[i] == ' '; i--) { - tmp[i] = '\0'; - } - sum = strtol(tmp, &err, 8); - if (sum < 0 || sum >= (long)(BLKSIZ*256) || *err != '\0') { - reason = "invalid checksum"; - goto bad; - } - if (sum != chksum(h)) { - reason = "incorrect checksum"; - goto bad; - } - memcpy(h->chksum, tmp, sizeof(tmp)); - return; + const char *reason; + char tmp[sizeof h->chksum], *err; + long sum, i; + + if (h->prefix[0] == '\0' && h->name[0] == '\0') { + reason = "empty filename"; + goto bad; + } + if (h->magic[0] && strncmp("ustar", h->magic, 5)) { + reason = "not ustar format"; + goto bad; + } + memcpy(tmp, h->chksum, sizeof(tmp)); + for (i = sizeof(tmp)-1; i > 0 && tmp[i] == ' '; i--) { + tmp[i] = '\0'; + } + sum = strtol(tmp, &err, 8); + if (sum < 0 || sum >= (long)(BLKSIZ*256) || *err != '\0') { + reason = "invalid checksum"; + goto bad; + } + if (sum != chksum(h)) { + reason = "incorrect checksum"; + goto bad; + } + memcpy(h->chksum, tmp, sizeof(tmp)); + return; bad: - eprintf("malformed tar archive: %s\n", reason); + eprintf("malformed tar archive: %s\n", reason); } static void xt(int argc, char *argv[], int mode) { - long size; - char b[BLKSIZ], fname[PATH_MAX + 1], *p, *q = NULL, *stripped; - int i, m, n, match; - int (*fn)(char *, ssize_t, char[BLKSIZ]) = (mode == 'x') ? unarchive : print; - struct timespec times[2]; - struct header *h = (struct header *)b; - struct dirtime *dirtime; + long size; + char b[BLKSIZ], fname[PATH_MAX + 1], *p, *q = NULL, *stripped; + int i, m, n, match; + int (*fn)(char *, ssize_t, char[BLKSIZ]) = (mode == 'x') ? unarchive : print; + struct timespec times[2]; + struct header *h = (struct header *)b; + struct dirtime *dirtime; #if FEATURE_TAR_FILES_FROM - size_t idx; + size_t idx; #endif - while (eread(tarfd, b, BLKSIZ) > 0 && (h->name[0] || h->prefix[0])) { - chktar(h); - sanitize(h); - - if ((size = strtol(h->size, &p, 8)) < 0 || *p != '\0') - eprintf("strtol %s: invalid size\n", h->size); - - /* Long file path is read directly into fname*/ - if (h->type == 'L' || h->type == 'x' || h->type == 'g') { - - /* Read header only up to size of fname buffer */ - for (q = fname; q < fname+size; q += BLKSIZ) { - if (q + BLKSIZ >= fname + sizeof fname) - eprintf("name exceeds buffer: %.*s\n", q-fname, fname); - eread(tarfd, q, BLKSIZ); - } - - /* Convert pax x header with 'path=' field into L header */ - if (h->type == 'x') for (q = fname; q < fname+size-16; q += n) { - if ((n = strtol(q, &p, 10)) < 0 || *p != ' ') - eprintf("strtol %.*s: invalid number\n", p+1-q, q); - if (n && strncmp(p+1, "path=", 5) == 0) { - memmove(fname, p+6, size = q+n - p-6 - 1); - h->type = 'L'; - break; - } - } - fname[size] = '\0'; - - /* Non L-like header (eg. pax 'g') is skipped by setting q=null */ - if (h->type != 'L') - q = NULL; - continue; - } - - /* Ustar path is copied into fname if no L header (ie: q is NULL) */ - if (!q) { - m = sizeof h->prefix, n = sizeof h->name; - p = "/" + !h->prefix[0]; - snprintf(fname, sizeof fname, "%.*s%s%.*s", m, h->prefix, p, n, h->name); - } - q = NULL; - - /* If argc > 0 or files_from_cnt > 0 then only extract the matching files/dirs */ - if (argc || files_from_cnt) { - match = 0; - for (i = 0; i < argc; i++) { - if (strncmp(argv[i], fname, n = strlen(argv[i])) == 0) { - if (strchr("/", fname[n]) || argv[i][n-1] == '/') { - match = 1; - break; - } - } - } + while (eread(tarfd, b, BLKSIZ) > 0 && (h->name[0] || h->prefix[0])) { + chktar(h); + sanitize(h); + + if ((size = strtol(h->size, &p, 8)) < 0 || *p != '\0') + eprintf("strtol %s: invalid size\n", h->size); + + /* Long file path is read directly into fname*/ + if (h->type == 'L' || h->type == 'x' || h->type == 'g') { + + /* Read header only up to size of fname buffer */ + for (q = fname; q < fname+size; q += BLKSIZ) { + if (q + BLKSIZ >= fname + sizeof fname) + eprintf("name exceeds buffer: %.*s\n", q-fname, fname); + eread(tarfd, q, BLKSIZ); + } + + /* Convert pax x header with 'path=' field into L header */ + if (h->type == 'x') for (q = fname; q < fname+size-16; q += n) { + if ((n = strtol(q, &p, 10)) < 0 || *p != ' ') + eprintf("strtol %.*s: invalid number\n", p+1-q, q); + if (n && strncmp(p+1, "path=", 5) == 0) { + memmove(fname, p+6, size = q+n - p-6 - 1); + h->type = 'L'; + break; + } + } + fname[size] = '\0'; + + /* Non L-like header (eg. pax 'g') is skipped by setting q=null */ + if (h->type != 'L') + q = NULL; + continue; + } + + /* Ustar path is copied into fname if no L header (ie: q is NULL) */ + if (!q) { + m = sizeof h->prefix, n = sizeof h->name; + p = "/" + !h->prefix[0]; + snprintf(fname, sizeof fname, "%.*s%s%.*s", m, h->prefix, p, n, h->name); + } + q = NULL; + + /* If argc > 0 or files_from_cnt > 0 then only extract the matching files/dirs */ + if (argc || files_from_cnt) { + match = 0; + for (i = 0; i < argc; i++) { + if (strncmp(argv[i], fname, n = strlen(argv[i])) == 0) { + if (strchr("/", fname[n]) || argv[i][n-1] == '/') { + match = 1; + break; + } + } + } #if FEATURE_TAR_FILES_FROM - if (!match) { - for (idx = 0; idx < files_from_cnt; idx++) { - if (strncmp(files_from[idx], fname, n = strlen(files_from[idx])) == 0) { - if (strchr("/", fname[n]) || files_from[idx][n-1] == '/') { - match = 1; - break; - } - } - } - } + if (!match) { + for (idx = 0; idx < files_from_cnt; idx++) { + if (strncmp(files_from[idx], fname, n = strlen(files_from[idx])) == 0) { + if (strchr("/", fname[n]) || files_from[idx][n-1] == '/') { + match = 1; + break; + } + } + } + } #endif - if (!match) { - skipblk(size); - continue; - } - } + if (!match) { + skipblk(size); + continue; + } + } - stripped = fname; + stripped = fname; #if FEATURE_TAR_STRIP_COMPONENTS - if (mode == 'x' && strip_components_count > 0) { - stripped = strip_components(fname, strip_components_count); - if (!stripped || *stripped == '\0') { - skipblk(size); - continue; - } - } + if (mode == 'x' && strip_components_count > 0) { + stripped = strip_components(fname, strip_components_count); + if (!stripped || *stripped == '\0') { + skipblk(size); + continue; + } + } #endif - fn(stripped, size, b); - if (vflag && mode != 't') - safe_puts(fname); - } - - if (mode == 'x' && !mflag) { - while ((dirtime = popdirtime())) { - times[0].tv_sec = times[1].tv_sec = dirtime->mtime; - times[0].tv_nsec = times[1].tv_nsec = 0; - if (utimensat(AT_FDCWD, dirtime->name, times, 0) < 0) - eprintf("utimensat %s:", fname); - free(dirtime->name); - } - free(dirtimes); - dirtimes = NULL; - } + fn(stripped, size, b); + if (vflag && mode != 't') + safe_puts(fname); + } + + if (mode == 'x' && !mflag) { + while ((dirtime = popdirtime())) { + times[0].tv_sec = times[1].tv_sec = dirtime->mtime; + times[0].tv_nsec = times[1].tv_nsec = 0; + if (utimensat(AT_FDCWD, dirtime->name, times, 0) < 0) + eprintf("utimensat %s:", fname); + free(dirtime->name); + } + free(dirtimes); + dirtimes = NULL; + } } char **args; @@ -790,13 +803,13 @@ 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); + 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); + eprintf("usage: %s [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p] " + "[-f file] [file ...]\n", argv0); #endif } @@ -808,247 +821,247 @@ int main(int argc, char *argv[]) { #if FEATURE_TAR_CREATE - struct recursor r = { .fn = c, .follow = 'P', .flags = DIRFIRST }; + struct recursor r = { .fn = c, .follow = 'P', .flags = DIRFIRST }; #endif - struct stat st; - char *file = NULL, *dir = ".", mode = '\0'; - int fd; - size_t i; + struct stat st; + char *file = NULL, *dir = ".", mode = '\0'; + int fd; + size_t i; - argv0 = argv[0]; + argv0 = argv[0]; #if FEATURE_TAR_CREATE - if (argc > 1 && strchr("cxt", mode = *argv[1])) + if (argc > 1 && strchr("cxt", mode = *argv[1])) #else - if (argc > 1 && strchr("xt", mode = *argv[1])) + if (argc > 1 && strchr("xt", mode = *argv[1])) #endif - *(argv[1]+1) ? *argv[1] = '-' : (*++argv = argv0, --argc); + *(argv[1]+1) ? *argv[1] = '-' : (*++argv = argv0, --argc); - ARGBEGIN { - // ?man -x: extract files from an archive - case 'x': + ARGBEGIN { + // ?man -x: extract files from an archive + case 'x': #if FEATURE_TAR_CREATE - // ?man -c: create a new archive - case 'c': + // ?man -c: create a new archive + case 'c': #endif - // ?man -t: list the contents of an archive - case 't': - mode = ARGC(); - break; - // ?man -C:dir: specify option flag - case 'C': - dir = EARGF(usage()); - break; - // ?man -f:file: specify archive file - case 'f': - file = EARGF(usage()); - break; - // ?man -m: specify mode or limit - case 'm': - mflag = 1; - break; - // ?man -J: specify option flag - case 'J': - // ?man -Z: specify option flag - case 'Z': - // ?man -a: print or show all entries - case 'a': - // ?man -j: specify option flag - case 'j': - // ?man -z: specify option flag - case 'z': - filtermode = ARGC(); - filtertool = filtertools[filtermode]; - break; - // ?man -h: suppress headers or print help - case 'h': + // ?man -t: list the contents of an archive + case 't': + mode = ARGC(); + break; + // ?man -C:dir: specify option flag + case 'C': + dir = EARGF(usage()); + break; + // ?man -f:file: specify archive file + case 'f': + file = EARGF(usage()); + break; + // ?man -m: specify mode or limit + case 'm': + mflag = 1; + break; + // ?man -J: specify option flag + case 'J': + // ?man -Z: specify option flag + case 'Z': + // ?man -a: print or show all entries + case 'a': + // ?man -j: specify option flag + case 'j': + // ?man -z: specify option flag + case 'z': + filtermode = ARGC(); + filtertool = filtertools[filtermode]; + break; + // ?man -h: suppress headers or print help + case 'h': #if FEATURE_TAR_CREATE - r.follow = 'L'; + r.follow = 'L'; #endif - break; - // ?man -v: verbosely list files processed - case 'v': - vflag = 1; - break; - // ?man -p: preserve file attributes - case 'p': - break; /* do nothing as already default behaviour */ + break; + // ?man -v: verbosely list files processed + case 'v': + vflag = 1; + break; + // ?man -p: preserve file attributes + case 'p': + break; /* do nothing as already default behaviour */ #if FEATURE_TAR_TO_STDOUT - // ?man -O: extract files to stdout - case 'O': - Oflag_stdout = 1; - break; + // ?man -O: extract files to stdout + case 'O': + Oflag_stdout = 1; + break; #endif #if FEATURE_TAR_KEEP_OLD - // ?man -k: keep existing files, do not overwrite - case 'k': - kflag_keep = 1; - break; + // ?man -k: keep existing files, do not overwrite + case 'k': + kflag_keep = 1; + break; #endif #if FEATURE_TAR_FILES_FROM - // ?man -T:file: -T file: read filenames from file - case 'T': - load_files_from_file(EARGF(usage())); - break; + // ?man -T:file: -T file: read filenames from file + case 'T': + load_files_from_file(EARGF(usage())); + break; #endif #if FEATURE_TAR_EXCLUDE_FROM - // ?man -X:file: -X file: exclude patterns in file - case 'X': - load_excludes_from_file(EARGF(usage())); - break; + // ?man -X:file: -X file: exclude patterns in file + case 'X': + load_excludes_from_file(EARGF(usage())); + break; #endif #if FEATURE_TAR_STRIP_COMPONENTS - // ?man -s:num: -strip-components num: strip num components - case 's': - if (strcmp(argv[0], "strip-components") == 0) { - argv[0] = "s"; - strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX); - brk_ = 1; - } else if (strncmp(argv[0], "strip-components=", 17) == 0) { - strip_components_count = estrtonum(argv[0] + 17, 0, INT_MAX); - brk_ = 1; - } else { - usage(); - } - break; + // ?man -s:num: -strip-components num: strip num components + case 's': + if (strcmp(argv[0], "strip-components") == 0) { + argv[0] = "s"; + strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX); + brk_ = 1; + } else if (strncmp(argv[0], "strip-components=", 17) == 0) { + strip_components_count = estrtonum(argv[0] + 17, 0, INT_MAX); + brk_ = 1; + } else { + usage(); + } + break; #endif - // ?man --:num: specify - option - case '-': + // ?man --:num: specify - option + case '-': #if FEATURE_TAR_EXCLUDE - if (strncmp(argv[0], "-exclude=", 9) == 0) { - add_exclude(argv[0] + 9); - brk_ = 1; - break; - } else if (strcmp(argv[0], "-exclude") == 0) { - argv[0] = "-"; - add_exclude(EARGF(usage())); - brk_ = 1; - break; - } + if (strncmp(argv[0], "-exclude=", 9) == 0) { + add_exclude(argv[0] + 9); + brk_ = 1; + break; + } else if (strcmp(argv[0], "-exclude") == 0) { + argv[0] = "-"; + add_exclude(EARGF(usage())); + brk_ = 1; + break; + } #endif #if FEATURE_TAR_EXCLUDE_FROM - if (strncmp(argv[0], "-exclude-from=", 14) == 0) { - load_excludes_from_file(argv[0] + 14); - brk_ = 1; - break; - } else if (strcmp(argv[0], "-exclude-from") == 0) { - argv[0] = "-"; - load_excludes_from_file(EARGF(usage())); - brk_ = 1; - break; - } + if (strncmp(argv[0], "-exclude-from=", 14) == 0) { + load_excludes_from_file(argv[0] + 14); + brk_ = 1; + break; + } else if (strcmp(argv[0], "-exclude-from") == 0) { + argv[0] = "-"; + load_excludes_from_file(EARGF(usage())); + brk_ = 1; + break; + } #endif #if FEATURE_TAR_TO_STDOUT - if (strcmp(argv[0], "-to-stdout") == 0) { - Oflag_stdout = 1; - brk_ = 1; - break; - } + if (strcmp(argv[0], "-to-stdout") == 0) { + Oflag_stdout = 1; + brk_ = 1; + break; + } #endif #if FEATURE_TAR_KEEP_OLD - if (strcmp(argv[0], "-keep-old-files") == 0) { - kflag_keep = 1; - brk_ = 1; - break; - } + if (strcmp(argv[0], "-keep-old-files") == 0) { + kflag_keep = 1; + brk_ = 1; + break; + } #endif #if FEATURE_TAR_STRIP_COMPONENTS - if (strncmp(argv[0], "-strip-components=", 18) == 0) { - strip_components_count = estrtonum(argv[0] + 18, 0, INT_MAX); - brk_ = 1; - break; - } else if (strcmp(argv[0], "-strip-components") == 0) { - argv[0] = "-"; - strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX); - brk_ = 1; - break; - } + if (strncmp(argv[0], "-strip-components=", 18) == 0) { + strip_components_count = estrtonum(argv[0] + 18, 0, INT_MAX); + brk_ = 1; + break; + } else if (strcmp(argv[0], "-strip-components") == 0) { + argv[0] = "-"; + strip_components_count = estrtonum(EARGF(usage()), 0, INT_MAX); + brk_ = 1; + break; + } #endif #if FEATURE_TAR_FILES_FROM - if (strncmp(argv[0], "-files-from=", 12) == 0) { - load_files_from_file(argv[0] + 12); - brk_ = 1; - break; - } else if (strcmp(argv[0], "-files-from") == 0) { - argv[0] = "-"; - load_files_from_file(EARGF(usage())); - brk_ = 1; - break; - } + if (strncmp(argv[0], "-files-from=", 12) == 0) { + load_files_from_file(argv[0] + 12); + brk_ = 1; + break; + } else if (strcmp(argv[0], "-files-from") == 0) { + argv[0] = "-"; + load_files_from_file(EARGF(usage())); + brk_ = 1; + break; + } #endif - usage(); - break; - default: - usage(); - } ARGEND + usage(); + break; + default: + usage(); + } ARGEND - switch (mode) { + switch (mode) { #if FEATURE_TAR_CREATE - // ?man -c: create a new archive - case 'c': - if (!argc && !files_from_cnt) - usage(); - tarfd = 1; - if (file && *file != '-') { - tarfd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0644); - if (tarfd < 0) - eprintf("open %s:", file); - if (lstat(file, &st) < 0) - eprintf("lstat %s:", file); - tarinode = st.st_ino; - tardev = st.st_dev; - } - - if (filtertool) - tarfd = comp(tarfd, filtertool, "-cf"); - - if (chdir(dir) < 0) - eprintf("chdir %s:", dir); - for (; *argv; argc--, argv++) - recurse(AT_FDCWD, *argv, NULL, &r); + // ?man -c: create a new archive + case 'c': + if (!argc && !files_from_cnt) + usage(); + tarfd = 1; + if (file && *file != '-') { + tarfd = open(file, O_WRONLY | O_TRUNC | O_CREAT, 0644); + if (tarfd < 0) + eprintf("open %s:", file); + if (lstat(file, &st) < 0) + eprintf("lstat %s:", file); + tarinode = st.st_ino; + tardev = st.st_dev; + } + + if (filtertool) + tarfd = comp(tarfd, filtertool, "-cf"); + + if (chdir(dir) < 0) + eprintf("chdir %s:", dir); + for (; *argv; argc--, argv++) + recurse(AT_FDCWD, *argv, NULL, &r); #if FEATURE_TAR_FILES_FROM - for (i = 0; i < files_from_cnt; i++) - recurse(AT_FDCWD, files_from[i], NULL, &r); + for (i = 0; i < files_from_cnt; i++) + recurse(AT_FDCWD, files_from[i], NULL, &r); #endif - break; + break; #endif - // ?man -t: list the contents of an archive - case 't': - // ?man -x: extract files from an archive - case 'x': - tarfd = 0; - if (file && *file != '-') { - tarfd = open(file, O_RDONLY); - if (tarfd < 0) - eprintf("open %s:", file); - } - - if (filtertool) { - fd = tarfd; - tarfd = decomp(tarfd, filtertool, "-cdf"); - close(fd); - } - - if (chdir(dir) < 0) - eprintf("chdir %s:", dir); - xt(argc, argv, mode); - break; - default: - usage(); - } + // ?man -t: list the contents of an archive + case 't': + // ?man -x: extract files from an archive + case 'x': + tarfd = 0; + if (file && *file != '-') { + tarfd = open(file, O_RDONLY); + if (tarfd < 0) + eprintf("open %s:", file); + } + + if (filtertool) { + fd = tarfd; + tarfd = decomp(tarfd, filtertool, "-cdf"); + close(fd); + } + + if (chdir(dir) < 0) + eprintf("chdir %s:", dir); + xt(argc, argv, mode); + break; + default: + usage(); + } #if FEATURE_TAR_EXCLUDE - if (excludes) { - for (i = 0; i < excludes_cnt; i++) - free(excludes[i]); - free(excludes); - } + if (excludes) { + for (i = 0; i < excludes_cnt; i++) + free(excludes[i]); + free(excludes); + } #endif #if FEATURE_TAR_FILES_FROM - if (files_from) { - for (i = 0; i < files_from_cnt; i++) - free(files_from[i]); - free(files_from); - } + if (files_from) { + for (i = 0; i < files_from_cnt; i++) + free(files_from[i]); + free(files_from); + } #endif - return recurse_status; + return recurse_status; } diff --git a/cmd/pseudo/watch.c b/cmd/pseudo/watch.c @@ -6,6 +6,7 @@ #include <stdlib.h> #include <unistd.h> +#include "wexec.h" #include "util.h" static void @@ -58,7 +59,7 @@ main(int argc, char *argv[]) for (;;) { printf("\x1b[2J\x1b[H"); /* clear */ fflush(NULL); - system(cmd); + wsystem(cmd); usleep(interval); } return 0; diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c @@ -1,13 +1,7 @@ /* See LICENSE file for copyright and license details. */ - - #include <sys/stat.h> #include <sys/types.h> -#ifndef makedev -#include <sys/sysmacros.h> -#endif -#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -15,17 +9,21 @@ #include "util.h" +#ifndef makedev +#include <sys/sysmacros.h> +#endif + static void usage(void) { eprintf("usage: %s [-m mode] name b|c|u major minor\n" - " %s [-m mode] name p\n", - argv0, argv0); + " %s [-m mode] name p\n", + argv0, argv0); } // ?man mknod: create special files -// ?man arguments: name b|c|u major minor -// ?man create block or character special files +// ?man arguments: name type [major minor] +// ?man create a block special, character special, or fifo file int main(int argc, char *argv[]) { @@ -33,13 +31,13 @@ main(int argc, char *argv[]) dev_t dev; ARGBEGIN { -// ?man -m:mode: specify mode or limit -case 'm': + case 'm': + // ?man -m:mode: set the file mode bits of the created node mode = parsemode(EARGF(usage()), mode, umask(0)); break; default: usage(); - } ARGEND; + } ARGEND if (argc < 2) usage(); @@ -69,7 +67,8 @@ case 'm': } else { if (argc != 4) usage(); - dev = makedev(estrtonum(argv[2], 0, LLONG_MAX), estrtonum(argv[3], 0, LLONG_MAX)); + dev = makedev(estrtonum(argv[2], 0, LLONG_MAX), + estrtonum(argv[3], 0, LLONG_MAX)); } if (mknod(argv[0], mode, dev) == -1) diff --git a/cmd/xsi/passwd.c b/cmd/xsi/passwd.c @@ -1,185 +1,43 @@ /* See LICENSE file for copyright and license details. */ - - -#include <sys/ioctl.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <sys/syscall.h> +#include "config.h" +#include "passwd.h" +#include "text.h" +#include "util.h" #include <errno.h> -#include <fcntl.h> -#include <limits.h> #include <pwd.h> -#include <shadow.h> -#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/stat.h> #include <unistd.h> -#include "config.h" -#include "passwd.h" -#include "text.h" -#include "util.h" - -static FILE * -spw_get_file(const char *user) -{ - FILE *fp = NULL; - char file[PATH_MAX]; - int r; - - r = snprintf(file, sizeof(file), "/etc/tcb/%s/shadow", user); - if (r < 0 || (size_t)r >= sizeof(file)) - eprintf("snprintf:"); - fp = fopen(file, "r+"); - if (!fp) - fp = fopen("/etc/shadow", "r+"); - return fp; -} - -static int -spw_write_file(FILE *fp, const struct spwd *spw, char *pwhash) -{ - struct spwd *spwent; - int r = -1, w = 0; - FILE *tfp = NULL; - - /* write to temporary file. */ - tfp = tmpfile(); - if (!tfp) { - weprintf("tmpfile:"); - goto cleanup; - } - while ((spwent = fgetspent(fp))) { - /* update entry on name match */ - if (strcmp(spwent->sp_namp, spw->sp_namp) == 0) { - spwent->sp_pwdp = pwhash; - w++; - } - errno = 0; - if (putspent(spwent, tfp) == -1) { - weprintf("putspent:"); - goto cleanup; - } - } - if (!w) { - weprintf("shadow: no matching entry to write to\n"); - goto cleanup; - } - fflush(tfp); - - if (fseek(fp, 0, SEEK_SET) == -1 || fseek(tfp, 0, SEEK_SET) == -1) { - weprintf("fseek:"); - goto cleanup; - } - - /* write temporary file to (tcb) shadow file */ - fconcat(tfp, "tmpfile", fp, "shadow"); - ftruncate(fileno(fp), ftell(tfp)); - - r = 0; /* success */ -cleanup: - if (tfp) - fclose(tfp); - return r; -} - -static int -pw_write_file(FILE *fp, const struct passwd *pw, char *pwhash) { - struct passwd *pwent; - int r = -1, w = 0; - FILE *tfp = NULL; - - /* write to temporary file. */ - tfp = tmpfile(); - if (!tfp) { - weprintf("tmpfile:"); - goto cleanup; - } - while ((pwent = fgetpwent(fp))) { - /* update entry on name match */ - if (strcmp(pwent->pw_name, pw->pw_name) == 0) { - pwent->pw_passwd = pwhash; - w++; - } - errno = 0; - if (putpwent(pwent, tfp) == -1) { - weprintf("putpwent:"); - goto cleanup; - } - } - if (!w) { - weprintf("passwd: no matching entry to write to\n"); - goto cleanup; - } - fflush(tfp); - - if (fseek(fp, 0, SEEK_SET) == -1 || fseek(tfp, 0, SEEK_SET) == -1) { - weprintf("fseek:"); - goto cleanup; - } - - /* write to passwd file. */ - fconcat(tfp, "tmpfile", fp, "passwd"); - ftruncate(fileno(fp), ftell(tfp)); - - r = 0; /* success */ -cleanup: - if (tfp) - fclose(tfp); - return r; -} - -/* generates a random base64-encoded salt string of length 16 */ -static void -gensalt(char *s) -{ - static const char b64[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - uint8_t buf[12]; - uint32_t n; - int i; - - if (syscall(SYS_getrandom, buf, sizeof(buf), 0) < 0) - eprintf("getrandom:"); - for (i = 0; i < 12; i += 3) { - n = buf[i] << 16 | buf[i+1] << 8 | buf[i+2]; - *s++ = b64[n%64]; n /= 64; - *s++ = b64[n%64]; n /= 64; - *s++ = b64[n%64]; n /= 64; - *s++ = b64[n]; - } - *s++ = '\0'; -} - static void usage(void) { eprintf("usage: %s [username]\n", argv0); } -// ?man passwd: change user password -// ?man arguments: username -// ?man update a user authentication password +// ?man passwd: change a user password +// ?man arguments: [username] +// ?man change the password associated with the calling user or with username int main(int argc, char *argv[]) { - char *cryptpass1 = NULL, *cryptpass2 = NULL, *cryptpass3 = NULL; - char *inpass, *p, *prevhash = NULL, salt[sizeof(PW_CIPHER) + 16] = PW_CIPHER; + struct pwdb_entry ent; struct passwd *pw; - struct spwd *spw = NULL; - FILE *fp = NULL; - int r = -1, status = 1; + char *inpass, *prevhash = NULL, *newhash = NULL, salt[PW_SALT_MAX]; + char *c1, *c2; + int status = 1; ARGBEGIN { default: usage(); - } ARGEND; + } ARGEND pw_init(); umask(077); - errno = 0; if (argc == 0) pw = getpwuid(getuid()); else @@ -191,103 +49,68 @@ main(int argc, char *argv[]) eprintf("who are you?\n"); } - /* is using shadow entry ? */ - if (pw->pw_passwd[0] == 'x' && pw->pw_passwd[1] == '\0') { - errno = 0; - spw = getspnam(pw->pw_name); - if (!spw) { - if (errno) - eprintf("getspnam: %s:", pw->pw_name); - else - eprintf("who are you?\n"); - } - } + if (pwdb_lookup(&ent, pw->pw_name) < 0) + return 1; + prevhash = ent.hash; - /* Flush pending input */ - ioctl(0, TCFLSH, (void *)0); - - if (getuid() == 0) { - goto newpass; - } else { - if (pw->pw_passwd[0] == '!' || - pw->pw_passwd[0] == '*') + if (getuid() != 0) { + if (prevhash[0] == '!' || prevhash[0] == '*') eprintf("denied\n"); - if (pw->pw_passwd[0] == '\0') { - goto newpass; + if (prevhash[0] == '\0') { + /* no password set */ + } else { + printf("Changing password for %s\n", pw->pw_name); + inpass = getpass("Old password: "); + if (!inpass) + eprintf("getpass:"); + if (inpass[0] == '\0') + eprintf("no password supplied\n"); + c1 = crypt(inpass, prevhash); + if (!c1) + eprintf("crypt:"); + if (strcmp(c1, prevhash) != 0) + eprintf("incorrect password\n"); + explicit_bzero(inpass, strlen(inpass)); } - if (pw->pw_passwd[0] == 'x' && - pw->pw_passwd[1] == '\0') - prevhash = spw->sp_pwdp; - else - prevhash = pw->pw_passwd; } - printf("Changing password for %s\n", pw->pw_name); - inpass = getpass("Old password: "); - if (!inpass) - eprintf("getpass:"); - if (inpass[0] == '\0') - eprintf("no password supplied\n"); - p = crypt(inpass, prevhash); - if (!p) - eprintf("crypt:"); - cryptpass1 = estrdup(p); - if (strcmp(cryptpass1, prevhash) != 0) - eprintf("incorrect password\n"); - -newpass: inpass = getpass("Enter new password: "); if (!inpass) eprintf("getpass:"); if (inpass[0] == '\0') eprintf("no password supplied\n"); - if(prevhash) { - p = crypt(inpass, prevhash); - if (!p) - eprintf("crypt:"); - if (cryptpass1 && strcmp(cryptpass1, p) == 0) + if (prevhash && prevhash[0] != '\0') { + c1 = crypt(inpass, prevhash); + if (c1 && strcmp(c1, prevhash) == 0) eprintf("password left unchanged\n"); } - gensalt(salt + strlen(salt)); - p = crypt(inpass, salt); - if (!p) - eprintf("crypt:"); - cryptpass2 = estrdup(p); - /* Flush pending input */ - ioctl(0, TCFLSH, (void *)0); + if (pw_gensalt(salt, sizeof(salt)) < 0) + eprintf("pw_gensalt:"); + c1 = crypt(inpass, salt); + if (!c1) + eprintf("crypt:"); + newhash = estrdup(c1); + explicit_bzero(inpass, strlen(inpass)); inpass = getpass("Retype new password: "); if (!inpass) eprintf("getpass:"); if (inpass[0] == '\0') eprintf("no password supplied\n"); - p = crypt(inpass, salt); - if (!p) + c2 = crypt(inpass, salt); + if (!c2) eprintf("crypt:"); - cryptpass3 = estrdup(p); - if (strcmp(cryptpass2, cryptpass3) != 0) + if (strcmp(c2, newhash) != 0) eprintf("passwords don't match\n"); + explicit_bzero(inpass, strlen(inpass)); - fp = spw_get_file(pw->pw_name); - if (fp) { - r = spw_write_file(fp, spw, cryptpass3); - } else { - fp = fopen("/etc/passwd", "r+"); - if (fp) - r = pw_write_file(fp, pw, cryptpass3); - else - weprintf("fopen:"); - } - if (!r) + if (pwdb_update(pw->pw_name, newhash) == 0) status = 0; - if (fp) - fclose(fp); - free(cryptpass3); - free(cryptpass2); - free(cryptpass1); - + free(newhash); + free(ent.name); + free(ent.hash); return status; } diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c @@ -1,7 +1,7 @@ /* See LICENSE file for copyright and license details. */ - - -#include <sys/types.h> +#include "config.h" +#include "passwd.h" +#include "util.h" #include <errno.h> #include <grp.h> @@ -9,13 +9,15 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/types.h> #include <unistd.h> -#include "passwd.h" -#include "util.h" - extern char **environ; +#ifndef ENV_PATH_SHELL +#define ENV_PATH_SHELL "/bin/sh" +#endif + static int lflag = 0; static int pflag = 0; @@ -25,9 +27,9 @@ usage(void) eprintf("usage: %s [-lp] [username]\n", argv0); } -// ?man su: run command with substitute user id -// ?man arguments: username -// ?man run a shell or command with another user id +// ?man su: run a command with substitute user and group id +// ?man arguments: [username] +// ?man run a shell or command as the named user. defaults to root int main(int argc, char *argv[]) { @@ -38,17 +40,17 @@ main(int argc, char *argv[]) uid_t uid; ARGBEGIN { - // ?man -l: list in long format case 'l': + // ?man -l: make the shell a login shell lflag = 1; break; - // ?man -p: preserve file attributes case 'p': + // ?man -p: preserve the current environment pflag = 1; break; default: usage(); - } ARGEND; + } ARGEND if (argc > 1) usage(); @@ -70,6 +72,7 @@ main(int argc, char *argv[]) eprintf("getpass:"); if (pw_check(pw, pass) <= 0) exit(1); + explicit_bzero(pass, strlen(pass)); } if (initgroups(usr, pw->pw_gid) < 0) @@ -79,7 +82,7 @@ main(int argc, char *argv[]) if (setuid(pw->pw_uid) < 0) eprintf("setuid:"); - shell = pw->pw_shell[0] == '\0' ? "/bin/sh" : pw->pw_shell; + shell = pw->pw_shell[0] == '\0' ? ENV_PATH_SHELL : pw->pw_shell; if (lflag) { term = getenv("TERM"); clearenv(); @@ -87,7 +90,8 @@ main(int argc, char *argv[]) setenv("SHELL", shell, 1); setenv("USER", pw->pw_name, 1); setenv("LOGNAME", pw->pw_name, 1); - setenv("TERM", term ? term : "linux", 1); + setenv("TERM", term ? term : "dumb", 1); + setenv("PATH", ENV_PATH, 1); if (chdir(pw->pw_dir) < 0) eprintf("chdir %s:", pw->pw_dir); newargv[0] = shell; diff --git a/config.mk b/config.mk @@ -232,6 +232,17 @@ FEATURE_SH_WORDEXP = 1 FEATURE_CAL_EXT = 1 FEATURE_SED_PRESERVE_NEWLINE = 1 FEATURE_LS_COLOR = 1 +FEATURE_DIFF3_MERGE = 1 +FEATURE_DIFF3_EDSCRIPT = 1 +FEATURE_DIFF_CONTEXT = 1 +FEATURE_DIFF_UNIFIED = 1 +FEATURE_DIFF_ED = 1 +FEATURE_DIFF_BRIEF = 1 +FEATURE_DIFF_SIDEBYSIDE = 1 +FEATURE_PATCH_BACKUP = 1 +FEATURE_PATCH_FUZZ = 1 +FEATURE_PATCH_STRIP_CR = 1 +FEATURE_INPROC_EXEC = 0 FEATURE_MODPROBE_SHOW_DEPENDS = 1 FEATURE_MODPROBE_BLACKLIST = 1 FEATURE_MODPROBE_SYSLOG = 1 @@ -255,68 +266,79 @@ FEATURE_IP_LINK_SET = 1 FEATURE_IP_ADDR_FLUSH = 1 CPPFLAGS =\ - -Ishared\ - -DPREFIX=\"\$(PREFIX)\"\ - -D_DEFAULT_SOURCE\ - -D_GNU_SOURCE\ - -D_NETBSD_SOURCE\ - -D_BSD_SOURCE\ - -D_XOPEN_SOURCE=700\ - -D_FILE_OFFSET_BITS=64\ - -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)\ - -DFEATURE_SED_PRESERVE_NEWLINE=$(FEATURE_SED_PRESERVE_NEWLINE)\ - -DFEATURE_LS_COLOR=$(FEATURE_LS_COLOR)\ - -DFEATURE_MODPROBE_SHOW_DEPENDS=$(FEATURE_MODPROBE_SHOW_DEPENDS)\ - -DFEATURE_MODPROBE_BLACKLIST=$(FEATURE_MODPROBE_BLACKLIST)\ - -DFEATURE_MODPROBE_SYSLOG=$(FEATURE_MODPROBE_SYSLOG)\ - -DFEATURE_MODPROBE_DIR_OVERRIDE=$(FEATURE_MODPROBE_DIR_OVERRIDE)\ - -DFEATURE_DEPMOD_ALIAS=$(FEATURE_DEPMOD_ALIAS)\ - -DFEATURE_DEPMOD_SYMBOLS=$(FEATURE_DEPMOD_SYMBOLS)\ - -DFEATURE_USE_LIBRESSL=$(FEATURE_USE_LIBRESSL)\ - -DFEATURE_USE_BEARSSL=$(FEATURE_USE_BEARSSL)\ - -DFEATURE_USE_OPENSSL=$(FEATURE_USE_OPENSSL)\ - -DFEATURE_TAR_TTY_SAFE=$(FEATURE_TAR_TTY_SAFE)\ - -DFEATURE_TAR_NOFOLLOW=$(FEATURE_TAR_NOFOLLOW)\ - -DFEATURE_READLINK_REALPATH=$(FEATURE_READLINK_REALPATH)\ - -DFEATURE_UMOUNT_OPTIONS=$(FEATURE_UMOUNT_OPTIONS)\ - -DFEATURE_TAR_TO_STDOUT=$(FEATURE_TAR_TO_STDOUT)\ - -DFEATURE_TAR_KEEP_OLD=$(FEATURE_TAR_KEEP_OLD)\ - -DFEATURE_TAR_STRIP_COMPONENTS=$(FEATURE_TAR_STRIP_COMPONENTS)\ - -DFEATURE_TAR_FILES_FROM=$(FEATURE_TAR_FILES_FROM)\ - -DFEATURE_TAR_EXCLUDE_FROM=$(FEATURE_TAR_EXCLUDE_FROM)\ - -DFEATURE_IP_ROUTE_ADD_DEL=$(FEATURE_IP_ROUTE_ADD_DEL)\ - -DFEATURE_IP_LINK_SET=$(FEATURE_IP_LINK_SET)\ - -DFEATURE_IP_ADDR_FLUSH=$(FEATURE_IP_ADDR_FLUSH) $(CPPFLAGS_TLS) + -Ishared\ + -DPREFIX=\"\$(PREFIX)\"\ + -D_DEFAULT_SOURCE\ + -D_GNU_SOURCE\ + -D_NETBSD_SOURCE\ + -D_BSD_SOURCE\ + -D_XOPEN_SOURCE=700\ + -D_FILE_OFFSET_BITS=64\ + -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)\ + -DFEATURE_SED_PRESERVE_NEWLINE=$(FEATURE_SED_PRESERVE_NEWLINE)\ + -DFEATURE_LS_COLOR=$(FEATURE_LS_COLOR)\ + -DFEATURE_DIFF3_MERGE=$(FEATURE_DIFF3_MERGE)\ + -DFEATURE_DIFF3_EDSCRIPT=$(FEATURE_DIFF3_EDSCRIPT)\ + -DFEATURE_DIFF_CONTEXT=$(FEATURE_DIFF_CONTEXT)\ + -DFEATURE_DIFF_UNIFIED=$(FEATURE_DIFF_UNIFIED)\ + -DFEATURE_DIFF_ED=$(FEATURE_DIFF_ED)\ + -DFEATURE_DIFF_BRIEF=$(FEATURE_DIFF_BRIEF)\ + -DFEATURE_DIFF_SIDEBYSIDE=$(FEATURE_DIFF_SIDEBYSIDE)\ + -DFEATURE_PATCH_BACKUP=$(FEATURE_PATCH_BACKUP)\ + -DFEATURE_PATCH_FUZZ=$(FEATURE_PATCH_FUZZ)\ + -DFEATURE_PATCH_STRIP_CR=$(FEATURE_PATCH_STRIP_CR)\ + -DFEATURE_INPROC_EXEC=$(FEATURE_INPROC_EXEC)\ + -DFEATURE_MODPROBE_SHOW_DEPENDS=$(FEATURE_MODPROBE_SHOW_DEPENDS)\ + -DFEATURE_MODPROBE_BLACKLIST=$(FEATURE_MODPROBE_BLACKLIST)\ + -DFEATURE_MODPROBE_SYSLOG=$(FEATURE_MODPROBE_SYSLOG)\ + -DFEATURE_MODPROBE_DIR_OVERRIDE=$(FEATURE_MODPROBE_DIR_OVERRIDE)\ + -DFEATURE_DEPMOD_ALIAS=$(FEATURE_DEPMOD_ALIAS)\ + -DFEATURE_DEPMOD_SYMBOLS=$(FEATURE_DEPMOD_SYMBOLS)\ + -DFEATURE_USE_LIBRESSL=$(FEATURE_USE_LIBRESSL)\ + -DFEATURE_USE_BEARSSL=$(FEATURE_USE_BEARSSL)\ + -DFEATURE_USE_OPENSSL=$(FEATURE_USE_OPENSSL)\ + -DFEATURE_TAR_TTY_SAFE=$(FEATURE_TAR_TTY_SAFE)\ + -DFEATURE_TAR_NOFOLLOW=$(FEATURE_TAR_NOFOLLOW)\ + -DFEATURE_READLINK_REALPATH=$(FEATURE_READLINK_REALPATH)\ + -DFEATURE_UMOUNT_OPTIONS=$(FEATURE_UMOUNT_OPTIONS)\ + -DFEATURE_TAR_TO_STDOUT=$(FEATURE_TAR_TO_STDOUT)\ + -DFEATURE_TAR_KEEP_OLD=$(FEATURE_TAR_KEEP_OLD)\ + -DFEATURE_TAR_STRIP_COMPONENTS=$(FEATURE_TAR_STRIP_COMPONENTS)\ + -DFEATURE_TAR_FILES_FROM=$(FEATURE_TAR_FILES_FROM)\ + -DFEATURE_TAR_EXCLUDE_FROM=$(FEATURE_TAR_EXCLUDE_FROM)\ + -DFEATURE_IP_ROUTE_ADD_DEL=$(FEATURE_IP_ROUTE_ADD_DEL)\ + -DFEATURE_IP_LINK_SET=$(FEATURE_IP_LINK_SET)\ + -DFEATURE_IP_ADDR_FLUSH=$(FEATURE_IP_ADDR_FLUSH) $(CPPFLAGS_TLS) CC = cc CFLAGS = diff --git a/deps.mk b/deps.mk @@ -1,75 +1,71 @@ #AUTOGENERATED -cmd/extra/b3sum.o: cmd/extra/b3sum.c -cmd/extra/b3sum.o: shared/util.h -cmd/extra/b3sum.o: shared/arg.h -cmd/extra/b3sum.o: shared/compat.h -cmd/extra/b3sum.o: shared/arg.h -cmd/extra/blkid.o: cmd/extra/blkid.c -cmd/extra/blkid.o: shared/util.h -cmd/extra/blkid.o: shared/arg.h -cmd/extra/blkid.o: shared/compat.h -cmd/extra/blkid.o: shared/diskutil.h -cmd/extra/fdisk.o: cmd/extra/fdisk.c -cmd/extra/fdisk.o: shared/util.h -cmd/extra/fdisk.o: shared/arg.h -cmd/extra/fdisk.o: shared/compat.h -cmd/extra/fdisk.o: shared/diskutil.h -cmd/extra/lsblk.o: cmd/extra/lsblk.c -cmd/extra/lsblk.o: shared/util.h -cmd/extra/lsblk.o: shared/arg.h -cmd/extra/lsblk.o: shared/compat.h -cmd/extra/lsblk.o: shared/diskutil.h -cmd/extra/sync.o: cmd/extra/sync.c -cmd/extra/sync.o: shared/arg.h -cmd/extra/sync.o: shared/util.h -cmd/extra/sync.o: shared/arg.h -cmd/extra/sync.o: shared/compat.h -cmd/linux/blkdiscard.o: cmd/linux/blkdiscard.c -cmd/linux/blkdiscard.o: shared/util.h -cmd/linux/blkdiscard.o: shared/arg.h -cmd/linux/blkdiscard.o: shared/compat.h -cmd/linux/chvt.o: cmd/linux/chvt.c -cmd/linux/chvt.o: shared/util.h -cmd/linux/chvt.o: shared/arg.h -cmd/linux/chvt.o: shared/compat.h -cmd/linux/ctrlaltdel.o: cmd/linux/ctrlaltdel.c -cmd/linux/ctrlaltdel.o: shared/reboot.h -cmd/linux/ctrlaltdel.o: shared/util.h -cmd/linux/ctrlaltdel.o: shared/arg.h -cmd/linux/ctrlaltdel.o: shared/compat.h -cmd/linux/depmod.o: cmd/linux/depmod.c -cmd/linux/depmod.o: shared/fs.h -cmd/linux/depmod.o: shared/util.h -cmd/linux/depmod.o: shared/arg.h -cmd/linux/depmod.o: shared/compat.h -cmd/linux/eject.o: cmd/linux/eject.c -cmd/linux/eject.o: shared/util.h -cmd/linux/eject.o: shared/arg.h -cmd/linux/eject.o: shared/compat.h -cmd/linux/freeramdisk.o: cmd/linux/freeramdisk.c -cmd/linux/freeramdisk.o: shared/util.h -cmd/linux/freeramdisk.o: shared/arg.h -cmd/linux/freeramdisk.o: shared/compat.h -cmd/linux/fsfreeze.o: cmd/linux/fsfreeze.c -cmd/linux/fsfreeze.o: shared/util.h -cmd/linux/fsfreeze.o: shared/arg.h -cmd/linux/fsfreeze.o: shared/compat.h +cmd/linux/switch_root.o: cmd/linux/switch_root.c +cmd/linux/switch_root.o: shared/util.h +cmd/linux/switch_root.o: shared/arg.h +cmd/linux/switch_root.o: shared/compat.h +cmd/linux/unshare.o: cmd/linux/unshare.c +cmd/linux/unshare.o: shared/wexec.h +cmd/linux/unshare.o: shared/util.h +cmd/linux/unshare.o: shared/arg.h +cmd/linux/unshare.o: shared/compat.h +cmd/linux/mount.o: cmd/linux/mount.c +cmd/linux/mount.o: shared/text.h +cmd/linux/mount.o: shared/wexec.h +cmd/linux/mount.o: shared/util.h +cmd/linux/mount.o: shared/arg.h +cmd/linux/mount.o: shared/compat.h +cmd/linux/pivot_root.o: cmd/linux/pivot_root.c +cmd/linux/pivot_root.o: shared/util.h +cmd/linux/pivot_root.o: shared/arg.h +cmd/linux/pivot_root.o: shared/compat.h +cmd/linux/umount.o: cmd/linux/umount.c +cmd/linux/umount.o: shared/util.h +cmd/linux/umount.o: shared/arg.h +cmd/linux/umount.o: shared/compat.h +cmd/linux/rmmod.o: cmd/linux/rmmod.c +cmd/linux/rmmod.o: shared/util.h +cmd/linux/rmmod.o: shared/arg.h +cmd/linux/rmmod.o: shared/compat.h cmd/linux/hwclock.o: cmd/linux/hwclock.c cmd/linux/hwclock.o: shared/rtc.h +cmd/linux/hwclock.o: shared/paths.h cmd/linux/hwclock.o: shared/util.h cmd/linux/hwclock.o: shared/arg.h cmd/linux/hwclock.o: shared/compat.h -cmd/linux/lsmod.o: cmd/linux/lsmod.c -cmd/linux/lsmod.o: shared/text.h -cmd/linux/lsmod.o: shared/util.h -cmd/linux/lsmod.o: shared/arg.h -cmd/linux/lsmod.o: shared/compat.h +cmd/linux/sysctl.o: cmd/linux/sysctl.c +cmd/linux/sysctl.o: shared/text.h +cmd/linux/sysctl.o: shared/paths.h +cmd/linux/sysctl.o: shared/util.h +cmd/linux/sysctl.o: shared/arg.h +cmd/linux/sysctl.o: shared/compat.h +cmd/linux/tunctl.o: cmd/linux/tunctl.c +cmd/linux/tunctl.o: shared/paths.h +cmd/linux/tunctl.o: shared/util.h +cmd/linux/tunctl.o: shared/arg.h +cmd/linux/tunctl.o: shared/compat.h +cmd/linux/fsfreeze.o: cmd/linux/fsfreeze.c +cmd/linux/fsfreeze.o: shared/util.h +cmd/linux/fsfreeze.o: shared/arg.h +cmd/linux/fsfreeze.o: shared/compat.h +cmd/linux/blkdiscard.o: cmd/linux/blkdiscard.c +cmd/linux/blkdiscard.o: shared/util.h +cmd/linux/blkdiscard.o: shared/arg.h +cmd/linux/blkdiscard.o: shared/compat.h +cmd/linux/swaplabel.o: cmd/linux/swaplabel.c +cmd/linux/swaplabel.o: shared/util.h +cmd/linux/swaplabel.o: shared/arg.h +cmd/linux/swaplabel.o: shared/compat.h cmd/linux/lsusb.o: cmd/linux/lsusb.c cmd/linux/lsusb.o: shared/text.h +cmd/linux/lsusb.o: shared/paths.h cmd/linux/lsusb.o: shared/util.h cmd/linux/lsusb.o: shared/arg.h cmd/linux/lsusb.o: shared/compat.h +cmd/linux/readahead.o: cmd/linux/readahead.c +cmd/linux/readahead.o: shared/util.h +cmd/linux/readahead.o: shared/arg.h +cmd/linux/readahead.o: shared/compat.h cmd/linux/mkswap.o: cmd/linux/mkswap.c cmd/linux/mkswap.o: shared/util.h cmd/linux/mkswap.o: shared/arg.h @@ -78,952 +74,171 @@ cmd/linux/mountpoint.o: cmd/linux/mountpoint.c cmd/linux/mountpoint.o: shared/util.h cmd/linux/mountpoint.o: shared/arg.h cmd/linux/mountpoint.o: shared/compat.h -cmd/linux/pivot_root.o: cmd/linux/pivot_root.c -cmd/linux/pivot_root.o: shared/util.h -cmd/linux/pivot_root.o: shared/arg.h -cmd/linux/pivot_root.o: shared/compat.h -cmd/linux/readahead.o: cmd/linux/readahead.c -cmd/linux/readahead.o: shared/util.h -cmd/linux/readahead.o: shared/arg.h -cmd/linux/readahead.o: shared/compat.h -cmd/linux/rmmod.o: cmd/linux/rmmod.c -cmd/linux/rmmod.o: shared/util.h -cmd/linux/rmmod.o: shared/arg.h -cmd/linux/rmmod.o: shared/compat.h -cmd/linux/swaplabel.o: cmd/linux/swaplabel.c -cmd/linux/swaplabel.o: shared/util.h -cmd/linux/swaplabel.o: shared/arg.h -cmd/linux/swaplabel.o: shared/compat.h +cmd/linux/lsmod.o: cmd/linux/lsmod.c +cmd/linux/lsmod.o: shared/text.h +cmd/linux/lsmod.o: shared/paths.h +cmd/linux/lsmod.o: shared/util.h +cmd/linux/lsmod.o: shared/arg.h +cmd/linux/lsmod.o: shared/compat.h +cmd/linux/chvt.o: cmd/linux/chvt.c +cmd/linux/chvt.o: shared/paths.h +cmd/linux/chvt.o: shared/util.h +cmd/linux/chvt.o: shared/arg.h +cmd/linux/chvt.o: shared/compat.h cmd/linux/swapoff.o: cmd/linux/swapoff.c cmd/linux/swapoff.o: shared/util.h cmd/linux/swapoff.o: shared/arg.h cmd/linux/swapoff.o: shared/compat.h -cmd/linux/swapon.o: cmd/linux/swapon.c -cmd/linux/swapon.o: shared/util.h -cmd/linux/swapon.o: shared/arg.h -cmd/linux/swapon.o: shared/compat.h -cmd/linux/sysctl.o: cmd/linux/sysctl.c -cmd/linux/sysctl.o: shared/text.h -cmd/linux/sysctl.o: shared/util.h -cmd/linux/sysctl.o: shared/arg.h -cmd/linux/sysctl.o: shared/compat.h -cmd/linux/tunctl.o: cmd/linux/tunctl.c -cmd/linux/tunctl.o: shared/util.h -cmd/linux/tunctl.o: shared/arg.h -cmd/linux/tunctl.o: shared/compat.h -cmd/linux/umount.o: cmd/linux/umount.c -cmd/linux/umount.o: shared/util.h -cmd/linux/umount.o: shared/arg.h -cmd/linux/umount.o: shared/compat.h +cmd/linux/eject.o: cmd/linux/eject.c +cmd/linux/eject.o: shared/paths.h +cmd/linux/eject.o: shared/util.h +cmd/linux/eject.o: shared/arg.h +cmd/linux/eject.o: shared/compat.h +cmd/linux/depmod.o: cmd/linux/depmod.c +cmd/linux/depmod.o: shared/fs.h +cmd/linux/depmod.o: shared/wexec.h +cmd/linux/depmod.o: shared/util.h +cmd/linux/depmod.o: shared/arg.h +cmd/linux/depmod.o: shared/compat.h cmd/linux/vtallow.o: cmd/linux/vtallow.c +cmd/linux/vtallow.o: shared/paths.h cmd/linux/vtallow.o: shared/util.h cmd/linux/vtallow.o: shared/arg.h cmd/linux/vtallow.o: shared/compat.h -cmd/linux/insmod.o: cmd/linux/insmod.c -cmd/linux/insmod.o: shared/util.h -cmd/linux/insmod.o: shared/arg.h -cmd/linux/insmod.o: shared/compat.h +cmd/linux/freeramdisk.o: cmd/linux/freeramdisk.c +cmd/linux/freeramdisk.o: shared/paths.h +cmd/linux/freeramdisk.o: shared/util.h +cmd/linux/freeramdisk.o: shared/arg.h +cmd/linux/freeramdisk.o: shared/compat.h +cmd/linux/swapon.o: cmd/linux/swapon.c +cmd/linux/swapon.o: shared/util.h +cmd/linux/swapon.o: shared/arg.h +cmd/linux/swapon.o: shared/compat.h +cmd/linux/ctrlaltdel.o: cmd/linux/ctrlaltdel.c +cmd/linux/ctrlaltdel.o: shared/reboot.h +cmd/linux/ctrlaltdel.o: shared/util.h +cmd/linux/ctrlaltdel.o: shared/arg.h +cmd/linux/ctrlaltdel.o: shared/compat.h cmd/linux/modprobe.o: cmd/linux/modprobe.c cmd/linux/modprobe.o: shared/arg.h cmd/linux/modprobe.o: shared/fs.h +cmd/linux/modprobe.o: shared/paths.h cmd/linux/modprobe.o: shared/util.h cmd/linux/modprobe.o: shared/arg.h cmd/linux/modprobe.o: shared/compat.h -cmd/linux/mount.o: cmd/linux/mount.c -cmd/linux/mount.o: shared/text.h -cmd/linux/mount.o: shared/util.h -cmd/linux/mount.o: shared/arg.h -cmd/linux/mount.o: shared/compat.h -cmd/linux/switch_root.o: cmd/linux/switch_root.c -cmd/linux/switch_root.o: shared/util.h -cmd/linux/switch_root.o: shared/arg.h -cmd/linux/switch_root.o: shared/compat.h -cmd/linux/unshare.o: cmd/linux/unshare.c -cmd/linux/unshare.o: shared/util.h -cmd/linux/unshare.o: shared/arg.h -cmd/linux/unshare.o: shared/compat.h -cmd/net/httpd.o: cmd/net/httpd.c -cmd/net/httpd.o: shared/util.h -cmd/net/httpd.o: shared/arg.h -cmd/net/httpd.o: shared/compat.h -cmd/net/httpd.o: shared/arg.h -cmd/net/ping.o: cmd/net/ping.c -cmd/net/ping.o: shared/util.h -cmd/net/ping.o: shared/arg.h -cmd/net/ping.o: shared/compat.h -cmd/net/ping.o: shared/arg.h -cmd/net/sdhcp.o: cmd/net/sdhcp.c -cmd/net/sdhcp.o: shared/arg.h -cmd/net/sdhcp.o: shared/util.h -cmd/net/sdhcp.o: shared/arg.h -cmd/net/sdhcp.o: shared/compat.h -cmd/net/tftp.o: cmd/net/tftp.c -cmd/net/tftp.o: shared/util.h -cmd/net/tftp.o: shared/arg.h -cmd/net/tftp.o: shared/compat.h -cmd/net/wget.o: cmd/net/wget.c -cmd/net/wget.o: shared/util.h -cmd/net/wget.o: shared/arg.h -cmd/net/wget.o: shared/compat.h -cmd/net/wget.o: shared/arg.h -cmd/net/wget.o: shared/tls.h -cmd/net/host.o: cmd/net/host.c -cmd/net/host.o: shared/util.h -cmd/net/host.o: shared/arg.h -cmd/net/host.o: shared/compat.h -cmd/net/host.o: shared/arg.h -cmd/net/ifconfig.o: cmd/net/ifconfig.c -cmd/net/ifconfig.o: shared/util.h -cmd/net/ifconfig.o: shared/arg.h -cmd/net/ifconfig.o: shared/compat.h -cmd/net/ip.o: cmd/net/ip.c -cmd/net/ip.o: shared/util.h -cmd/net/ip.o: shared/arg.h -cmd/net/ip.o: shared/compat.h -cmd/net/netcat.o: cmd/net/netcat.c -cmd/net/netcat.o: shared/util.h -cmd/net/netcat.o: shared/arg.h -cmd/net/netcat.o: shared/compat.h -cmd/posix/awk/b.o: cmd/posix/awk/b.c -cmd/posix/awk/b.o: cmd/posix/awk/awk.h -cmd/posix/awk/b.o: cmd/posix/awk/proto.h -cmd/posix/awk/b.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/lex.o: cmd/posix/awk/lex.c -cmd/posix/awk/lex.o: cmd/posix/awk/awk.h -cmd/posix/awk/lex.o: cmd/posix/awk/proto.h -cmd/posix/awk/lex.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/lib.o: cmd/posix/awk/lib.c -cmd/posix/awk/lib.o: cmd/posix/awk/awk.h -cmd/posix/awk/lib.o: cmd/posix/awk/proto.h -cmd/posix/awk/main.o: cmd/posix/awk/main.c -cmd/posix/awk/main.o: cmd/posix/awk/awk.h -cmd/posix/awk/main.o: cmd/posix/awk/proto.h -cmd/posix/awk/maketab.o: cmd/posix/awk/maketab.c -cmd/posix/awk/maketab.o: cmd/posix/awk/awk.h -cmd/posix/awk/maketab.o: cmd/posix/awk/proto.h -cmd/posix/awk/maketab.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/math.o: cmd/posix/awk/math.c -cmd/posix/awk/math.o: cmd/posix/awk/awk.h -cmd/posix/awk/math.o: cmd/posix/awk/proto.h -cmd/posix/awk/parse.o: cmd/posix/awk/parse.c -cmd/posix/awk/parse.o: cmd/posix/awk/awk.h -cmd/posix/awk/parse.o: cmd/posix/awk/proto.h -cmd/posix/awk/parse.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/run.o: cmd/posix/awk/run.c -cmd/posix/awk/run.o: cmd/posix/awk/awk.h -cmd/posix/awk/run.o: cmd/posix/awk/proto.h -cmd/posix/awk/run.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/tran.o: cmd/posix/awk/tran.c -cmd/posix/awk/tran.o: cmd/posix/awk/awk.h -cmd/posix/awk/tran.o: cmd/posix/awk/proto.h -cmd/posix/awk/awkgram.tab.o: cmd/posix/awk/awkgram.tab.c -cmd/posix/awk/awkgram.tab.o: cmd/posix/awk/awk.h -cmd/posix/awk/awkgram.tab.o: cmd/posix/awk/proto.h -cmd/posix/awk/awkgram.tab.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/awk/proctab.o: cmd/posix/awk/proctab.c -cmd/posix/awk/proctab.o: cmd/posix/awk/awk.h -cmd/posix/awk/proctab.o: cmd/posix/awk/proto.h -cmd/posix/awk/proctab.o: cmd/posix/awk/awkgram.tab.h -cmd/posix/cal.o: cmd/posix/cal.c -cmd/posix/cal.o: shared/util.h -cmd/posix/cal.o: shared/arg.h -cmd/posix/cal.o: shared/compat.h -cmd/posix/cat.o: cmd/posix/cat.c -cmd/posix/cat.o: shared/util.h -cmd/posix/cat.o: shared/arg.h -cmd/posix/cat.o: shared/compat.h -cmd/posix/chgrp.o: cmd/posix/chgrp.c -cmd/posix/chgrp.o: shared/fs.h -cmd/posix/chgrp.o: shared/util.h -cmd/posix/chgrp.o: shared/arg.h -cmd/posix/chgrp.o: shared/compat.h -cmd/posix/chmod.o: cmd/posix/chmod.c -cmd/posix/chmod.o: shared/fs.h -cmd/posix/chmod.o: shared/util.h -cmd/posix/chmod.o: shared/arg.h -cmd/posix/chmod.o: shared/compat.h -cmd/posix/chown.o: cmd/posix/chown.c -cmd/posix/chown.o: shared/fs.h -cmd/posix/chown.o: shared/util.h -cmd/posix/chown.o: shared/arg.h -cmd/posix/chown.o: shared/compat.h -cmd/posix/cksum.o: cmd/posix/cksum.c -cmd/posix/cksum.o: shared/util.h -cmd/posix/cksum.o: shared/arg.h -cmd/posix/cksum.o: shared/compat.h -cmd/posix/cmp.o: cmd/posix/cmp.c -cmd/posix/cmp.o: shared/util.h -cmd/posix/cmp.o: shared/arg.h -cmd/posix/cmp.o: shared/compat.h -cmd/posix/comm.o: cmd/posix/comm.c -cmd/posix/comm.o: shared/text.h -cmd/posix/comm.o: shared/util.h -cmd/posix/comm.o: shared/arg.h -cmd/posix/comm.o: shared/compat.h -cmd/posix/cp.o: cmd/posix/cp.c -cmd/posix/cp.o: shared/fs.h -cmd/posix/cp.o: shared/util.h -cmd/posix/cp.o: shared/arg.h -cmd/posix/cp.o: shared/compat.h -cmd/posix/dd.o: cmd/posix/dd.c -cmd/posix/dd.o: shared/util.h -cmd/posix/dd.o: shared/arg.h -cmd/posix/dd.o: shared/compat.h -cmd/posix/df.o: cmd/posix/df.c -cmd/posix/df.o: shared/util.h -cmd/posix/df.o: shared/arg.h -cmd/posix/df.o: shared/compat.h -cmd/posix/dirname.o: cmd/posix/dirname.c -cmd/posix/dirname.o: shared/util.h -cmd/posix/dirname.o: shared/arg.h -cmd/posix/dirname.o: shared/compat.h -cmd/posix/du.o: cmd/posix/du.c -cmd/posix/du.o: shared/fs.h -cmd/posix/du.o: shared/util.h -cmd/posix/du.o: shared/arg.h -cmd/posix/du.o: shared/compat.h -cmd/posix/echo.o: cmd/posix/echo.c -cmd/posix/echo.o: shared/util.h -cmd/posix/echo.o: shared/arg.h -cmd/posix/echo.o: shared/compat.h -cmd/posix/ed.o: cmd/posix/ed.c -cmd/posix/ed.o: shared/util.h -cmd/posix/ed.o: shared/arg.h -cmd/posix/ed.o: shared/compat.h -cmd/posix/expand.o: cmd/posix/expand.c -cmd/posix/expand.o: shared/utf.h -cmd/posix/expand.o: shared/util.h -cmd/posix/expand.o: shared/arg.h -cmd/posix/expand.o: shared/compat.h -cmd/posix/expr.o: cmd/posix/expr.c -cmd/posix/expr.o: shared/utf.h -cmd/posix/expr.o: shared/util.h -cmd/posix/expr.o: shared/arg.h -cmd/posix/expr.o: shared/compat.h -cmd/posix/false.o: cmd/posix/false.c -cmd/posix/fold.o: cmd/posix/fold.c -cmd/posix/fold.o: shared/text.h -cmd/posix/fold.o: shared/util.h -cmd/posix/fold.o: shared/arg.h -cmd/posix/fold.o: shared/compat.h -cmd/posix/fold.o: shared/utf.h -cmd/posix/head.o: cmd/posix/head.c -cmd/posix/head.o: shared/util.h -cmd/posix/head.o: shared/arg.h -cmd/posix/head.o: shared/compat.h -cmd/posix/id.o: cmd/posix/id.c -cmd/posix/id.o: shared/util.h -cmd/posix/id.o: shared/arg.h -cmd/posix/id.o: shared/compat.h -cmd/posix/join.o: cmd/posix/join.c -cmd/posix/join.o: shared/text.h -cmd/posix/join.o: shared/utf.h -cmd/posix/join.o: shared/util.h -cmd/posix/join.o: shared/arg.h -cmd/posix/join.o: shared/compat.h -cmd/posix/kill.o: cmd/posix/kill.c -cmd/posix/kill.o: shared/sig.h -cmd/posix/kill.o: shared/util.h -cmd/posix/kill.o: shared/arg.h -cmd/posix/kill.o: shared/compat.h -cmd/posix/link.o: cmd/posix/link.c -cmd/posix/link.o: shared/util.h -cmd/posix/link.o: shared/arg.h -cmd/posix/link.o: shared/compat.h -cmd/posix/logger.o: cmd/posix/logger.c -cmd/posix/logger.o: shared/util.h -cmd/posix/logger.o: shared/arg.h -cmd/posix/logger.o: shared/compat.h -cmd/posix/logname.o: cmd/posix/logname.c -cmd/posix/logname.o: shared/util.h -cmd/posix/logname.o: shared/arg.h -cmd/posix/logname.o: shared/compat.h -cmd/posix/make/defaults.o: cmd/posix/make/defaults.c -cmd/posix/make/main.o: cmd/posix/make/main.c -cmd/posix/make/main.o: cmd/posix/make/make.h -cmd/posix/make/parser.o: cmd/posix/make/parser.c -cmd/posix/make/parser.o: cmd/posix/make/make.h -cmd/posix/make/posix.o: cmd/posix/make/posix.c -cmd/posix/make/posix.o: cmd/posix/make/make.h -cmd/posix/make/rules.o: cmd/posix/make/rules.c -cmd/posix/make/rules.o: cmd/posix/make/make.h -cmd/posix/mesg.o: cmd/posix/mesg.c -cmd/posix/mesg.o: shared/util.h -cmd/posix/mesg.o: shared/arg.h -cmd/posix/mesg.o: shared/compat.h -cmd/posix/mkdir.o: cmd/posix/mkdir.c -cmd/posix/mkdir.o: shared/util.h -cmd/posix/mkdir.o: shared/arg.h -cmd/posix/mkdir.o: shared/compat.h -cmd/posix/mkfifo.o: cmd/posix/mkfifo.c -cmd/posix/mkfifo.o: shared/util.h -cmd/posix/mkfifo.o: shared/arg.h -cmd/posix/mkfifo.o: shared/compat.h -cmd/posix/mv.o: cmd/posix/mv.c -cmd/posix/mv.o: shared/fs.h -cmd/posix/mv.o: shared/util.h -cmd/posix/mv.o: shared/arg.h -cmd/posix/mv.o: shared/compat.h -cmd/posix/nl.o: cmd/posix/nl.c -cmd/posix/nl.o: shared/text.h -cmd/posix/nl.o: shared/utf.h -cmd/posix/nl.o: shared/util.h -cmd/posix/nl.o: shared/arg.h -cmd/posix/nl.o: shared/compat.h -cmd/posix/od.o: cmd/posix/od.c -cmd/posix/od.o: shared/queue.h -cmd/posix/od.o: shared/util.h -cmd/posix/od.o: shared/arg.h -cmd/posix/od.o: shared/compat.h -cmd/posix/paste.o: cmd/posix/paste.c -cmd/posix/paste.o: shared/utf.h -cmd/posix/paste.o: shared/util.h -cmd/posix/paste.o: shared/arg.h -cmd/posix/paste.o: shared/compat.h -cmd/posix/pathchk.o: cmd/posix/pathchk.c -cmd/posix/pathchk.o: shared/util.h -cmd/posix/pathchk.o: shared/arg.h -cmd/posix/pathchk.o: shared/compat.h -cmd/posix/pax.o: cmd/posix/pax.c -cmd/posix/pax.o: shared/arg.h -cmd/posix/ps.o: cmd/posix/ps.c -cmd/posix/ps.o: shared/proc.h -cmd/posix/ps.o: shared/util.h -cmd/posix/ps.o: shared/arg.h -cmd/posix/ps.o: shared/compat.h -cmd/posix/pwd.o: cmd/posix/pwd.c -cmd/posix/pwd.o: shared/util.h -cmd/posix/pwd.o: shared/arg.h -cmd/posix/pwd.o: shared/compat.h -cmd/posix/readlink.o: cmd/posix/readlink.c -cmd/posix/readlink.o: shared/util.h -cmd/posix/readlink.o: shared/arg.h -cmd/posix/readlink.o: shared/compat.h -cmd/posix/renice.o: cmd/posix/renice.c -cmd/posix/renice.o: shared/util.h -cmd/posix/renice.o: shared/arg.h -cmd/posix/renice.o: shared/compat.h -cmd/posix/rm.o: cmd/posix/rm.c -cmd/posix/rm.o: shared/fs.h -cmd/posix/rm.o: shared/util.h -cmd/posix/rm.o: shared/arg.h -cmd/posix/rm.o: shared/compat.h -cmd/posix/rmdir.o: cmd/posix/rmdir.c -cmd/posix/rmdir.o: shared/util.h -cmd/posix/rmdir.o: shared/arg.h -cmd/posix/rmdir.o: shared/compat.h -cmd/posix/sh/alias.o: cmd/posix/sh/alias.c -cmd/posix/sh/alias.o: cmd/posix/sh/shell.h -cmd/posix/sh/alias.o: shared/sig.h -cmd/posix/sh/alias.o: cmd/posix/sh/output.h -cmd/posix/sh/alias.o: cmd/posix/sh/error.h -cmd/posix/sh/alias.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/alias.o: cmd/posix/sh/mystring.h -cmd/posix/sh/alias.o: cmd/posix/sh/alias.h -cmd/posix/sh/alias.o: cmd/posix/sh/options.h -cmd/posix/sh/alias.o: cmd/posix/sh/builtins.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/arith_yacc.c -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/arith.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/shell.h -cmd/posix/sh/arith_yacc.o: shared/sig.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/arith_yacc.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/expand.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/error.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/output.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/options.h -cmd/posix/sh/arith_yacc.o: cmd/posix/sh/var.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/arith_yylex.c -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/shell.h -cmd/posix/sh/arith_yylex.o: shared/sig.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/arith_yacc.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/expand.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/error.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/parser.h -cmd/posix/sh/arith_yylex.o: cmd/posix/sh/syntax.h -cmd/posix/sh/cd.o: cmd/posix/sh/cd.c -cmd/posix/sh/cd.o: cmd/posix/sh/shell.h -cmd/posix/sh/cd.o: shared/sig.h -cmd/posix/sh/cd.o: cmd/posix/sh/var.h -cmd/posix/sh/cd.o: cmd/posix/sh/nodes.h -cmd/posix/sh/cd.o: cmd/posix/sh/jobs.h -cmd/posix/sh/cd.o: cmd/posix/sh/options.h -cmd/posix/sh/cd.o: cmd/posix/sh/output.h -cmd/posix/sh/cd.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/cd.o: cmd/posix/sh/error.h -cmd/posix/sh/cd.o: cmd/posix/sh/exec.h -cmd/posix/sh/cd.o: cmd/posix/sh/redir.h -cmd/posix/sh/cd.o: cmd/posix/sh/mystring.h -cmd/posix/sh/cd.o: cmd/posix/sh/show.h -cmd/posix/sh/cd.o: cmd/posix/sh/cd.h -cmd/posix/sh/cd.o: cmd/posix/sh/builtins.h -cmd/posix/sh/echo.o: cmd/posix/sh/echo.c -cmd/posix/sh/echo.o: cmd/posix/sh/bltin.h -cmd/posix/sh/echo.o: cmd/posix/sh/shell.h -cmd/posix/sh/echo.o: shared/sig.h -cmd/posix/sh/echo.o: cmd/posix/sh/mystring.h -cmd/posix/sh/error.o: cmd/posix/sh/error.c -cmd/posix/sh/error.o: cmd/posix/sh/shell.h -cmd/posix/sh/error.o: shared/sig.h -cmd/posix/sh/error.o: cmd/posix/sh/eval.h -cmd/posix/sh/error.o: cmd/posix/sh/main.h -cmd/posix/sh/error.o: cmd/posix/sh/options.h -cmd/posix/sh/error.o: cmd/posix/sh/output.h -cmd/posix/sh/error.o: cmd/posix/sh/error.h -cmd/posix/sh/error.o: cmd/posix/sh/nodes.h -cmd/posix/sh/error.o: cmd/posix/sh/show.h -cmd/posix/sh/error.o: cmd/posix/sh/trap.h -cmd/posix/sh/eval.o: cmd/posix/sh/eval.c -cmd/posix/sh/eval.o: cmd/posix/sh/shell.h -cmd/posix/sh/eval.o: shared/sig.h -cmd/posix/sh/eval.o: cmd/posix/sh/nodes.h -cmd/posix/sh/eval.o: cmd/posix/sh/syntax.h -cmd/posix/sh/eval.o: cmd/posix/sh/expand.h -cmd/posix/sh/eval.o: cmd/posix/sh/parser.h -cmd/posix/sh/eval.o: cmd/posix/sh/jobs.h -cmd/posix/sh/eval.o: cmd/posix/sh/eval.h -cmd/posix/sh/eval.o: cmd/posix/sh/builtins.h -cmd/posix/sh/eval.o: cmd/posix/sh/options.h -cmd/posix/sh/eval.o: cmd/posix/sh/exec.h -cmd/posix/sh/eval.o: cmd/posix/sh/redir.h -cmd/posix/sh/eval.o: cmd/posix/sh/input.h -cmd/posix/sh/eval.o: cmd/posix/sh/output.h -cmd/posix/sh/eval.o: cmd/posix/sh/trap.h -cmd/posix/sh/eval.o: cmd/posix/sh/var.h -cmd/posix/sh/eval.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/eval.o: cmd/posix/sh/error.h -cmd/posix/sh/eval.o: cmd/posix/sh/show.h -cmd/posix/sh/eval.o: cmd/posix/sh/mystring.h -cmd/posix/sh/exec.o: cmd/posix/sh/exec.c -cmd/posix/sh/exec.o: cmd/posix/sh/shell.h -cmd/posix/sh/exec.o: shared/sig.h -cmd/posix/sh/exec.o: cmd/posix/sh/main.h -cmd/posix/sh/exec.o: cmd/posix/sh/nodes.h -cmd/posix/sh/exec.o: cmd/posix/sh/parser.h -cmd/posix/sh/exec.o: cmd/posix/sh/redir.h -cmd/posix/sh/exec.o: cmd/posix/sh/eval.h -cmd/posix/sh/exec.o: cmd/posix/sh/exec.h -cmd/posix/sh/exec.o: cmd/posix/sh/builtins.h -cmd/posix/sh/exec.o: cmd/posix/sh/var.h -cmd/posix/sh/exec.o: cmd/posix/sh/options.h -cmd/posix/sh/exec.o: cmd/posix/sh/input.h -cmd/posix/sh/exec.o: cmd/posix/sh/output.h -cmd/posix/sh/exec.o: cmd/posix/sh/syntax.h -cmd/posix/sh/exec.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/exec.o: cmd/posix/sh/error.h -cmd/posix/sh/exec.o: cmd/posix/sh/mystring.h -cmd/posix/sh/exec.o: cmd/posix/sh/show.h -cmd/posix/sh/exec.o: cmd/posix/sh/jobs.h -cmd/posix/sh/exec.o: cmd/posix/sh/alias.h -cmd/posix/sh/expand.o: cmd/posix/sh/expand.c -cmd/posix/sh/expand.o: cmd/posix/sh/shell.h -cmd/posix/sh/expand.o: shared/sig.h -cmd/posix/sh/expand.o: cmd/posix/sh/main.h -cmd/posix/sh/expand.o: cmd/posix/sh/nodes.h -cmd/posix/sh/expand.o: cmd/posix/sh/eval.h -cmd/posix/sh/expand.o: cmd/posix/sh/expand.h -cmd/posix/sh/expand.o: cmd/posix/sh/syntax.h -cmd/posix/sh/expand.o: cmd/posix/sh/parser.h -cmd/posix/sh/expand.o: cmd/posix/sh/jobs.h -cmd/posix/sh/expand.o: cmd/posix/sh/options.h -cmd/posix/sh/expand.o: cmd/posix/sh/var.h -cmd/posix/sh/expand.o: cmd/posix/sh/input.h -cmd/posix/sh/expand.o: cmd/posix/sh/output.h -cmd/posix/sh/expand.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/expand.o: cmd/posix/sh/error.h -cmd/posix/sh/expand.o: cmd/posix/sh/mystring.h -cmd/posix/sh/expand.o: cmd/posix/sh/arith.h -cmd/posix/sh/expand.o: cmd/posix/sh/show.h -cmd/posix/sh/expand.o: cmd/posix/sh/builtins.h -cmd/posix/sh/input.o: cmd/posix/sh/input.c -cmd/posix/sh/input.o: cmd/posix/sh/shell.h -cmd/posix/sh/input.o: shared/sig.h -cmd/posix/sh/input.o: cmd/posix/sh/redir.h -cmd/posix/sh/input.o: cmd/posix/sh/syntax.h -cmd/posix/sh/input.o: cmd/posix/sh/input.h -cmd/posix/sh/input.o: cmd/posix/sh/output.h -cmd/posix/sh/input.o: cmd/posix/sh/options.h -cmd/posix/sh/input.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/input.o: cmd/posix/sh/error.h -cmd/posix/sh/input.o: cmd/posix/sh/alias.h -cmd/posix/sh/input.o: cmd/posix/sh/parser.h -cmd/posix/sh/input.o: cmd/posix/sh/trap.h -cmd/posix/sh/jobs.o: cmd/posix/sh/jobs.c -cmd/posix/sh/jobs.o: cmd/posix/sh/shell.h -cmd/posix/sh/jobs.o: shared/sig.h -cmd/posix/sh/jobs.o: cmd/posix/sh/redir.h -cmd/posix/sh/jobs.o: cmd/posix/sh/exec.h -cmd/posix/sh/jobs.o: cmd/posix/sh/show.h -cmd/posix/sh/jobs.o: cmd/posix/sh/main.h -cmd/posix/sh/jobs.o: cmd/posix/sh/parser.h -cmd/posix/sh/jobs.o: cmd/posix/sh/nodes.h -cmd/posix/sh/jobs.o: cmd/posix/sh/jobs.h -cmd/posix/sh/jobs.o: cmd/posix/sh/options.h -cmd/posix/sh/jobs.o: cmd/posix/sh/trap.h -cmd/posix/sh/jobs.o: cmd/posix/sh/syntax.h -cmd/posix/sh/jobs.o: cmd/posix/sh/input.h -cmd/posix/sh/jobs.o: cmd/posix/sh/output.h -cmd/posix/sh/jobs.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/jobs.o: cmd/posix/sh/error.h -cmd/posix/sh/jobs.o: cmd/posix/sh/mystring.h -cmd/posix/sh/jobs.o: cmd/posix/sh/var.h -cmd/posix/sh/jobs.o: cmd/posix/sh/builtins.h -cmd/posix/sh/jobs.o: cmd/posix/sh/eval.h -cmd/posix/sh/kill.o: cmd/posix/sh/kill.c -cmd/posix/sh/kill.o: shared/sig.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/lineedit.c -cmd/posix/sh/lineedit.o: shared/util.h -cmd/posix/sh/lineedit.o: shared/arg.h -cmd/posix/sh/lineedit.o: shared/compat.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/shell.h -cmd/posix/sh/lineedit.o: shared/sig.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/alias.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/builtins.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/error.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/eval.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/exec.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/main.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/mystring.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/options.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/output.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/parser.h -cmd/posix/sh/lineedit.o: cmd/posix/sh/var.h -cmd/posix/sh/mail.o: cmd/posix/sh/mail.c -cmd/posix/sh/mail.o: cmd/posix/sh/shell.h -cmd/posix/sh/mail.o: shared/sig.h -cmd/posix/sh/mail.o: cmd/posix/sh/mail.h -cmd/posix/sh/mail.o: cmd/posix/sh/var.h -cmd/posix/sh/mail.o: cmd/posix/sh/output.h -cmd/posix/sh/mail.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/mail.o: cmd/posix/sh/error.h -cmd/posix/sh/main.o: cmd/posix/sh/main.c -cmd/posix/sh/main.o: cmd/posix/sh/shell.h -cmd/posix/sh/main.o: shared/sig.h -cmd/posix/sh/main.o: cmd/posix/sh/main.h -cmd/posix/sh/main.o: cmd/posix/sh/mail.h -cmd/posix/sh/main.o: cmd/posix/sh/options.h -cmd/posix/sh/main.o: cmd/posix/sh/output.h -cmd/posix/sh/main.o: cmd/posix/sh/parser.h -cmd/posix/sh/main.o: cmd/posix/sh/nodes.h -cmd/posix/sh/main.o: cmd/posix/sh/expand.h -cmd/posix/sh/main.o: cmd/posix/sh/eval.h -cmd/posix/sh/main.o: cmd/posix/sh/jobs.h -cmd/posix/sh/main.o: cmd/posix/sh/input.h -cmd/posix/sh/main.o: cmd/posix/sh/trap.h -cmd/posix/sh/main.o: cmd/posix/sh/var.h -cmd/posix/sh/main.o: cmd/posix/sh/show.h -cmd/posix/sh/main.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/main.o: cmd/posix/sh/error.h -cmd/posix/sh/main.o: cmd/posix/sh/mystring.h -cmd/posix/sh/main.o: cmd/posix/sh/exec.h -cmd/posix/sh/main.o: cmd/posix/sh/cd.h -cmd/posix/sh/main.o: cmd/posix/sh/redir.h -cmd/posix/sh/main.o: cmd/posix/sh/builtins.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/memalloc.c -cmd/posix/sh/memalloc.o: cmd/posix/sh/shell.h -cmd/posix/sh/memalloc.o: shared/sig.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/output.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/error.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/mystring.h -cmd/posix/sh/memalloc.o: cmd/posix/sh/expand.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/miscbltin.c -cmd/posix/sh/miscbltin.o: cmd/posix/sh/shell.h -cmd/posix/sh/miscbltin.o: shared/sig.h -cmd/posix/sh/miscbltin.o: shared/redline.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/options.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/var.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/output.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/error.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/mystring.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/syntax.h -cmd/posix/sh/miscbltin.o: cmd/posix/sh/trap.h -cmd/posix/sh/mknodes.o: cmd/posix/sh/mknodes.c -cmd/posix/sh/mksyntax.o: cmd/posix/sh/mksyntax.c -cmd/posix/sh/mksyntax.o: cmd/posix/sh/parser.h -cmd/posix/sh/mystring.o: cmd/posix/sh/mystring.c -cmd/posix/sh/mystring.o: cmd/posix/sh/shell.h -cmd/posix/sh/mystring.o: shared/sig.h -cmd/posix/sh/mystring.o: cmd/posix/sh/syntax.h -cmd/posix/sh/mystring.o: cmd/posix/sh/error.h -cmd/posix/sh/mystring.o: cmd/posix/sh/mystring.h -cmd/posix/sh/options.o: cmd/posix/sh/options.c -cmd/posix/sh/options.o: cmd/posix/sh/shell.h -cmd/posix/sh/options.o: shared/sig.h -cmd/posix/sh/options.o: cmd/posix/sh/options.h -cmd/posix/sh/options.o: cmd/posix/sh/nodes.h -cmd/posix/sh/options.o: cmd/posix/sh/eval.h -cmd/posix/sh/options.o: cmd/posix/sh/jobs.h -cmd/posix/sh/options.o: cmd/posix/sh/input.h -cmd/posix/sh/options.o: cmd/posix/sh/output.h -cmd/posix/sh/options.o: cmd/posix/sh/trap.h -cmd/posix/sh/options.o: cmd/posix/sh/var.h -cmd/posix/sh/options.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/options.o: cmd/posix/sh/error.h -cmd/posix/sh/options.o: cmd/posix/sh/mystring.h -cmd/posix/sh/options.o: cmd/posix/sh/builtins.h -cmd/posix/sh/output.o: cmd/posix/sh/output.c -cmd/posix/sh/output.o: cmd/posix/sh/shell.h -cmd/posix/sh/output.o: shared/sig.h -cmd/posix/sh/output.o: cmd/posix/sh/syntax.h -cmd/posix/sh/output.o: cmd/posix/sh/output.h -cmd/posix/sh/output.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/output.o: cmd/posix/sh/error.h -cmd/posix/sh/output.o: cmd/posix/sh/var.h -cmd/posix/sh/parser.o: cmd/posix/sh/parser.c -cmd/posix/sh/parser.o: cmd/posix/sh/shell.h -cmd/posix/sh/parser.o: shared/sig.h -cmd/posix/sh/parser.o: cmd/posix/sh/parser.h -cmd/posix/sh/parser.o: cmd/posix/sh/nodes.h -cmd/posix/sh/parser.o: cmd/posix/sh/expand.h -cmd/posix/sh/parser.o: cmd/posix/sh/syntax.h -cmd/posix/sh/parser.o: cmd/posix/sh/options.h -cmd/posix/sh/parser.o: cmd/posix/sh/input.h -cmd/posix/sh/parser.o: cmd/posix/sh/output.h -cmd/posix/sh/parser.o: cmd/posix/sh/var.h -cmd/posix/sh/parser.o: cmd/posix/sh/error.h -cmd/posix/sh/parser.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/parser.o: cmd/posix/sh/mystring.h -cmd/posix/sh/parser.o: cmd/posix/sh/alias.h -cmd/posix/sh/parser.o: cmd/posix/sh/show.h -cmd/posix/sh/parser.o: cmd/posix/sh/eval.h -cmd/posix/sh/parser.o: cmd/posix/sh/exec.h -cmd/posix/sh/parser.o: cmd/posix/sh/main.h -cmd/posix/sh/parser.o: cmd/posix/sh/jobs.h -cmd/posix/sh/parser.o: cmd/posix/sh/token.h -cmd/posix/sh/printf.o: cmd/posix/sh/printf.c -cmd/posix/sh/redir.o: cmd/posix/sh/redir.c -cmd/posix/sh/redir.o: cmd/posix/sh/shell.h -cmd/posix/sh/redir.o: shared/sig.h -cmd/posix/sh/redir.o: cmd/posix/sh/nodes.h -cmd/posix/sh/redir.o: cmd/posix/sh/jobs.h -cmd/posix/sh/redir.o: cmd/posix/sh/expand.h -cmd/posix/sh/redir.o: cmd/posix/sh/redir.h -cmd/posix/sh/redir.o: cmd/posix/sh/output.h -cmd/posix/sh/redir.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/redir.o: cmd/posix/sh/error.h -cmd/posix/sh/redir.o: cmd/posix/sh/options.h -cmd/posix/sh/show.o: cmd/posix/sh/show.c -cmd/posix/sh/show.o: cmd/posix/sh/shell.h -cmd/posix/sh/show.o: shared/sig.h -cmd/posix/sh/show.o: cmd/posix/sh/parser.h -cmd/posix/sh/show.o: cmd/posix/sh/nodes.h -cmd/posix/sh/show.o: cmd/posix/sh/mystring.h -cmd/posix/sh/show.o: cmd/posix/sh/show.h -cmd/posix/sh/test.o: cmd/posix/sh/test.c -cmd/posix/sh/trap.o: cmd/posix/sh/trap.c -cmd/posix/sh/trap.o: cmd/posix/sh/shell.h -cmd/posix/sh/trap.o: shared/sig.h -cmd/posix/sh/trap.o: cmd/posix/sh/main.h -cmd/posix/sh/trap.o: cmd/posix/sh/nodes.h -cmd/posix/sh/trap.o: cmd/posix/sh/eval.h -cmd/posix/sh/trap.o: cmd/posix/sh/jobs.h -cmd/posix/sh/trap.o: cmd/posix/sh/show.h -cmd/posix/sh/trap.o: cmd/posix/sh/options.h -cmd/posix/sh/trap.o: cmd/posix/sh/syntax.h -cmd/posix/sh/trap.o: cmd/posix/sh/output.h -cmd/posix/sh/trap.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/trap.o: cmd/posix/sh/error.h -cmd/posix/sh/trap.o: cmd/posix/sh/trap.h -cmd/posix/sh/trap.o: cmd/posix/sh/mystring.h -cmd/posix/sh/trap.o: cmd/posix/sh/builtins.h -cmd/posix/sh/var.o: cmd/posix/sh/var.c -cmd/posix/sh/var.o: cmd/posix/sh/shell.h -cmd/posix/sh/var.o: shared/sig.h -cmd/posix/sh/var.o: cmd/posix/sh/output.h -cmd/posix/sh/var.o: cmd/posix/sh/expand.h -cmd/posix/sh/var.o: cmd/posix/sh/nodes.h -cmd/posix/sh/var.o: cmd/posix/sh/eval.h -cmd/posix/sh/var.o: cmd/posix/sh/exec.h -cmd/posix/sh/var.o: cmd/posix/sh/syntax.h -cmd/posix/sh/var.o: cmd/posix/sh/options.h -cmd/posix/sh/var.o: cmd/posix/sh/mail.h -cmd/posix/sh/var.o: cmd/posix/sh/var.h -cmd/posix/sh/var.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/var.o: cmd/posix/sh/error.h -cmd/posix/sh/var.o: cmd/posix/sh/mystring.h -cmd/posix/sh/var.o: cmd/posix/sh/parser.h -cmd/posix/sh/var.o: cmd/posix/sh/builtins.h -cmd/posix/sh/syntax.o: cmd/posix/sh/syntax.c -cmd/posix/sh/syntax.o: cmd/posix/sh/parser.h -cmd/posix/sh/syntax.o: cmd/posix/sh/shell.h -cmd/posix/sh/syntax.o: shared/sig.h -cmd/posix/sh/syntax.o: cmd/posix/sh/syntax.h -cmd/posix/sh/nodes.o: cmd/posix/sh/nodes.c -cmd/posix/sh/nodes.o: cmd/posix/sh/shell.h -cmd/posix/sh/nodes.o: shared/sig.h -cmd/posix/sh/nodes.o: cmd/posix/sh/nodes.h -cmd/posix/sh/nodes.o: cmd/posix/sh/memalloc.h -cmd/posix/sh/nodes.o: cmd/posix/sh/mystring.h -cmd/posix/sh/builtins.o: cmd/posix/sh/builtins.c -cmd/posix/sh/builtins.o: cmd/posix/sh/shell.h -cmd/posix/sh/builtins.o: shared/sig.h -cmd/posix/sh/builtins.o: cmd/posix/sh/builtins.h -cmd/posix/sleep.o: cmd/posix/sleep.c -cmd/posix/sleep.o: shared/util.h -cmd/posix/sleep.o: shared/arg.h -cmd/posix/sleep.o: shared/compat.h -cmd/posix/sort.o: cmd/posix/sort.c -cmd/posix/sort.o: shared/queue.h -cmd/posix/sort.o: shared/text.h -cmd/posix/sort.o: shared/utf.h -cmd/posix/sort.o: shared/util.h -cmd/posix/sort.o: shared/arg.h -cmd/posix/sort.o: shared/compat.h -cmd/posix/split.o: cmd/posix/split.c -cmd/posix/split.o: shared/util.h -cmd/posix/split.o: shared/arg.h -cmd/posix/split.o: shared/compat.h -cmd/posix/tail.o: cmd/posix/tail.c -cmd/posix/tail.o: shared/utf.h -cmd/posix/tail.o: shared/util.h -cmd/posix/tail.o: shared/arg.h -cmd/posix/tail.o: shared/compat.h -cmd/posix/tee.o: cmd/posix/tee.c -cmd/posix/tee.o: shared/util.h -cmd/posix/tee.o: shared/arg.h -cmd/posix/tee.o: shared/compat.h -cmd/posix/test.o: cmd/posix/test.c -cmd/posix/test.o: shared/util.h -cmd/posix/test.o: shared/arg.h -cmd/posix/test.o: shared/compat.h -cmd/posix/touch.o: cmd/posix/touch.c -cmd/posix/touch.o: shared/util.h -cmd/posix/touch.o: shared/arg.h -cmd/posix/touch.o: shared/compat.h -cmd/posix/true.o: cmd/posix/true.c -cmd/posix/tsort.o: cmd/posix/tsort.c -cmd/posix/tsort.o: shared/util.h -cmd/posix/tsort.o: shared/arg.h -cmd/posix/tsort.o: shared/compat.h -cmd/posix/tty.o: cmd/posix/tty.c -cmd/posix/tty.o: shared/util.h -cmd/posix/tty.o: shared/arg.h -cmd/posix/tty.o: shared/compat.h -cmd/posix/uname.o: cmd/posix/uname.c -cmd/posix/uname.o: shared/util.h -cmd/posix/uname.o: shared/arg.h -cmd/posix/uname.o: shared/compat.h -cmd/posix/unexpand.o: cmd/posix/unexpand.c -cmd/posix/unexpand.o: shared/utf.h -cmd/posix/unexpand.o: shared/util.h -cmd/posix/unexpand.o: shared/arg.h -cmd/posix/unexpand.o: shared/compat.h -cmd/posix/uniq.o: cmd/posix/uniq.c -cmd/posix/uniq.o: shared/text.h -cmd/posix/uniq.o: shared/util.h -cmd/posix/uniq.o: shared/arg.h -cmd/posix/uniq.o: shared/compat.h -cmd/posix/unlink.o: cmd/posix/unlink.c -cmd/posix/unlink.o: shared/util.h -cmd/posix/unlink.o: shared/arg.h -cmd/posix/unlink.o: shared/compat.h -cmd/posix/uudecode.o: cmd/posix/uudecode.c -cmd/posix/uudecode.o: shared/util.h -cmd/posix/uudecode.o: shared/arg.h -cmd/posix/uudecode.o: shared/compat.h -cmd/posix/wc.o: cmd/posix/wc.c -cmd/posix/wc.o: shared/utf.h -cmd/posix/wc.o: shared/util.h -cmd/posix/wc.o: shared/arg.h -cmd/posix/wc.o: shared/compat.h -cmd/posix/who.o: cmd/posix/who.c -cmd/posix/who.o: shared/config.h -cmd/posix/who.o: shared/util.h -cmd/posix/who.o: shared/arg.h -cmd/posix/who.o: shared/compat.h -cmd/posix/xargs.o: cmd/posix/xargs.c -cmd/posix/xargs.o: shared/util.h -cmd/posix/xargs.o: shared/arg.h -cmd/posix/xargs.o: shared/compat.h -cmd/posix/basename.o: cmd/posix/basename.c -cmd/posix/basename.o: shared/util.h -cmd/posix/basename.o: shared/arg.h -cmd/posix/basename.o: shared/compat.h -cmd/posix/cut.o: cmd/posix/cut.c -cmd/posix/cut.o: shared/text.h -cmd/posix/cut.o: shared/utf.h -cmd/posix/cut.o: shared/util.h -cmd/posix/cut.o: shared/arg.h -cmd/posix/cut.o: shared/compat.h -cmd/posix/date.o: cmd/posix/date.c -cmd/posix/date.o: shared/util.h -cmd/posix/date.o: shared/arg.h -cmd/posix/date.o: shared/compat.h -cmd/posix/diff.o: cmd/posix/diff.c shared/util.h shared/arg.h shared/compat.h -cmd/posix/env.o: cmd/posix/env.c -cmd/posix/env.o: shared/util.h -cmd/posix/env.o: shared/arg.h -cmd/posix/env.o: shared/compat.h -cmd/posix/find.o: cmd/posix/find.c -cmd/posix/find.o: shared/config.h -cmd/posix/find.o: shared/util.h -cmd/posix/find.o: shared/arg.h -cmd/posix/find.o: shared/compat.h -cmd/posix/getconf.o: cmd/posix/getconf.c -cmd/posix/getconf.o: shared/util.h -cmd/posix/getconf.o: shared/arg.h -cmd/posix/getconf.o: shared/compat.h -cmd/posix/getconf.o: cmd/posix/getconf.h -cmd/posix/grep.o: cmd/posix/grep.c -cmd/posix/grep.o: shared/config.h -cmd/posix/grep.o: shared/queue.h -cmd/posix/grep.o: shared/util.h -cmd/posix/grep.o: shared/arg.h -cmd/posix/grep.o: shared/compat.h -cmd/posix/ln.o: cmd/posix/ln.c -cmd/posix/ln.o: shared/util.h -cmd/posix/ln.o: shared/arg.h -cmd/posix/ln.o: shared/compat.h -cmd/posix/ls.o: cmd/posix/ls.c -cmd/posix/ls.o: shared/utf.h -cmd/posix/ls.o: shared/util.h -cmd/posix/ls.o: shared/arg.h -cmd/posix/ls.o: shared/compat.h -cmd/posix/nice.o: cmd/posix/nice.c -cmd/posix/nice.o: shared/util.h -cmd/posix/nice.o: shared/arg.h -cmd/posix/nice.o: shared/compat.h -cmd/posix/nohup.o: cmd/posix/nohup.c -cmd/posix/nohup.o: shared/util.h -cmd/posix/nohup.o: shared/arg.h -cmd/posix/nohup.o: shared/compat.h -cmd/posix/printf.o: cmd/posix/printf.c -cmd/posix/printf.o: shared/utf.h -cmd/posix/printf.o: shared/util.h -cmd/posix/printf.o: shared/arg.h -cmd/posix/printf.o: shared/compat.h -cmd/posix/sed.o: cmd/posix/sed.c -cmd/posix/sed.o: shared/config.h -cmd/posix/sed.o: shared/utf.h -cmd/posix/sed.o: shared/util.h -cmd/posix/sed.o: shared/arg.h -cmd/posix/sed.o: shared/compat.h -cmd/posix/time.o: cmd/posix/time.c -cmd/posix/time.o: shared/util.h -cmd/posix/time.o: shared/arg.h -cmd/posix/time.o: shared/compat.h -cmd/posix/tr.o: cmd/posix/tr.c -cmd/posix/tr.o: shared/utf.h -cmd/posix/tr.o: shared/util.h -cmd/posix/tr.o: shared/arg.h -cmd/posix/tr.o: shared/compat.h -cmd/posix/uuencode.o: cmd/posix/uuencode.c -cmd/posix/uuencode.o: shared/util.h -cmd/posix/uuencode.o: shared/arg.h -cmd/posix/uuencode.o: shared/compat.h -cmd/posix/patch.o: cmd/posix/patch.c shared/util.h shared/arg.h shared/compat.h -cmd/posix/diff3.o: cmd/posix/diff3.c shared/util.h shared/arg.h shared/compat.h -cmd/pseudo/mkpasswd.o: cmd/pseudo/mkpasswd.c shared/util.h shared/arg.h shared/compat.h -cmd/pseudo/base64.o: cmd/pseudo/base64.c -cmd/pseudo/base64.o: shared/util.h -cmd/pseudo/base64.o: shared/arg.h -cmd/pseudo/base64.o: shared/compat.h -cmd/pseudo/base64.o: shared/arg.h +cmd/linux/insmod.o: cmd/linux/insmod.c +cmd/linux/insmod.o: shared/util.h +cmd/linux/insmod.o: shared/arg.h +cmd/linux/insmod.o: shared/compat.h cmd/pseudo/clear.o: cmd/pseudo/clear.c cmd/pseudo/clear.o: shared/util.h cmd/pseudo/clear.o: shared/arg.h cmd/pseudo/clear.o: shared/compat.h -cmd/pseudo/cols.o: cmd/pseudo/cols.c -cmd/pseudo/cols.o: shared/text.h -cmd/pseudo/cols.o: shared/util.h -cmd/pseudo/cols.o: shared/arg.h -cmd/pseudo/cols.o: shared/compat.h -cmd/pseudo/cron.o: cmd/pseudo/cron.c -cmd/pseudo/cron.o: shared/queue.h -cmd/pseudo/cron.o: shared/util.h -cmd/pseudo/cron.o: shared/arg.h -cmd/pseudo/cron.o: shared/compat.h -cmd/pseudo/dmesg.o: cmd/pseudo/dmesg.c -cmd/pseudo/dmesg.o: shared/util.h -cmd/pseudo/dmesg.o: shared/arg.h -cmd/pseudo/dmesg.o: shared/compat.h -cmd/pseudo/fallocate.o: cmd/pseudo/fallocate.c -cmd/pseudo/fallocate.o: shared/util.h -cmd/pseudo/fallocate.o: shared/arg.h -cmd/pseudo/fallocate.o: shared/compat.h -cmd/pseudo/free.o: cmd/pseudo/free.c -cmd/pseudo/free.o: shared/util.h -cmd/pseudo/free.o: shared/arg.h -cmd/pseudo/free.o: shared/compat.h -cmd/pseudo/halt.o: cmd/pseudo/halt.c -cmd/pseudo/halt.o: shared/reboot.h -cmd/pseudo/halt.o: shared/util.h -cmd/pseudo/halt.o: shared/arg.h -cmd/pseudo/halt.o: shared/compat.h -cmd/pseudo/hostname.o: cmd/pseudo/hostname.c -cmd/pseudo/hostname.o: shared/util.h -cmd/pseudo/hostname.o: shared/arg.h -cmd/pseudo/hostname.o: shared/compat.h -cmd/pseudo/killall5.o: cmd/pseudo/killall5.c -cmd/pseudo/killall5.o: shared/proc.h -cmd/pseudo/killall5.o: shared/queue.h -cmd/pseudo/killall5.o: shared/util.h -cmd/pseudo/killall5.o: shared/arg.h -cmd/pseudo/killall5.o: shared/compat.h +cmd/pseudo/yes.o: cmd/pseudo/yes.c +cmd/pseudo/yes.o: shared/util.h +cmd/pseudo/yes.o: shared/arg.h +cmd/pseudo/yes.o: shared/compat.h +cmd/pseudo/sponge.o: cmd/pseudo/sponge.c +cmd/pseudo/sponge.o: shared/util.h +cmd/pseudo/sponge.o: shared/arg.h +cmd/pseudo/sponge.o: shared/compat.h cmd/pseudo/last.o: cmd/pseudo/last.c cmd/pseudo/last.o: shared/config.h +cmd/pseudo/last.o: shared/paths.h cmd/pseudo/last.o: shared/util.h cmd/pseudo/last.o: shared/arg.h cmd/pseudo/last.o: shared/compat.h +cmd/pseudo/truncate.o: cmd/pseudo/truncate.c +cmd/pseudo/truncate.o: shared/util.h +cmd/pseudo/truncate.o: shared/arg.h +cmd/pseudo/truncate.o: shared/compat.h +cmd/pseudo/xinstall.o: cmd/pseudo/xinstall.c +cmd/pseudo/xinstall.o: shared/util.h +cmd/pseudo/xinstall.o: shared/arg.h +cmd/pseudo/xinstall.o: shared/compat.h cmd/pseudo/lastlog.o: cmd/pseudo/lastlog.c cmd/pseudo/lastlog.o: shared/text.h cmd/pseudo/lastlog.o: shared/util.h cmd/pseudo/lastlog.o: shared/arg.h cmd/pseudo/lastlog.o: shared/compat.h +cmd/pseudo/base64.o: cmd/pseudo/base64.c +cmd/pseudo/base64.o: shared/util.h +cmd/pseudo/base64.o: shared/arg.h +cmd/pseudo/base64.o: shared/compat.h +cmd/pseudo/base64.o: shared/arg.h +cmd/pseudo/sha384sum.o: cmd/pseudo/sha384sum.c +cmd/pseudo/sha384sum.o: shared/crypt.h +cmd/pseudo/sha384sum.o: shared/sha384.h +cmd/pseudo/sha384sum.o: shared/sha512.h +cmd/pseudo/sha384sum.o: shared/util.h +cmd/pseudo/sha384sum.o: shared/arg.h +cmd/pseudo/sha384sum.o: shared/compat.h +cmd/pseudo/getty.o: cmd/pseudo/getty.c +cmd/pseudo/getty.o: shared/config.h +cmd/pseudo/getty.o: shared/paths.h +cmd/pseudo/getty.o: shared/wexec.h +cmd/pseudo/getty.o: shared/util.h +cmd/pseudo/getty.o: shared/arg.h +cmd/pseudo/getty.o: shared/compat.h +cmd/pseudo/flock.o: cmd/pseudo/flock.c +cmd/pseudo/flock.o: shared/wexec.h +cmd/pseudo/flock.o: shared/util.h +cmd/pseudo/flock.o: shared/arg.h +cmd/pseudo/flock.o: shared/compat.h +cmd/pseudo/pwdx.o: cmd/pseudo/pwdx.c +cmd/pseudo/pwdx.o: shared/util.h +cmd/pseudo/pwdx.o: shared/arg.h +cmd/pseudo/pwdx.o: shared/compat.h +cmd/pseudo/sha512sum.o: cmd/pseudo/sha512sum.c +cmd/pseudo/sha512sum.o: shared/crypt.h +cmd/pseudo/sha512sum.o: shared/sha512.h +cmd/pseudo/sha512sum.o: shared/util.h +cmd/pseudo/sha512sum.o: shared/arg.h +cmd/pseudo/sha512sum.o: shared/compat.h +cmd/pseudo/hostname.o: cmd/pseudo/hostname.c +cmd/pseudo/hostname.o: shared/util.h +cmd/pseudo/hostname.o: shared/arg.h +cmd/pseudo/hostname.o: shared/compat.h cmd/pseudo/login.o: cmd/pseudo/login.c cmd/pseudo/login.o: shared/config.h +cmd/pseudo/login.o: shared/paths.h cmd/pseudo/login.o: shared/passwd.h +cmd/pseudo/login.o: shared/wexec.h cmd/pseudo/login.o: shared/util.h cmd/pseudo/login.o: shared/arg.h cmd/pseudo/login.o: shared/compat.h -cmd/pseudo/md5sum.o: cmd/pseudo/md5sum.c -cmd/pseudo/md5sum.o: shared/crypt.h -cmd/pseudo/md5sum.o: shared/md5.h -cmd/pseudo/md5sum.o: shared/util.h -cmd/pseudo/md5sum.o: shared/arg.h -cmd/pseudo/md5sum.o: shared/compat.h -cmd/pseudo/mktemp.o: cmd/pseudo/mktemp.c -cmd/pseudo/mktemp.o: shared/util.h -cmd/pseudo/mktemp.o: shared/arg.h -cmd/pseudo/mktemp.o: shared/compat.h -cmd/pseudo/nologin.o: cmd/pseudo/nologin.c -cmd/pseudo/pagesize.o: cmd/pseudo/pagesize.c -cmd/pseudo/pagesize.o: shared/util.h -cmd/pseudo/pagesize.o: shared/arg.h -cmd/pseudo/pagesize.o: shared/compat.h -cmd/pseudo/pidof.o: cmd/pseudo/pidof.c -cmd/pseudo/pidof.o: shared/proc.h -cmd/pseudo/pidof.o: shared/queue.h -cmd/pseudo/pidof.o: shared/util.h -cmd/pseudo/pidof.o: shared/arg.h -cmd/pseudo/pidof.o: shared/compat.h +cmd/pseudo/chroot.o: cmd/pseudo/chroot.c +cmd/pseudo/chroot.o: shared/wexec.h +cmd/pseudo/chroot.o: shared/util.h +cmd/pseudo/chroot.o: shared/arg.h +cmd/pseudo/chroot.o: shared/compat.h cmd/pseudo/printenv.o: cmd/pseudo/printenv.c cmd/pseudo/printenv.o: shared/util.h cmd/pseudo/printenv.o: shared/arg.h cmd/pseudo/printenv.o: shared/compat.h -cmd/pseudo/pwdx.o: cmd/pseudo/pwdx.c -cmd/pseudo/pwdx.o: shared/util.h -cmd/pseudo/pwdx.o: shared/arg.h -cmd/pseudo/pwdx.o: shared/compat.h -cmd/pseudo/rev.o: cmd/pseudo/rev.c -cmd/pseudo/rev.o: shared/text.h -cmd/pseudo/rev.o: shared/util.h -cmd/pseudo/rev.o: shared/arg.h -cmd/pseudo/rev.o: shared/compat.h -cmd/pseudo/seq.o: cmd/pseudo/seq.c -cmd/pseudo/seq.o: shared/util.h -cmd/pseudo/seq.o: shared/arg.h -cmd/pseudo/seq.o: shared/compat.h cmd/pseudo/sha1sum.o: cmd/pseudo/sha1sum.c cmd/pseudo/sha1sum.o: shared/crypt.h cmd/pseudo/sha1sum.o: shared/sha1.h cmd/pseudo/sha1sum.o: shared/util.h cmd/pseudo/sha1sum.o: shared/arg.h cmd/pseudo/sha1sum.o: shared/compat.h +cmd/pseudo/sha256sum.o: cmd/pseudo/sha256sum.c +cmd/pseudo/sha256sum.o: shared/crypt.h +cmd/pseudo/sha256sum.o: shared/sha256.h +cmd/pseudo/sha256sum.o: shared/util.h +cmd/pseudo/sha256sum.o: shared/arg.h +cmd/pseudo/sha256sum.o: shared/compat.h +cmd/pseudo/nologin.o: cmd/pseudo/nologin.c +cmd/pseudo/mktemp.o: cmd/pseudo/mktemp.c +cmd/pseudo/mktemp.o: shared/util.h +cmd/pseudo/mktemp.o: shared/arg.h +cmd/pseudo/mktemp.o: shared/compat.h +cmd/pseudo/uptime.o: cmd/pseudo/uptime.c +cmd/pseudo/uptime.o: shared/config.h +cmd/pseudo/uptime.o: shared/paths.h +cmd/pseudo/uptime.o: shared/util.h +cmd/pseudo/uptime.o: shared/arg.h +cmd/pseudo/uptime.o: shared/compat.h cmd/pseudo/sha224sum.o: cmd/pseudo/sha224sum.c cmd/pseudo/sha224sum.o: shared/crypt.h cmd/pseudo/sha224sum.o: shared/sha224.h @@ -1031,26 +246,39 @@ cmd/pseudo/sha224sum.o: shared/sha256.h cmd/pseudo/sha224sum.o: shared/util.h cmd/pseudo/sha224sum.o: shared/arg.h cmd/pseudo/sha224sum.o: shared/compat.h -cmd/pseudo/sha256sum.o: cmd/pseudo/sha256sum.c -cmd/pseudo/sha256sum.o: shared/crypt.h -cmd/pseudo/sha256sum.o: shared/sha256.h -cmd/pseudo/sha256sum.o: shared/util.h -cmd/pseudo/sha256sum.o: shared/arg.h -cmd/pseudo/sha256sum.o: shared/compat.h -cmd/pseudo/sha384sum.o: cmd/pseudo/sha384sum.c -cmd/pseudo/sha384sum.o: shared/crypt.h -cmd/pseudo/sha384sum.o: shared/sha384.h -cmd/pseudo/sha384sum.o: shared/sha512.h -cmd/pseudo/sha384sum.o: shared/util.h -cmd/pseudo/sha384sum.o: shared/arg.h -cmd/pseudo/sha384sum.o: shared/compat.h -cmd/pseudo/sha512-224sum.o: cmd/pseudo/sha512-224sum.c -cmd/pseudo/sha512-224sum.o: shared/crypt.h -cmd/pseudo/sha512-224sum.o: shared/sha512-224.h -cmd/pseudo/sha512-224sum.o: shared/sha512.h -cmd/pseudo/sha512-224sum.o: shared/util.h -cmd/pseudo/sha512-224sum.o: shared/arg.h -cmd/pseudo/sha512-224sum.o: shared/compat.h +cmd/pseudo/halt.o: cmd/pseudo/halt.c +cmd/pseudo/halt.o: shared/reboot.h +cmd/pseudo/halt.o: shared/util.h +cmd/pseudo/halt.o: shared/arg.h +cmd/pseudo/halt.o: shared/compat.h +cmd/pseudo/mkpasswd.o: cmd/pseudo/mkpasswd.c +cmd/pseudo/mkpasswd.o: shared/passwd.h +cmd/pseudo/mkpasswd.o: shared/paths.h +cmd/pseudo/mkpasswd.o: shared/util.h +cmd/pseudo/mkpasswd.o: shared/arg.h +cmd/pseudo/mkpasswd.o: shared/compat.h +cmd/pseudo/setsid.o: cmd/pseudo/setsid.c +cmd/pseudo/setsid.o: shared/wexec.h +cmd/pseudo/setsid.o: shared/util.h +cmd/pseudo/setsid.o: shared/arg.h +cmd/pseudo/setsid.o: shared/compat.h +cmd/pseudo/fallocate.o: cmd/pseudo/fallocate.c +cmd/pseudo/fallocate.o: shared/util.h +cmd/pseudo/fallocate.o: shared/arg.h +cmd/pseudo/fallocate.o: shared/compat.h +cmd/pseudo/seq.o: cmd/pseudo/seq.c +cmd/pseudo/seq.o: shared/util.h +cmd/pseudo/seq.o: shared/arg.h +cmd/pseudo/seq.o: shared/compat.h +cmd/pseudo/cols.o: cmd/pseudo/cols.c +cmd/pseudo/cols.o: shared/text.h +cmd/pseudo/cols.o: shared/util.h +cmd/pseudo/cols.o: shared/arg.h +cmd/pseudo/cols.o: shared/compat.h +cmd/pseudo/whoami.o: cmd/pseudo/whoami.c +cmd/pseudo/whoami.o: shared/util.h +cmd/pseudo/whoami.o: shared/arg.h +cmd/pseudo/whoami.o: shared/compat.h cmd/pseudo/sha512-256sum.o: cmd/pseudo/sha512-256sum.c cmd/pseudo/sha512-256sum.o: shared/crypt.h cmd/pseudo/sha512-256sum.o: shared/sha512-256.h @@ -1058,360 +286,850 @@ cmd/pseudo/sha512-256sum.o: shared/sha512.h cmd/pseudo/sha512-256sum.o: shared/util.h cmd/pseudo/sha512-256sum.o: shared/arg.h cmd/pseudo/sha512-256sum.o: shared/compat.h -cmd/pseudo/sha512sum.o: cmd/pseudo/sha512sum.c -cmd/pseudo/sha512sum.o: shared/crypt.h -cmd/pseudo/sha512sum.o: shared/sha512.h -cmd/pseudo/sha512sum.o: shared/util.h -cmd/pseudo/sha512sum.o: shared/arg.h -cmd/pseudo/sha512sum.o: shared/compat.h -cmd/pseudo/sponge.o: cmd/pseudo/sponge.c -cmd/pseudo/sponge.o: shared/util.h -cmd/pseudo/sponge.o: shared/arg.h -cmd/pseudo/sponge.o: shared/compat.h +cmd/pseudo/pidof.o: cmd/pseudo/pidof.c +cmd/pseudo/pidof.o: shared/proc.h +cmd/pseudo/pidof.o: shared/queue.h +cmd/pseudo/pidof.o: shared/util.h +cmd/pseudo/pidof.o: shared/arg.h +cmd/pseudo/pidof.o: shared/compat.h +cmd/pseudo/pagesize.o: cmd/pseudo/pagesize.c +cmd/pseudo/pagesize.o: shared/util.h +cmd/pseudo/pagesize.o: shared/arg.h +cmd/pseudo/pagesize.o: shared/compat.h +cmd/pseudo/killall5.o: cmd/pseudo/killall5.c +cmd/pseudo/killall5.o: shared/proc.h +cmd/pseudo/killall5.o: shared/queue.h +cmd/pseudo/killall5.o: shared/util.h +cmd/pseudo/killall5.o: shared/arg.h +cmd/pseudo/killall5.o: shared/compat.h +cmd/pseudo/sha512-224sum.o: cmd/pseudo/sha512-224sum.c +cmd/pseudo/sha512-224sum.o: shared/crypt.h +cmd/pseudo/sha512-224sum.o: shared/sha512-224.h +cmd/pseudo/sha512-224sum.o: shared/sha512.h +cmd/pseudo/sha512-224sum.o: shared/util.h +cmd/pseudo/sha512-224sum.o: shared/arg.h +cmd/pseudo/sha512-224sum.o: shared/compat.h cmd/pseudo/stat.o: cmd/pseudo/stat.c cmd/pseudo/stat.o: shared/config.h +cmd/pseudo/stat.o: shared/paths.h cmd/pseudo/stat.o: shared/util.h cmd/pseudo/stat.o: shared/arg.h cmd/pseudo/stat.o: shared/compat.h -cmd/pseudo/truncate.o: cmd/pseudo/truncate.c -cmd/pseudo/truncate.o: shared/util.h -cmd/pseudo/truncate.o: shared/arg.h -cmd/pseudo/truncate.o: shared/compat.h -cmd/pseudo/uptime.o: cmd/pseudo/uptime.c -cmd/pseudo/uptime.o: shared/config.h -cmd/pseudo/uptime.o: shared/util.h -cmd/pseudo/uptime.o: shared/arg.h -cmd/pseudo/uptime.o: shared/compat.h -cmd/pseudo/watch.o: cmd/pseudo/watch.c -cmd/pseudo/watch.o: shared/util.h -cmd/pseudo/watch.o: shared/arg.h -cmd/pseudo/watch.o: shared/compat.h +cmd/pseudo/md5sum.o: cmd/pseudo/md5sum.c +cmd/pseudo/md5sum.o: shared/crypt.h +cmd/pseudo/md5sum.o: shared/md5.h +cmd/pseudo/md5sum.o: shared/util.h +cmd/pseudo/md5sum.o: shared/arg.h +cmd/pseudo/md5sum.o: shared/compat.h +cmd/pseudo/cron.o: cmd/pseudo/cron.c +cmd/pseudo/cron.o: shared/queue.h +cmd/pseudo/cron.o: shared/paths.h +cmd/pseudo/cron.o: shared/wexec.h +cmd/pseudo/cron.o: shared/util.h +cmd/pseudo/cron.o: shared/arg.h +cmd/pseudo/cron.o: shared/compat.h cmd/pseudo/which.o: cmd/pseudo/which.c cmd/pseudo/which.o: shared/util.h cmd/pseudo/which.o: shared/arg.h cmd/pseudo/which.o: shared/compat.h -cmd/pseudo/whoami.o: cmd/pseudo/whoami.c -cmd/pseudo/whoami.o: shared/util.h -cmd/pseudo/whoami.o: shared/arg.h -cmd/pseudo/whoami.o: shared/compat.h -cmd/pseudo/xinstall.o: cmd/pseudo/xinstall.c -cmd/pseudo/xinstall.o: shared/util.h -cmd/pseudo/xinstall.o: shared/arg.h -cmd/pseudo/xinstall.o: shared/compat.h -cmd/pseudo/yes.o: cmd/pseudo/yes.c -cmd/pseudo/yes.o: shared/util.h -cmd/pseudo/yes.o: shared/arg.h -cmd/pseudo/yes.o: shared/compat.h -cmd/pseudo/chroot.o: cmd/pseudo/chroot.c -cmd/pseudo/chroot.o: shared/util.h -cmd/pseudo/chroot.o: shared/arg.h -cmd/pseudo/chroot.o: shared/compat.h -cmd/pseudo/flock.o: cmd/pseudo/flock.c -cmd/pseudo/flock.o: shared/util.h -cmd/pseudo/flock.o: shared/arg.h -cmd/pseudo/flock.o: shared/compat.h -cmd/pseudo/getty.o: cmd/pseudo/getty.c -cmd/pseudo/getty.o: shared/config.h -cmd/pseudo/getty.o: shared/util.h -cmd/pseudo/getty.o: shared/arg.h -cmd/pseudo/getty.o: shared/compat.h cmd/pseudo/respawn.o: cmd/pseudo/respawn.c +cmd/pseudo/respawn.o: shared/wexec.h cmd/pseudo/respawn.o: shared/util.h cmd/pseudo/respawn.o: shared/arg.h cmd/pseudo/respawn.o: shared/compat.h -cmd/pseudo/setsid.o: cmd/pseudo/setsid.c -cmd/pseudo/setsid.o: shared/util.h -cmd/pseudo/setsid.o: shared/arg.h -cmd/pseudo/setsid.o: shared/compat.h +cmd/pseudo/free.o: cmd/pseudo/free.c +cmd/pseudo/free.o: shared/util.h +cmd/pseudo/free.o: shared/arg.h +cmd/pseudo/free.o: shared/compat.h +cmd/pseudo/watch.o: cmd/pseudo/watch.c +cmd/pseudo/watch.o: shared/wexec.h +cmd/pseudo/watch.o: shared/util.h +cmd/pseudo/watch.o: shared/arg.h +cmd/pseudo/watch.o: shared/compat.h +cmd/pseudo/dmesg.o: cmd/pseudo/dmesg.c +cmd/pseudo/dmesg.o: shared/util.h +cmd/pseudo/dmesg.o: shared/arg.h +cmd/pseudo/dmesg.o: shared/compat.h +cmd/pseudo/rev.o: cmd/pseudo/rev.c +cmd/pseudo/rev.o: shared/text.h +cmd/pseudo/rev.o: shared/util.h +cmd/pseudo/rev.o: shared/arg.h +cmd/pseudo/rev.o: shared/compat.h cmd/pseudo/tar.o: cmd/pseudo/tar.c cmd/pseudo/tar.o: shared/config.h +cmd/pseudo/tar.o: shared/paths.h cmd/pseudo/tar.o: shared/fs.h cmd/pseudo/tar.o: shared/utf.h +cmd/pseudo/tar.o: shared/wexec.h cmd/pseudo/tar.o: shared/util.h cmd/pseudo/tar.o: shared/arg.h cmd/pseudo/tar.o: shared/compat.h +cmd/posix/true.o: cmd/posix/true.c +cmd/posix/paste.o: cmd/posix/paste.c +cmd/posix/paste.o: shared/utf.h +cmd/posix/paste.o: shared/util.h +cmd/posix/paste.o: shared/arg.h +cmd/posix/paste.o: shared/compat.h +cmd/posix/logger.o: cmd/posix/logger.c +cmd/posix/logger.o: shared/util.h +cmd/posix/logger.o: shared/arg.h +cmd/posix/logger.o: shared/compat.h +cmd/posix/pathchk.o: cmd/posix/pathchk.c +cmd/posix/pathchk.o: shared/util.h +cmd/posix/pathchk.o: shared/arg.h +cmd/posix/pathchk.o: shared/compat.h +cmd/posix/make/main.o: cmd/posix/make/main.c +cmd/posix/make/main.o: cmd/posix/make/make.h +cmd/posix/make/main.o: shared/util.h +cmd/posix/make/main.o: shared/arg.h +cmd/posix/make/main.o: shared/compat.h +cmd/posix/make/main.o: shared/wexec.h +cmd/posix/make/parser.o: cmd/posix/make/parser.c +cmd/posix/make/parser.o: cmd/posix/make/make.h +cmd/posix/make/parser.o: shared/util.h +cmd/posix/make/parser.o: shared/arg.h +cmd/posix/make/parser.o: shared/compat.h +cmd/posix/make/parser.o: shared/wexec.h +cmd/posix/make/posix.o: cmd/posix/make/posix.c +cmd/posix/make/posix.o: cmd/posix/make/make.h +cmd/posix/make/posix.o: shared/util.h +cmd/posix/make/posix.o: shared/arg.h +cmd/posix/make/posix.o: shared/compat.h +cmd/posix/make/posix.o: shared/wexec.h +cmd/posix/make/defaults.o: cmd/posix/make/defaults.c +cmd/posix/make/rules.o: cmd/posix/make/rules.c +cmd/posix/make/rules.o: cmd/posix/make/make.h +cmd/posix/make/rules.o: shared/util.h +cmd/posix/make/rules.o: shared/arg.h +cmd/posix/make/rules.o: shared/compat.h +cmd/posix/make/rules.o: shared/wexec.h +cmd/posix/tty.o: cmd/posix/tty.c +cmd/posix/tty.o: shared/util.h +cmd/posix/tty.o: shared/arg.h +cmd/posix/tty.o: shared/compat.h +cmd/posix/od.o: cmd/posix/od.c +cmd/posix/od.o: shared/queue.h +cmd/posix/od.o: shared/util.h +cmd/posix/od.o: shared/arg.h +cmd/posix/od.o: shared/compat.h +cmd/posix/df.o: cmd/posix/df.c +cmd/posix/df.o: shared/util.h +cmd/posix/df.o: shared/arg.h +cmd/posix/df.o: shared/compat.h +cmd/posix/uudecode.o: cmd/posix/uudecode.c +cmd/posix/uudecode.o: shared/util.h +cmd/posix/uudecode.o: shared/arg.h +cmd/posix/uudecode.o: shared/compat.h +cmd/posix/uuencode.o: cmd/posix/uuencode.c +cmd/posix/uuencode.o: shared/util.h +cmd/posix/uuencode.o: shared/arg.h +cmd/posix/uuencode.o: shared/compat.h +cmd/posix/mv.o: cmd/posix/mv.c +cmd/posix/mv.o: shared/fs.h +cmd/posix/mv.o: shared/util.h +cmd/posix/mv.o: shared/arg.h +cmd/posix/mv.o: shared/compat.h +cmd/posix/sed.o: cmd/posix/sed.c +cmd/posix/sed.o: shared/config.h +cmd/posix/sed.o: shared/paths.h +cmd/posix/sed.o: shared/utf.h +cmd/posix/sed.o: shared/util.h +cmd/posix/sed.o: shared/arg.h +cmd/posix/sed.o: shared/compat.h +cmd/posix/nl.o: cmd/posix/nl.c +cmd/posix/nl.o: shared/text.h +cmd/posix/nl.o: shared/utf.h +cmd/posix/nl.o: shared/util.h +cmd/posix/nl.o: shared/arg.h +cmd/posix/nl.o: shared/compat.h +cmd/posix/mesg.o: cmd/posix/mesg.c +cmd/posix/mesg.o: shared/util.h +cmd/posix/mesg.o: shared/arg.h +cmd/posix/mesg.o: shared/compat.h +cmd/posix/id.o: cmd/posix/id.c +cmd/posix/id.o: shared/util.h +cmd/posix/id.o: shared/arg.h +cmd/posix/id.o: shared/compat.h +cmd/posix/find.o: cmd/posix/find.c +cmd/posix/find.o: shared/config.h +cmd/posix/find.o: shared/paths.h +cmd/posix/find.o: shared/wexec.h +cmd/posix/find.o: shared/util.h +cmd/posix/find.o: shared/arg.h +cmd/posix/find.o: shared/compat.h +cmd/posix/ed.o: cmd/posix/ed.c +cmd/posix/ed.o: shared/wexec.h +cmd/posix/ed.o: shared/util.h +cmd/posix/ed.o: shared/arg.h +cmd/posix/ed.o: shared/compat.h +cmd/posix/echo.o: cmd/posix/echo.c +cmd/posix/echo.o: shared/util.h +cmd/posix/echo.o: shared/arg.h +cmd/posix/echo.o: shared/compat.h +cmd/posix/touch.o: cmd/posix/touch.c +cmd/posix/touch.o: shared/util.h +cmd/posix/touch.o: shared/arg.h +cmd/posix/touch.o: shared/compat.h +cmd/posix/chmod.o: cmd/posix/chmod.c +cmd/posix/chmod.o: shared/fs.h +cmd/posix/chmod.o: shared/util.h +cmd/posix/chmod.o: shared/arg.h +cmd/posix/chmod.o: shared/compat.h +cmd/posix/basename.o: cmd/posix/basename.c +cmd/posix/basename.o: shared/util.h +cmd/posix/basename.o: shared/arg.h +cmd/posix/basename.o: shared/compat.h +cmd/posix/sort.o: cmd/posix/sort.c +cmd/posix/sort.o: shared/queue.h +cmd/posix/sort.o: shared/text.h +cmd/posix/sort.o: shared/utf.h +cmd/posix/sort.o: shared/util.h +cmd/posix/sort.o: shared/arg.h +cmd/posix/sort.o: shared/compat.h +cmd/posix/mkfifo.o: cmd/posix/mkfifo.c +cmd/posix/mkfifo.o: shared/util.h +cmd/posix/mkfifo.o: shared/arg.h +cmd/posix/mkfifo.o: shared/compat.h +cmd/posix/getconf.o: cmd/posix/getconf.c +cmd/posix/getconf.o: shared/util.h +cmd/posix/getconf.o: shared/arg.h +cmd/posix/getconf.o: shared/compat.h +cmd/posix/getconf.o: cmd/posix/getconf.h +cmd/posix/tsort.o: cmd/posix/tsort.c +cmd/posix/tsort.o: shared/util.h +cmd/posix/tsort.o: shared/arg.h +cmd/posix/tsort.o: shared/compat.h +cmd/posix/pax.o: cmd/posix/pax.c +cmd/posix/pax.o: shared/arg.h +cmd/posix/grep.o: cmd/posix/grep.c +cmd/posix/grep.o: shared/config.h +cmd/posix/grep.o: shared/paths.h +cmd/posix/grep.o: shared/queue.h +cmd/posix/grep.o: shared/util.h +cmd/posix/grep.o: shared/arg.h +cmd/posix/grep.o: shared/compat.h +cmd/posix/tr.o: cmd/posix/tr.c +cmd/posix/tr.o: shared/utf.h +cmd/posix/tr.o: shared/util.h +cmd/posix/tr.o: shared/arg.h +cmd/posix/tr.o: shared/compat.h +cmd/posix/cmp.o: cmd/posix/cmp.c +cmd/posix/cmp.o: shared/util.h +cmd/posix/cmp.o: shared/arg.h +cmd/posix/cmp.o: shared/compat.h +cmd/posix/diff.o: cmd/posix/diff.c +cmd/posix/diff.o: shared/paths.h +cmd/posix/diff.o: shared/util.h +cmd/posix/diff.o: shared/arg.h +cmd/posix/diff.o: shared/compat.h +cmd/posix/diff.o: shared/wexec.h +cmd/posix/uniq.o: cmd/posix/uniq.c +cmd/posix/uniq.o: shared/text.h +cmd/posix/uniq.o: shared/util.h +cmd/posix/uniq.o: shared/arg.h +cmd/posix/uniq.o: shared/compat.h +cmd/posix/time.o: cmd/posix/time.c +cmd/posix/time.o: shared/wexec.h +cmd/posix/time.o: shared/util.h +cmd/posix/time.o: shared/arg.h +cmd/posix/time.o: shared/compat.h +cmd/posix/renice.o: cmd/posix/renice.c +cmd/posix/renice.o: shared/util.h +cmd/posix/renice.o: shared/arg.h +cmd/posix/renice.o: shared/compat.h +cmd/posix/nice.o: cmd/posix/nice.c +cmd/posix/nice.o: shared/wexec.h +cmd/posix/nice.o: shared/util.h +cmd/posix/nice.o: shared/arg.h +cmd/posix/nice.o: shared/compat.h +cmd/posix/cal.o: cmd/posix/cal.c +cmd/posix/cal.o: shared/util.h +cmd/posix/cal.o: shared/arg.h +cmd/posix/cal.o: shared/compat.h +cmd/posix/cut.o: cmd/posix/cut.c +cmd/posix/cut.o: shared/text.h +cmd/posix/cut.o: shared/utf.h +cmd/posix/cut.o: shared/util.h +cmd/posix/cut.o: shared/arg.h +cmd/posix/cut.o: shared/compat.h +cmd/posix/comm.o: cmd/posix/comm.c +cmd/posix/comm.o: shared/text.h +cmd/posix/comm.o: shared/util.h +cmd/posix/comm.o: shared/arg.h +cmd/posix/comm.o: shared/compat.h +cmd/posix/env.o: cmd/posix/env.c +cmd/posix/env.o: shared/wexec.h +cmd/posix/env.o: shared/util.h +cmd/posix/env.o: shared/arg.h +cmd/posix/env.o: shared/compat.h +cmd/posix/sleep.o: cmd/posix/sleep.c +cmd/posix/sleep.o: shared/util.h +cmd/posix/sleep.o: shared/arg.h +cmd/posix/sleep.o: shared/compat.h +cmd/posix/cksum.o: cmd/posix/cksum.c +cmd/posix/cksum.o: shared/util.h +cmd/posix/cksum.o: shared/arg.h +cmd/posix/cksum.o: shared/compat.h +cmd/posix/diff3.o: cmd/posix/diff3.c +cmd/posix/diff3.o: shared/config.h +cmd/posix/diff3.o: shared/paths.h +cmd/posix/diff3.o: shared/diffutil.h +cmd/posix/diff3.o: shared/util.h +cmd/posix/diff3.o: shared/arg.h +cmd/posix/diff3.o: shared/compat.h +cmd/posix/link.o: cmd/posix/link.c +cmd/posix/link.o: shared/util.h +cmd/posix/link.o: shared/arg.h +cmd/posix/link.o: shared/compat.h +cmd/posix/kill.o: cmd/posix/kill.c +cmd/posix/kill.o: shared/sig.h +cmd/posix/kill.o: shared/util.h +cmd/posix/kill.o: shared/arg.h +cmd/posix/kill.o: shared/compat.h +cmd/posix/mkdir.o: cmd/posix/mkdir.c +cmd/posix/mkdir.o: shared/util.h +cmd/posix/mkdir.o: shared/arg.h +cmd/posix/mkdir.o: shared/compat.h +cmd/posix/chgrp.o: cmd/posix/chgrp.c +cmd/posix/chgrp.o: shared/fs.h +cmd/posix/chgrp.o: shared/util.h +cmd/posix/chgrp.o: shared/arg.h +cmd/posix/chgrp.o: shared/compat.h +cmd/posix/dirname.o: cmd/posix/dirname.c +cmd/posix/dirname.o: shared/util.h +cmd/posix/dirname.o: shared/arg.h +cmd/posix/dirname.o: shared/compat.h +cmd/posix/date.o: cmd/posix/date.c +cmd/posix/date.o: shared/util.h +cmd/posix/date.o: shared/arg.h +cmd/posix/date.o: shared/compat.h +cmd/posix/expand.o: cmd/posix/expand.c +cmd/posix/expand.o: shared/utf.h +cmd/posix/expand.o: shared/util.h +cmd/posix/expand.o: shared/arg.h +cmd/posix/expand.o: shared/compat.h +cmd/posix/du.o: cmd/posix/du.c +cmd/posix/du.o: shared/fs.h +cmd/posix/du.o: shared/util.h +cmd/posix/du.o: shared/arg.h +cmd/posix/du.o: shared/compat.h +cmd/posix/nohup.o: cmd/posix/nohup.c +cmd/posix/nohup.o: shared/wexec.h +cmd/posix/nohup.o: shared/util.h +cmd/posix/nohup.o: shared/arg.h +cmd/posix/nohup.o: shared/compat.h +cmd/posix/split.o: cmd/posix/split.c +cmd/posix/split.o: shared/util.h +cmd/posix/split.o: shared/arg.h +cmd/posix/split.o: shared/compat.h +cmd/posix/xargs.o: cmd/posix/xargs.c +cmd/posix/xargs.o: shared/wexec.h +cmd/posix/xargs.o: shared/util.h +cmd/posix/xargs.o: shared/arg.h +cmd/posix/xargs.o: shared/compat.h +cmd/posix/tee.o: cmd/posix/tee.c +cmd/posix/tee.o: shared/util.h +cmd/posix/tee.o: shared/arg.h +cmd/posix/tee.o: shared/compat.h +cmd/posix/false.o: cmd/posix/false.c +cmd/posix/ln.o: cmd/posix/ln.c +cmd/posix/ln.o: shared/util.h +cmd/posix/ln.o: shared/arg.h +cmd/posix/ln.o: shared/compat.h +cmd/posix/wc.o: cmd/posix/wc.c +cmd/posix/wc.o: shared/utf.h +cmd/posix/wc.o: shared/util.h +cmd/posix/wc.o: shared/arg.h +cmd/posix/wc.o: shared/compat.h +cmd/posix/logname.o: cmd/posix/logname.c +cmd/posix/logname.o: shared/util.h +cmd/posix/logname.o: shared/arg.h +cmd/posix/logname.o: shared/compat.h +cmd/posix/fold.o: cmd/posix/fold.c +cmd/posix/fold.o: shared/text.h +cmd/posix/fold.o: shared/util.h +cmd/posix/fold.o: shared/arg.h +cmd/posix/fold.o: shared/compat.h +cmd/posix/fold.o: shared/utf.h +cmd/posix/unlink.o: cmd/posix/unlink.c +cmd/posix/unlink.o: shared/util.h +cmd/posix/unlink.o: shared/arg.h +cmd/posix/unlink.o: shared/compat.h +cmd/posix/printf.o: cmd/posix/printf.c +cmd/posix/printf.o: shared/utf.h +cmd/posix/printf.o: shared/util.h +cmd/posix/printf.o: shared/arg.h +cmd/posix/printf.o: shared/compat.h +cmd/posix/head.o: cmd/posix/head.c +cmd/posix/head.o: shared/util.h +cmd/posix/head.o: shared/arg.h +cmd/posix/head.o: shared/compat.h +cmd/posix/patch.o: cmd/posix/patch.c +cmd/posix/patch.o: shared/wexec.h +cmd/posix/patch.o: shared/paths.h +cmd/posix/patch.o: shared/util.h +cmd/posix/patch.o: shared/arg.h +cmd/posix/patch.o: shared/compat.h +cmd/posix/readlink.o: cmd/posix/readlink.c +cmd/posix/readlink.o: shared/util.h +cmd/posix/readlink.o: shared/arg.h +cmd/posix/readlink.o: shared/compat.h +cmd/posix/rmdir.o: cmd/posix/rmdir.c +cmd/posix/rmdir.o: shared/util.h +cmd/posix/rmdir.o: shared/arg.h +cmd/posix/rmdir.o: shared/compat.h +cmd/posix/tail.o: cmd/posix/tail.c +cmd/posix/tail.o: shared/utf.h +cmd/posix/tail.o: shared/util.h +cmd/posix/tail.o: shared/arg.h +cmd/posix/tail.o: shared/compat.h +cmd/posix/who.o: cmd/posix/who.c +cmd/posix/who.o: shared/config.h +cmd/posix/who.o: shared/paths.h +cmd/posix/who.o: shared/util.h +cmd/posix/who.o: shared/arg.h +cmd/posix/who.o: shared/compat.h +cmd/posix/cat.o: cmd/posix/cat.c +cmd/posix/cat.o: shared/util.h +cmd/posix/cat.o: shared/arg.h +cmd/posix/cat.o: shared/compat.h +cmd/posix/ls.o: cmd/posix/ls.c +cmd/posix/ls.o: shared/utf.h +cmd/posix/ls.o: shared/util.h +cmd/posix/ls.o: shared/arg.h +cmd/posix/ls.o: shared/compat.h +cmd/posix/cp.o: cmd/posix/cp.c +cmd/posix/cp.o: shared/fs.h +cmd/posix/cp.o: shared/util.h +cmd/posix/cp.o: shared/arg.h +cmd/posix/cp.o: shared/compat.h +cmd/posix/chown.o: cmd/posix/chown.c +cmd/posix/chown.o: shared/fs.h +cmd/posix/chown.o: shared/util.h +cmd/posix/chown.o: shared/arg.h +cmd/posix/chown.o: shared/compat.h +cmd/posix/ps.o: cmd/posix/ps.c +cmd/posix/ps.o: shared/proc.h +cmd/posix/ps.o: shared/util.h +cmd/posix/ps.o: shared/arg.h +cmd/posix/ps.o: shared/compat.h +cmd/posix/unexpand.o: cmd/posix/unexpand.c +cmd/posix/unexpand.o: shared/utf.h +cmd/posix/unexpand.o: shared/util.h +cmd/posix/unexpand.o: shared/arg.h +cmd/posix/unexpand.o: shared/compat.h +cmd/posix/test.o: cmd/posix/test.c +cmd/posix/test.o: shared/util.h +cmd/posix/test.o: shared/arg.h +cmd/posix/test.o: shared/compat.h +cmd/posix/rm.o: cmd/posix/rm.c +cmd/posix/rm.o: shared/fs.h +cmd/posix/rm.o: shared/util.h +cmd/posix/rm.o: shared/arg.h +cmd/posix/rm.o: shared/compat.h +cmd/posix/uname.o: cmd/posix/uname.c +cmd/posix/uname.o: shared/util.h +cmd/posix/uname.o: shared/arg.h +cmd/posix/uname.o: shared/compat.h +cmd/posix/join.o: cmd/posix/join.c +cmd/posix/join.o: shared/text.h +cmd/posix/join.o: shared/utf.h +cmd/posix/join.o: shared/util.h +cmd/posix/join.o: shared/arg.h +cmd/posix/join.o: shared/compat.h +cmd/posix/dd.o: cmd/posix/dd.c +cmd/posix/dd.o: shared/util.h +cmd/posix/dd.o: shared/arg.h +cmd/posix/dd.o: shared/compat.h +cmd/posix/expr.o: cmd/posix/expr.c +cmd/posix/expr.o: shared/utf.h +cmd/posix/expr.o: shared/util.h +cmd/posix/expr.o: shared/arg.h +cmd/posix/expr.o: shared/compat.h +cmd/posix/pwd.o: cmd/posix/pwd.c +cmd/posix/pwd.o: shared/util.h +cmd/posix/pwd.o: shared/arg.h +cmd/posix/pwd.o: shared/compat.h +cmd/extra/blkid.o: cmd/extra/blkid.c +cmd/extra/blkid.o: shared/util.h +cmd/extra/blkid.o: shared/arg.h +cmd/extra/blkid.o: shared/compat.h +cmd/extra/blkid.o: shared/diskutil.h +cmd/extra/blkid.o: shared/paths.h +cmd/extra/b3sum.o: cmd/extra/b3sum.c +cmd/extra/b3sum.o: shared/util.h +cmd/extra/b3sum.o: shared/arg.h +cmd/extra/b3sum.o: shared/compat.h +cmd/extra/b3sum.o: shared/arg.h +cmd/extra/sync.o: cmd/extra/sync.c +cmd/extra/sync.o: shared/arg.h +cmd/extra/sync.o: shared/util.h +cmd/extra/sync.o: shared/arg.h +cmd/extra/sync.o: shared/compat.h +cmd/extra/fdisk.o: cmd/extra/fdisk.c +cmd/extra/fdisk.o: shared/util.h +cmd/extra/fdisk.o: shared/arg.h +cmd/extra/fdisk.o: shared/compat.h +cmd/extra/fdisk.o: shared/diskutil.h +cmd/extra/fdisk.o: shared/paths.h +cmd/extra/lsblk.o: cmd/extra/lsblk.c +cmd/extra/lsblk.o: shared/util.h +cmd/extra/lsblk.o: shared/arg.h +cmd/extra/lsblk.o: shared/compat.h +cmd/extra/lsblk.o: shared/diskutil.h +cmd/extra/lsblk.o: shared/paths.h cmd/xsi/mknod.o: cmd/xsi/mknod.c cmd/xsi/mknod.o: shared/util.h cmd/xsi/mknod.o: shared/arg.h cmd/xsi/mknod.o: shared/compat.h +cmd/xsi/su.o: cmd/xsi/su.c +cmd/xsi/su.o: shared/config.h +cmd/xsi/su.o: shared/paths.h +cmd/xsi/su.o: shared/passwd.h +cmd/xsi/su.o: shared/util.h +cmd/xsi/su.o: shared/arg.h +cmd/xsi/su.o: shared/compat.h cmd/xsi/passwd.o: cmd/xsi/passwd.c cmd/xsi/passwd.o: shared/config.h +cmd/xsi/passwd.o: shared/paths.h cmd/xsi/passwd.o: shared/passwd.h cmd/xsi/passwd.o: shared/text.h cmd/xsi/passwd.o: shared/util.h cmd/xsi/passwd.o: shared/arg.h cmd/xsi/passwd.o: shared/compat.h -cmd/xsi/su.o: cmd/xsi/su.c -cmd/xsi/su.o: shared/passwd.h -cmd/xsi/su.o: shared/util.h -cmd/xsi/su.o: shared/arg.h -cmd/xsi/su.o: shared/compat.h -shared/libredline/redline.o: shared/libredline/redline.c -shared/libredline/redline.o: shared/redline.h -shared/libutf/fgetrune.o: shared/libutf/fgetrune.c -shared/libutf/fgetrune.o: shared/libutf/../utf.h -shared/libutf/fputrune.o: shared/libutf/fputrune.c -shared/libutf/fputrune.o: shared/libutf/../utf.h -shared/libutf/isalnumrune.o: shared/libutf/isalnumrune.c -shared/libutf/isalnumrune.o: shared/libutf/../utf.h -shared/libutf/isalnumrune.o: shared/libutf/runetype.h -shared/libutf/isalpharune.o: shared/libutf/isalpharune.c -shared/libutf/isalpharune.o: shared/libutf/../utf.h -shared/libutf/isalpharune.o: shared/libutf/runetype.h -shared/libutf/isblankrune.o: shared/libutf/isblankrune.c -shared/libutf/isblankrune.o: shared/libutf/../utf.h -shared/libutf/isblankrune.o: shared/libutf/runetype.h -shared/libutf/iscntrlrune.o: shared/libutf/iscntrlrune.c -shared/libutf/iscntrlrune.o: shared/libutf/../utf.h -shared/libutf/iscntrlrune.o: shared/libutf/runetype.h -shared/libutf/isdigitrune.o: shared/libutf/isdigitrune.c -shared/libutf/isdigitrune.o: shared/libutf/../utf.h -shared/libutf/isdigitrune.o: shared/libutf/runetype.h -shared/libutf/isgraphrune.o: shared/libutf/isgraphrune.c -shared/libutf/isgraphrune.o: shared/libutf/../utf.h -shared/libutf/isgraphrune.o: shared/libutf/runetype.h -shared/libutf/isprintrune.o: shared/libutf/isprintrune.c -shared/libutf/isprintrune.o: shared/libutf/../utf.h -shared/libutf/isprintrune.o: shared/libutf/runetype.h -shared/libutf/ispunctrune.o: shared/libutf/ispunctrune.c -shared/libutf/ispunctrune.o: shared/libutf/../utf.h -shared/libutf/ispunctrune.o: shared/libutf/runetype.h -shared/libutf/isspacerune.o: shared/libutf/isspacerune.c -shared/libutf/isspacerune.o: shared/libutf/../utf.h -shared/libutf/isspacerune.o: shared/libutf/runetype.h -shared/libutf/istitlerune.o: shared/libutf/istitlerune.c -shared/libutf/istitlerune.o: shared/libutf/../utf.h -shared/libutf/istitlerune.o: shared/libutf/runetype.h -shared/libutf/isxdigitrune.o: shared/libutf/isxdigitrune.c -shared/libutf/isxdigitrune.o: shared/libutf/../utf.h -shared/libutf/isxdigitrune.o: shared/libutf/runetype.h -shared/libutf/lowerrune.o: shared/libutf/lowerrune.c -shared/libutf/lowerrune.o: shared/libutf/../utf.h -shared/libutf/lowerrune.o: shared/libutf/runetype.h -shared/libutf/rune.o: shared/libutf/rune.c -shared/libutf/rune.o: shared/libutf/../utf.h -shared/libutf/runetype.o: shared/libutf/runetype.c -shared/libutf/runetype.o: shared/libutf/../utf.h -shared/libutf/upperrune.o: shared/libutf/upperrune.c -shared/libutf/upperrune.o: shared/libutf/../utf.h -shared/libutf/upperrune.o: shared/libutf/runetype.h -shared/libutf/utf.o: shared/libutf/utf.c -shared/libutf/utf.o: shared/libutf/../utf.h -shared/libutf/utftorunestr.o: shared/libutf/utftorunestr.c -shared/libutf/utftorunestr.o: shared/libutf/../utf.h -shared/libutil/agetcwd.o: shared/libutil/agetcwd.c -shared/libutil/agetcwd.o: shared/libutil/../util.h -shared/libutil/agetcwd.o: shared/libutil/../arg.h -shared/libutil/agetcwd.o: shared/libutil/../compat.h -shared/libutil/agetline.o: shared/libutil/agetline.c -shared/libutil/agetline.o: shared/libutil/../text.h -shared/libutil/agetline.o: shared/libutil/../util.h -shared/libutil/agetline.o: shared/libutil/../arg.h -shared/libutil/agetline.o: shared/libutil/../compat.h +cmd/net/tftp.o: cmd/net/tftp.c +cmd/net/tftp.o: shared/util.h +cmd/net/tftp.o: shared/arg.h +cmd/net/tftp.o: shared/compat.h +cmd/net/httpd.o: cmd/net/httpd.c +cmd/net/httpd.o: shared/util.h +cmd/net/httpd.o: shared/arg.h +cmd/net/httpd.o: shared/compat.h +cmd/net/httpd.o: shared/arg.h +cmd/net/host.o: cmd/net/host.c +cmd/net/host.o: shared/util.h +cmd/net/host.o: shared/arg.h +cmd/net/host.o: shared/compat.h +cmd/net/host.o: shared/arg.h +cmd/net/ping.o: cmd/net/ping.c +cmd/net/ping.o: shared/util.h +cmd/net/ping.o: shared/arg.h +cmd/net/ping.o: shared/compat.h +cmd/net/ping.o: shared/arg.h +cmd/net/ip.o: cmd/net/ip.c +cmd/net/ip.o: shared/util.h +cmd/net/ip.o: shared/arg.h +cmd/net/ip.o: shared/compat.h +cmd/net/wget.o: cmd/net/wget.c +cmd/net/wget.o: shared/util.h +cmd/net/wget.o: shared/arg.h +cmd/net/wget.o: shared/compat.h +cmd/net/wget.o: shared/arg.h +cmd/net/wget.o: shared/tls.h +cmd/net/sdhcp.o: cmd/net/sdhcp.c +cmd/net/sdhcp.o: shared/arg.h +cmd/net/sdhcp.o: shared/wexec.h +cmd/net/sdhcp.o: shared/util.h +cmd/net/sdhcp.o: shared/arg.h +cmd/net/sdhcp.o: shared/compat.h +cmd/net/netcat.o: cmd/net/netcat.c +cmd/net/netcat.o: shared/util.h +cmd/net/netcat.o: shared/arg.h +cmd/net/netcat.o: shared/compat.h +cmd/net/ifconfig.o: cmd/net/ifconfig.c +cmd/net/ifconfig.o: shared/util.h +cmd/net/ifconfig.o: shared/arg.h +cmd/net/ifconfig.o: shared/compat.h +shared/libutil/memmem.o: shared/libutil/memmem.c +shared/libutil/memmem.o: shared/libutil/../util.h +shared/libutil/memmem.o: shared/libutil/../arg.h +shared/libutil/memmem.o: shared/libutil/../compat.h +shared/libutil/estrtoul.o: shared/libutil/estrtoul.c +shared/libutil/estrtoul.o: shared/libutil/../util.h +shared/libutil/estrtoul.o: shared/libutil/../arg.h +shared/libutil/estrtoul.o: shared/libutil/../compat.h +shared/libutil/proc.o: shared/libutil/proc.c +shared/libutil/proc.o: shared/libutil/../proc.h +shared/libutil/proc.o: shared/libutil/../paths.h +shared/libutil/proc.o: shared/libutil/../util.h +shared/libutil/proc.o: shared/libutil/../arg.h +shared/libutil/proc.o: shared/libutil/../compat.h +shared/libutil/estrtod.o: shared/libutil/estrtod.c +shared/libutil/estrtod.o: shared/libutil/../util.h +shared/libutil/estrtod.o: shared/libutil/../arg.h +shared/libutil/estrtod.o: shared/libutil/../compat.h +shared/libutil/tty.o: shared/libutil/tty.c +shared/libutil/tty.o: shared/libutil/../paths.h +shared/libutil/tty.o: shared/libutil/../util.h +shared/libutil/tty.o: shared/libutil/../arg.h +shared/libutil/tty.o: shared/libutil/../compat.h +shared/libutil/getlines.o: shared/libutil/getlines.c +shared/libutil/getlines.o: shared/libutil/../text.h +shared/libutil/getlines.o: shared/libutil/../util.h +shared/libutil/getlines.o: shared/libutil/../arg.h +shared/libutil/getlines.o: shared/libutil/../compat.h +shared/libutil/eregcomp.o: shared/libutil/eregcomp.c +shared/libutil/eregcomp.o: shared/libutil/../util.h +shared/libutil/eregcomp.o: shared/libutil/../arg.h +shared/libutil/eregcomp.o: shared/libutil/../compat.h +shared/libutil/strlcat.o: shared/libutil/strlcat.c +shared/libutil/strlcat.o: shared/libutil/../util.h +shared/libutil/strlcat.o: shared/libutil/../arg.h +shared/libutil/strlcat.o: shared/libutil/../compat.h +shared/libutil/unescape.o: shared/libutil/unescape.c +shared/libutil/unescape.o: shared/libutil/../util.h +shared/libutil/unescape.o: shared/libutil/../arg.h +shared/libutil/unescape.o: shared/libutil/../compat.h +shared/libutil/strtonum.o: shared/libutil/strtonum.c +shared/libutil/strtonum.o: shared/libutil/../util.h +shared/libutil/strtonum.o: shared/libutil/../arg.h +shared/libutil/strtonum.o: shared/libutil/../compat.h +shared/libutil/sig.o: shared/libutil/sig.c +shared/libutil/sig.o: shared/libutil/../sig.h shared/libutil/apathmax.o: shared/libutil/apathmax.c shared/libutil/apathmax.o: shared/libutil/../util.h shared/libutil/apathmax.o: shared/libutil/../arg.h shared/libutil/apathmax.o: shared/libutil/../compat.h -shared/libutil/concat.o: shared/libutil/concat.c -shared/libutil/concat.o: shared/libutil/../util.h -shared/libutil/concat.o: shared/libutil/../arg.h -shared/libutil/concat.o: shared/libutil/../compat.h -shared/libutil/confirm.o: shared/libutil/confirm.c -shared/libutil/confirm.o: shared/libutil/../util.h -shared/libutil/confirm.o: shared/libutil/../arg.h -shared/libutil/confirm.o: shared/libutil/../compat.h -shared/libutil/cp.o: shared/libutil/cp.c -shared/libutil/cp.o: shared/libutil/../fs.h -shared/libutil/cp.o: shared/libutil/../util.h -shared/libutil/cp.o: shared/libutil/../arg.h -shared/libutil/cp.o: shared/libutil/../compat.h -shared/libutil/crypt.o: shared/libutil/crypt.c -shared/libutil/crypt.o: shared/libutil/../crypt.h -shared/libutil/crypt.o: shared/libutil/../text.h -shared/libutil/crypt.o: shared/libutil/../util.h -shared/libutil/crypt.o: shared/libutil/../arg.h -shared/libutil/crypt.o: shared/libutil/../compat.h +shared/libutil/strnsubst.o: shared/libutil/strnsubst.c +shared/libutil/strnsubst.o: shared/libutil/../util.h +shared/libutil/strnsubst.o: shared/libutil/../arg.h +shared/libutil/strnsubst.o: shared/libutil/../compat.h shared/libutil/diskutil.o: shared/libutil/diskutil.c shared/libutil/diskutil.o: shared/libutil/../diskutil.h +shared/libutil/diskutil.o: shared/libutil/../paths.h shared/libutil/diskutil.o: shared/libutil/../util.h shared/libutil/diskutil.o: shared/libutil/../arg.h shared/libutil/diskutil.o: shared/libutil/../compat.h -shared/libutil/ealloc.o: shared/libutil/ealloc.c -shared/libutil/ealloc.o: shared/libutil/../util.h -shared/libutil/ealloc.o: shared/libutil/../arg.h -shared/libutil/ealloc.o: shared/libutil/../compat.h -shared/libutil/enmasse.o: shared/libutil/enmasse.c -shared/libutil/enmasse.o: shared/libutil/../util.h -shared/libutil/enmasse.o: shared/libutil/../arg.h -shared/libutil/enmasse.o: shared/libutil/../compat.h -shared/libutil/eprintf.o: shared/libutil/eprintf.c -shared/libutil/eprintf.o: shared/libutil/../util.h -shared/libutil/eprintf.o: shared/libutil/../arg.h -shared/libutil/eprintf.o: shared/libutil/../compat.h -shared/libutil/eregcomp.o: shared/libutil/eregcomp.c -shared/libutil/eregcomp.o: shared/libutil/../util.h -shared/libutil/eregcomp.o: shared/libutil/../arg.h -shared/libutil/eregcomp.o: shared/libutil/../compat.h -shared/libutil/estrtod.o: shared/libutil/estrtod.c -shared/libutil/estrtod.o: shared/libutil/../util.h -shared/libutil/estrtod.o: shared/libutil/../arg.h -shared/libutil/estrtod.o: shared/libutil/../compat.h -shared/libutil/estrtol.o: shared/libutil/estrtol.c -shared/libutil/estrtol.o: shared/libutil/../util.h -shared/libutil/estrtol.o: shared/libutil/../arg.h -shared/libutil/estrtol.o: shared/libutil/../compat.h -shared/libutil/estrtoul.o: shared/libutil/estrtoul.c -shared/libutil/estrtoul.o: shared/libutil/../util.h -shared/libutil/estrtoul.o: shared/libutil/../arg.h -shared/libutil/estrtoul.o: shared/libutil/../compat.h +shared/libutil/confirm.o: shared/libutil/confirm.c +shared/libutil/confirm.o: shared/libutil/../util.h +shared/libutil/confirm.o: shared/libutil/../arg.h +shared/libutil/confirm.o: shared/libutil/../compat.h shared/libutil/explicit_bzero.o: shared/libutil/explicit_bzero.c shared/libutil/explicit_bzero.o: shared/libutil/../util.h -shared/libutil/explicit_bzero.o: shared/libutil/../arg.h -shared/libutil/explicit_bzero.o: shared/libutil/../compat.h -shared/libutil/fconcat.o: shared/libutil/fconcat.c -shared/libutil/fconcat.o: shared/libutil/../text.h -shared/libutil/fconcat.o: shared/libutil/../util.h -shared/libutil/fconcat.o: shared/libutil/../arg.h -shared/libutil/fconcat.o: shared/libutil/../compat.h -shared/libutil/fnck.o: shared/libutil/fnck.c -shared/libutil/fnck.o: shared/libutil/../util.h -shared/libutil/fnck.o: shared/libutil/../arg.h -shared/libutil/fnck.o: shared/libutil/../compat.h -shared/libutil/fshut.o: shared/libutil/fshut.c -shared/libutil/fshut.o: shared/libutil/../util.h -shared/libutil/fshut.o: shared/libutil/../arg.h -shared/libutil/fshut.o: shared/libutil/../compat.h -shared/libutil/getlines.o: shared/libutil/getlines.c -shared/libutil/getlines.o: shared/libutil/../text.h -shared/libutil/getlines.o: shared/libutil/../util.h -shared/libutil/getlines.o: shared/libutil/../arg.h -shared/libutil/getlines.o: shared/libutil/../compat.h -shared/libutil/human.o: shared/libutil/human.c -shared/libutil/human.o: shared/libutil/../util.h -shared/libutil/human.o: shared/libutil/../arg.h -shared/libutil/human.o: shared/libutil/../compat.h -shared/libutil/linecmp.o: shared/libutil/linecmp.c -shared/libutil/linecmp.o: shared/libutil/../text.h -shared/libutil/linecmp.o: shared/libutil/../util.h -shared/libutil/linecmp.o: shared/libutil/../arg.h -shared/libutil/linecmp.o: shared/libutil/../compat.h -shared/libutil/md5.o: shared/libutil/md5.c -shared/libutil/md5.o: shared/libutil/../md5.h -shared/libutil/memmem.o: shared/libutil/memmem.c -shared/libutil/memmem.o: shared/libutil/../util.h -shared/libutil/memmem.o: shared/libutil/../arg.h -shared/libutil/memmem.o: shared/libutil/../compat.h -shared/libutil/mkdirp.o: shared/libutil/mkdirp.c -shared/libutil/mkdirp.o: shared/libutil/../util.h -shared/libutil/mkdirp.o: shared/libutil/../arg.h -shared/libutil/mkdirp.o: shared/libutil/../compat.h +shared/libutil/explicit_bzero.o: shared/libutil/../arg.h +shared/libutil/explicit_bzero.o: shared/libutil/../compat.h +shared/libutil/sha224.o: shared/libutil/sha224.c +shared/libutil/sha224.o: shared/libutil/../sha224.h +shared/libutil/sha224.o: shared/libutil/../sha256.h +shared/libutil/estrtol.o: shared/libutil/estrtol.c +shared/libutil/estrtol.o: shared/libutil/../util.h +shared/libutil/estrtol.o: shared/libutil/../arg.h +shared/libutil/estrtol.o: shared/libutil/../compat.h +shared/libutil/strlcpy.o: shared/libutil/strlcpy.c +shared/libutil/strlcpy.o: shared/libutil/../util.h +shared/libutil/strlcpy.o: shared/libutil/../arg.h +shared/libutil/strlcpy.o: shared/libutil/../compat.h shared/libutil/mode.o: shared/libutil/mode.c shared/libutil/mode.o: shared/libutil/../util.h shared/libutil/mode.o: shared/libutil/../arg.h shared/libutil/mode.o: shared/libutil/../compat.h shared/libutil/net.o: shared/libutil/net.c +shared/libutil/net.o: shared/libutil/../paths.h shared/libutil/net.o: shared/libutil/../util.h shared/libutil/net.o: shared/libutil/../arg.h shared/libutil/net.o: shared/libutil/../compat.h +shared/libutil/wexec.o: shared/libutil/wexec.c +shared/libutil/wexec.o: shared/libutil/../config.h +shared/libutil/wexec.o: shared/libutil/../paths.h +shared/libutil/wexec.o: shared/libutil/../wexec.h +shared/libutil/wexec.o: shared/libutil/../paths.h +shared/libutil/wexec.o: shared/libutil/../util.h +shared/libutil/wexec.o: shared/libutil/../arg.h +shared/libutil/wexec.o: shared/libutil/../compat.h +shared/libutil/crypt.o: shared/libutil/crypt.c +shared/libutil/crypt.o: shared/libutil/../crypt.h +shared/libutil/crypt.o: shared/libutil/../text.h +shared/libutil/crypt.o: shared/libutil/../util.h +shared/libutil/crypt.o: shared/libutil/../arg.h +shared/libutil/crypt.o: shared/libutil/../compat.h shared/libutil/parseoffset.o: shared/libutil/parseoffset.c shared/libutil/parseoffset.o: shared/libutil/../util.h shared/libutil/parseoffset.o: shared/libutil/../arg.h shared/libutil/parseoffset.o: shared/libutil/../compat.h -shared/libutil/passwd.o: shared/libutil/passwd.c -shared/libutil/passwd.o: shared/libutil/../passwd.h -shared/libutil/passwd.o: shared/libutil/../text.h -shared/libutil/passwd.o: shared/libutil/../util.h -shared/libutil/passwd.o: shared/libutil/../arg.h -shared/libutil/passwd.o: shared/libutil/../compat.h -shared/libutil/proc.o: shared/libutil/proc.c -shared/libutil/proc.o: shared/libutil/../proc.h -shared/libutil/proc.o: shared/libutil/../util.h -shared/libutil/proc.o: shared/libutil/../arg.h -shared/libutil/proc.o: shared/libutil/../compat.h -shared/libutil/putword.o: shared/libutil/putword.c -shared/libutil/putword.o: shared/libutil/../util.h -shared/libutil/putword.o: shared/libutil/../arg.h -shared/libutil/putword.o: shared/libutil/../compat.h -shared/libutil/reallocarray.o: shared/libutil/reallocarray.c -shared/libutil/reallocarray.o: shared/libutil/../util.h -shared/libutil/reallocarray.o: shared/libutil/../arg.h -shared/libutil/reallocarray.o: shared/libutil/../compat.h +shared/libutil/strsep.o: shared/libutil/strsep.c +shared/libutil/strsep.o: shared/libutil/../util.h +shared/libutil/strsep.o: shared/libutil/../arg.h +shared/libutil/strsep.o: shared/libutil/../compat.h +shared/libutil/concat.o: shared/libutil/concat.c +shared/libutil/concat.o: shared/libutil/../util.h +shared/libutil/concat.o: shared/libutil/../arg.h +shared/libutil/concat.o: shared/libutil/../compat.h +shared/libutil/human.o: shared/libutil/human.c +shared/libutil/human.o: shared/libutil/../util.h +shared/libutil/human.o: shared/libutil/../arg.h +shared/libutil/human.o: shared/libutil/../compat.h +shared/libutil/tls.o: shared/libutil/tls.c +shared/libutil/tls.o: shared/libutil/../tls.h +shared/libutil/tls.o: shared/libutil/../paths.h +shared/libutil/tls.o: shared/libutil/../util.h +shared/libutil/tls.o: shared/libutil/../arg.h +shared/libutil/tls.o: shared/libutil/../compat.h +shared/libutil/sha384.o: shared/libutil/sha384.c +shared/libutil/sha384.o: shared/libutil/../sha384.h +shared/libutil/sha384.o: shared/libutil/../sha512.h +shared/libutil/fnck.o: shared/libutil/fnck.c +shared/libutil/fnck.o: shared/libutil/../util.h +shared/libutil/fnck.o: shared/libutil/../arg.h +shared/libutil/fnck.o: shared/libutil/../compat.h +shared/libutil/agetcwd.o: shared/libutil/agetcwd.c +shared/libutil/agetcwd.o: shared/libutil/../util.h +shared/libutil/agetcwd.o: shared/libutil/../arg.h +shared/libutil/agetcwd.o: shared/libutil/../compat.h +shared/libutil/linecmp.o: shared/libutil/linecmp.c +shared/libutil/linecmp.o: shared/libutil/../text.h +shared/libutil/linecmp.o: shared/libutil/../util.h +shared/libutil/linecmp.o: shared/libutil/../arg.h +shared/libutil/linecmp.o: shared/libutil/../compat.h shared/libutil/recurse.o: shared/libutil/recurse.c shared/libutil/recurse.o: shared/libutil/../fs.h shared/libutil/recurse.o: shared/libutil/../util.h shared/libutil/recurse.o: shared/libutil/../arg.h shared/libutil/recurse.o: shared/libutil/../compat.h -shared/libutil/recurse_dir.o: shared/libutil/recurse_dir.c -shared/libutil/recurse_dir.o: shared/libutil/../util.h -shared/libutil/recurse_dir.o: shared/libutil/../arg.h -shared/libutil/recurse_dir.o: shared/libutil/../compat.h -shared/libutil/rm.o: shared/libutil/rm.c -shared/libutil/rm.o: shared/libutil/../fs.h -shared/libutil/rm.o: shared/libutil/../util.h -shared/libutil/rm.o: shared/libutil/../arg.h -shared/libutil/rm.o: shared/libutil/../compat.h +shared/libutil/fshut.o: shared/libutil/fshut.c +shared/libutil/fshut.o: shared/libutil/../util.h +shared/libutil/fshut.o: shared/libutil/../arg.h +shared/libutil/fshut.o: shared/libutil/../compat.h +shared/libutil/agetline.o: shared/libutil/agetline.c +shared/libutil/agetline.o: shared/libutil/../text.h +shared/libutil/agetline.o: shared/libutil/../util.h +shared/libutil/agetline.o: shared/libutil/../arg.h +shared/libutil/agetline.o: shared/libutil/../compat.h +shared/libutil/reallocarray.o: shared/libutil/reallocarray.c +shared/libutil/reallocarray.o: shared/libutil/../util.h +shared/libutil/reallocarray.o: shared/libutil/../arg.h +shared/libutil/reallocarray.o: shared/libutil/../compat.h +shared/libutil/fconcat.o: shared/libutil/fconcat.c +shared/libutil/fconcat.o: shared/libutil/../text.h +shared/libutil/fconcat.o: shared/libutil/../util.h +shared/libutil/fconcat.o: shared/libutil/../arg.h +shared/libutil/fconcat.o: shared/libutil/../compat.h +shared/libutil/cp.o: shared/libutil/cp.c +shared/libutil/cp.o: shared/libutil/../fs.h +shared/libutil/cp.o: shared/libutil/../util.h +shared/libutil/cp.o: shared/libutil/../arg.h +shared/libutil/cp.o: shared/libutil/../compat.h shared/libutil/sha1.o: shared/libutil/sha1.c shared/libutil/sha1.o: shared/libutil/../sha1.h -shared/libutil/sha224.o: shared/libutil/sha224.c -shared/libutil/sha224.o: shared/libutil/../sha224.h -shared/libutil/sha224.o: shared/libutil/../sha256.h -shared/libutil/sha256.o: shared/libutil/sha256.c -shared/libutil/sha256.o: shared/libutil/../sha256.h -shared/libutil/sha384.o: shared/libutil/sha384.c -shared/libutil/sha384.o: shared/libutil/../sha384.h -shared/libutil/sha384.o: shared/libutil/../sha512.h -shared/libutil/sha512-224.o: shared/libutil/sha512-224.c -shared/libutil/sha512-224.o: shared/libutil/../sha512-224.h -shared/libutil/sha512-224.o: shared/libutil/../sha512.h +shared/libutil/sysinfo.o: shared/libutil/sysinfo.c +shared/libutil/sysinfo.o: shared/libutil/../util.h +shared/libutil/sysinfo.o: shared/libutil/../arg.h +shared/libutil/sysinfo.o: shared/libutil/../compat.h +shared/libutil/diffutil.o: shared/libutil/diffutil.c +shared/libutil/diffutil.o: shared/libutil/../diffutil.h +shared/libutil/diffutil.o: shared/libutil/../text.h +shared/libutil/diffutil.o: shared/libutil/../util.h +shared/libutil/diffutil.o: shared/libutil/../arg.h +shared/libutil/diffutil.o: shared/libutil/../compat.h +shared/libutil/md5.o: shared/libutil/md5.c +shared/libutil/md5.o: shared/libutil/../md5.h shared/libutil/sha512-256.o: shared/libutil/sha512-256.c shared/libutil/sha512-256.o: shared/libutil/../sha512-256.h shared/libutil/sha512-256.o: shared/libutil/../sha512.h -shared/libutil/sha512.o: shared/libutil/sha512.c -shared/libutil/sha512.o: shared/libutil/../sha512.h -shared/libutil/sig.o: shared/libutil/sig.c -shared/libutil/sig.o: shared/libutil/../sig.h shared/libutil/strcasestr.o: shared/libutil/strcasestr.c shared/libutil/strcasestr.o: shared/libutil/../util.h shared/libutil/strcasestr.o: shared/libutil/../arg.h shared/libutil/strcasestr.o: shared/libutil/../compat.h -shared/libutil/strlcat.o: shared/libutil/strlcat.c -shared/libutil/strlcat.o: shared/libutil/../util.h -shared/libutil/strlcat.o: shared/libutil/../arg.h -shared/libutil/strlcat.o: shared/libutil/../compat.h -shared/libutil/strlcpy.o: shared/libutil/strlcpy.c -shared/libutil/strlcpy.o: shared/libutil/../util.h -shared/libutil/strlcpy.o: shared/libutil/../arg.h -shared/libutil/strlcpy.o: shared/libutil/../compat.h -shared/libutil/strnsubst.o: shared/libutil/strnsubst.c -shared/libutil/strnsubst.o: shared/libutil/../util.h -shared/libutil/strnsubst.o: shared/libutil/../arg.h -shared/libutil/strnsubst.o: shared/libutil/../compat.h -shared/libutil/strsep.o: shared/libutil/strsep.c -shared/libutil/strsep.o: shared/libutil/../util.h -shared/libutil/strsep.o: shared/libutil/../arg.h -shared/libutil/strsep.o: shared/libutil/../compat.h -shared/libutil/strtonum.o: shared/libutil/strtonum.c -shared/libutil/strtonum.o: shared/libutil/../util.h -shared/libutil/strtonum.o: shared/libutil/../arg.h -shared/libutil/strtonum.o: shared/libutil/../compat.h -shared/libutil/sysinfo.o: shared/libutil/sysinfo.c -shared/libutil/sysinfo.o: shared/libutil/../util.h -shared/libutil/sysinfo.o: shared/libutil/../arg.h -shared/libutil/sysinfo.o: shared/libutil/../compat.h -shared/libutil/tls.o: shared/libutil/tls.c -shared/libutil/tls.o: shared/libutil/../tls.h -shared/libutil/tls.o: shared/libutil/../util.h -shared/libutil/tls.o: shared/libutil/../arg.h -shared/libutil/tls.o: shared/libutil/../compat.h -shared/libutil/tty.o: shared/libutil/tty.c -shared/libutil/tty.o: shared/libutil/../util.h -shared/libutil/tty.o: shared/libutil/../arg.h -shared/libutil/tty.o: shared/libutil/../compat.h -shared/libutil/unescape.o: shared/libutil/unescape.c -shared/libutil/unescape.o: shared/libutil/../util.h -shared/libutil/unescape.o: shared/libutil/../arg.h -shared/libutil/unescape.o: shared/libutil/../compat.h +shared/libutil/putword.o: shared/libutil/putword.c +shared/libutil/putword.o: shared/libutil/../util.h +shared/libutil/putword.o: shared/libutil/../arg.h +shared/libutil/putword.o: shared/libutil/../compat.h shared/libutil/writeall.o: shared/libutil/writeall.c shared/libutil/writeall.o: shared/libutil/../util.h shared/libutil/writeall.o: shared/libutil/../arg.h shared/libutil/writeall.o: shared/libutil/../compat.h +shared/libutil/sha512-224.o: shared/libutil/sha512-224.c +shared/libutil/sha512-224.o: shared/libutil/../sha512-224.h +shared/libutil/sha512-224.o: shared/libutil/../sha512.h +shared/libutil/sha512.o: shared/libutil/sha512.c +shared/libutil/sha512.o: shared/libutil/../sha512.h +shared/libutil/rm.o: shared/libutil/rm.c +shared/libutil/rm.o: shared/libutil/../fs.h +shared/libutil/rm.o: shared/libutil/../util.h +shared/libutil/rm.o: shared/libutil/../arg.h +shared/libutil/rm.o: shared/libutil/../compat.h +shared/libutil/eprintf.o: shared/libutil/eprintf.c +shared/libutil/eprintf.o: shared/libutil/../util.h +shared/libutil/eprintf.o: shared/libutil/../arg.h +shared/libutil/eprintf.o: shared/libutil/../compat.h +shared/libutil/enmasse.o: shared/libutil/enmasse.c +shared/libutil/enmasse.o: shared/libutil/../util.h +shared/libutil/enmasse.o: shared/libutil/../arg.h +shared/libutil/enmasse.o: shared/libutil/../compat.h +shared/libutil/recurse_dir.o: shared/libutil/recurse_dir.c +shared/libutil/recurse_dir.o: shared/libutil/../util.h +shared/libutil/recurse_dir.o: shared/libutil/../arg.h +shared/libutil/recurse_dir.o: shared/libutil/../compat.h +shared/libutil/passwd.o: shared/libutil/passwd.c +shared/libutil/passwd.o: shared/libutil/../passwd.h +shared/libutil/passwd.o: shared/libutil/../paths.h +shared/libutil/passwd.o: shared/libutil/../text.h +shared/libutil/passwd.o: shared/libutil/../util.h +shared/libutil/passwd.o: shared/libutil/../arg.h +shared/libutil/passwd.o: shared/libutil/../compat.h +shared/libutil/passwd.o: shared/libutil/../config.h +shared/libutil/passwd.o: shared/libutil/../paths.h +shared/libutil/passwd.o: shared/crypt.h +shared/libutil/sha256.o: shared/libutil/sha256.c +shared/libutil/sha256.o: shared/libutil/../sha256.h +shared/libutil/ealloc.o: shared/libutil/ealloc.c +shared/libutil/ealloc.o: shared/libutil/../util.h +shared/libutil/ealloc.o: shared/libutil/../arg.h +shared/libutil/ealloc.o: shared/libutil/../compat.h +shared/libutil/mkdirp.o: shared/libutil/mkdirp.c +shared/libutil/mkdirp.o: shared/libutil/../util.h +shared/libutil/mkdirp.o: shared/libutil/../arg.h +shared/libutil/mkdirp.o: shared/libutil/../compat.h +shared/libredline/redline.o: shared/libredline/redline.c +shared/libredline/redline.o: shared/libredline/../paths.h +shared/libredline/redline.o: shared/redline.h +shared/libutf/isdigitrune.o: shared/libutf/isdigitrune.c +shared/libutf/isdigitrune.o: shared/libutf/../utf.h +shared/libutf/isdigitrune.o: shared/libutf/runetype.h +shared/libutf/lowerrune.o: shared/libutf/lowerrune.c +shared/libutf/lowerrune.o: shared/libutf/../utf.h +shared/libutf/lowerrune.o: shared/libutf/runetype.h +shared/libutf/isblankrune.o: shared/libutf/isblankrune.c +shared/libutf/isblankrune.o: shared/libutf/../utf.h +shared/libutf/isblankrune.o: shared/libutf/runetype.h +shared/libutf/runetype.o: shared/libutf/runetype.c +shared/libutf/runetype.o: shared/libutf/../utf.h +shared/libutf/ispunctrune.o: shared/libutf/ispunctrune.c +shared/libutf/ispunctrune.o: shared/libutf/../utf.h +shared/libutf/ispunctrune.o: shared/libutf/runetype.h +shared/libutf/isalpharune.o: shared/libutf/isalpharune.c +shared/libutf/isalpharune.o: shared/libutf/../utf.h +shared/libutf/isalpharune.o: shared/libutf/runetype.h +shared/libutf/fgetrune.o: shared/libutf/fgetrune.c +shared/libutf/fgetrune.o: shared/libutf/../utf.h +shared/libutf/isprintrune.o: shared/libutf/isprintrune.c +shared/libutf/isprintrune.o: shared/libutf/../utf.h +shared/libutf/isprintrune.o: shared/libutf/runetype.h +shared/libutf/upperrune.o: shared/libutf/upperrune.c +shared/libutf/upperrune.o: shared/libutf/../utf.h +shared/libutf/upperrune.o: shared/libutf/runetype.h +shared/libutf/isalnumrune.o: shared/libutf/isalnumrune.c +shared/libutf/isalnumrune.o: shared/libutf/../utf.h +shared/libutf/isalnumrune.o: shared/libutf/runetype.h +shared/libutf/utftorunestr.o: shared/libutf/utftorunestr.c +shared/libutf/utftorunestr.o: shared/libutf/../utf.h +shared/libutf/isxdigitrune.o: shared/libutf/isxdigitrune.c +shared/libutf/isxdigitrune.o: shared/libutf/../utf.h +shared/libutf/isxdigitrune.o: shared/libutf/runetype.h +shared/libutf/isspacerune.o: shared/libutf/isspacerune.c +shared/libutf/isspacerune.o: shared/libutf/../utf.h +shared/libutf/isspacerune.o: shared/libutf/runetype.h +shared/libutf/rune.o: shared/libutf/rune.c +shared/libutf/rune.o: shared/libutf/../utf.h +shared/libutf/iscntrlrune.o: shared/libutf/iscntrlrune.c +shared/libutf/iscntrlrune.o: shared/libutf/../utf.h +shared/libutf/iscntrlrune.o: shared/libutf/runetype.h +shared/libutf/istitlerune.o: shared/libutf/istitlerune.c +shared/libutf/istitlerune.o: shared/libutf/../utf.h +shared/libutf/istitlerune.o: shared/libutf/runetype.h +shared/libutf/utf.o: shared/libutf/utf.c +shared/libutf/utf.o: shared/libutf/../utf.h +shared/libutf/isgraphrune.o: shared/libutf/isgraphrune.c +shared/libutf/isgraphrune.o: shared/libutf/../utf.h +shared/libutf/isgraphrune.o: shared/libutf/runetype.h +shared/libutf/fputrune.o: shared/libutf/fputrune.c +shared/libutf/fputrune.o: shared/libutf/../utf.h diff --git a/scripts/mkbox b/scripts/mkbox @@ -9,7 +9,7 @@ set -e : "${CC:=cc}" -: "${CPPFLAGS:=-Ishared -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64}" +: "${CPPFLAGS:=-Ishared -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64 -DFEATURE_INPROC_EXEC=1}" : "${CFLAGS:=-std=c99 -Wall -Wextra -pedantic}" : "${LDFLAGS:=}" : "${LDLIBS:=-lcrypt -lresolv}" @@ -24,8 +24,8 @@ LIBUTIL="${ROOT}/shared/libutil/libutil.a" LIBUTF="${ROOT}/shared/libutf/libutf.a" die() { - printf 'mkbox: %s\n' "$*" >&2 - exit 1 + printf 'mkbox: %s\n' "$*" >&2 + exit 1 } # Clean up build directory on exit or signal termination @@ -36,9 +36,9 @@ trap 'rm -rf "${BDIR}"' EXIT INT QUIT TERM [ -f "${LIBUTF}" ] || die "libutf.a not found; run 'make' first" [ -f "${ROOT}/cmd/posix/getconf.h" ] || { - printf 'mkbox: generating getconf.h\n' - "${ROOT}/scripts/getconf.sh" > "${ROOT}/cmd/posix/getconf.h" || - die "scripts/getconf.sh failed" + printf 'mkbox: generating getconf.h\n' + "${ROOT}/scripts/getconf.sh" > "${ROOT}/cmd/posix/getconf.h" || + die "scripts/getconf.sh failed" } rm -rf "${BDIR}" @@ -48,284 +48,284 @@ OBJS="" DECL_F="${BDIR}/decls.inc" : > "${DECL_F}" for _c in posix linux net pseudo xsi extra; do - : > "${BDIR}/entries_${_c}.inc" + : > "${BDIR}/entries_${_c}.inc" done unset _c alias_entry() { - printf '\t{ "%s", %s_main, "%s" },\n' "$1" "$2" "$3" \ - >> "${BDIR}/entries_${3}.inc" + printf '\t{ "%s", %s_main, "%s" },\n' "$1" "$2" "$3" \ + >> "${BDIR}/entries_${3}.inc" } compile_tool() { - src="$1" - name="$2" - fn="$3" - catg="$4" - extra="${5:-}" - out="${BDIR}/${fn}.o" - symf="${BDIR}/${fn}.syms" - - printf 'mkbox: cc %s\n' "${name}" - eval "${CC} ${CPPFLAGS} ${extra} ${CFLAGS} -c \"\$src\" -o \"\$out\"" || - die "compile failed: ${src}" - printf 'main %s_main\n' "${fn}" > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${out}" || - die "objcopy failed: ${name}" - ${OBJCOPY} --keep-global-symbol="${fn}_main" "${out}" || - die "objcopy localize failed: ${name}" - rm -f "${symf}" - OBJS="${OBJS} ${out}" - printf 'int %s_main(int, char **);\n' "${fn}" >> "${DECL_F}" - printf '\t{ "%s", %s_main, "%s" },\n' "${name}" "${fn}" "${catg}" \ - >> "${BDIR}/entries_${catg}.inc" + src="$1" + name="$2" + fn="$3" + catg="$4" + extra="${5:-}" + out="${BDIR}/${fn}.o" + symf="${BDIR}/${fn}.syms" + + printf 'mkbox: cc %s\n' "${name}" + eval "${CC} ${CPPFLAGS} ${extra} ${CFLAGS} -c \"\$src\" -o \"\$out\"" || + die "compile failed: ${src}" + printf 'main %s_main\n' "${fn}" > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${out}" || + die "objcopy failed: ${name}" + ${OBJCOPY} --keep-global-symbol="${fn}_main" "${out}" || + die "objcopy localize failed: ${name}" + rm -f "${symf}" + OBJS="${OBJS} ${out}" + printf 'int %s_main(int, char **);\n' "${fn}" >> "${DECL_F}" + printf '\t{ "%s", %s_main, "%s" },\n' "${name}" "${fn}" "${catg}" \ + >> "${BDIR}/entries_${catg}.inc" } compile_make() { - mdir="${ROOT}/cmd/posix/make" - symf="${BDIR}/make.syms" - printf 'mkbox: cc make (multi)\n' - make_objs="" - for s in defaults parser posix rules; do - out="${BDIR}/make_${s}.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/\$s.c\" -o \"\$out\"" || - die "compile failed: make/${s}.c" - make_objs="${make_objs} ${out}" - done - out_main="${BDIR}/make_main.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/main.c\" -o \"\${out_main}\"" || - die "compile failed: make/main.c" - make_objs="${make_objs} ${out_main}" - - # Combined incremental link to resolve internal symbols cleanly - combined="${BDIR}/make_combined.o" - ${LD:-ld} -r -o "${combined}" ${make_objs} || - die "ld -r failed: make" - - printf 'main make_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: make" - ${OBJCOPY} --keep-global-symbol=make_main "${combined}" || - die "objcopy localize failed: make" - rm -f "${symf}" ${make_objs} - - OBJS="${OBJS} ${combined}" - printf 'int make_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "make", make_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" + mdir="${ROOT}/cmd/posix/make" + symf="${BDIR}/make.syms" + printf 'mkbox: cc make (multi)\n' + make_objs="" + for s in defaults parser posix rules; do + out="${BDIR}/make_${s}.o" + eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/\$s.c\" -o \"\$out\"" || + die "compile failed: make/${s}.c" + make_objs="${make_objs} ${out}" + done + out_main="${BDIR}/make_main.o" + eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/main.c\" -o \"\${out_main}\"" || + die "compile failed: make/main.c" + make_objs="${make_objs} ${out_main}" + + # Combined incremental link to resolve internal symbols cleanly + combined="${BDIR}/make_combined.o" + ${LD:-ld} -r -o "${combined}" ${make_objs} || + die "ld -r failed: make" + + printf 'main make_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: make" + ${OBJCOPY} --keep-global-symbol=make_main "${combined}" || + die "objcopy localize failed: make" + rm -f "${symf}" ${make_objs} + + OBJS="${OBJS} ${combined}" + printf 'int make_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "make", make_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" } compile_diff() { - ddir="${ROOT}/cmd/posix/diff" - symf="${BDIR}/diff.syms" - diff_objs="" - - printf 'mkbox: cc diff (multi)\n' - for s in diff diffdir diffreg pr xmalloc; do - out="${BDIR}/diff_${s}.o" - eval "${CC} ${CPPFLAGS} -I\"\$ddir\" ${CFLAGS} -c \"\$ddir/\$s.c\" -o \"\$out\"" || - die "compile failed: diff/${s}.c" - diff_objs="${diff_objs} ${out}" - done - - combined="${BDIR}/diff_combined.o" - ${LD:-ld} -r -o "${combined}" ${diff_objs} || - die "ld -r failed: diff" - - printf 'main diff_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: diff" - ${OBJCOPY} --keep-global-symbol=diff_main "${combined}" || - die "objcopy localize failed: diff" - rm -f "${symf}" ${diff_objs} - - OBJS="${OBJS} ${combined}" - LDLIBS="${LDLIBS} -lm" - printf 'int diff_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "diff", diff_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" + ddir="${ROOT}/cmd/posix/diff" + symf="${BDIR}/diff.syms" + diff_objs="" + + printf 'mkbox: cc diff (multi)\n' + for s in diff diffdir diffreg pr xmalloc; do + out="${BDIR}/diff_${s}.o" + eval "${CC} ${CPPFLAGS} -I\"\$ddir\" ${CFLAGS} -c \"\$ddir/\$s.c\" -o \"\$out\"" || + die "compile failed: diff/${s}.c" + diff_objs="${diff_objs} ${out}" + done + + combined="${BDIR}/diff_combined.o" + ${LD:-ld} -r -o "${combined}" ${diff_objs} || + die "ld -r failed: diff" + + printf 'main diff_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: diff" + ${OBJCOPY} --keep-global-symbol=diff_main "${combined}" || + die "objcopy localize failed: diff" + rm -f "${symf}" ${diff_objs} + + OBJS="${OBJS} ${combined}" + LDLIBS="${LDLIBS} -lm" + printf 'int diff_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "diff", diff_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" } compile_patch() { - pdir="${ROOT}/cmd/posix/patch" - symf="${BDIR}/patch.syms" - patch_objs="" - - printf 'mkbox: cc patch (multi)\n' - for s in patch pch inp util backupfile mkpath; do - out="${BDIR}/patch_${s}.o" - eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$pdir/\$s.c\" -o \"\$out\"" || - die "compile failed: patch/${s}.c" - patch_objs="${patch_objs} ${out}" - done - - combined="${BDIR}/patch_combined.o" - ${LD:-ld} -r -o "${combined}" ${patch_objs} || - die "ld -r failed: patch" - - printf 'main patch_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: patch" - ${OBJCOPY} --keep-global-symbol=patch_main "${combined}" || - die "objcopy localize failed: patch" - rm -f "${symf}" ${patch_objs} - - OBJS="${OBJS} ${combined}" - printf 'int patch_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "patch", patch_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" + pdir="${ROOT}/cmd/posix/patch" + symf="${BDIR}/patch.syms" + patch_objs="" + + printf 'mkbox: cc patch (multi)\n' + for s in patch pch inp util backupfile mkpath; do + out="${BDIR}/patch_${s}.o" + eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$pdir/\$s.c\" -o \"\$out\"" || + die "compile failed: patch/${s}.c" + patch_objs="${patch_objs} ${out}" + done + + combined="${BDIR}/patch_combined.o" + ${LD:-ld} -r -o "${combined}" ${patch_objs} || + die "ld -r failed: patch" + + printf 'main patch_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: patch" + ${OBJCOPY} --keep-global-symbol=patch_main "${combined}" || + die "objcopy localize failed: patch" + rm -f "${symf}" ${patch_objs} + + OBJS="${OBJS} ${combined}" + printf 'int patch_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "patch", patch_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" } compile_diff3() { - ddir="${ROOT}/cmd/extra/diff3" - pdir="${ROOT}/cmd/posix/diff" - symf="${BDIR}/diff3.syms" - diff3_objs="" - - printf 'mkbox: cc diff3 (multi)\n' - for s in diff3; do - out="${BDIR}/diff3_${s}.o" - eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$ddir/\$s.c\" -o \"\$out\"" || - die "compile failed: diff3/${s}.c" - diff3_objs="${diff3_objs} ${out}" - done - out="${BDIR}/diff3_xmalloc.o" - eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$pdir/xmalloc.c\" -o \"\$out\"" || - die "compile failed: diff/xmalloc.c" - diff3_objs="${diff3_objs} ${out}" - - combined="${BDIR}/diff3_combined.o" - ${LD:-ld} -r -o "${combined}" ${diff3_objs} || - die "ld -r failed: diff3" - - printf 'main diff3_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: diff3" - ${OBJCOPY} --keep-global-symbol=diff3_main "${combined}" || - die "objcopy localize failed: diff3" - rm -f "${symf}" ${diff3_objs} - - OBJS="${OBJS} ${combined}" - printf 'int diff3_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "diff3", diff3_main, "extra" },\n' >> "${BDIR}/entries_extra.inc" + ddir="${ROOT}/cmd/extra/diff3" + pdir="${ROOT}/cmd/posix/diff" + symf="${BDIR}/diff3.syms" + diff3_objs="" + + printf 'mkbox: cc diff3 (multi)\n' + for s in diff3; do + out="${BDIR}/diff3_${s}.o" + eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$ddir/\$s.c\" -o \"\$out\"" || + die "compile failed: diff3/${s}.c" + diff3_objs="${diff3_objs} ${out}" + done + out="${BDIR}/diff3_xmalloc.o" + eval "${CC} ${CPPFLAGS} -I\"\$pdir\" ${CFLAGS} -c \"\$pdir/xmalloc.c\" -o \"\$out\"" || + die "compile failed: diff/xmalloc.c" + diff3_objs="${diff3_objs} ${out}" + + combined="${BDIR}/diff3_combined.o" + ${LD:-ld} -r -o "${combined}" ${diff3_objs} || + die "ld -r failed: diff3" + + printf 'main diff3_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: diff3" + ${OBJCOPY} --keep-global-symbol=diff3_main "${combined}" || + die "objcopy localize failed: diff3" + rm -f "${symf}" ${diff3_objs} + + OBJS="${OBJS} ${combined}" + printf 'int diff3_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "diff3", diff3_main, "extra" },\n' >> "${BDIR}/entries_extra.inc" } compile_awk() { - adir="${ROOT}/cmd/posix/awk" - symf="${BDIR}/awk.syms" - awk_objs="" - - printf 'mkbox: yacc awk/awkgram.y\n' - ${YACC} -d -o "${adir}/awkgram.tab.c" "${adir}/awkgram.y" || - die "yacc failed: awk/awkgram.y" - - # maketab is a host code-generator, only needs CFLAGS, no CPPFLAGS - printf 'mkbox: cc awk/maketab\n' - ${CC} ${CFLAGS} -o "${BDIR}/awk_maketab" "${adir}/maketab.c" || - die "compile failed: awk/maketab.c" - - printf 'mkbox: gen awk/proctab.c\n' - "${BDIR}/awk_maketab" "${adir}/awkgram.tab.h" > "${adir}/proctab.c" || - die "maketab failed" - - for s in b main parse proctab tran lib run lex math; do - out="${BDIR}/awk_${s}.o" - eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/${s}.c\" -o \"\$out\"" || - die "compile failed: awk/${s}.c" - awk_objs="${awk_objs} ${out}" - done - out="${BDIR}/awk_awkgram.tab.o" - eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/awkgram.tab.c\" -o \"\$out\"" || - die "compile failed: awk/awkgram.tab.c" - awk_objs="${awk_objs} ${out}" - - combined="${BDIR}/awk_combined.o" - ${LD:-ld} -r -o "${combined}" ${awk_objs} || - die "ld -r failed: awk" - - printf 'main awk_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: awk" - ${OBJCOPY} --keep-global-symbol=awk_main "${combined}" || - die "objcopy localize failed: awk" - rm -f "${symf}" ${awk_objs} - - OBJS="${OBJS} ${combined}" - LDLIBS="${LDLIBS} -lm" - printf 'int awk_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "awk", awk_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" + adir="${ROOT}/cmd/posix/awk" + symf="${BDIR}/awk.syms" + awk_objs="" + + printf 'mkbox: yacc awk/awkgram.y\n' + ${YACC} -d -o "${adir}/awkgram.tab.c" "${adir}/awkgram.y" || + die "yacc failed: awk/awkgram.y" + + # maketab is a host code-generator, only needs CFLAGS, no CPPFLAGS + printf 'mkbox: cc awk/maketab\n' + ${CC} ${CFLAGS} -o "${BDIR}/awk_maketab" "${adir}/maketab.c" || + die "compile failed: awk/maketab.c" + + printf 'mkbox: gen awk/proctab.c\n' + "${BDIR}/awk_maketab" "${adir}/awkgram.tab.h" > "${adir}/proctab.c" || + die "maketab failed" + + for s in b main parse proctab tran lib run lex math; do + out="${BDIR}/awk_${s}.o" + eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/${s}.c\" -o \"\$out\"" || + die "compile failed: awk/${s}.c" + awk_objs="${awk_objs} ${out}" + done + out="${BDIR}/awk_awkgram.tab.o" + eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/awkgram.tab.c\" -o \"\$out\"" || + die "compile failed: awk/awkgram.tab.c" + awk_objs="${awk_objs} ${out}" + + combined="${BDIR}/awk_combined.o" + ${LD:-ld} -r -o "${combined}" ${awk_objs} || + die "ld -r failed: awk" + + printf 'main awk_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: awk" + ${OBJCOPY} --keep-global-symbol=awk_main "${combined}" || + die "objcopy localize failed: awk" + rm -f "${symf}" ${awk_objs} + + OBJS="${OBJS} ${combined}" + LDLIBS="${LDLIBS} -lm" + printf 'int awk_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "awk", awk_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" } compile_sh() { - sdir="${ROOT}/cmd/posix/sh" - symf="${BDIR}/sh.syms" - sh_objs="" - - # mknodes and mksyntax are host code-generators, not part of the shell - printf 'mkbox: cc sh/mknodes\n' - ${CC} ${CFLAGS} -o "${BDIR}/sh_mknodes" "${sdir}/mknodes.c" || - die "compile failed: sh/mknodes.c" - - printf 'mkbox: cc sh/mksyntax\n' - ${CC} ${CPPFLAGS} -I"${sdir}" ${CFLAGS} -o "${BDIR}/sh_mksyntax" "${sdir}/mksyntax.c" || - die "compile failed: sh/mksyntax.c" - - printf 'mkbox: gen sh/nodes.{c,h}\n' - (cd "${sdir}" && "${BDIR}/sh_mknodes" nodetypes nodes.c.pat) || - die "mknodes failed" - - printf 'mkbox: gen sh/syntax.{c,h}\n' - (cd "${sdir}" && "${BDIR}/sh_mksyntax") || - die "mksyntax failed" - - printf 'mkbox: gen sh/builtins.{c,h}\n' - (cd "${sdir}" && sh mkbuiltins .) || - die "mkbuiltins failed" - - printf 'mkbox: gen sh/token.h\n' - (cd "${sdir}" && sh mktokens) || - die "mktokens failed" - - for s in alias arith_yacc arith_yylex cd echo error eval exec \ - expand lineedit input jobs kill mail main memalloc \ - miscbltin mystring options output parser printf redir \ - show test trap var builtins nodes syntax; do - out="${BDIR}/sh_${s}.o" - eval "${CC} ${CPPFLAGS} -DSHELL -I\"\$sdir\" ${CFLAGS} -c \"\$sdir/${s}.c\" -o \"\$out\"" || - die "compile failed: sh/${s}.c" - sh_objs="${sh_objs} ${out}" - done - - combined="${BDIR}/sh_combined.o" - ${LD:-ld} -r -o "${combined}" ${sh_objs} || - die "ld -r failed: sh" - - printf 'main sh_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: sh" - ${OBJCOPY} --keep-global-symbol=sh_main "${combined}" || - die "objcopy localize failed: sh" - rm -f "${symf}" ${sh_objs} - - OBJS="${OBJS} ${combined}" - printf 'int sh_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "sh", sh_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" + sdir="${ROOT}/cmd/posix/sh" + symf="${BDIR}/sh.syms" + sh_objs="" + + # mknodes and mksyntax are host code-generators, not part of the shell + printf 'mkbox: cc sh/mknodes\n' + ${CC} ${CFLAGS} -o "${BDIR}/sh_mknodes" "${sdir}/mknodes.c" || + die "compile failed: sh/mknodes.c" + + printf 'mkbox: cc sh/mksyntax\n' + ${CC} ${CPPFLAGS} -I"${sdir}" ${CFLAGS} -o "${BDIR}/sh_mksyntax" "${sdir}/mksyntax.c" || + die "compile failed: sh/mksyntax.c" + + printf 'mkbox: gen sh/nodes.{c,h}\n' + (cd "${sdir}" && "${BDIR}/sh_mknodes" nodetypes nodes.c.pat) || + die "mknodes failed" + + printf 'mkbox: gen sh/syntax.{c,h}\n' + (cd "${sdir}" && "${BDIR}/sh_mksyntax") || + die "mksyntax failed" + + printf 'mkbox: gen sh/builtins.{c,h}\n' + (cd "${sdir}" && sh mkbuiltins .) || + die "mkbuiltins failed" + + printf 'mkbox: gen sh/token.h\n' + (cd "${sdir}" && sh mktokens) || + die "mktokens failed" + + for s in alias arith_yacc arith_yylex cd echo error eval exec \ + expand lineedit input jobs kill mail main memalloc \ + miscbltin mystring options output parser printf redir \ + show test trap var builtins nodes syntax; do + out="${BDIR}/sh_${s}.o" + eval "${CC} ${CPPFLAGS} -DSHELL -I\"\$sdir\" ${CFLAGS} -c \"\$sdir/${s}.c\" -o \"\$out\"" || + die "compile failed: sh/${s}.c" + sh_objs="${sh_objs} ${out}" + done + + combined="${BDIR}/sh_combined.o" + ${LD:-ld} -r -o "${combined}" ${sh_objs} || + die "ld -r failed: sh" + + printf 'main sh_main\n' > "${symf}" + ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || + die "objcopy failed: sh" + ${OBJCOPY} --keep-global-symbol=sh_main "${combined}" || + die "objcopy localize failed: sh" + rm -f "${symf}" ${sh_objs} + + OBJS="${OBJS} ${combined}" + printf 'int sh_main(int, char **);\n' >> "${DECL_F}" + printf '\t{ "sh", sh_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" } process_dir() { - dir="$1" - catg="$2" - extra="${3:-}" - for src in "${dir}"/*.c; do - [ -f "${src}" ] || continue - name=${src##*/} - name=${name%.c} - fn=$(printf '%s' "${name}" | tr '.-' '__') - compile_tool "${src}" "${name}" "${fn}" "${catg}" "${extra}" - if [ "${name}" = "test" ]; then - alias_entry "[" "test" "${catg}" - fi - if [ "${name}" = "xinstall" ]; then - alias_entry "install" "xinstall" "${catg}" - fi - done + dir="$1" + catg="$2" + extra="${3:-}" + for src in "${dir}"/*.c; do + [ -f "${src}" ] || continue + name=${src##*/} + name=${name%.c} + fn=$(printf '%s' "${name}" | tr '.-' '__') + compile_tool "${src}" "${name}" "${fn}" "${catg}" "${extra}" + if [ "${name}" = "test" ]; then + alias_entry "[" "test" "${catg}" + fi + if [ "${name}" = "xinstall" ]; then + alias_entry "install" "xinstall" "${catg}" + fi + done } process_dir "${ROOT}/cmd/posix" "posix" @@ -350,6 +350,7 @@ cat > "${DISP}" << 'DISPATCH_HEAD' 2026 xplshn [anto@xplshn.com.ar](mailto:anto@xplshn.com.ar) */ /* routes argv[0] to the appropriate tool main */ +#include "wexec.h" #include "util.h" #include <stdio.h> @@ -366,9 +367,9 @@ cat "${DECL_F}" >> "${DISP}" cat >> "${DISP}" << 'DISPATCH_STRUCT' struct Cmd { - const char *name; - int (*fn)(int, char **); - const char *cat; + const char *name; + int (*fn)(int, char **); + const char *cat; }; static struct Cmd cmds[] = { @@ -378,115 +379,118 @@ DISPATCH_STRUCT # entries have the form: \t{ "name", fn_main, "cat" }, # splitting on " makes field 2 the tool name for _c in posix linux net pseudo xsi extra; do - sort -t'"' -k2,2 "${BDIR}/entries_${_c}.inc" + sort -t'"' -k2,2 "${BDIR}/entries_${_c}.inc" done >> "${DISP}" unset _c cat >> "${DISP}" << 'DISPATCH_TAIL' - { NULL, NULL, NULL } + { NULL, NULL, NULL } }; static void usage(void) { - struct Cmd *c; - const char *last; - int col; - - last = NULL; - col = 0; - fprintf(stderr, "usage: %s [-i path] [command [args...]]\n", argv0); - for (c = cmds; c->name; c++) { - if (!last || strcmp(c->cat, last) != 0) { - if (last) - fprintf(stderr, "\n\n"); - last = c->cat; - fprintf(stderr, "%s:\n", last); - col = 0; - } - if (col == 0) { - fprintf(stderr, "\t%s", c->name); - col = 8 + strlen(c->name); - } else if (col + 2 + strlen(c->name) >= 78) { - fprintf(stderr, ",\n\t%s", c->name); - col = 8 + strlen(c->name); - } else { - fprintf(stderr, ", %s", c->name); - col += 2 + strlen(c->name); - } - } - if (last) - fputc('\n', stderr); - exit(1); + struct Cmd *c; + const char *last; + int col; + + last = NULL; + col = 0; + fprintf(stderr, "usage: %s [-i path] [command [args...]]\n", argv0); + for (c = cmds; c->name; c++) { + if (!last || strcmp(c->cat, last) != 0) { + if (last) + fprintf(stderr, "\n\n"); + last = c->cat; + fprintf(stderr, "%s:\n", last); + col = 0; + } + if (col == 0) { + fprintf(stderr, "\t%s", c->name); + col = 8 + strlen(c->name); + } else if (col + 2 + strlen(c->name) >= 78) { + fprintf(stderr, ",\n\t%s", c->name); + col = 8 + strlen(c->name); + } else { + fprintf(stderr, ", %s", c->name); + col += 2 + strlen(c->name); + } + } + if (last) + fputc('\n', stderr); + exit(1); } static void x_install(const char *path) { - struct Cmd *c; - char buf[4096]; - int r; - - for (c = cmds; c->name; c++) { - r = snprintf(buf, sizeof buf, "%s/%s", path, c->name); - if (r < 0 || r >= (int)sizeof buf) - eprintf("install: '%s/%s': path too long\n", path, c->name); - remove(buf); - if (symlink("aruu-box", buf) < 0) - eprintf("install: symlink '%s':", buf); - } + struct Cmd *c; + char buf[4096]; + int r; + + for (c = cmds; c->name; c++) { + r = snprintf(buf, sizeof buf, "%s/%s", path, c->name); + if (r < 0 || r >= (int)sizeof buf) + eprintf("install: '%s/%s': path too long\n", path, c->name); + remove(buf); + if (symlink("aruu-box", buf) < 0) + eprintf("install: symlink '%s':", buf); + } } int main(int argc, char *argv[]) { - struct Cmd *c; - char *s; - - argv0 = argv[0]; - - s = strrchr(argv[0], '/'); - if (s) - s++; - else - s = argv[0]; - - if (strcmp(s, "aruu-box") == 0) { - if (argc < 2) - usage(); - argc--; - argv++; - if (strcmp(argv[0], "-i") == 0) { - if (argc < 2) - eprintf("usage: aruu-box -i path\n"); - x_install(argv[1]); - return 0; - } - s = strrchr(argv[0], '/'); - if (s) - s++; - else - s = argv[0]; - } - for (c = cmds; c->name; c++) { - if (strcmp(c->name, s) == 0) { - argv0 = (char *)c->name; - argv[0] = (char *)c->name; - return c->fn(argc, argv); - } - } - enprintf(127, "%s: not found\n", s); - return 1; + struct Cmd *c; + char *s; + + argv0 = argv[0]; + + for (c = cmds; c->name; c++) + wexec_register(c->name, c->fn); + + s = strrchr(argv[0], '/'); + if (s) + s++; + else + s = argv[0]; + + if (strcmp(s, "aruu-box") == 0) { + if (argc < 2) + usage(); + argc--; + argv++; + if (strcmp(argv[0], "-i") == 0) { + if (argc < 2) + eprintf("usage: aruu-box -i path\n"); + x_install(argv[1]); + return 0; + } + s = strrchr(argv[0], '/'); + if (s) + s++; + else + s = argv[0]; + } + for (c = cmds; c->name; c++) { + if (strcmp(c->name, s) == 0) { + argv0 = (char *)c->name; + argv[0] = (char *)c->name; + return c->fn(argc, argv); + } + } + enprintf(127, "%s: not found\n", s); + return 1; } DISPATCH_TAIL printf 'mkbox: cc dispatch\n' eval "${CC} ${CPPFLAGS} ${CFLAGS} -c \"\$DISP\" -o \"\${BDIR}/aruu-box.o\"" || - die "compile failed: dispatch" + die "compile failed: dispatch" OBJS="${OBJS} ${BDIR}/aruu-box.o" printf 'mkbox: ld aruu-box\n' eval "${CC} ${LDFLAGS} -o \"\$BOX\" \$OBJS \"\$LIBREDLINE\" \"\$LIBUTIL\" \"\$LIBUTF\" \${LDLIBS}" || - die "link failed" + die "link failed" printf 'mkbox: done => %s\n' "${BOX}" diff --git a/shared/config.h b/shared/config.h @@ -1,13 +1,14 @@ /* See LICENSE file for copyright and license details. */ +#include "paths.h" -#define ENV_PATH "/bin" -#define PW_CIPHER "$6$" /* sha-512 */ +#define ENV_PATH ARUU_PATH_BIN +#define PW_CIPHER "$6$" #undef UTMP_PATH -#define UTMP_PATH "/var/run/utmp" +#define UTMP_PATH ARUU_PATH_UTMP #undef BTMP_PATH -#define BTMP_PATH "/var/log/btmp" +#define BTMP_PATH ARUU_PATH_BTMP #undef WTMP_PATH -#define WTMP_PATH "/var/log/wtmp" +#define WTMP_PATH ARUU_PATH_WTMP #ifndef FEATURE_FIND_DELETE #define FEATURE_FIND_DELETE 1 @@ -87,3 +88,36 @@ #ifndef FEATURE_LS_COLOR #define FEATURE_LS_COLOR 1 #endif +#ifndef FEATURE_DIFF3_MERGE +#define FEATURE_DIFF3_MERGE 1 +#endif +#ifndef FEATURE_DIFF3_EDSCRIPT +#define FEATURE_DIFF3_EDSCRIPT 1 +#endif +#ifndef FEATURE_DIFF_CONTEXT +#define FEATURE_DIFF_CONTEXT 1 +#endif +#ifndef FEATURE_DIFF_UNIFIED +#define FEATURE_DIFF_UNIFIED 1 +#endif +#ifndef FEATURE_DIFF_ED +#define FEATURE_DIFF_ED 1 +#endif +#ifndef FEATURE_DIFF_BRIEF +#define FEATURE_DIFF_BRIEF 1 +#endif +#ifndef FEATURE_DIFF_SIDEBYSIDE +#define FEATURE_DIFF_SIDEBYSIDE 1 +#endif +#ifndef FEATURE_PATCH_BACKUP +#define FEATURE_PATCH_BACKUP 1 +#endif +#ifndef FEATURE_PATCH_FUZZ +#define FEATURE_PATCH_FUZZ 1 +#endif +#ifndef FEATURE_PATCH_STRIP_CR +#define FEATURE_PATCH_STRIP_CR 1 +#endif +#ifndef FEATURE_INPROC_EXEC +#define FEATURE_INPROC_EXEC 0 +#endif diff --git a/shared/diffutil.h b/shared/diffutil.h @@ -0,0 +1,66 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef ARUU_DIFFUTIL_H +#define ARUU_DIFFUTIL_H + +#include <stdio.h> +#include <sys/types.h> + +struct diffline { + char *data; + size_t len; +}; + +struct difffile { + struct diffline *lines; + size_t nlines; +}; + +struct diffrange { + size_t from; + size_t to; +}; + +struct diffhunk { + struct diffrange old; + struct diffrange new; +}; + +struct diffhunks { + struct diffhunk *v; + size_t n; +}; + +enum diffformat { + DIFF_NORMAL, + DIFF_UNIFIED, + DIFF_CONTEXT, + DIFF_ED, + DIFF_RCSED, + DIFF_BRIEF, +}; + +struct diffopts { + enum diffformat format; + size_t context; + int ignore_case; + int ignore_blanks; + int strip_cr; + int treat_binary; +}; + +#define DIFF_SAME 0 +#define DIFF_DIFFER 1 +#define DIFF_ERROR 2 + +int diff_load(struct difffile *df, const char *path); +void diff_free(struct difffile *df); +int diff_compute(struct diffhunks *hunks, const struct difffile *old, + const struct difffile *new, const struct diffopts *opts); +void diff_hunks_free(struct diffhunks *hunks); +int diff_format(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new, + const char *oldlabel, const char *newlabel, + const struct diffopts *opts); +int diff_looks_binary(const struct difffile *df); + +#endif diff --git a/shared/diskutil.h b/shared/diskutil.h @@ -2,30 +2,21 @@ #ifndef ARUU_DISKUTIL_H #define ARUU_DISKUTIL_H +#include "paths.h" + #include <stddef.h> #include <stdint.h> -#ifndef PATH_DEV -#define PATH_DEV "/dev" -#endif - -#ifndef PATH_PROC -#define PATH_PROC "/proc" -#endif - -#define PATH_PARTITIONS PATH_PROC "/partitions" -#define PATH_MOUNTS PATH_PROC "/mounts" - struct BlockDev { int fd; - uint64_t size; /* size in bytes */ - size_t sec_size; /* sector size */ + uint64_t size; + size_t sec_size; }; struct BlockDevInfo { char name[32]; - char path[128]; /* absolute path to device node */ - char type[16]; /* disk, part, loop */ + char path[128]; + char type[16]; uint64_t size; int major; int minor; @@ -37,14 +28,14 @@ struct BlockDevInfo { int blockdev_open(struct BlockDev *dev, const char *path, int writable); int blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf, - size_t sector_count); + size_t sector_count); int blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf, - size_t sector_count); + size_t sector_count); void blockdev_close(struct BlockDev *dev); int blockdev_detect_fs(struct BlockDev *dev, char *type, size_t type_sz, - char *label, size_t label_sz, char *uuid, - size_t uuid_sz); + char *label, size_t label_sz, char *uuid, + size_t uuid_sz); struct BlockDevInfo *blockdev_get_list(void); void blockdev_free_list(struct BlockDevInfo *list); diff --git a/shared/libredline/redline.c b/shared/libredline/redline.c @@ -1,5 +1,6 @@ /* see license file for copyright and license details */ +#include "../paths.h" #include "redline.h" #include <ctype.h> @@ -41,26 +42,26 @@ #define ESC 27 struct redlineState { - int in_completion; - int ifd; - int ofd; - char *buf; - size_t buflen; - const char *prompt; - size_t plen; - size_t pos; - size_t oldpos; - size_t len; - size_t cols; - size_t oldrows; - int oldrpos; - int history_index; + int in_completion; + int ifd; + int ofd; + char *buf; + size_t buflen; + const char *prompt; + size_t plen; + size_t pos; + size_t oldpos; + size_t len; + size_t cols; + size_t oldrows; + int oldrpos; + int history_index; }; struct abuf { - char *b; - int len; + char *b; + int len; }; static struct termios orig_termios; @@ -79,1334 +80,1334 @@ static void (*completionCallback)(const char *, struct redlineCompletions *) = N static int utf8ByteLen(char c) { - unsigned char uc = (unsigned char)c; - if ((uc & 0x80) == 0) return 1; - if ((uc & 0xE0) == 0xC0) return 2; - if ((uc & 0xF0) == 0xE0) return 3; - if ((uc & 0xF8) == 0xF0) return 4; - return 1; + unsigned char uc = (unsigned char)c; + if ((uc & 0x80) == 0) return 1; + if ((uc & 0xE0) == 0xC0) return 2; + if ((uc & 0xF0) == 0xE0) return 3; + if ((uc & 0xF8) == 0xF0) return 4; + return 1; } /* decode character starting at s */ static uint32_t utf8DecodeChar(const char *s, size_t *len) { - uint32_t cp = 0; - int l = utf8ByteLen(*s); - *len = l; - if (l == 1) { - cp = ((unsigned char)*s); - } else if (l == 2) { - cp = ((unsigned char)*s & 0x1F) << 6; - cp |= ((unsigned char)*(s+1) & 0x3F); - } else if (l == 3) { - cp = ((unsigned char)*s & 0x0F) << 12; - cp |= ((unsigned char)*(s+1) & 0x3F) << 6; - cp |= ((unsigned char)*(s+2) & 0x3F); - } else if (l == 4) { - cp = ((unsigned char)*s & 0x07) << 18; - cp |= ((unsigned char)*(s+1) & 0x3F) << 12; - cp |= ((unsigned char)*(s+2) & 0x3F) << 6; - cp |= ((unsigned char)*(s+3) & 0x3F); - } - return cp; + uint32_t cp = 0; + int l = utf8ByteLen(*s); + *len = l; + if (l == 1) { + cp = ((unsigned char)*s); + } else if (l == 2) { + cp = ((unsigned char)*s & 0x1F) << 6; + cp |= ((unsigned char)*(s+1) & 0x3F); + } else if (l == 3) { + cp = ((unsigned char)*s & 0x0F) << 12; + cp |= ((unsigned char)*(s+1) & 0x3F) << 6; + cp |= ((unsigned char)*(s+2) & 0x3F); + } else if (l == 4) { + cp = ((unsigned char)*s & 0x07) << 18; + cp |= ((unsigned char)*(s+1) & 0x3F) << 12; + cp |= ((unsigned char)*(s+2) & 0x3F) << 6; + cp |= ((unsigned char)*(s+3) & 0x3F); + } + return cp; } static int isZWJ(uint32_t cp) { - return cp == 0x200D; + return cp == 0x200D; } static int isCombiningMark(uint32_t cp) { - return (cp >= 0x0300 && cp <= 0x036F) || (cp >= 0x1DC0 && cp <= 0x1DFF) || - (cp >= 0x20D0 && cp <= 0x20FF) || (cp >= 0xFE20 && cp <= 0xFE2F); + return (cp >= 0x0300 && cp <= 0x036F) || (cp >= 0x1DC0 && cp <= 0x1DFF) || + (cp >= 0x20D0 && cp <= 0x20FF) || (cp >= 0xFE20 && cp <= 0xFE2F); } static int isVariationSelector(uint32_t cp) { - return (cp >= 0xFE00 && cp <= 0xFE0F) || (cp >= 0xE0100 && cp <= 0xE01EF); + return (cp >= 0xFE00 && cp <= 0xFE0F) || (cp >= 0xE0100 && cp <= 0xE01EF); } static int isSkinToneModifier(uint32_t cp) { - return cp >= 0x1F3FB && cp <= 0x1F3FF; + return cp >= 0x1F3FB && cp <= 0x1F3FF; } static int isGraphemeExtend(uint32_t cp) { - return isCombiningMark(cp) || isVariationSelector(cp) || isSkinToneModifier(cp); + return isCombiningMark(cp) || isVariationSelector(cp) || isSkinToneModifier(cp); } /* decode character going backward from pos */ static uint32_t utf8DecodePrev(const char *buf, size_t pos, size_t *cplen) { - size_t i = 1; - while (pos >= i && i <= 4) { - unsigned char uc = (unsigned char)buf[pos-i]; - if ((uc & 0x80) == 0) { - if (i == 1) { - *cplen = 1; - return uc; - } - break; - } - if ((uc & 0xC0) == 0xC0) { - int l = utf8ByteLen(buf[pos-i]); - if ((size_t)l == i) { - *cplen = i; - return utf8DecodeChar(buf + pos - i, cplen); - } - break; - } - i++; - } - *cplen = 1; - return (unsigned char)buf[pos-1]; + size_t i = 1; + while (pos >= i && i <= 4) { + unsigned char uc = (unsigned char)buf[pos-i]; + if ((uc & 0x80) == 0) { + if (i == 1) { + *cplen = 1; + return uc; + } + break; + } + if ((uc & 0xC0) == 0xC0) { + int l = utf8ByteLen(buf[pos-i]); + if ((size_t)l == i) { + *cplen = i; + return utf8DecodeChar(buf + pos - i, cplen); + } + break; + } + i++; + } + *cplen = 1; + return (unsigned char)buf[pos-1]; } /* calculate width of utf-8 char pos */ static size_t utf8PrevCharLen(const char *buf, size_t pos) { - size_t len = 0; - size_t next_len = 0; - uint32_t cp; - if (pos == 0) return 0; - cp = utf8DecodePrev(buf, pos, &len); - pos -= len; - while (pos > 0 && isGraphemeExtend(cp)) { - cp = utf8DecodePrev(buf, pos, &next_len); - len += next_len; - pos -= next_len; - } - if (pos > 0 && isZWJ(cp)) { - size_t j = utf8PrevCharLen(buf, pos); - if (j > 0) len += j; - } - return len; + size_t len = 0; + size_t next_len = 0; + uint32_t cp; + if (pos == 0) return 0; + cp = utf8DecodePrev(buf, pos, &len); + pos -= len; + while (pos > 0 && isGraphemeExtend(cp)) { + cp = utf8DecodePrev(buf, pos, &next_len); + len += next_len; + pos -= next_len; + } + if (pos > 0 && isZWJ(cp)) { + size_t j = utf8PrevCharLen(buf, pos); + if (j > 0) len += j; + } + return len; } /* calculate width of next utf-8 char */ static size_t utf8NextCharLen(const char *buf, size_t pos, size_t len) { - size_t clen = 0; - size_t offset = 0; - uint32_t cp; - if (pos >= len) return 0; - cp = utf8DecodeChar(buf + pos, &clen); - offset = clen; - while (pos + offset < len) { - size_t next_len = 0; - uint32_t next_cp = utf8DecodeChar(buf + pos + offset, &next_len); - if (isGraphemeExtend(next_cp)) { - offset += next_len; - } else if (isZWJ(cp)) { - offset += next_len; - cp = next_cp; - } else { - break; - } - } - return offset; + size_t clen = 0; + size_t offset = 0; + uint32_t cp; + if (pos >= len) return 0; + cp = utf8DecodeChar(buf + pos, &clen); + offset = clen; + while (pos + offset < len) { + size_t next_len = 0; + uint32_t next_cp = utf8DecodeChar(buf + pos + offset, &next_len); + if (isGraphemeExtend(next_cp)) { + offset += next_len; + } else if (isZWJ(cp)) { + offset += next_len; + cp = next_cp; + } else { + break; + } + } + return offset; } /* get columns needed to display char */ static int utf8CharWidth(uint32_t cp) { - if (cp == 0) return 0; - if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0; - if ((cp >= 0x1100 && cp <= 0x115f) || - (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) || - (cp >= 0xac00 && cp <= 0xd7a3) || - (cp >= 0xf900 && cp <= 0xfaff) || - (cp >= 0xfe10 && cp <= 0xfe19) || - (cp >= 0xfe30 && cp <= 0xfe6f) || - (cp >= 0xff00 && cp <= 0xff60) || - (cp >= 0xffe0 && cp <= 0xffe6) || - (cp >= 0x20000 && cp <= 0x2fffd) || - (cp >= 0x30000 && cp <= 0x3fffd)) { - return 2; - } - return 1; + if (cp == 0) return 0; + if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0; + if ((cp >= 0x1100 && cp <= 0x115f) || + (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) || + (cp >= 0xac00 && cp <= 0xd7a3) || + (cp >= 0xf900 && cp <= 0xfaff) || + (cp >= 0xfe10 && cp <= 0xfe19) || + (cp >= 0xfe30 && cp <= 0xfe6f) || + (cp >= 0xff00 && cp <= 0xff60) || + (cp >= 0xffe0 && cp <= 0xffe6) || + (cp >= 0x20000 && cp <= 0x2fffd) || + (cp >= 0x30000 && cp <= 0x3fffd)) { + return 2; + } + return 1; } /* get ansi escape sequence length */ static size_t ansiEscapeLen(const char *s, size_t len) { - size_t i = 0; - if (len < 2 || s[0] != '\x1b' || s[1] != '[') return 0; - i = 2; - while (i < len) { - char c = s[i]; - if ((c >= '0' && c <= '9') || c == ';' || c == '?' || c == '"') { - i++; - } else if (c >= 'A' && c <= 'Z') { - return i + 1; - } else if (c >= 'a' && c <= 'z') { - return i + 1; - } else { - break; - } - } - return 0; + size_t i = 0; + if (len < 2 || s[0] != '\x1b' || s[1] != '[') return 0; + i = 2; + while (i < len) { + char c = s[i]; + if ((c >= '0' && c <= '9') || c == ';' || c == '?' || c == '"') { + i++; + } else if (c >= 'A' && c <= 'Z') { + return i + 1; + } else if (c >= 'a' && c <= 'z') { + return i + 1; + } else { + break; + } + } + return 0; } /* calculate width of string */ static size_t utf8StrWidth(const char *s, size_t len) { - size_t width = 0; - size_t i = 0; - while (i < len) { - size_t elen = ansiEscapeLen(s + i, len - i); - if (elen > 0) { - i += elen; - continue; - } - size_t clen = 0; - uint32_t cp = utf8DecodeChar(s + i, &clen); - width += utf8CharWidth(cp); - i += clen; - } - return width; + size_t width = 0; + size_t i = 0; + while (i < len) { + size_t elen = ansiEscapeLen(s + i, len - i); + if (elen > 0) { + i += elen; + continue; + } + size_t clen = 0; + uint32_t cp = utf8DecodeChar(s + i, &clen); + width += utf8CharWidth(cp); + i += clen; + } + return width; } /* get single character width */ static int utf8SingleCharWidth(const char *s, size_t len) { - size_t clen = 0; - uint32_t cp = utf8DecodeChar(s, &clen); - (void)len; - return utf8CharWidth(cp); + size_t clen = 0; + uint32_t cp = utf8DecodeChar(s, &clen); + (void)len; + return utf8CharWidth(cp); } static int isUnsupportedTerm(void) { - char *term = getenv("TERM"); - int i; - static char *unsupported[] = {"dumb", "cons25", "emacs", NULL}; - if (term == NULL) return 0; - for (i = 0; unsupported[i]; i++) { - if (strcasecmp(term, unsupported[i]) == 0) - return 1; - } - return 0; + char *term = getenv("TERM"); + int i; + static char *unsupported[] = {"dumb", "cons25", "emacs", NULL}; + if (term == NULL) return 0; + for (i = 0; unsupported[i]; i++) { + if (strcasecmp(term, unsupported[i]) == 0) + return 1; + } + return 0; } static void sigwinchHandler(int sig) { - (void)sig; - winch_received = 1; + (void)sig; + winch_received = 1; } static int enableRawMode(int fd) { - struct termios raw; - struct sigaction sa; - - if (!isatty(STDIN_FILENO)) - return -1; - if (tcgetattr(fd, &orig_termios) == -1) - return -1; - - raw = orig_termios; - raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); - raw.c_oflag &= ~(OPOST); - raw.c_cflag |= (CS8); - raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); - raw.c_cc[VMIN] = 1; - raw.c_cc[VTIME] = 0; - - if (tcsetattr(fd, TCSAFLUSH, &raw) < 0) - return -1; - - rawmode = 1; - - /* register sigwinch handler */ - sa.sa_handler = sigwinchHandler; - sigemptyset(&sa.sa_mask); - sa.sa_flags = 0; - sigaction(SIGWINCH, &sa, &orig_sigwinch); - - return 0; + struct termios raw; + struct sigaction sa; + + if (!isatty(STDIN_FILENO)) + return -1; + if (tcgetattr(fd, &orig_termios) == -1) + return -1; + + raw = orig_termios; + raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); + raw.c_oflag &= ~(OPOST); + raw.c_cflag |= (CS8); + raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); + raw.c_cc[VMIN] = 1; + raw.c_cc[VTIME] = 0; + + if (tcsetattr(fd, TCSAFLUSH, &raw) < 0) + return -1; + + rawmode = 1; + + /* register sigwinch handler */ + sa.sa_handler = sigwinchHandler; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sigaction(SIGWINCH, &sa, &orig_sigwinch); + + return 0; } static void disableRawMode(int fd) { - if (rawmode) { - tcsetattr(fd, TCSAFLUSH, &orig_termios); - sigaction(SIGWINCH, &orig_sigwinch, NULL); - rawmode = 0; - } + if (rawmode) { + tcsetattr(fd, TCSAFLUSH, &orig_termios); + sigaction(SIGWINCH, &orig_sigwinch, NULL); + rawmode = 0; + } } static int getCursorPosition(int ifd, int ofd) { - char buf[32]; - int cols, rows; - unsigned int i = 0; - - if (write(ofd, "\x1b[6n", 4) != 4) return -1; - - while (i < sizeof(buf)-1) { - if (read(ifd,buf+i,1) != 1) break; - if (buf[i] == 'R') break; - i++; - } - buf[i] = '\0'; - - if (buf[0] != 27 || buf[1] != '[') return -1; - if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1; - return cols; + char buf[32]; + int cols, rows; + unsigned int i = 0; + + if (write(ofd, "\x1b[6n", 4) != 4) return -1; + + while (i < sizeof(buf)-1) { + if (read(ifd,buf+i,1) != 1) break; + if (buf[i] == 'R') break; + i++; + } + buf[i] = '\0'; + + if (buf[0] != 27 || buf[1] != '[') return -1; + if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1; + return cols; } static int getColumns(int ifd, int ofd) { - struct winsize ws; - char *cols_env; - int tty_fd; - int cols = 0; - - if (ioctl(ofd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) - return ws.ws_col; - if (ioctl(ifd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) - return ws.ws_col; - if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) - return ws.ws_col; - if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) - return ws.ws_col; - if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) - return ws.ws_col; - - tty_fd = open("/dev/tty", O_RDWR | O_NOCTTY); - if (tty_fd >= 0) { - if (ioctl(tty_fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) { - cols = ws.ws_col; - } - close(tty_fd); - if (cols >= 20) return cols; - } - - cols_env = getenv("COLUMNS"); - if (cols_env) { - cols = atoi(cols_env); - if (cols >= 20) return cols; - } - - /* fallback to cursor position query */ - int start; - - if (!isatty(ifd) || !isatty(ofd)) return 80; - - start = getCursorPosition(ifd,ofd); - if (start == -1) return 80; - - if (write(ofd,"\x1b[999C",6) != 6) return 80; - cols = getCursorPosition(ifd,ofd); - if (cols == -1) return 80; - - if (cols > start) { - char seq[32]; - snprintf(seq,sizeof(seq),"\x1b[%dD",cols-start); - if (write(ofd,seq,strlen(seq)) == -1) {} - } - if (cols < 20) return 80; - return cols; + struct winsize ws; + char *cols_env; + int tty_fd; + int cols = 0; + + if (ioctl(ofd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) + return ws.ws_col; + if (ioctl(ifd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) + return ws.ws_col; + if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) + return ws.ws_col; + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) + return ws.ws_col; + if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) + return ws.ws_col; + + tty_fd = open(ARUU_PATH_DEVTTY, O_RDWR | O_NOCTTY); + if (tty_fd >= 0) { + if (ioctl(tty_fd, TIOCGWINSZ, &ws) == 0 && ws.ws_col >= 20) { + cols = ws.ws_col; + } + close(tty_fd); + if (cols >= 20) return cols; + } + + cols_env = getenv("COLUMNS"); + if (cols_env) { + cols = atoi(cols_env); + if (cols >= 20) return cols; + } + + /* fallback to cursor position query */ + int start; + + if (!isatty(ifd) || !isatty(ofd)) return 80; + + start = getCursorPosition(ifd,ofd); + if (start == -1) return 80; + + if (write(ofd,"\x1b[999C",6) != 6) return 80; + cols = getCursorPosition(ifd,ofd); + if (cols == -1) return 80; + + if (cols > start) { + char seq[32]; + snprintf(seq,sizeof(seq),"\x1b[%dD",cols-start); + if (write(ofd,seq,strlen(seq)) == -1) {} + } + if (cols < 20) return 80; + return cols; } static void redlineBeep(void) { - fprintf(stderr, "\x7"); - fflush(stderr); + fprintf(stderr, "\x7"); + fflush(stderr); } static void freeCompletions(struct redlineCompletions *lc) { - size_t i; - if (lc->cvec) { - for (i = 0; i < lc->len; i++) { - free(lc->cvec[i]); - } - free(lc->cvec); - } + size_t i; + if (lc->cvec) { + for (i = 0; i < lc->len; i++) { + free(lc->cvec[i]); + } + free(lc->cvec); + } } static size_t longestCommonPrefix(struct redlineCompletions *lc) { - size_t i, j; - if (lc->len == 0) return 0; - for (i = 0; ; i++) { - char c = lc->cvec[0][i]; - if (c == '\0') return i; - for (j = 1; j < lc->len; j++) { - if (lc->cvec[j][i] != c) { - return i; - } - } - } + size_t i, j; + if (lc->len == 0) return 0; + for (i = 0; ; i++) { + char c = lc->cvec[0][i]; + if (c == '\0') return i; + for (j = 1; j < lc->len; j++) { + if (lc->cvec[j][i] != c) { + return i; + } + } + } } static void printCompletions(struct redlineState *ls, struct redlineCompletions *lc) { - size_t max_len = 0; - size_t i, j, k; - size_t col_width, num_cols, num_rows; - size_t sp, len, idx; - const char *comp; - const char *name; - - for (i = 0; i < lc->len; i++) { - comp = lc->cvec[i]; - sp = strlen(comp); - if (sp > 0 && comp[sp-1] == ' ') { - sp--; - } - while (sp > 0 && comp[sp-1] != ' ') { - sp--; - } - len = strlen(comp + sp); - if (len > 0 && (comp + sp)[len-1] == ' ') { - len--; - } - if (len > max_len) { - max_len = len; - } - } - - col_width = max_len + 2; - num_cols = ls->cols / col_width; - if (num_cols == 0) num_cols = 1; - num_rows = (lc->len + num_cols - 1) / num_cols; - - if (write(ls->ofd, "\r\n", 2) == -1) {} - for (i = 0; i < num_rows; i++) { - for (j = 0; j < num_cols; j++) { - idx = j * num_rows + i; - if (idx < lc->len) { - comp = lc->cvec[idx]; - sp = strlen(comp); - if (sp > 0 && comp[sp-1] == ' ') { - sp--; - } - while (sp > 0 && comp[sp-1] != ' ') { - sp--; - } - name = comp + sp; - len = strlen(name); - if (len > 0 && name[len-1] == ' ') { - len--; - } - if (write(ls->ofd, name, len) == -1) {} - if (j < num_cols - 1) { - for (k = len; k < col_width; k++) { - if (write(ls->ofd, " ", 1) == -1) {} - } - } - } - } - if (write(ls->ofd, "\r\n", 2) == -1) {} - } + size_t max_len = 0; + size_t i, j, k; + size_t col_width, num_cols, num_rows; + size_t sp, len, idx; + const char *comp; + const char *name; + + for (i = 0; i < lc->len; i++) { + comp = lc->cvec[i]; + sp = strlen(comp); + if (sp > 0 && comp[sp-1] == ' ') { + sp--; + } + while (sp > 0 && comp[sp-1] != ' ') { + sp--; + } + len = strlen(comp + sp); + if (len > 0 && (comp + sp)[len-1] == ' ') { + len--; + } + if (len > max_len) { + max_len = len; + } + } + + col_width = max_len + 2; + num_cols = ls->cols / col_width; + if (num_cols == 0) num_cols = 1; + num_rows = (lc->len + num_cols - 1) / num_cols; + + if (write(ls->ofd, "\r\n", 2) == -1) {} + for (i = 0; i < num_rows; i++) { + for (j = 0; j < num_cols; j++) { + idx = j * num_rows + i; + if (idx < lc->len) { + comp = lc->cvec[idx]; + sp = strlen(comp); + if (sp > 0 && comp[sp-1] == ' ') { + sp--; + } + while (sp > 0 && comp[sp-1] != ' ') { + sp--; + } + name = comp + sp; + len = strlen(name); + if (len > 0 && name[len-1] == ' ') { + len--; + } + if (write(ls->ofd, name, len) == -1) {} + if (j < num_cols - 1) { + for (k = len; k < col_width; k++) { + if (write(ls->ofd, " ", 1) == -1) {} + } + } + } + } + if (write(ls->ofd, "\r\n", 2) == -1) {} + } } static void abInit(struct abuf *ab) { - ab->b = NULL; - ab->len = 0; + ab->b = NULL; + ab->len = 0; } static void abAppend(struct abuf *ab, const char *s, int len) { - char *new = realloc(ab->b,ab->len+len); - if (new == NULL) return; - memcpy(new+ab->len,s,len); - ab->b = new; - ab->len += len; + char *new = realloc(ab->b,ab->len+len); + if (new == NULL) return; + memcpy(new+ab->len,s,len); + ab->b = new; + ab->len += len; } static void abFree(struct abuf *ab) { - free(ab->b); + free(ab->b); } static void refreshSingleLine(struct redlineState *l, int flags) { - char seq[64]; - size_t pwidth = utf8StrWidth(l->prompt, l->plen); - int fd = l->ofd; - char *buf = l->buf; - size_t len = l->len; - size_t pos = l->pos; - size_t poscol; - size_t lencol; - struct abuf ab; - - poscol = utf8StrWidth(buf, pos); - lencol = utf8StrWidth(buf, len); - - while (pwidth + poscol >= l->cols) { - size_t clen = utf8NextCharLen(buf, 0, len); - int cwidth = utf8SingleCharWidth(buf, clen); - buf += clen; - len -= clen; - pos -= clen; - poscol -= cwidth; - lencol -= cwidth; - } - - while (pwidth + lencol > l->cols) { - size_t clen = utf8PrevCharLen(buf, len); - int cwidth = utf8SingleCharWidth(buf + len - clen, clen); - len -= clen; - lencol -= cwidth; - } - - abInit(&ab); - snprintf(seq,sizeof(seq),"\r"); - abAppend(&ab,seq,strlen(seq)); - - if (flags & 1) { - abAppend(&ab,l->prompt,l->plen); - abAppend(&ab,buf,len); - } - - snprintf(seq,sizeof(seq),"\x1b[0K"); - abAppend(&ab,seq,strlen(seq)); - - if (flags & 1) { - snprintf(seq,sizeof(seq),"\r\x1b[%dC", (int)(poscol+pwidth)); - abAppend(&ab,seq,strlen(seq)); - } - - if (write(fd,ab.b,ab.len) == -1) {} - abFree(&ab); + char seq[64]; + size_t pwidth = utf8StrWidth(l->prompt, l->plen); + int fd = l->ofd; + char *buf = l->buf; + size_t len = l->len; + size_t pos = l->pos; + size_t poscol; + size_t lencol; + struct abuf ab; + + poscol = utf8StrWidth(buf, pos); + lencol = utf8StrWidth(buf, len); + + while (pwidth + poscol >= l->cols) { + size_t clen = utf8NextCharLen(buf, 0, len); + int cwidth = utf8SingleCharWidth(buf, clen); + buf += clen; + len -= clen; + pos -= clen; + poscol -= cwidth; + lencol -= cwidth; + } + + while (pwidth + lencol > l->cols) { + size_t clen = utf8PrevCharLen(buf, len); + int cwidth = utf8SingleCharWidth(buf + len - clen, clen); + len -= clen; + lencol -= cwidth; + } + + abInit(&ab); + snprintf(seq,sizeof(seq),"\r"); + abAppend(&ab,seq,strlen(seq)); + + if (flags & 1) { + abAppend(&ab,l->prompt,l->plen); + abAppend(&ab,buf,len); + } + + snprintf(seq,sizeof(seq),"\x1b[0K"); + abAppend(&ab,seq,strlen(seq)); + + if (flags & 1) { + snprintf(seq,sizeof(seq),"\r\x1b[%dC", (int)(poscol+pwidth)); + abAppend(&ab,seq,strlen(seq)); + } + + if (write(fd,ab.b,ab.len) == -1) {} + abFree(&ab); } static void refreshMultiLine(struct redlineState *l, int flags) { - char seq[64]; - size_t pwidth = utf8StrWidth(l->prompt, l->plen); - size_t bufwidth; - size_t poswidth; - int rows; - int rpos2; - int col; - int old_rows = l->oldrows; - int rpos = l->oldrpos; - int fd = l->ofd, j; - struct abuf ab; - - (void)flags; - - bufwidth = utf8StrWidth(l->buf, l->len); - poswidth = utf8StrWidth(l->buf, l->pos); - rows = (pwidth+bufwidth+l->cols-1)/l->cols; - l->oldrows = rows; - - abInit(&ab); - - /* move cursor up to the first row, column 0 of the input area */ - if (rpos > 1) { - snprintf(seq, 64, "\r\x1b[%dA", rpos - 1); - abAppend(&ab, seq, strlen(seq)); - } else { - abAppend(&ab, "\r", 1); - } - - /* clear all old rows */ - for (j = 0; j < old_rows; j++) { - abAppend(&ab, "\x1b[0K", 4); - if (j < old_rows - 1) { - abAppend(&ab, "\n\r", 2); - } - } - - /* move cursor back to the first row, column 0 */ - if (old_rows > 1) { - snprintf(seq, 64, "\r\x1b[%dA", old_rows - 1); - abAppend(&ab, seq, strlen(seq)); - } else { - abAppend(&ab, "\r", 1); - } - - /* print prompt and new buffer */ - abAppend(&ab, l->prompt, l->plen); - abAppend(&ab, l->buf, l->len); - - /* if cursor is at the end of the line and wraps, print a newline */ - if (l->pos && l->pos == l->len && (poswidth+pwidth) % l->cols == 0) { - abAppend(&ab, "\n\r", 2); - rows++; - if (rows > (int)l->oldrows) l->oldrows = rows; - } - - /* calculate cursor row and column */ - rpos2 = (pwidth+poswidth+l->cols)/l->cols; - col = (pwidth+poswidth) % l->cols; - - /* move cursor to the correct row and column */ - if (rows - rpos2 > 0) { - snprintf(seq, 64, "\x1b[%dA", rows - rpos2); - abAppend(&ab, seq, strlen(seq)); - } - if (col) { - snprintf(seq, 64, "\r\x1b[%dC", col); - abAppend(&ab, seq, strlen(seq)); - } else { - abAppend(&ab, "\r", 1); - } - - l->oldpos = l->pos; - l->oldrpos = rpos2; - - if (write(fd, ab.b, ab.len) == -1) {} - abFree(&ab); + char seq[64]; + size_t pwidth = utf8StrWidth(l->prompt, l->plen); + size_t bufwidth; + size_t poswidth; + int rows; + int rpos2; + int col; + int old_rows = l->oldrows; + int rpos = l->oldrpos; + int fd = l->ofd, j; + struct abuf ab; + + (void)flags; + + bufwidth = utf8StrWidth(l->buf, l->len); + poswidth = utf8StrWidth(l->buf, l->pos); + rows = (pwidth+bufwidth+l->cols-1)/l->cols; + l->oldrows = rows; + + abInit(&ab); + + /* move cursor up to the first row, column 0 of the input area */ + if (rpos > 1) { + snprintf(seq, 64, "\r\x1b[%dA", rpos - 1); + abAppend(&ab, seq, strlen(seq)); + } else { + abAppend(&ab, "\r", 1); + } + + /* clear all old rows */ + for (j = 0; j < old_rows; j++) { + abAppend(&ab, "\x1b[0K", 4); + if (j < old_rows - 1) { + abAppend(&ab, "\n\r", 2); + } + } + + /* move cursor back to the first row, column 0 */ + if (old_rows > 1) { + snprintf(seq, 64, "\r\x1b[%dA", old_rows - 1); + abAppend(&ab, seq, strlen(seq)); + } else { + abAppend(&ab, "\r", 1); + } + + /* print prompt and new buffer */ + abAppend(&ab, l->prompt, l->plen); + abAppend(&ab, l->buf, l->len); + + /* if cursor is at the end of the line and wraps, print a newline */ + if (l->pos && l->pos == l->len && (poswidth+pwidth) % l->cols == 0) { + abAppend(&ab, "\n\r", 2); + rows++; + if (rows > (int)l->oldrows) l->oldrows = rows; + } + + /* calculate cursor row and column */ + rpos2 = (pwidth+poswidth+l->cols)/l->cols; + col = (pwidth+poswidth) % l->cols; + + /* move cursor to the correct row and column */ + if (rows - rpos2 > 0) { + snprintf(seq, 64, "\x1b[%dA", rows - rpos2); + abAppend(&ab, seq, strlen(seq)); + } + if (col) { + snprintf(seq, 64, "\r\x1b[%dC", col); + abAppend(&ab, seq, strlen(seq)); + } else { + abAppend(&ab, "\r", 1); + } + + l->oldpos = l->pos; + l->oldrpos = rpos2; + + if (write(fd, ab.b, ab.len) == -1) {} + abFree(&ab); } static void refreshLineWithFlags(struct redlineState *l, int flags) { - if (mlmode) - refreshMultiLine(l,flags); - else - refreshSingleLine(l,flags); + if (mlmode) + refreshMultiLine(l,flags); + else + refreshSingleLine(l,flags); } static void refreshLine(struct redlineState *l) { - refreshLineWithFlags(l, 1); + refreshLineWithFlags(l, 1); } static int completeLine(struct redlineState *ls, int keypressed) { - struct redlineCompletions lc = { 0, NULL }; - size_t lcp_len; - int c = keypressed; - int proceed = 1; - char query[128]; - char answer = 0; - - if (c != 9) { - ls->in_completion = 0; - return c; - } - - completionCallback(ls->buf, &lc); - if (lc.len == 0) { - redlineBeep(); - ls->in_completion = 0; - c = 0; - } else if (lc.len == 1) { - size_t nwritten = snprintf(ls->buf, ls->buflen, "%s", lc.cvec[0]); - ls->len = ls->pos = nwritten; - refreshLine(ls); - ls->in_completion = 0; - c = 0; - } else { - lcp_len = longestCommonPrefix(&lc); - if (lcp_len > ls->len) { - size_t nwritten = snprintf(ls->buf, ls->buflen, "%.*s", (int)lcp_len, lc.cvec[0]); - ls->len = ls->pos = nwritten; - refreshLine(ls); - ls->in_completion = 1; - c = 0; - } else { - /* prefix cannot be expanded further */ - if (ls->in_completion == 0) { - /* first tab: beep and wait for the second tab */ - redlineBeep(); - ls->in_completion = 1; - c = 0; - } else { - /* second tab: display possibilities */ - if (lc.len > 100) { - snprintf(query, sizeof(query), "\r\nDisplay all %d possibilities? (y or n) ", (int)lc.len); - if (write(ls->ofd, query, strlen(query)) == -1) {} - while (1) { - if (read(ls->ifd, &answer, 1) != 1) { - proceed = 0; - break; - } - if (answer == 'y' || answer == 'Y' || answer == ' ' || answer == '\t') { - proceed = 1; - break; - } - if (answer == 'n' || answer == 'N' || answer == 27 || answer == 3 || answer == 4) { - proceed = 0; - break; - } - redlineBeep(); - } - } - if (proceed) { - printCompletions(ls, &lc); - } else { - if (write(ls->ofd, "\r\n", 2) == -1) {} - } - ls->oldrows = 0; - refreshLine(ls); - ls->in_completion = 0; - c = 0; - } - } - } - - freeCompletions(&lc); - return c; + struct redlineCompletions lc = { 0, NULL }; + size_t lcp_len; + int c = keypressed; + int proceed = 1; + char query[128]; + char answer = 0; + + if (c != 9) { + ls->in_completion = 0; + return c; + } + + completionCallback(ls->buf, &lc); + if (lc.len == 0) { + redlineBeep(); + ls->in_completion = 0; + c = 0; + } else if (lc.len == 1) { + size_t nwritten = snprintf(ls->buf, ls->buflen, "%s", lc.cvec[0]); + ls->len = ls->pos = nwritten; + refreshLine(ls); + ls->in_completion = 0; + c = 0; + } else { + lcp_len = longestCommonPrefix(&lc); + if (lcp_len > ls->len) { + size_t nwritten = snprintf(ls->buf, ls->buflen, "%.*s", (int)lcp_len, lc.cvec[0]); + ls->len = ls->pos = nwritten; + refreshLine(ls); + ls->in_completion = 1; + c = 0; + } else { + /* prefix cannot be expanded further */ + if (ls->in_completion == 0) { + /* first tab: beep and wait for the second tab */ + redlineBeep(); + ls->in_completion = 1; + c = 0; + } else { + /* second tab: display possibilities */ + if (lc.len > 100) { + snprintf(query, sizeof(query), "\r\nDisplay all %d possibilities? (y or n) ", (int)lc.len); + if (write(ls->ofd, query, strlen(query)) == -1) {} + while (1) { + if (read(ls->ifd, &answer, 1) != 1) { + proceed = 0; + break; + } + if (answer == 'y' || answer == 'Y' || answer == ' ' || answer == '\t') { + proceed = 1; + break; + } + if (answer == 'n' || answer == 'N' || answer == 27 || answer == 3 || answer == 4) { + proceed = 0; + break; + } + redlineBeep(); + } + } + if (proceed) { + printCompletions(ls, &lc); + } else { + if (write(ls->ofd, "\r\n", 2) == -1) {} + } + ls->oldrows = 0; + refreshLine(ls); + ls->in_completion = 0; + c = 0; + } + } + } + + freeCompletions(&lc); + return c; } static int redlineEditInsert(struct redlineState *l, const char *c, int clen) { - if (l->len + clen >= l->buflen) { - return 0; - } - if (l->len == l->pos) { - memcpy(l->buf + l->pos, c, clen); - l->pos += clen; - l->len += clen; - l->buf[l->len] = '\0'; - refreshLine(l); - } else { - memmove(l->buf + l->pos + clen, l->buf + l->pos, l->len - l->pos); - memcpy(l->buf + l->pos, c, clen); - l->pos += clen; - l->len += clen; - l->buf[l->len] = '\0'; - refreshLine(l); - } - return 1; + if (l->len + clen >= l->buflen) { + return 0; + } + if (l->len == l->pos) { + memcpy(l->buf + l->pos, c, clen); + l->pos += clen; + l->len += clen; + l->buf[l->len] = '\0'; + refreshLine(l); + } else { + memmove(l->buf + l->pos + clen, l->buf + l->pos, l->len - l->pos); + memcpy(l->buf + l->pos, c, clen); + l->pos += clen; + l->len += clen; + l->buf[l->len] = '\0'; + refreshLine(l); + } + return 1; } static void redlineEditBackspace(struct redlineState *l) { - if (l->pos > 0 && l->len > 0) { - size_t clen = utf8PrevCharLen(l->buf, l->pos); - memmove(l->buf+l->pos-clen, l->buf+l->pos, l->len-l->pos); - l->pos -= clen; - l->len -= clen; - l->buf[l->len] = '\0'; - refreshLine(l); - } + if (l->pos > 0 && l->len > 0) { + size_t clen = utf8PrevCharLen(l->buf, l->pos); + memmove(l->buf+l->pos-clen, l->buf+l->pos, l->len-l->pos); + l->pos -= clen; + l->len -= clen; + l->buf[l->len] = '\0'; + refreshLine(l); + } } static void redlineEditDelete(struct redlineState *l) { - if (l->len > 0 && l->pos < l->len) { - size_t clen = utf8NextCharLen(l->buf, l->pos, l->len); - memmove(l->buf+l->pos, l->buf+l->pos+clen, l->len-l->pos-clen); - l->len -= clen; - l->buf[l->len] = '\0'; - refreshLine(l); - } + if (l->len > 0 && l->pos < l->len) { + size_t clen = utf8NextCharLen(l->buf, l->pos, l->len); + memmove(l->buf+l->pos, l->buf+l->pos+clen, l->len-l->pos-clen); + l->len -= clen; + l->buf[l->len] = '\0'; + refreshLine(l); + } } static void redlineEditMoveLeft(struct redlineState *l) { - if (l->pos > 0) { - l->pos -= utf8PrevCharLen(l->buf, l->pos); - refreshLine(l); - } + if (l->pos > 0) { + l->pos -= utf8PrevCharLen(l->buf, l->pos); + refreshLine(l); + } } static void redlineEditMoveRight(struct redlineState *l) { - if (l->pos != l->len) { - l->pos += utf8NextCharLen(l->buf, l->pos, l->len); - refreshLine(l); - } + if (l->pos != l->len) { + l->pos += utf8NextCharLen(l->buf, l->pos, l->len); + refreshLine(l); + } } static void redlineEditMoveHome(struct redlineState *l) { - if (l->pos != 0) { - l->pos = 0; - refreshLine(l); - } + if (l->pos != 0) { + l->pos = 0; + refreshLine(l); + } } static void redlineEditMoveEnd(struct redlineState *l) { - if (l->pos != l->len) { - l->pos = l->len; - refreshLine(l); - } + if (l->pos != l->len) { + l->pos = l->len; + refreshLine(l); + } } static void redlineEditMoveWordLeft(struct redlineState *l) { - if (l->pos > 0) { - while (l->pos > 0 && l->buf[l->pos-1] == ' ') - l->pos -= utf8PrevCharLen(l->buf, l->pos); - while (l->pos > 0 && l->buf[l->pos-1] != ' ') - l->pos -= utf8PrevCharLen(l->buf, l->pos); - refreshLine(l); - } + if (l->pos > 0) { + while (l->pos > 0 && l->buf[l->pos-1] == ' ') + l->pos -= utf8PrevCharLen(l->buf, l->pos); + while (l->pos > 0 && l->buf[l->pos-1] != ' ') + l->pos -= utf8PrevCharLen(l->buf, l->pos); + refreshLine(l); + } } static void redlineEditMoveWordRight(struct redlineState *l) { - if (l->pos < l->len) { - while (l->pos < l->len && l->buf[l->pos] == ' ') - l->pos += utf8NextCharLen(l->buf, l->pos, l->len); - while (l->pos < l->len && l->buf[l->pos] != ' ') - l->pos += utf8NextCharLen(l->buf, l->pos, l->len); - refreshLine(l); - } + if (l->pos < l->len) { + while (l->pos < l->len && l->buf[l->pos] == ' ') + l->pos += utf8NextCharLen(l->buf, l->pos, l->len); + while (l->pos < l->len && l->buf[l->pos] != ' ') + l->pos += utf8NextCharLen(l->buf, l->pos, l->len); + refreshLine(l); + } } static void killBufferSave(const char *text, size_t len) { - free(kill_buffer); - kill_buffer = malloc(len + 1); - if (kill_buffer) { - memcpy(kill_buffer, text, len); - kill_buffer[len] = '\0'; - } + free(kill_buffer); + kill_buffer = malloc(len + 1); + if (kill_buffer) { + memcpy(kill_buffer, text, len); + kill_buffer[len] = '\0'; + } } static void redlineEditDeleteWordRight(struct redlineState *l) { - size_t old_pos = l->pos; - size_t diff; - if (l->pos < l->len) { - while (l->pos < l->len && l->buf[l->pos] == ' ') - l->pos += utf8NextCharLen(l->buf, l->pos, l->len); - while (l->pos < l->len && l->buf[l->pos] != ' ') - l->pos += utf8NextCharLen(l->buf, l->pos, l->len); - diff = l->pos - old_pos; - l->pos = old_pos; - killBufferSave(l->buf + l->pos, diff); - memmove(l->buf + l->pos, l->buf + l->pos + diff, l->len - l->pos - diff + 1); - l->len -= diff; - refreshLine(l); - } + size_t old_pos = l->pos; + size_t diff; + if (l->pos < l->len) { + while (l->pos < l->len && l->buf[l->pos] == ' ') + l->pos += utf8NextCharLen(l->buf, l->pos, l->len); + while (l->pos < l->len && l->buf[l->pos] != ' ') + l->pos += utf8NextCharLen(l->buf, l->pos, l->len); + diff = l->pos - old_pos; + l->pos = old_pos; + killBufferSave(l->buf + l->pos, diff); + memmove(l->buf + l->pos, l->buf + l->pos + diff, l->len - l->pos - diff + 1); + l->len -= diff; + refreshLine(l); + } } static void redlineEditDeletePrevWord(struct redlineState *l) { - size_t old_pos = l->pos; - size_t diff; - if (l->pos > 0) { - while (l->pos > 0 && l->buf[l->pos-1] == ' ') - l->pos -= utf8PrevCharLen(l->buf, l->pos); - while (l->pos > 0 && l->buf[l->pos-1] != ' ') - l->pos -= utf8PrevCharLen(l->buf, l->pos); - diff = old_pos - l->pos; - killBufferSave(l->buf + l->pos, diff); - memmove(l->buf + l->pos, l->buf + old_pos, l->len - old_pos + 1); - l->len -= diff; - refreshLine(l); - } + size_t old_pos = l->pos; + size_t diff; + if (l->pos > 0) { + while (l->pos > 0 && l->buf[l->pos-1] == ' ') + l->pos -= utf8PrevCharLen(l->buf, l->pos); + while (l->pos > 0 && l->buf[l->pos-1] != ' ') + l->pos -= utf8PrevCharLen(l->buf, l->pos); + diff = old_pos - l->pos; + killBufferSave(l->buf + l->pos, diff); + memmove(l->buf + l->pos, l->buf + old_pos, l->len - old_pos + 1); + l->len -= diff; + refreshLine(l); + } } void redlineHistoryAdd(const char *line) { - char *linecopy; - if (history_max_len == 0) return; - if (history == NULL) { - history = malloc(sizeof(char*) * history_max_len); - if (history == NULL) return; - memset(history,0,sizeof(char*)*history_max_len); - } - if (history_len && strcmp(history[history_len-1], line) == 0) return; - linecopy = strdup(line); - if (!linecopy) return; - if (history_len == history_max_len) { - free(history[0]); - memmove(history,history+1,sizeof(char*)*(history_max_len-1)); - history_len--; - } - history[history_len] = linecopy; - history_len++; + char *linecopy; + if (history_max_len == 0) return; + if (history == NULL) { + history = malloc(sizeof(char*) * history_max_len); + if (history == NULL) return; + memset(history,0,sizeof(char*)*history_max_len); + } + if (history_len && strcmp(history[history_len-1], line) == 0) return; + linecopy = strdup(line); + if (!linecopy) return; + if (history_len == history_max_len) { + free(history[0]); + memmove(history,history+1,sizeof(char*)*(history_max_len-1)); + history_len--; + } + history[history_len] = linecopy; + history_len++; } void redlineHistorySetMaxLen(int len) { - char **new; - if (len < 1) return; - if (history) { - int tocopy = history_len; - new = malloc(sizeof(char*)*len); - if (new == NULL) return; - if (len < tocopy) { - int j; - for (j = 0; j < tocopy-len; j++) free(history[j]); - tocopy = len; - } - memset(new,0,sizeof(char*)*len); - memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy); - free(history); - history = new; - } - history_max_len = len; - if (history_len > history_max_len) - history_len = history_max_len; + char **new; + if (len < 1) return; + if (history) { + int tocopy = history_len; + new = malloc(sizeof(char*)*len); + if (new == NULL) return; + if (len < tocopy) { + int j; + for (j = 0; j < tocopy-len; j++) free(history[j]); + tocopy = len; + } + memset(new,0,sizeof(char*)*len); + memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy); + free(history); + history = new; + } + history_max_len = len; + if (history_len > history_max_len) + history_len = history_max_len; } int redlineHistorySave(const char *filename) { - mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO); - FILE *fp; - int j; - - fp = fopen(filename,"w"); - umask(old_umask); - if (fp == NULL) return -1; - chmod(filename,S_IRUSR|S_IWUSR); - for (j = 0; j < history_len; j++) { - fprintf(fp,"%s\n",history[j]); - } - fclose(fp); - return 0; + mode_t old_umask = umask(S_IXUSR|S_IRWXG|S_IRWXO); + FILE *fp; + int j; + + fp = fopen(filename,"w"); + umask(old_umask); + if (fp == NULL) return -1; + chmod(filename,S_IRUSR|S_IWUSR); + for (j = 0; j < history_len; j++) { + fprintf(fp,"%s\n",history[j]); + } + fclose(fp); + return 0; } int redlineHistoryLoad(const char *filename) { - FILE *fp = fopen(filename,"r"); - char buf[REDLINE_INITIAL_BUFLEN]; - if (fp == NULL) return -1; - while (fgets(buf,sizeof(buf),fp) != NULL) { - char *p = strchr(buf,'\r'); - if (!p) p = strchr(buf,'\n'); - if (p) *p = '\0'; - redlineHistoryAdd(buf); - } - fclose(fp); - return 0; + FILE *fp = fopen(filename,"r"); + char buf[REDLINE_INITIAL_BUFLEN]; + if (fp == NULL) return -1; + while (fgets(buf,sizeof(buf),fp) != NULL) { + char *p = strchr(buf,'\r'); + if (!p) p = strchr(buf,'\n'); + if (p) *p = '\0'; + redlineHistoryAdd(buf); + } + fclose(fp); + return 0; } char * redlineHistoryGet(int idx) { - if (idx >= 0 && idx < history_len) - return history[idx]; - return NULL; + if (idx >= 0 && idx < history_len) + return history[idx]; + return NULL; } int redlineHistoryLen(void) { - return history_len; + return history_len; } static void redlineEditHistoryNext(struct redlineState *l, int dir) { - if (history_len > 1) { - const char *src; - size_t len; - free(history[history_len - 1 - l->history_index]); - history[history_len - 1 - l->history_index] = strdup(l->buf); - l->history_index += (dir == 1) ? 1 : -1; - if (l->history_index < 0) { - l->history_index = 0; - return; - } else if (l->history_index >= history_len) { - l->history_index = history_len - 1; - return; - } - src = history[history_len - 1 - l->history_index]; - len = strlen(src); - if (len >= l->buflen) len = l->buflen - 1; - memcpy(l->buf, src, len); - l->buf[len] = '\0'; - l->len = l->pos = len; - refreshLine(l); - } + if (history_len > 1) { + const char *src; + size_t len; + free(history[history_len - 1 - l->history_index]); + history[history_len - 1 - l->history_index] = strdup(l->buf); + l->history_index += (dir == 1) ? 1 : -1; + if (l->history_index < 0) { + l->history_index = 0; + return; + } else if (l->history_index >= history_len) { + l->history_index = history_len - 1; + return; + } + src = history[history_len - 1 - l->history_index]; + len = strlen(src); + if (len >= l->buflen) len = l->buflen - 1; + memcpy(l->buf, src, len); + l->buf[len] = '\0'; + l->len = l->pos = len; + refreshLine(l); + } } static char * redlineReadLine(FILE *fp) { - char *line = NULL; - size_t len = 0, cap = 0; - while (1) { - if (len+1 >= cap) { - size_t newcap = cap ? cap*2 : 16; - char *new = realloc(line, newcap); - if (!new) { - free(line); - return NULL; - } - line = new; - cap = newcap; - } - int c = fgetc(fp); - if (c == EOF || c == '\n') { - if (c == EOF && len == 0) { - free(line); - return NULL; - } - line[len] = '\0'; - return line; - } - line[len++] = c; - } + char *line = NULL; + size_t len = 0, cap = 0; + while (1) { + if (len+1 >= cap) { + size_t newcap = cap ? cap*2 : 16; + char *new = realloc(line, newcap); + if (!new) { + free(line); + return NULL; + } + line = new; + cap = newcap; + } + int c = fgetc(fp); + if (c == EOF || c == '\n') { + if (c == EOF && len == 0) { + free(line); + return NULL; + } + line[len] = '\0'; + return line; + } + line[len++] = c; + } } static char * redlineNoTTY(void) { - return redlineReadLine(stdin); + return redlineReadLine(stdin); } void redlineClearScreen(void) { - if (write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7) == -1) {} + if (write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7) == -1) {} } static char * redlineEditFeed(struct redlineState *l) { - char c; - int nread; - char seq[3]; - char param[8]; - size_t plen; - char final; - char p; - int is_word_jump; - char tmp[32]; - size_t prevlen; - size_t currlen; - size_t prevstart; - char utf8[4]; - int utf8len; - int i; - - if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return redlineNoTTY(); - - while (1) { - nread = read(l->ifd, &c, 1); - if (nread < 0) { - if (errno == EINTR) { - if (winch_received) { - winch_received = 0; - l->cols = getColumns(l->ifd, l->ofd); - refreshLine(l); - } - continue; - } - return (errno == EAGAIN || errno == EWOULDBLOCK) ? "more" : NULL; - } else if (nread == 0) { - return NULL; - } - break; - } - - if ((l->in_completion || c == 9) && completionCallback != NULL) { - int retval = completeLine(l, c); - if (retval == 0) return "more"; - c = retval; - } - - switch (c) { - case ENTER: - if (mlmode) redlineEditMoveEnd(l); - return strdup(l->buf); - case CTRL_C: - errno = EAGAIN; - return NULL; - case BACKSPACE: - case 8: - redlineEditBackspace(l); - break; - case CTRL_D: - if (l->len > 0) { - redlineEditDelete(l); - } else { - errno = ENOENT; - return NULL; - } - break; - case CTRL_T: - if (l->pos > 0 && l->pos < l->len) { - prevlen = utf8PrevCharLen(l->buf, l->pos); - currlen = utf8NextCharLen(l->buf, l->pos, l->len); - prevstart = l->pos - prevlen; - if (prevlen > sizeof(tmp) || currlen > sizeof(tmp)) break; - memcpy(tmp, l->buf + l->pos, currlen); - memmove(l->buf + prevstart + currlen, l->buf + prevstart, prevlen); - memcpy(l->buf + prevstart, tmp, currlen); - if (l->pos + currlen <= l->len) l->pos += currlen; - refreshLine(l); - } - break; - case CTRL_B: - redlineEditMoveLeft(l); - break; - case CTRL_F: - redlineEditMoveRight(l); - break; - case CTRL_P: - redlineEditHistoryNext(l, 1); - break; - case CTRL_N: - redlineEditHistoryNext(l, 0); - break; - case ESC: - if (read(l->ifd, seq, 1) == -1) break; - if (seq[0] == '[' || seq[0] == 'O') { - if (read(l->ifd, seq+1, 1) == -1) break; - if (seq[0] == '[') { - if (seq[1] >= '0' && seq[1] <= '9') { - plen = 1; - final = 0; - param[0] = seq[1]; - while (plen < sizeof(param)) { - if (read(l->ifd, &p, 1) != 1) break; - if ((p >= '0' && p <= '9') || p == ';') { - param[plen++] = p; - } else { - final = p; - break; - } - } - if (final == '~') { - if (plen == 1 && param[0] == '3') { - redlineEditDelete(l); - } - } else if (final == 'D' || final == 'C') { - is_word_jump = 0; - if (plen == 3 && param[0] == '1' && param[1] == ';' && (param[2] == '5' || param[2] == '3')) { - is_word_jump = 1; - } else if (plen == 1 && (param[0] == '5' || param[0] == '3')) { - is_word_jump = 1; - } - if (is_word_jump) { - if (final == 'D') { - redlineEditMoveWordLeft(l); - } else { - redlineEditMoveWordRight(l); - } - } - } - } else { - switch (seq[1]) { - case 'A': - redlineEditHistoryNext(l, 1); - break; - case 'B': - redlineEditHistoryNext(l, 0); - break; - case 'C': - redlineEditMoveRight(l); - break; - case 'D': - redlineEditMoveLeft(l); - break; - case 'H': - redlineEditMoveHome(l); - break; - case 'F': - redlineEditMoveEnd(l); - break; - } - } - } else if (seq[0] == 'O') { - switch (seq[1]) { - case 'H': - redlineEditMoveHome(l); - break; - case 'F': - redlineEditMoveEnd(l); - break; - } - } - } else { - if (seq[0] == 'b' || seq[0] == 'B') { - redlineEditMoveWordLeft(l); - } else if (seq[0] == 'f' || seq[0] == 'F') { - redlineEditMoveWordRight(l); - } else if (seq[0] == 'd' || seq[0] == 'D') { - redlineEditDeleteWordRight(l); - } else if (seq[0] == 127 || seq[0] == 8) { - redlineEditDeletePrevWord(l); - } - } - break; - default: - utf8len = utf8ByteLen(c); - utf8[0] = c; - if (utf8len > 1) { - for (i = 1; i < utf8len; i++) { - if (read(l->ifd, utf8+i, 1) != 1) break; - } - } - if (redlineEditInsert(l, utf8, utf8len) == 0) return NULL; - break; - case CTRL_U: - killBufferSave(l->buf, l->pos); - memmove(l->buf, l->buf + l->pos, l->len - l->pos + 1); - l->len -= l->pos; - l->pos = 0; - refreshLine(l); - break; - case CTRL_K: - killBufferSave(l->buf + l->pos, l->len - l->pos); - l->buf[l->pos] = '\0'; - l->len = l->pos; - refreshLine(l); - break; - case CTRL_A: - redlineEditMoveHome(l); - break; - case CTRL_E: - redlineEditMoveEnd(l); - break; - case CTRL_L: - redlineClearScreen(); - refreshLine(l); - break; - case CTRL_W: - redlineEditDeletePrevWord(l); - break; - case CTRL_Y: - if (kill_buffer) { - redlineEditInsert(l, kill_buffer, strlen(kill_buffer)); - } - break; - } - return "more"; + char c; + int nread; + char seq[3]; + char param[8]; + size_t plen; + char final; + char p; + int is_word_jump; + char tmp[32]; + size_t prevlen; + size_t currlen; + size_t prevstart; + char utf8[4]; + int utf8len; + int i; + + if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return redlineNoTTY(); + + while (1) { + nread = read(l->ifd, &c, 1); + if (nread < 0) { + if (errno == EINTR) { + if (winch_received) { + winch_received = 0; + l->cols = getColumns(l->ifd, l->ofd); + refreshLine(l); + } + continue; + } + return (errno == EAGAIN || errno == EWOULDBLOCK) ? "more" : NULL; + } else if (nread == 0) { + return NULL; + } + break; + } + + if ((l->in_completion || c == 9) && completionCallback != NULL) { + int retval = completeLine(l, c); + if (retval == 0) return "more"; + c = retval; + } + + switch (c) { + case ENTER: + if (mlmode) redlineEditMoveEnd(l); + return strdup(l->buf); + case CTRL_C: + errno = EAGAIN; + return NULL; + case BACKSPACE: + case 8: + redlineEditBackspace(l); + break; + case CTRL_D: + if (l->len > 0) { + redlineEditDelete(l); + } else { + errno = ENOENT; + return NULL; + } + break; + case CTRL_T: + if (l->pos > 0 && l->pos < l->len) { + prevlen = utf8PrevCharLen(l->buf, l->pos); + currlen = utf8NextCharLen(l->buf, l->pos, l->len); + prevstart = l->pos - prevlen; + if (prevlen > sizeof(tmp) || currlen > sizeof(tmp)) break; + memcpy(tmp, l->buf + l->pos, currlen); + memmove(l->buf + prevstart + currlen, l->buf + prevstart, prevlen); + memcpy(l->buf + prevstart, tmp, currlen); + if (l->pos + currlen <= l->len) l->pos += currlen; + refreshLine(l); + } + break; + case CTRL_B: + redlineEditMoveLeft(l); + break; + case CTRL_F: + redlineEditMoveRight(l); + break; + case CTRL_P: + redlineEditHistoryNext(l, 1); + break; + case CTRL_N: + redlineEditHistoryNext(l, 0); + break; + case ESC: + if (read(l->ifd, seq, 1) == -1) break; + if (seq[0] == '[' || seq[0] == 'O') { + if (read(l->ifd, seq+1, 1) == -1) break; + if (seq[0] == '[') { + if (seq[1] >= '0' && seq[1] <= '9') { + plen = 1; + final = 0; + param[0] = seq[1]; + while (plen < sizeof(param)) { + if (read(l->ifd, &p, 1) != 1) break; + if ((p >= '0' && p <= '9') || p == ';') { + param[plen++] = p; + } else { + final = p; + break; + } + } + if (final == '~') { + if (plen == 1 && param[0] == '3') { + redlineEditDelete(l); + } + } else if (final == 'D' || final == 'C') { + is_word_jump = 0; + if (plen == 3 && param[0] == '1' && param[1] == ';' && (param[2] == '5' || param[2] == '3')) { + is_word_jump = 1; + } else if (plen == 1 && (param[0] == '5' || param[0] == '3')) { + is_word_jump = 1; + } + if (is_word_jump) { + if (final == 'D') { + redlineEditMoveWordLeft(l); + } else { + redlineEditMoveWordRight(l); + } + } + } + } else { + switch (seq[1]) { + case 'A': + redlineEditHistoryNext(l, 1); + break; + case 'B': + redlineEditHistoryNext(l, 0); + break; + case 'C': + redlineEditMoveRight(l); + break; + case 'D': + redlineEditMoveLeft(l); + break; + case 'H': + redlineEditMoveHome(l); + break; + case 'F': + redlineEditMoveEnd(l); + break; + } + } + } else if (seq[0] == 'O') { + switch (seq[1]) { + case 'H': + redlineEditMoveHome(l); + break; + case 'F': + redlineEditMoveEnd(l); + break; + } + } + } else { + if (seq[0] == 'b' || seq[0] == 'B') { + redlineEditMoveWordLeft(l); + } else if (seq[0] == 'f' || seq[0] == 'F') { + redlineEditMoveWordRight(l); + } else if (seq[0] == 'd' || seq[0] == 'D') { + redlineEditDeleteWordRight(l); + } else if (seq[0] == 127 || seq[0] == 8) { + redlineEditDeletePrevWord(l); + } + } + break; + default: + utf8len = utf8ByteLen(c); + utf8[0] = c; + if (utf8len > 1) { + for (i = 1; i < utf8len; i++) { + if (read(l->ifd, utf8+i, 1) != 1) break; + } + } + if (redlineEditInsert(l, utf8, utf8len) == 0) return NULL; + break; + case CTRL_U: + killBufferSave(l->buf, l->pos); + memmove(l->buf, l->buf + l->pos, l->len - l->pos + 1); + l->len -= l->pos; + l->pos = 0; + refreshLine(l); + break; + case CTRL_K: + killBufferSave(l->buf + l->pos, l->len - l->pos); + l->buf[l->pos] = '\0'; + l->len = l->pos; + refreshLine(l); + break; + case CTRL_A: + redlineEditMoveHome(l); + break; + case CTRL_E: + redlineEditMoveEnd(l); + break; + case CTRL_L: + redlineClearScreen(); + refreshLine(l); + break; + case CTRL_W: + redlineEditDeletePrevWord(l); + break; + case CTRL_Y: + if (kill_buffer) { + redlineEditInsert(l, kill_buffer, strlen(kill_buffer)); + } + break; + } + return "more"; } static int redlineEditStart(struct redlineState *l, int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt) { - l->in_completion = 0; - l->ifd = stdin_fd; - l->ofd = stdout_fd; - l->buf = buf; - l->buflen = buflen; - l->prompt = prompt; - l->plen = strlen(prompt); - l->pos = 0; - l->oldpos = 0; - l->len = 0; - l->cols = getColumns(stdin_fd, stdout_fd); - l->oldrows = 0; - l->oldrpos = 0; - l->history_index = 0; - l->buf[0] = '\0'; - - if (enableRawMode(l->ifd) == -1) return -1; - refreshLine(l); - return 0; + l->in_completion = 0; + l->ifd = stdin_fd; + l->ofd = stdout_fd; + l->buf = buf; + l->buflen = buflen; + l->prompt = prompt; + l->plen = strlen(prompt); + l->pos = 0; + l->oldpos = 0; + l->len = 0; + l->cols = getColumns(stdin_fd, stdout_fd); + l->oldrows = 0; + l->oldrpos = 0; + l->history_index = 0; + l->buf[0] = '\0'; + + if (enableRawMode(l->ifd) == -1) return -1; + refreshLine(l); + return 0; } static void redlineEditStop(struct redlineState *l) { - if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return; - disableRawMode(l->ifd); - printf("\n"); + if (!isatty(l->ifd) && !getenv("REDLINE_ASSUME_TTY")) return; + disableRawMode(l->ifd); + printf("\n"); } char * redline(const char *prompt) { - struct redlineState l; - char *buf; - char *res; - - if (!isatty(STDIN_FILENO) || isUnsupportedTerm()) { - if (write(STDOUT_FILENO, prompt, strlen(prompt)) == -1) {} - return redlineNoTTY(); - } - - buf = malloc(REDLINE_INITIAL_BUFLEN); - if (buf == NULL) return NULL; - if (redlineEditStart(&l, STDIN_FILENO, STDOUT_FILENO, buf, REDLINE_INITIAL_BUFLEN, prompt) == -1) { - free(buf); - return NULL; - } - redlineHistoryAdd(""); - while (1) { - res = redlineEditFeed(&l); - if (res == NULL || strcmp(res, "more") != 0) { - break; - } - } - redlineEditStop(&l); - if (history_len > 0) { - history_len--; - free(history[history_len]); - } - free(l.buf); - return res; + struct redlineState l; + char *buf; + char *res; + + if (!isatty(STDIN_FILENO) || isUnsupportedTerm()) { + if (write(STDOUT_FILENO, prompt, strlen(prompt)) == -1) {} + return redlineNoTTY(); + } + + buf = malloc(REDLINE_INITIAL_BUFLEN); + if (buf == NULL) return NULL; + if (redlineEditStart(&l, STDIN_FILENO, STDOUT_FILENO, buf, REDLINE_INITIAL_BUFLEN, prompt) == -1) { + free(buf); + return NULL; + } + redlineHistoryAdd(""); + while (1) { + res = redlineEditFeed(&l); + if (res == NULL || strcmp(res, "more") != 0) { + break; + } + } + redlineEditStop(&l); + if (history_len > 0) { + history_len--; + free(history[history_len]); + } + free(l.buf); + return res; } void redlineSetCompletionCallback(void (*cb)(const char *, struct redlineCompletions *)) { - completionCallback = cb; + completionCallback = cb; } void redlineAddCompletion(struct redlineCompletions *lc, const char *str) { - size_t len = strlen(str); - char *copy, **cvec; - - copy = malloc(len+1); - if (copy == NULL) return; - memcpy(copy,str,len+1); - cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1)); - if (cvec == NULL) { - free(copy); - return; - } - lc->cvec = cvec; - lc->cvec[lc->len++] = copy; + size_t len = strlen(str); + char *copy, **cvec; + + copy = malloc(len+1); + if (copy == NULL) return; + memcpy(copy,str,len+1); + cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1)); + if (cvec == NULL) { + free(copy); + return; + } + lc->cvec = cvec; + lc->cvec[lc->len++] = copy; } void redlineSetMultiLine(int ml) { - mlmode = ml; + mlmode = ml; } diff --git a/shared/libutil/diffutil.c b/shared/libutil/diffutil.c @@ -0,0 +1,586 @@ +/* See LICENSE file for copyright and license details. */ +#include "../diffutil.h" +#include "../text.h" +#include "../util.h" + +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static int +read_all(FILE *fp, char **out, size_t *outlen, const char *path) +{ + char buf[8192]; + char *data; + size_t cap, len; + ssize_t n; + + data = NULL; + cap = len = 0; + while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { + if (len + (size_t)n > cap) { + cap = (len + (size_t)n) * 2 + 64; + data = erealloc(data, cap); + } + memcpy(data + len, buf, (size_t)n); + len += (size_t)n; + } + if (ferror(fp)) { + weprintf("read %s:", path); + free(data); + return -1; + } + if (!data) { + data = emalloc(1); + data[0] = '\0'; + } else if (len == cap) { + data = erealloc(data, cap + 1); + data[len] = '\0'; + } + *out = data; + *outlen = len; + return 0; +} + +static void +split_lines(struct diffline **out, size_t *outn, char *data, size_t len) +{ + struct diffline *lines; + size_t i, n, start; + + n = 0; + for (i = 0; i < len; i++) + if (data[i] == '\n') + n++; + if (len > 0 && (len == 0 || data[len - 1] != '\n')) + n++; + if (n == 0) { + *out = NULL; + *outn = 0; + return; + } + lines = ecalloc(n, sizeof(*lines)); + i = 0; + start = 0; + for (n = 0; n < (size_t)len; n++) { + if (data[n] == '\n') { + lines[i].data = data + start; + lines[i].len = n - start; + i++; + start = n + 1; + } + } + if (start < len) { + lines[i].data = data + start; + lines[i].len = len - start; + i++; + } + *out = lines; + *outn = i; +} + +int +diff_load(struct difffile *df, const char *path) +{ + FILE *fp; + char *data; + size_t len; + + if (!strcmp(path, "-")) { + fp = stdin; + } else if (!(fp = fopen(path, "r"))) { + weprintf("open %s:", path); + return -1; + } + if (read_all(fp, &data, &len, path) < 0) { + if (fp != stdin) + fclose(fp); + return -1; + } + if (fp != stdin) + fclose(fp); + df->lines = NULL; + df->nlines = 0; + if (len == 0) { + df->lines = ecalloc(1, sizeof(*df->lines)); + df->lines[0].data = data; + df->lines[0].len = 0; + df->nlines = 0; + return 0; + } + split_lines(&df->lines, &df->nlines, data, len); + { + struct diffline *grown; + grown = erealloc(df->lines, (df->nlines + 1) * sizeof(*grown)); + grown[df->nlines].data = data; + grown[df->nlines].len = 0; + df->lines = grown; + } + return 0; +} + +void +diff_free(struct difffile *df) +{ + char *base; + + if (!df->lines) + return; + if (df->nlines == 0) { + free(df->lines[0].data); + free(df->lines); + df->lines = NULL; + df->nlines = 0; + return; + } + base = df->lines[df->nlines].data; + free(base); + free(df->lines); + df->lines = NULL; + df->nlines = 0; +} + +static int +lines_equal(const struct diffline *a, const struct diffline *b, + const struct diffopts *opts) +{ + size_t i, j; + + if (opts && opts->ignore_blanks) { + i = j = 0; + while (i < a->len && j < b->len) { + while (i < a->len && isspace((unsigned char)a->data[i])) + i++; + while (j < b->len && isspace((unsigned char)b->data[j])) + j++; + if (i >= a->len || j >= b->len) + break; + if (opts->ignore_case) { + if (tolower((unsigned char)a->data[i]) != + tolower((unsigned char)b->data[j])) + return 0; + } else if (a->data[i] != b->data[j]) { + return 0; + } + i++; + j++; + } + while (i < a->len && isspace((unsigned char)a->data[i])) + i++; + while (j < b->len && isspace((unsigned char)b->data[j])) + j++; + return i == a->len && j == b->len; + } + + if (opts && opts->ignore_case) { + if (a->len != b->len) + return 0; + for (i = 0; i < a->len; i++) { + if (tolower((unsigned char)a->data[i]) != + tolower((unsigned char)b->data[i])) + return 0; + } + return 1; + } + + if (a->len != b->len) + return 0; + return memcmp(a->data, b->data, a->len) == 0; +} + +struct lcs_cell { + int diag; + int up; + int left; +}; + +int +diff_compute(struct diffhunks *hunks, const struct difffile *old, + const struct difffile *new, const struct diffopts *opts) +{ + struct lcs_cell *c; + size_t n, m, i, j, k, cap; + struct diffhunk *h; + int *xs, *ys; + size_t hfrom, hto, vfrom, vto; + struct diffopts default_opts; + + if (!opts) { + memset(&default_opts, 0, sizeof(default_opts)); + default_opts.context = 3; + opts = &default_opts; + } + + n = old->nlines; + m = new->nlines; + + if (n == 0 && m == 0) { + hunks->v = NULL; + hunks->n = 0; + return 0; + } + + c = ecalloc((n + 1) * (m + 1), sizeof(*c)); + for (i = 0; i <= n; i++) { + for (j = 0; j <= m; j++) { + if (i == 0 && j == 0) { + c[i * (m + 1) + j].diag = 0; + continue; + } + if (i > 0 && j > 0 && + lines_equal(&old->lines[i - 1], &new->lines[j - 1], opts)) { + c[i * (m + 1) + j].diag = c[(i - 1) * (m + 1) + (j - 1)].diag + 1; + c[i * (m + 1) + j].up = 0; + c[i * (m + 1) + j].left = 0; + continue; + } + if (i > 0 && (j == 0 || c[(i - 1) * (m + 1) + j].diag >= + c[i * (m + 1) + (j - 1)].diag)) { + c[i * (m + 1) + j].diag = c[(i - 1) * (m + 1) + j].diag; + c[i * (m + 1) + j].up = 1; + c[i * (m + 1) + j].left = 0; + } else { + c[i * (m + 1) + j].diag = c[i * (m + 1) + (j - 1)].diag; + c[i * (m + 1) + j].up = 0; + c[i * (m + 1) + j].left = 1; + } + } + } + + cap = n + m + 16; + xs = ecalloc(cap, sizeof(*xs)); + ys = ecalloc(cap, sizeof(*ys)); + k = 0; + i = n; + j = m; + while (i > 0 || j > 0) { + if (i > 0 && j > 0 && + lines_equal(&old->lines[i - 1], &new->lines[j - 1], opts)) { + xs[k] = 0; + ys[k] = 0; + i--; + j--; + } else if (i > 0 && c[i * (m + 1) + j].up) { + xs[k] = 1; + ys[k] = 0; + i--; + } else { + xs[k] = 0; + ys[k] = 2; + j--; + } + k++; + } + hunks->v = NULL; + hunks->n = 0; + h = NULL; + i = 0; + j = 0; + { + size_t step, idx; + int op; + step = k; + while (step > 0) { + idx = step - 1; + op = xs[idx] | ys[idx]; + if (op == 0) { + step--; + i++; + j++; + continue; + } + hfrom = i; + vfrom = j; + hto = i; + vto = j; + while (step > 0) { + idx = step - 1; + op = xs[idx] | ys[idx]; + if (op == 0) + break; + if (xs[idx] == 1) + hto++; + if (ys[idx] == 2) + vto++; + step--; + } + i = hto; + j = vto; + hunks->v = erealloc(hunks->v, (hunks->n + 1) * sizeof(*h)); + h = &hunks->v[hunks->n]; + h->old.from = hfrom; + h->old.to = hto; + h->new.from = vfrom; + h->new.to = vto; + hunks->n++; + } + } + free(c); + free(xs); + free(ys); + return 0; +} + +void +diff_hunks_free(struct diffhunks *hunks) +{ + if (!hunks) + return; + free(hunks->v); + hunks->v = NULL; + hunks->n = 0; +} + +int +diff_looks_binary(const struct difffile *df) +{ + size_t i, scan; + + scan = 4096; + for (i = 0; i < df->nlines && scan > 0; i++) { + size_t take = df->lines[i].len < scan ? df->lines[i].len : scan; + if (memchr(df->lines[i].data, '\0', take)) + return 1; + scan -= take; + } + return 0; +} + +static void +print_range(FILE *out, size_t from, size_t to) +{ + if (to - from <= 1) + fprintf(out, "%zu", from + 1); + else + fprintf(out, "%zu,%zu", from + 1, to); +} + +static void +print_lines(FILE *out, const struct diffline *lines, size_t from, size_t to, + char prefix) +{ + size_t i; + for (i = from; i < to; i++) { + fputc(prefix, out); + fwrite(lines[i].data, 1, lines[i].len, out); + fputc('\n', out); + } +} + +static int +format_normal(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new) +{ + size_t i; + for (i = 0; i < hunks->n; i++) { + struct diffhunk *h = &hunks->v[i]; + size_t oldn = h->old.to - h->old.from; + size_t newn = h->new.to - h->new.from; + char oc; + + oc = oldn == 0 ? 'a' : (newn == 0 ? 'd' : 'c'); + print_range(out, h->old.from, h->old.to); + fputc(oc, out); + print_range(out, h->new.from, h->new.to); + fputc('\n', out); + if (oldn && newn) { + print_lines(out, old->lines, h->old.from, h->old.to, '<'); + fprintf(out, "---\n"); + print_lines(out, new->lines, h->new.from, h->new.to, '>'); + } else if (oldn) { + print_lines(out, old->lines, h->old.from, h->old.to, '<'); + } else { + print_lines(out, new->lines, h->new.from, h->new.to, '>'); + } + } + return 0; +} + +static void +emit_unified_hunk(FILE *out, const struct diffhunk *h, + const struct difffile *old, const struct difffile *new, + size_t ctx) +{ + size_t oldfrom, oldto, newfrom, newto; + size_t i; + + oldfrom = h->old.from < ctx ? 0 : h->old.from - ctx; + oldto = h->old.to + ctx; + if (oldto > old->nlines) + oldto = old->nlines; + newfrom = h->new.from < ctx ? 0 : h->new.from - ctx; + newto = h->new.to + ctx; + if (newto > new->nlines) + newto = new->nlines; + + if (oldto - oldfrom <= 1) + fprintf(out, "@@ -%zu +%zu,%zu @@\n", oldfrom + 1, newfrom + 1, + newto - newfrom); + else if (newto - newfrom <= 1) + fprintf(out, "@@ -%zu,%zu +%zu @@\n", oldfrom + 1, oldto - oldfrom, + newfrom + 1); + else + fprintf(out, "@@ -%zu,%zu +%zu,%zu @@\n", oldfrom + 1, + oldto - oldfrom, newfrom + 1, newto - newfrom); + + for (i = oldfrom; i < h->old.from; i++) { + fputc(' ', out); + fwrite(old->lines[i].data, 1, old->lines[i].len, out); + fputc('\n', out); + } + print_lines(out, old->lines, h->old.from, h->old.to, '-'); + print_lines(out, new->lines, h->new.from, h->new.to, '+'); + for (i = h->old.to; i < oldto; i++) { + fputc(' ', out); + fwrite(old->lines[i].data, 1, old->lines[i].len, out); + fputc('\n', out); + } +} + +static int +format_unified(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new, + const char *oldlabel, const char *newlabel, size_t ctx) +{ + size_t i; + if (oldlabel) + fprintf(out, "--- %s\n", oldlabel); + if (newlabel) + fprintf(out, "+++ %s\n", newlabel); + for (i = 0; i < hunks->n; i++) + emit_unified_hunk(out, &hunks->v[i], old, new, ctx); + return 0; +} + +static void +emit_context_hunk(FILE *out, const struct diffhunk *h, + const struct difffile *old, const struct difffile *new, + size_t ctx) +{ + size_t oldfrom, oldto, newfrom, newto; + size_t i; + + oldfrom = h->old.from < ctx ? 0 : h->old.from - ctx; + oldto = h->old.to + ctx; + if (oldto > old->nlines) + oldto = old->nlines; + newfrom = h->new.from < ctx ? 0 : h->new.from - ctx; + newto = h->new.to + ctx; + if (newto > new->nlines) + newto = new->nlines; + + fprintf(out, "***************\n"); + if (oldto - oldfrom <= 1) + fprintf(out, "*** %zu ****\n", oldfrom + 1); + else + fprintf(out, "*** %zu,%zu ****\n", oldfrom + 1, oldto - oldfrom); + for (i = oldfrom; i < h->old.from; i++) { + fputc(' ', out); + fwrite(old->lines[i].data, 1, old->lines[i].len, out); + fputc('\n', out); + } + print_lines(out, old->lines, h->old.from, h->old.to, '-'); + for (i = h->old.to; i < oldto; i++) { + fputc(' ', out); + fwrite(old->lines[i].data, 1, old->lines[i].len, out); + fputc('\n', out); + } + if (newto - newfrom <= 1) + fprintf(out, "--- %zu ----\n", newfrom + 1); + else + fprintf(out, "--- %zu,%zu ----\n", newfrom + 1, newto - newfrom); + for (i = newfrom; i < h->new.from; i++) { + fputc(' ', out); + fwrite(new->lines[i].data, 1, new->lines[i].len, out); + fputc('\n', out); + } + print_lines(out, new->lines, h->new.from, h->new.to, '+'); + for (i = h->new.to; i < newto; i++) { + fputc(' ', out); + fwrite(new->lines[i].data, 1, new->lines[i].len, out); + fputc('\n', out); + } +} + +static int +format_context(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new, + const char *oldlabel, const char *newlabel, size_t ctx) +{ + size_t i; + if (oldlabel) + fprintf(out, "*** %s\n", oldlabel); + if (newlabel) + fprintf(out, "--- %s\n", newlabel); + for (i = 0; i < hunks->n; i++) + emit_context_hunk(out, &hunks->v[i], old, new, ctx); + return 0; +} + +static int +format_ed(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new) +{ + size_t i; + (void)old; + for (i = 0; i < hunks->n; i++) { + struct diffhunk *h = &hunks->v[i]; + size_t oldn = h->old.to - h->old.from; + size_t newn = h->new.to - h->new.from; + char op; + + op = oldn == 0 ? 'a' : (newn == 0 ? 'd' : 'c'); + print_range(out, h->old.from, h->old.to); + fputc(op, out); + fputc('\n', out); + if (op == 'a' || op == 'c') { + size_t j; + for (j = h->new.from; j < h->new.to; j++) { + if (new->lines[j].len == 1 && new->lines[j].data[0] == '.') + fprintf(out, "..\n"); + else if (new->lines[j].len == 0) + fprintf(out, ".\n"); + else { + fwrite(new->lines[j].data, 1, new->lines[j].len, out); + fputc('\n', out); + } + } + fprintf(out, ".\n"); + } + } + return 0; +} + +int +diff_format(FILE *out, const struct diffhunks *hunks, + const struct difffile *old, const struct difffile *new, + const char *oldlabel, const char *newlabel, + const struct diffopts *opts) +{ + struct diffopts default_opts; + size_t ctx; + + if (!opts) { + memset(&default_opts, 0, sizeof(default_opts)); + default_opts.context = 3; + opts = &default_opts; + } + ctx = opts->context ? opts->context : 3; + switch (opts->format) { + case DIFF_NORMAL: + return format_normal(out, hunks, old, new); + case DIFF_UNIFIED: + return format_unified(out, hunks, old, new, oldlabel, newlabel, ctx); + case DIFF_CONTEXT: + return format_context(out, hunks, old, new, oldlabel, newlabel, ctx); + case DIFF_ED: + case DIFF_RCSED: + return format_ed(out, hunks, old, new); + case DIFF_BRIEF: + if (hunks->n > 0) + return 1; + return 0; + } + return 0; +} diff --git a/shared/libutil/diskutil.c b/shared/libutil/diskutil.c @@ -31,711 +31,714 @@ int blockdev_open(struct BlockDev *dev, const char *path, int writable) { - struct stat st; - int fd, flags; + struct stat st; + int fd, flags; - flags = writable ? O_RDWR : O_RDONLY; - fd = open(path, flags); - if (fd < 0) - return -1; + flags = writable ? O_RDWR : O_RDONLY; + fd = open(path, flags); + if (fd < 0) + return -1; - if (fstat(fd, &st) < 0) { - close(fd); - return -1; - } + if (fstat(fd, &st) < 0) { + close(fd); + return -1; + } - dev->fd = fd; - dev->size = st.st_size; - dev->sec_size = 512; + dev->fd = fd; + dev->size = st.st_size; + dev->sec_size = 512; - if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) { + if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) { #if defined(__linux__) - uint64_t size_bytes = 0; - int sec_size = 0; - if (ioctl(fd, BLKGETSIZE64, &size_bytes) >= 0) - dev->size = size_bytes; - if (ioctl(fd, BLKSSZGET, &sec_size) >= 0) - dev->sec_size = sec_size; + uint64_t size_bytes = 0; + int sec_size = 0; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Woverflow" + if (ioctl(fd, BLKGETSIZE64, &size_bytes) >= 0) + dev->size = size_bytes; + if (ioctl(fd, BLKSSZGET, &sec_size) >= 0) + dev->sec_size = sec_size; +#pragma GCC diagnostic pop #elif defined(__FreeBSD__) - off_t size_bytes = 0; - unsigned int sec_size = 0; - if (ioctl(fd, DIOCGMEDIASIZE, &size_bytes) >= 0) - dev->size = size_bytes; - if (ioctl(fd, DIOCGSECTORSIZE, &sec_size) >= 0) - dev->sec_size = sec_size; + off_t size_bytes = 0; + unsigned int sec_size = 0; + if (ioctl(fd, DIOCGMEDIASIZE, &size_bytes) >= 0) + dev->size = size_bytes; + if (ioctl(fd, DIOCGSECTORSIZE, &sec_size) >= 0) + dev->sec_size = sec_size; #elif defined(__OpenBSD__) || defined(__NetBSD__) - struct disklabel dl; - if (ioctl(fd, DIOCGDINFO, &dl) >= 0) { - dev->size = (uint64_t)dl.d_secsize * DL_GETDSIZE(&dl); - dev->sec_size = dl.d_secsize; - } + struct disklabel dl; + if (ioctl(fd, DIOCGDINFO, &dl) >= 0) { + dev->size = (uint64_t)dl.d_secsize * DL_GETDSIZE(&dl); + dev->sec_size = dl.d_secsize; + } #endif - } + } - return 0; + return 0; } int blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf, size_t sector_count) { - off_t offset = (off_t)sector * dev->sec_size; - size_t size = sector_count * dev->sec_size; - ssize_t n; + off_t offset = (off_t)sector * dev->sec_size; + size_t size = sector_count * dev->sec_size; + ssize_t n; - if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) - return -1; + if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) + return -1; - n = read(dev->fd, buf, size); - if (n < 0 || (size_t)n != size) - return -1; + n = read(dev->fd, buf, size); + if (n < 0 || (size_t)n != size) + return -1; - return 0; + return 0; } int blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf, size_t sector_count) { - off_t offset = (off_t)sector * dev->sec_size; - size_t size = sector_count * dev->sec_size; - ssize_t n; + off_t offset = (off_t)sector * dev->sec_size; + size_t size = sector_count * dev->sec_size; + ssize_t n; - if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) - return -1; + if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) + return -1; - n = write(dev->fd, buf, size); - if (n < 0 || (size_t)n != size) - return -1; + n = write(dev->fd, buf, size); + if (n < 0 || (size_t)n != size) + return -1; - return 0; + return 0; } void blockdev_close(struct BlockDev *dev) { - if (dev->fd >= 0) { - close(dev->fd); - dev->fd = -1; - } + if (dev->fd >= 0) { + close(dev->fd); + dev->fd = -1; + } } struct BlockDevInfo * blockdev_get_list(void) { #if defined(__linux__) - FILE *fp; - FILE *mfile; - char line[256]; - char mline[512]; - char devpath[128]; - char mnt[256]; - char fs[64]; - struct BlockDevInfo *head = NULL; - struct BlockDevInfo *tail = NULL; - struct BlockDevInfo *info; - struct BlockDevInfo *curr; - unsigned int major, minor; - unsigned long long blocks; - char name[64]; - int is_part; - - fp = fopen(PATH_PARTITIONS, "r"); - if (!fp) - return NULL; - - while (fgets(line, sizeof(line), fp)) { - if (sscanf(line, " %u %u %llu %63s", &major, &minor, &blocks, name) != 4) - continue; - - info = ecalloc(1, sizeof(*info)); - - strlcpy(info->name, name, sizeof(info->name)); - snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, name); - info->size = blocks * 1024; - info->major = major; - info->minor = minor; - - /* search tree topology to link partition node under proper target parent disk */ - is_part = 0; - for (curr = head; curr; curr = curr->next) { - size_t len = strlen(curr->name); - if (strncmp(name, curr->name, len) == 0) { - char c = name[len]; - if (curr->name[len - 1] >= '0' && curr->name[len - 1] <= '9') { - if (c == 'p' && name[len + 1] >= '0' && name[len + 1] <= '9') - is_part = 1; - } else { - if (c >= '0' && c <= '9') - is_part = 1; - } - if (is_part) { - strlcpy(info->type, "part", sizeof(info->type)); - struct BlockDevInfo *p = curr->parts; - if (!p) { - curr->parts = info; - } else { - while (p->next) - p = p->next; - p->next = info; - } - break; - } - } - } - - if (!is_part) { - strlcpy(info->type, "disk", sizeof(info->type)); - if (!head) { - head = info; - } else { - tail->next = info; - } - tail = info; - } - } - fclose(fp); - - mfile = fopen(PATH_MOUNTS, "r"); - if (mfile) { - while (fgets(mline, sizeof(mline), mfile)) { - if (sscanf(mline, "%127s %255s %63s", devpath, mnt, fs) == 3) { - char *devname = devpath; - size_t dev_len = strlen(PATH_DEV); - if (strncmp(devpath, PATH_DEV, dev_len) == 0 && devpath[dev_len] == '/') - devname = devpath + dev_len + 1; - struct BlockDevInfo *curr; - for (curr = head; curr; curr = curr->next) { - if (strcmp(curr->name, devname) == 0) { - strlcpy(curr->mountpoint, mnt, sizeof(curr->mountpoint)); - strlcpy(curr->fstype, fs, sizeof(curr->fstype)); - } - struct BlockDevInfo *part; - for (part = curr->parts; part; part = part->next) { - if (strcmp(part->name, devname) == 0) { - strlcpy(part->mountpoint, mnt, sizeof(part->mountpoint)); - strlcpy(part->fstype, fs, sizeof(part->fstype)); - } - } - } - } - } - fclose(mfile); - } - - return head; + FILE *fp; + FILE *mfile; + char line[256]; + char mline[512]; + char devpath[128]; + char mnt[256]; + char fs[64]; + struct BlockDevInfo *head = NULL; + struct BlockDevInfo *tail = NULL; + struct BlockDevInfo *info; + struct BlockDevInfo *curr; + unsigned int major, minor; + unsigned long long blocks; + char name[64]; + int is_part; + + fp = fopen(ARUU_LINUX_PATH_PROC_PARTITIONS, "r"); + if (!fp) + return NULL; + + while (fgets(line, sizeof(line), fp)) { + if (sscanf(line, " %u %u %llu %63s", &major, &minor, &blocks, name) != 4) + continue; + + info = ecalloc(1, sizeof(*info)); + + strlcpy(info->name, name, sizeof(info->name)); + snprintf(info->path, sizeof(info->path), "%s/%s", ARUU_PATH_DEV, name); + info->size = blocks * 1024; + info->major = major; + info->minor = minor; + + /* search tree topology to link partition node under proper target parent disk */ + is_part = 0; + for (curr = head; curr; curr = curr->next) { + size_t len = strlen(curr->name); + if (strncmp(name, curr->name, len) == 0) { + char c = name[len]; + if (curr->name[len - 1] >= '0' && curr->name[len - 1] <= '9') { + if (c == 'p' && name[len + 1] >= '0' && name[len + 1] <= '9') + is_part = 1; + } else { + if (c >= '0' && c <= '9') + is_part = 1; + } + if (is_part) { + strlcpy(info->type, "part", sizeof(info->type)); + struct BlockDevInfo *p = curr->parts; + if (!p) { + curr->parts = info; + } else { + while (p->next) + p = p->next; + p->next = info; + } + break; + } + } + } + + if (!is_part) { + strlcpy(info->type, "disk", sizeof(info->type)); + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + } + fclose(fp); + + mfile = fopen(ARUU_LINUX_PATH_PROC_MOUNTS, "r"); + if (mfile) { + while (fgets(mline, sizeof(mline), mfile)) { + if (sscanf(mline, "%127s %255s %63s", devpath, mnt, fs) == 3) { + char *devname = devpath; + size_t dev_len = strlen(ARUU_PATH_DEV); + if (strncmp(devpath, ARUU_PATH_DEV, dev_len) == 0 && devpath[dev_len] == '/') + devname = devpath + dev_len + 1; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mnt, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, fs, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mnt, sizeof(part->mountpoint)); + strlcpy(part->fstype, fs, sizeof(part->fstype)); + } + } + } + } + } + fclose(mfile); + } + + return head; #elif defined(__FreeBSD__) - char disks[1024]; - char devpath[128]; - char *tok; - char *ptr; - struct BlockDevInfo *head = NULL; - struct BlockDevInfo *tail = NULL; - struct BlockDevInfo *info; - struct BlockDevInfo *part; - struct BlockDevInfo *p; - struct BlockDev dev; - DIR *dir; - struct dirent *de; - size_t disk_len; - size_t len; - struct statfs *mntbuf; - int mntsize; - int i; - - len = sizeof(disks); - if (sysctlbyname("kern.disks", disks, &len, NULL, 0) < 0) - return NULL; - - ptr = disks; - while ((tok = strsep(&ptr, " \t")) != NULL) { - if (!*tok) - continue; - - info = ecalloc(1, sizeof(*info)); - - strlcpy(info->name, tok, sizeof(info->name)); - snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, tok); - strlcpy(info->type, "disk", sizeof(info->type)); - - snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, tok); - if (blockdev_open(&dev, devpath, 0) == 0) { - info->size = dev.size; - blockdev_close(&dev); - } - - dir = opendir(PATH_DEV); - if (dir) { - disk_len = strlen(tok); - while ((de = readdir(dir)) != NULL) { - if (strncmp(de->d_name, tok, disk_len) == 0) { - char c = de->d_name[disk_len]; - if (c == 's' || c == 'p') { - part = ecalloc(1, sizeof(*part)); - strlcpy(part->name, de->d_name, sizeof(part->name)); - snprintf(part->path, sizeof(part->path), "%s/%s", PATH_DEV, de->d_name); - strlcpy(part->type, "part", sizeof(part->type)); - snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, de->d_name); - if (blockdev_open(&dev, devpath, 0) == 0) { - part->size = dev.size; - blockdev_close(&dev); - } - p = info->parts; - if (!p) { - info->parts = part; - } else { - while (p->next) - p = p->next; - p->next = part; - } - } - } - } - closedir(dir); - } - - if (!head) { - head = info; - } else { - tail->next = info; - } - tail = info; - } - - mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); - for (i = 0; i < mntsize; i++) { - char *frompath = mntbuf[i].f_mntfromname; - char *devname = frompath; - size_t dev_len = strlen(PATH_DEV); - if (strncmp(frompath, PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/') - devname = frompath + dev_len + 1; - struct BlockDevInfo *curr; - for (curr = head; curr; curr = curr->next) { - if (strcmp(curr->name, devname) == 0) { - strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); - strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); - } - struct BlockDevInfo *part; - for (part = curr->parts; part; part = part->next) { - if (strcmp(part->name, devname) == 0) { - strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); - strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); - } - } - } - } - - return head; + char disks[1024]; + char devpath[128]; + char *tok; + char *ptr; + struct BlockDevInfo *head = NULL; + struct BlockDevInfo *tail = NULL; + struct BlockDevInfo *info; + struct BlockDevInfo *part; + struct BlockDevInfo *p; + struct BlockDev dev; + DIR *dir; + struct dirent *de; + size_t disk_len; + size_t len; + struct statfs *mntbuf; + int mntsize; + int i; + + len = sizeof(disks); + if (sysctlbyname("kern.disks", disks, &len, NULL, 0) < 0) + return NULL; + + ptr = disks; + while ((tok = strsep(&ptr, " \t")) != NULL) { + if (!*tok) + continue; + + info = ecalloc(1, sizeof(*info)); + + strlcpy(info->name, tok, sizeof(info->name)); + snprintf(info->path, sizeof(info->path), "%s/%s", ARUU_PATH_DEV, tok); + strlcpy(info->type, "disk", sizeof(info->type)); + + snprintf(devpath, sizeof(devpath), "%s/%s", ARUU_PATH_DEV, tok); + if (blockdev_open(&dev, devpath, 0) == 0) { + info->size = dev.size; + blockdev_close(&dev); + } + + dir = opendir(ARUU_PATH_DEV); + if (dir) { + disk_len = strlen(tok); + while ((de = readdir(dir)) != NULL) { + if (strncmp(de->d_name, tok, disk_len) == 0) { + char c = de->d_name[disk_len]; + if (c == 's' || c == 'p') { + part = ecalloc(1, sizeof(*part)); + strlcpy(part->name, de->d_name, sizeof(part->name)); + snprintf(part->path, sizeof(part->path), "%s/%s", ARUU_PATH_DEV, de->d_name); + strlcpy(part->type, "part", sizeof(part->type)); + snprintf(devpath, sizeof(devpath), "%s/%s", ARUU_PATH_DEV, de->d_name); + if (blockdev_open(&dev, devpath, 0) == 0) { + part->size = dev.size; + blockdev_close(&dev); + } + p = info->parts; + if (!p) { + info->parts = part; + } else { + while (p->next) + p = p->next; + p->next = part; + } + } + } + } + closedir(dir); + } + + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + + mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + for (i = 0; i < mntsize; i++) { + char *frompath = mntbuf[i].f_mntfromname; + char *devname = frompath; + size_t dev_len = strlen(ARUU_PATH_DEV); + if (strncmp(frompath, ARUU_PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/') + devname = frompath + dev_len + 1; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); + strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); + } + } + } + } + + return head; #elif defined(__OpenBSD__) - char disknames[1024]; - char devpath[128]; - char *tok; - char *ptr; - char *colon; - struct BlockDevInfo *head = NULL; - struct BlockDevInfo *tail = NULL; - struct BlockDevInfo *info; - struct BlockDevInfo *part; - struct BlockDevInfo *p; - struct BlockDev dev; - size_t len; - int mib[2]; - char c; - struct statfs *mntbuf; - int mntsize; - int i; - - mib[0] = CTL_HW; - mib[1] = HW_DISKNAMES; - len = sizeof(disknames); - if (sysctl(mib, 2, disknames, &len, NULL, 0) < 0) - return NULL; - - ptr = disknames; - while ((tok = strsep(&ptr, ",")) != NULL) { - colon = strchr(tok, ':'); - if (colon) - *colon = '\0'; - if (!*tok) - continue; - - info = ecalloc(1, sizeof(*info)); - - strlcpy(info->name, tok, sizeof(info->name)); - snprintf(info->path, sizeof(info->path), "%s/r%sc", PATH_DEV, tok); - strlcpy(info->type, "disk", sizeof(info->type)); - - snprintf(devpath, sizeof(devpath), "%s/r%sc", PATH_DEV, tok); - if (blockdev_open(&dev, devpath, 0) == 0) { - info->size = dev.size; - blockdev_close(&dev); - } - - for (c = 'a'; c <= 'p'; c++) { - if (c == 'c') - continue; - snprintf(devpath, sizeof(devpath), "%s/r%s%c", PATH_DEV, tok, c); - if (blockdev_open(&dev, devpath, 0) == 0) { - part = ecalloc(1, sizeof(*part)); - snprintf(part->name, sizeof(part->name), "%s%c", tok, c); - snprintf(part->path, sizeof(part->path), "%s/r%s%c", PATH_DEV, tok, c); - strlcpy(part->type, "part", sizeof(part->type)); - part->size = dev.size; - p = info->parts; - if (!p) { - info->parts = part; - } else { - while (p->next) - p = p->next; - p->next = part; - } - blockdev_close(&dev); - } - } - - if (!head) { - head = info; - } else { - tail->next = info; - } - tail = info; - } - - mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); - for (i = 0; i < mntsize; i++) { - char *frompath = mntbuf[i].f_mntfromname; - char *devname = frompath; - size_t dev_len = strlen(PATH_DEV); - if (strncmp(frompath, PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/') - devname = frompath + dev_len + 1; - struct BlockDevInfo *curr; - for (curr = head; curr; curr = curr->next) { - if (strcmp(curr->name, devname) == 0) { - strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); - strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); - } - struct BlockDevInfo *part; - for (part = curr->parts; part; part = part->next) { - if (strcmp(part->name, devname) == 0) { - strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); - strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); - } - } - } - } - - return head; + char disknames[1024]; + char devpath[128]; + char *tok; + char *ptr; + char *colon; + struct BlockDevInfo *head = NULL; + struct BlockDevInfo *tail = NULL; + struct BlockDevInfo *info; + struct BlockDevInfo *part; + struct BlockDevInfo *p; + struct BlockDev dev; + size_t len; + int mib[2]; + char c; + struct statfs *mntbuf; + int mntsize; + int i; + + mib[0] = CTL_HW; + mib[1] = HW_DISKNAMES; + len = sizeof(disknames); + if (sysctl(mib, 2, disknames, &len, NULL, 0) < 0) + return NULL; + + ptr = disknames; + while ((tok = strsep(&ptr, ",")) != NULL) { + colon = strchr(tok, ':'); + if (colon) + *colon = '\0'; + if (!*tok) + continue; + + info = ecalloc(1, sizeof(*info)); + + strlcpy(info->name, tok, sizeof(info->name)); + snprintf(info->path, sizeof(info->path), "%s/r%sc", ARUU_PATH_DEV, tok); + strlcpy(info->type, "disk", sizeof(info->type)); + + snprintf(devpath, sizeof(devpath), "%s/r%sc", ARUU_PATH_DEV, tok); + if (blockdev_open(&dev, devpath, 0) == 0) { + info->size = dev.size; + blockdev_close(&dev); + } + + for (c = 'a'; c <= 'p'; c++) { + if (c == 'c') + continue; + snprintf(devpath, sizeof(devpath), "%s/r%s%c", ARUU_PATH_DEV, tok, c); + if (blockdev_open(&dev, devpath, 0) == 0) { + part = ecalloc(1, sizeof(*part)); + snprintf(part->name, sizeof(part->name), "%s%c", tok, c); + snprintf(part->path, sizeof(part->path), "%s/r%s%c", ARUU_PATH_DEV, tok, c); + strlcpy(part->type, "part", sizeof(part->type)); + part->size = dev.size; + p = info->parts; + if (!p) { + info->parts = part; + } else { + while (p->next) + p = p->next; + p->next = part; + } + blockdev_close(&dev); + } + } + + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + + mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + for (i = 0; i < mntsize; i++) { + char *frompath = mntbuf[i].f_mntfromname; + char *devname = frompath; + size_t dev_len = strlen(ARUU_PATH_DEV); + if (strncmp(frompath, ARUU_PATH_DEV, dev_len) == 0 && frompath[dev_len] == '/') + devname = frompath + dev_len + 1; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); + strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); + } + } + } + } + + return head; #else - struct BlockDevInfo *head = NULL; - struct BlockDevInfo *tail = NULL; - struct BlockDevInfo *info; - struct BlockDev dev; - char devname[16]; - char devpath[128]; - char c; - - for (c = 'a'; c <= 'z'; c++) { - snprintf(devname, sizeof(devname), "sd%c", c); - snprintf(devpath, sizeof(devpath), "%s/%s", PATH_DEV, devname); - if (blockdev_open(&dev, devpath, 0) == 0) { - info = ecalloc(1, sizeof(*info)); - strlcpy(info->name, devname, sizeof(info->name)); - snprintf(info->path, sizeof(info->path), "%s/%s", PATH_DEV, devname); - strlcpy(info->type, "disk", sizeof(info->type)); - info->size = dev.size; - if (!head) { - head = info; - } else { - tail->next = info; - } - tail = info; - blockdev_close(&dev); - } - } - return head; + struct BlockDevInfo *head = NULL; + struct BlockDevInfo *tail = NULL; + struct BlockDevInfo *info; + struct BlockDev dev; + char devname[16]; + char devpath[128]; + char c; + + for (c = 'a'; c <= 'z'; c++) { + snprintf(devname, sizeof(devname), "sd%c", c); + snprintf(devpath, sizeof(devpath), "%s/%s", ARUU_PATH_DEV, devname); + if (blockdev_open(&dev, devpath, 0) == 0) { + info = ecalloc(1, sizeof(*info)); + strlcpy(info->name, devname, sizeof(info->name)); + snprintf(info->path, sizeof(info->path), "%s/%s", ARUU_PATH_DEV, devname); + strlcpy(info->type, "disk", sizeof(info->type)); + info->size = dev.size; + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + blockdev_close(&dev); + } + } + return head; #endif } void blockdev_free_list(struct BlockDevInfo *list) { - struct BlockDevInfo *curr = list; - while (curr) { - struct BlockDevInfo *next = curr->next; - struct BlockDevInfo *part = curr->parts; - while (part) { - struct BlockDevInfo *next_part = part->next; - free(part); - part = next_part; - } - free(curr); - curr = next; - } + struct BlockDevInfo *curr = list; + while (curr) { + struct BlockDevInfo *next = curr->next; + struct BlockDevInfo *part = curr->parts; + while (part) { + struct BlockDevInfo *next_part = part->next; + free(part); + part = next_part; + } + free(curr); + curr = next; + } } struct FsType { - const char *name; - size_t magic_offset; - size_t magic_len; - uint64_t magic1; - uint64_t magic2; - size_t uuid_offset; - size_t uuid_len; - size_t label_offset; - size_t label_len; + const char *name; + size_t magic_offset; + size_t magic_len; + uint64_t magic1; + uint64_t magic2; + size_t uuid_offset; + size_t uuid_len; + size_t label_offset; + size_t label_len; }; static const struct FsType fstypes[] = { - /* ext2/3/4 */ - { "ext", 1080, 2, 0xEF53, 0x53EF, 1128, 16, 1144, 16 }, - /* vfat / fat32 */ - { "vfat", 82, 5, 0x3233544146ULL, 0, 67, 4, 71, 11 }, - /* vfat / fat12/16 */ - { "vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11 }, - /* ntfs */ - { "ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0 }, - /* xfs */ - { "xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12 }, - /* btrfs */ - { "btrfs", 65600, 8, 0x4D5F53665248425FULL, 0, 65803, 16, 65819, 256 }, - /* f2fs */ - { "f2fs", 1024, 4, 0xF2F52010, 0x1020F5F2, 1132, 16, 1148, 512 }, - /* ufs1 */ - { "ufs1", 9564, 4, 0x011954, 0x54190100, 8428, 8, 0, 0 }, - /* ufs2 */ - { "ufs2", 66908, 4, 0x19540119, 0x19015419, 65772, 8, 66216, 32 }, - /* fossil */ - { "fossil", 131200, 4, 0x2340A3B1, 0xB1A34023, 0, 0, 131072, 127 }, + /* ext2/3/4 */ + { "ext", 1080, 2, 0xEF53, 0x53EF, 1128, 16, 1144, 16 }, + /* vfat / fat32 */ + { "vfat", 82, 5, 0x3233544146ULL, 0, 67, 4, 71, 11 }, + /* vfat / fat12/16 */ + { "vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11 }, + /* ntfs */ + { "ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0 }, + /* xfs */ + { "xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12 }, + /* btrfs */ + { "btrfs", 65600, 8, 0x4D5F53665248425FULL, 0, 65803, 16, 65819, 256 }, + /* f2fs */ + { "f2fs", 1024, 4, 0xF2F52010, 0x1020F5F2, 1132, 16, 1148, 512 }, + /* ufs1 */ + { "ufs1", 9564, 4, 0x011954, 0x54190100, 8428, 8, 0, 0 }, + /* ufs2 */ + { "ufs2", 66908, 4, 0x19540119, 0x19015419, 65772, 8, 66216, 32 }, + /* fossil */ + { "fossil", 131200, 4, 0x2340A3B1, 0xB1A34023, 0, 0, 131072, 127 }, }; static void format_uuid(const unsigned char *buf, size_t len, const char *type, char *out, size_t out_len) { - size_t i; - char *p; - - p = out; - if (strcmp(type, "vfat") == 0) { - snprintf(out, out_len, "%02X%02X-%02X%02X", buf[3], buf[2], buf[1], buf[0]); - return; - } - - if (strcmp(type, "ntfs") == 0) { - for (i = 8; i > 0; i--) { - snprintf(p, out_len - (p - out), "%02X", buf[i - 1]); - p += 2; - } - return; - } - - for (i = 0; i < len; i++) { - if (i == 4 || i == 6 || i == 8 || i == 10) { - *p++ = '-'; - } - snprintf(p, out_len - (p - out), "%02x", buf[i]); - p += 2; - } - *p = '\0'; + size_t i; + char *p; + + p = out; + if (strcmp(type, "vfat") == 0) { + snprintf(out, out_len, "%02X%02X-%02X%02X", buf[3], buf[2], buf[1], buf[0]); + return; + } + + if (strcmp(type, "ntfs") == 0) { + for (i = 8; i > 0; i--) { + snprintf(p, out_len - (p - out), "%02X", buf[i - 1]); + p += 2; + } + return; + } + + for (i = 0; i < len; i++) { + if (i == 4 || i == 6 || i == 8 || i == 10) { + *p++ = '-'; + } + snprintf(p, out_len - (p - out), "%02x", buf[i]); + p += 2; + } + *p = '\0'; } static int zfs_detect(const unsigned char *buf, size_t len) { - size_t offset; - uint64_t magic; - - for (offset = 131072; offset + 8 <= len; offset += 1024) { - magic = ((uint64_t)buf[offset + 7] << 56) | - ((uint64_t)buf[offset + 6] << 48) | - ((uint64_t)buf[offset + 5] << 40) | - ((uint64_t)buf[offset + 4] << 32) | - ((uint64_t)buf[offset + 3] << 24) | - ((uint64_t)buf[offset + 2] << 16) | - ((uint64_t)buf[offset + 1] << 8) | - (uint64_t)buf[offset]; - - if (magic == 0x00bab10c00000000ULL || magic == 0x0cb1ba0000000000ULL || - magic == 0x00bab10cULL || magic == 0x0cb1ba00ULL) - return 1; - } - return 0; + size_t offset; + uint64_t magic; + + for (offset = 131072; offset + 8 <= len; offset += 1024) { + magic = ((uint64_t)buf[offset + 7] << 56) | + ((uint64_t)buf[offset + 6] << 48) | + ((uint64_t)buf[offset + 5] << 40) | + ((uint64_t)buf[offset + 4] << 32) | + ((uint64_t)buf[offset + 3] << 24) | + ((uint64_t)buf[offset + 2] << 16) | + ((uint64_t)buf[offset + 1] << 8) | + (uint64_t)buf[offset]; + + if (magic == 0x00bab10c00000000ULL || magic == 0x0cb1ba0000000000ULL || + magic == 0x00bab10cULL || magic == 0x0cb1ba00ULL) + return 1; + } + return 0; } struct Plan9FsDef { - const char *name; - int blocksize; - int namelen; - int dirblks; - int indirblks; - int daddrbits; + const char *name; + int blocksize; + int namelen; + int dirblks; + int indirblks; + int daddrbits; }; static const struct Plan9FsDef p9_fs_defs[] = { - { "cwfs64x", 16384, 144, 6, 4, 64 }, - { "cwfs64", 16384, 56, 6, 4, 64 }, - { "cwfs", 16384, 28, 6, 2, 32 }, - { "fs64", 8192, 56, 6, 4, 64 }, - { "fs", 4096, 28, 6, 2, 32 }, + { "cwfs64x", 16384, 144, 6, 4, 64 }, + { "cwfs64", 16384, 56, 6, 4, 64 }, + { "cwfs", 16384, 28, 6, 2, 32 }, + { "fs64", 8192, 56, 6, 4, 64 }, + { "fs", 4096, 28, 6, 2, 32 }, }; static int plan9_magic_check(const unsigned char *p, const char **name) { - if (memcmp(p, "\x01\x1c\xe5\x0d", 4) == 0 || memcmp(p, "\x0d\xe5\x1c\x01", 4) == 0) { - *name = "hjfs"; - return 1; - } - if (memcmp(p, "gefs", 4) == 0 || memcmp(p, "sfeg", 4) == 0) { - *name = "gefs"; - return 1; - } - return 0; + if (memcmp(p, "\x01\x1c\xe5\x0d", 4) == 0 || memcmp(p, "\x0d\xe5\x1c\x01", 4) == 0) { + *name = "hjfs"; + return 1; + } + if (memcmp(p, "gefs", 4) == 0 || memcmp(p, "sfeg", 4) == 0) { + *name = "gefs"; + return 1; + } + return 0; } static int plan9_detect_other(const unsigned char *buf, size_t len, const char **name) { - if (len >= 4 && plan9_magic_check(buf, name)) - return 1; - if (len >= 516 && plan9_magic_check(buf + 512, name)) - return 1; - return 0; + if (len >= 4 && plan9_magic_check(buf, name)) + return 1; + if (len >= 516 && plan9_magic_check(buf + 512, name)) + return 1; + return 0; } static int plan9_detect_text(const unsigned char *buf, size_t len, const char **name) { - int blocksize = 0, namelen = 0, dirblks = 0, indirblks = 0, daddrbits = 0; - char line[128]; - char key[64]; - int val; - size_t i = 0, j; - - if (len >= 256 + 15) { - if (memcmp(buf + 256, "kfs wren device", 15) == 0) { - *name = "kfs"; - return 1; - } - } - - if (len < 512) - return 0; - i = 512; - if (len > 1536) - len = 1536; - - while (i < len) { - size_t k = 0; - while (i < len && buf[i] != '\n' && k < sizeof(line) - 1) { - line[k++] = buf[i++]; - } - if (i < len && buf[i] == '\n') - i++; - line[k] = '\0'; - - if (sscanf(line, "%63s %d", key, &val) == 2) { - if (strcmp(key, "blocksize") == 0) blocksize = val; - else if (strcmp(key, "namelen") == 0) namelen = val; - else if (strcmp(key, "dirblks") == 0) dirblks = val; - else if (strcmp(key, "indirblks") == 0) indirblks = val; - else if (strcmp(key, "daddrbits") == 0) daddrbits = val; - } - } - - for (j = 0; j < LEN(p9_fs_defs); j++) { - if (blocksize == p9_fs_defs[j].blocksize && - namelen == p9_fs_defs[j].namelen && - dirblks == p9_fs_defs[j].dirblks && - indirblks == p9_fs_defs[j].indirblks && - daddrbits == p9_fs_defs[j].daddrbits) { - *name = p9_fs_defs[j].name; - return 1; - } - } - - return 0; + int blocksize = 0, namelen = 0, dirblks = 0, indirblks = 0, daddrbits = 0; + char line[128]; + char key[64]; + int val; + size_t i = 0, j; + + if (len >= 256 + 15) { + if (memcmp(buf + 256, "kfs wren device", 15) == 0) { + *name = "kfs"; + return 1; + } + } + + if (len < 512) + return 0; + i = 512; + if (len > 1536) + len = 1536; + + while (i < len) { + size_t k = 0; + while (i < len && buf[i] != '\n' && k < sizeof(line) - 1) { + line[k++] = buf[i++]; + } + if (i < len && buf[i] == '\n') + i++; + line[k] = '\0'; + + if (sscanf(line, "%63s %d", key, &val) == 2) { + if (strcmp(key, "blocksize") == 0) blocksize = val; + else if (strcmp(key, "namelen") == 0) namelen = val; + else if (strcmp(key, "dirblks") == 0) dirblks = val; + else if (strcmp(key, "indirblks") == 0) indirblks = val; + else if (strcmp(key, "daddrbits") == 0) daddrbits = val; + } + } + + for (j = 0; j < LEN(p9_fs_defs); j++) { + if (blocksize == p9_fs_defs[j].blocksize && + namelen == p9_fs_defs[j].namelen && + dirblks == p9_fs_defs[j].dirblks && + indirblks == p9_fs_defs[j].indirblks && + daddrbits == p9_fs_defs[j].daddrbits) { + *name = p9_fs_defs[j].name; + return 1; + } + } + + return 0; } int blockdev_detect_fs(struct BlockDev *dev, char *type, size_t type_sz, char *label, size_t label_sz, char *uuid, size_t uuid_sz) { - unsigned char *buf; - size_t read_size = 262144; /* 256kb */ - size_t sectors_to_read; - size_t i, j; - int found = 0; - - if (dev->size < read_size) - read_size = dev->size; - - buf = emalloc(read_size); - sectors_to_read = (read_size + dev->sec_size - 1) / dev->sec_size; - if (blockdev_read(dev, 0, buf, sectors_to_read) < 0) { - free(buf); - return -2; - } - - for (i = 0; i < LEN(fstypes); i++) { - const struct FsType *fs = &fstypes[i]; - if (fs->magic_offset + fs->magic_len > read_size) - continue; - - uint64_t val = 0; - for (j = 0; j < fs->magic_len; j++) { - val |= ((uint64_t)buf[fs->magic_offset + j]) << (8 * j); - } - - if (val == fs->magic1 || (fs->magic2 && val == fs->magic2)) { - const char *type_name = fs->name; - if (strcmp(fs->name, "ext") == 0) { - if (buf[1116] & 4) - type_name = "ext3"; - else if (buf[1120] & 64) - type_name = "ext4"; - else - type_name = "ext2"; - } - - if (type && type_sz) - strlcpy(type, type_name, type_sz); - - if (label && label_sz && fs->label_len && fs->label_offset + fs->label_len <= read_size) { - snprintf(label, label_sz, "%.*s", (int)fs->label_len, buf + fs->label_offset); - /* strip trailing spaces */ - char *end = label + strlen(label) - 1; - while (end >= label && *end == ' ') { - *end = '\0'; - end--; - } - } - - if (uuid && uuid_sz && fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) { - format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, uuid_sz); - } - - found = 1; - break; - } - } - - if (!found && zfs_detect(buf, read_size)) { - if (type && type_sz) - strlcpy(type, "zfs_member", type_sz); - found = 1; - } - - if (!found) { - const char *p9_name = NULL; - if (plan9_detect_other(buf, read_size, &p9_name) || - plan9_detect_text(buf, read_size, &p9_name)) { - if (type && type_sz) - strlcpy(type, p9_name, type_sz); - found = 1; - } - } - - free(buf); - return found ? 0 : -1; + unsigned char *buf; + size_t read_size = 262144; /* 256kb */ + size_t sectors_to_read; + size_t i, j; + int found = 0; + + if (dev->size < read_size) + read_size = dev->size; + + buf = emalloc(read_size); + sectors_to_read = (read_size + dev->sec_size - 1) / dev->sec_size; + if (blockdev_read(dev, 0, buf, sectors_to_read) < 0) { + free(buf); + return -2; + } + + for (i = 0; i < LEN(fstypes); i++) { + const struct FsType *fs = &fstypes[i]; + if (fs->magic_offset + fs->magic_len > read_size) + continue; + + uint64_t val = 0; + for (j = 0; j < fs->magic_len; j++) { + val |= ((uint64_t)buf[fs->magic_offset + j]) << (8 * j); + } + + if (val == fs->magic1 || (fs->magic2 && val == fs->magic2)) { + const char *type_name = fs->name; + if (strcmp(fs->name, "ext") == 0) { + if (buf[1116] & 4) + type_name = "ext3"; + else if (buf[1120] & 64) + type_name = "ext4"; + else + type_name = "ext2"; + } + + if (type && type_sz) + strlcpy(type, type_name, type_sz); + + if (label && label_sz && fs->label_len && fs->label_offset + fs->label_len <= read_size) { + snprintf(label, label_sz, "%.*s", (int)fs->label_len, buf + fs->label_offset); + /* strip trailing spaces */ + char *end = label + strlen(label) - 1; + while (end >= label && *end == ' ') { + *end = '\0'; + end--; + } + } + + if (uuid && uuid_sz && fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) { + format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, uuid_sz); + } + + found = 1; + break; + } + } + + if (!found && zfs_detect(buf, read_size)) { + if (type && type_sz) + strlcpy(type, "zfs_member", type_sz); + found = 1; + } + + if (!found) { + const char *p9_name = NULL; + if (plan9_detect_other(buf, read_size, &p9_name) || + plan9_detect_text(buf, read_size, &p9_name)) { + if (type && type_sz) + strlcpy(type, p9_name, type_sz); + found = 1; + } + } + + free(buf); + return found ? 0 : -1; } diff --git a/shared/libutil/net.c b/shared/libutil/net.c @@ -1,3 +1,4 @@ +#include "../paths.h" #include "../util.h" #include <arpa/inet.h> @@ -23,162 +24,162 @@ static void get_mtu_metric(const char *name, int *mtu, int *metric) { - struct ifreq ifr; - int sock; - - *mtu = 0; - *metric = 0; - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0) - *mtu = ifr.ifr_mtu; - if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0) - *metric = ifr.ifr_metric; - close(sock); + struct ifreq ifr; + int sock; + + *mtu = 0; + *metric = 0; + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0) + *mtu = ifr.ifr_mtu; + if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0) + *metric = ifr.ifr_metric; + close(sock); } int net_get_interfaces(struct NetInterface **ifaces, int *count) { - struct ifaddrs *ifaddr, *ifa; - struct NetInterface *list = NULL; - struct NetInterface *iface; - int found_count = 0; - int i; - - if (getifaddrs(&ifaddr) < 0) - return -1; - - for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { - iface = NULL; - for (i = 0; i < found_count; i++) { - if (strcmp(list[i].name, ifa->ifa_name) == 0) { - iface = &list[i]; - break; - } - } - if (!iface) { - list = reallocarray(list, found_count + 1, sizeof(*list)); - if (!list) { - freeifaddrs(ifaddr); - return -1; - } - iface = &list[found_count]; - memset(iface, 0, sizeof(*iface)); - strlcpy(iface->name, ifa->ifa_name, sizeof(iface->name)); - iface->flags = ifa->ifa_flags; - get_mtu_metric(iface->name, &iface->mtu, &iface->metric); - found_count++; - } - - if (!ifa->ifa_addr) - continue; - - if (ifa->ifa_addr->sa_family == AF_INET) { - memcpy(&iface->ipv4_addr, ifa->ifa_addr, sizeof(struct sockaddr_in)); - iface->has_ipv4 = 1; - if (ifa->ifa_netmask) - memcpy(&iface->ipv4_mask, ifa->ifa_netmask, sizeof(struct sockaddr_in)); - if (ifa->ifa_dstaddr) - memcpy(&iface->ipv4_brd, ifa->ifa_dstaddr, sizeof(struct sockaddr_in)); - } else if (ifa->ifa_addr->sa_family == AF_INET6) { - memcpy(&iface->ipv6_addr, ifa->ifa_addr, sizeof(struct sockaddr_in6)); - iface->has_ipv6 = 1; - /* scope id could be set here from sin6_scope_id */ - } + struct ifaddrs *ifaddr, *ifa; + struct NetInterface *list = NULL; + struct NetInterface *iface; + int found_count = 0; + int i; + + if (getifaddrs(&ifaddr) < 0) + return -1; + + for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + iface = NULL; + for (i = 0; i < found_count; i++) { + if (strcmp(list[i].name, ifa->ifa_name) == 0) { + iface = &list[i]; + break; + } + } + if (!iface) { + list = reallocarray(list, found_count + 1, sizeof(*list)); + if (!list) { + freeifaddrs(ifaddr); + return -1; + } + iface = &list[found_count]; + memset(iface, 0, sizeof(*iface)); + strlcpy(iface->name, ifa->ifa_name, sizeof(iface->name)); + iface->flags = ifa->ifa_flags; + get_mtu_metric(iface->name, &iface->mtu, &iface->metric); + found_count++; + } + + if (!ifa->ifa_addr) + continue; + + if (ifa->ifa_addr->sa_family == AF_INET) { + memcpy(&iface->ipv4_addr, ifa->ifa_addr, sizeof(struct sockaddr_in)); + iface->has_ipv4 = 1; + if (ifa->ifa_netmask) + memcpy(&iface->ipv4_mask, ifa->ifa_netmask, sizeof(struct sockaddr_in)); + if (ifa->ifa_dstaddr) + memcpy(&iface->ipv4_brd, ifa->ifa_dstaddr, sizeof(struct sockaddr_in)); + } else if (ifa->ifa_addr->sa_family == AF_INET6) { + memcpy(&iface->ipv6_addr, ifa->ifa_addr, sizeof(struct sockaddr_in6)); + iface->has_ipv6 = 1; + /* scope id could be set here from sin6_scope_id */ + } #ifdef __linux__ - else if (ifa->ifa_addr->sa_family == AF_PACKET) { - struct sockaddr_ll *sll = (struct sockaddr_ll *)ifa->ifa_addr; - if (sll->sll_halen == 6) { - memcpy(iface->mac, sll->sll_addr, 6); - iface->has_mac = 1; - } - } + else if (ifa->ifa_addr->sa_family == AF_PACKET) { + struct sockaddr_ll *sll = (struct sockaddr_ll *)ifa->ifa_addr; + if (sll->sll_halen == 6) { + memcpy(iface->mac, sll->sll_addr, 6); + iface->has_mac = 1; + } + } #else - else if (ifa->ifa_addr->sa_family == AF_LINK) { - struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr; - if (sdl->sdl_alen == 6) { - memcpy(iface->mac, LLADDR(sdl), 6); - iface->has_mac = 1; - } - } + else if (ifa->ifa_addr->sa_family == AF_LINK) { + struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr; + if (sdl->sdl_alen == 6) { + memcpy(iface->mac, LLADDR(sdl), 6); + iface->has_mac = 1; + } + } #endif - } + } - freeifaddrs(ifaddr); - *ifaces = list; - *count = found_count; - return 0; + freeifaddrs(ifaddr); + *ifaces = list; + *count = found_count; + return 0; } #ifdef __linux__ int net_get_stats(const char *ifname, struct NetStats *stats) { - FILE *fp; - char line[256]; - char *p, *name; - int found = 0; - - memset(stats, 0, sizeof(*stats)); - fp = fopen("/proc/net/dev", "r"); - if (!fp) - return -1; - - while (fgets(line, sizeof(line), fp)) { - p = strchr(line, ':'); - if (p) { - *p = '\0'; - name = line; - while (isspace(*name)) - name++; - if (strcmp(name, ifname) == 0) { - if (sscanf(p + 1, "%llu %llu %llu %llu %*u %*u %*u %*u %llu %llu %llu %llu", - &stats->rx_bytes, &stats->rx_packets, &stats->rx_errs, &stats->rx_drop, - &stats->tx_bytes, &stats->tx_packets, &stats->tx_errs, &stats->tx_drop) == 8) { - found = 1; - } - break; - } - } - } - fclose(fp); - return found ? 0 : -1; + FILE *fp; + char line[256]; + char *p, *name; + int found = 0; + + memset(stats, 0, sizeof(*stats)); + fp = fopen(ARUU_LINUX_PATH_PROC "/net/dev", "r"); + if (!fp) + return -1; + + while (fgets(line, sizeof(line), fp)) { + p = strchr(line, ':'); + if (p) { + *p = '\0'; + name = line; + while (isspace(*name)) + name++; + if (strcmp(name, ifname) == 0) { + if (sscanf(p + 1, "%llu %llu %llu %llu %*u %*u %*u %*u %llu %llu %llu %llu", + &stats->rx_bytes, &stats->rx_packets, &stats->rx_errs, &stats->rx_drop, + &stats->tx_bytes, &stats->tx_packets, &stats->tx_errs, &stats->tx_drop) == 8) { + found = 1; + } + break; + } + } + } + fclose(fp); + return found ? 0 : -1; } #else int net_get_stats(const char *ifname, struct NetStats *stats) { - struct ifaddrs *ifaddr, *ifa; - int found = 0; - - memset(stats, 0, sizeof(*stats)); - if (getifaddrs(&ifaddr) < 0) - return -1; - - for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { - if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_LINK && - strcmp(ifa->ifa_name, ifname) == 0) { - struct if_data *ifd = (struct if_data *)ifa->ifa_data; - if (ifd) { - stats->rx_bytes = ifd->ifi_ibytes; - stats->rx_packets = ifd->ifi_ipackets; - stats->rx_errs = ifd->ifi_ierrors; - stats->rx_drop = ifd->ifi_iqdrops; - stats->tx_bytes = ifd->ifi_obytes; - stats->tx_packets = ifd->ifi_opackets; - stats->tx_errs = ifd->ifi_oerrors; - stats->tx_drop = 0; - found = 1; - break; - } - } - } - freeifaddrs(ifaddr); - return found ? 0 : -1; + struct ifaddrs *ifaddr, *ifa; + int found = 0; + + memset(stats, 0, sizeof(*stats)); + if (getifaddrs(&ifaddr) < 0) + return -1; + + for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_LINK && + strcmp(ifa->ifa_name, ifname) == 0) { + struct if_data *ifd = (struct if_data *)ifa->ifa_data; + if (ifd) { + stats->rx_bytes = ifd->ifi_ibytes; + stats->rx_packets = ifd->ifi_ipackets; + stats->rx_errs = ifd->ifi_ierrors; + stats->rx_drop = ifd->ifi_iqdrops; + stats->tx_bytes = ifd->ifi_obytes; + stats->tx_packets = ifd->ifi_opackets; + stats->tx_errs = ifd->ifi_oerrors; + stats->tx_drop = 0; + found = 1; + break; + } + } + } + freeifaddrs(ifaddr); + return found ? 0 : -1; } #endif @@ -186,385 +187,385 @@ net_get_stats(const char *ifname, struct NetStats *stats) int net_set_txqueuelen(const char *name, int qlen) { - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_qlen = qlen; - if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_qlen = qlen; + if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; } #else int net_set_txqueuelen(const char *name, int qlen) { - (void)name; - (void)qlen; - return -1; + (void)name; + (void)qlen; + return -1; } #endif int net_set_flags(const char *name, unsigned int flags, int set) { - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { - close(sock); - return -1; - } - if (set) - ifr.ifr_flags |= flags; - else - ifr.ifr_flags &= ~flags; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + if (set) + ifr.ifr_flags |= flags; + else + ifr.ifr_flags &= ~flags; + if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; } int net_set_mtu(const char *name, int mtu) { - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_mtu = mtu; - if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_mtu = mtu; + if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; } int -net_set_mac(const char *name, const unsigned char mac[6]) +net_set_mac(const char *name, const unsigned char *mac) { #ifdef __linux__ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_hwaddr.sa_family = 1; - memcpy(ifr.ifr_hwaddr.sa_data, mac, 6); - if (ioctl(sock, SIOCSIFHWADDR, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_hwaddr.sa_family = 1; + memcpy(ifr.ifr_hwaddr.sa_data, mac, 6); + if (ioctl(sock, SIOCSIFHWADDR, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; #else - (void)name; - (void)mac; - return -1; + (void)name; + (void)mac; + return -1; #endif } int net_add_addr(const char *name, const char *addr, int prefix) { - struct ifreq ifr; - struct sockaddr_in *sin; - int sock; - unsigned int mask; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - - sin = (struct sockaddr_in *)&ifr.ifr_addr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - - if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) { - close(sock); - return -1; - } - - if (prefix >= 0) { - mask = 0; - if (prefix > 0) - mask = htonl(~0U << (32 - prefix)); - sin = (struct sockaddr_in *)&ifr.ifr_netmask; - sin->sin_family = AF_INET; - sin->sin_addr.s_addr = mask; - if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) { - close(sock); - return -1; - } - } - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) { - ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - ioctl(sock, SIOCSIFFLAGS, &ifr); - } - - close(sock); - return 0; + struct ifreq ifr; + struct sockaddr_in *sin; + int sock; + unsigned int mask; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + + sin = (struct sockaddr_in *)&ifr.ifr_addr; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + + if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) { + close(sock); + return -1; + } + + if (prefix >= 0) { + mask = 0; + if (prefix > 0) + mask = htonl(~0U << (32 - prefix)); + sin = (struct sockaddr_in *)&ifr.ifr_netmask; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = mask; + if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) { + close(sock); + return -1; + } + } + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) { + ifr.ifr_flags |= IFF_UP | IFF_RUNNING; + ioctl(sock, SIOCSIFFLAGS, &ifr); + } + + close(sock); + return 0; } int net_del_addr(const char *name, const char *addr, int prefix) { - struct ifreq ifr; - struct sockaddr_in *sin; - int sock; - - (void)prefix; - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - - sin = (struct sockaddr_in *)&ifr.ifr_addr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - - if (ioctl(sock, SIOCDIFADDR, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + struct sockaddr_in *sin; + int sock; + + (void)prefix; + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + + sin = (struct sockaddr_in *)&ifr.ifr_addr; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + + if (ioctl(sock, SIOCDIFADDR, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; } int net_show_routes(void) { #ifdef __linux__ - FILE *fp; - char line[256]; - char iface[16], dest[16], gateway[16], mask[16]; - unsigned int d, g, m, flags, metric; - - fp = fopen("/proc/net/route", "r"); - if (!fp) - return -1; - - printf("%-10s %-15s %-15s %-15s %-6s %-6s\n", "Iface", "Destination", "Gateway", "Genmask", "Flags", "Metric"); - if (fgets(line, sizeof(line), fp)) { - while (fgets(line, sizeof(line), fp)) { - if (sscanf(line, "%15s %x %x %x %*u %*u %u %x", iface, &d, &g, &m, &metric, &flags) == 6) { - struct in_addr dest_addr, gw_addr, mask_addr; - dest_addr.s_addr = d; - gw_addr.s_addr = g; - mask_addr.s_addr = m; - strlcpy(dest, inet_ntoa(dest_addr), sizeof(dest)); - strlcpy(gateway, inet_ntoa(gw_addr), sizeof(gateway)); - strlcpy(mask, inet_ntoa(mask_addr), sizeof(mask)); - printf("%-10s %-15s %-15s %-15s 0x%04X %-6u\n", iface, dest, gateway, mask, flags, metric); - } - } - } - fclose(fp); - return 0; + FILE *fp; + char line[256]; + char iface[16], dest[16], gateway[16], mask[16]; + unsigned int d, g, m, flags, metric; + + fp = fopen(ARUU_LINUX_PATH_PROC "/net/route", "r"); + if (!fp) + return -1; + + printf("%-10s %-15s %-15s %-15s %-6s %-6s\n", "Iface", "Destination", "Gateway", "Genmask", "Flags", "Metric"); + if (fgets(line, sizeof(line), fp)) { + while (fgets(line, sizeof(line), fp)) { + if (sscanf(line, "%15s %x %x %x %*u %*u %u %x", iface, &d, &g, &m, &metric, &flags) == 6) { + struct in_addr dest_addr, gw_addr, mask_addr; + dest_addr.s_addr = d; + gw_addr.s_addr = g; + mask_addr.s_addr = m; + strlcpy(dest, inet_ntoa(dest_addr), sizeof(dest)); + strlcpy(gateway, inet_ntoa(gw_addr), sizeof(gateway)); + strlcpy(mask, inet_ntoa(mask_addr), sizeof(mask)); + printf("%-10s %-15s %-15s %-15s 0x%04X %-6u\n", iface, dest, gateway, mask, flags, metric); + } + } + } + fclose(fp); + return 0; #else - printf("route listing not implemented on this OS\n"); - return 0; + printf("route listing not implemented on this OS\n"); + return 0; #endif } int net_add_route(const char *dst, const char *gateway, const char *mask, const char *dev, int metric) { - struct rtentry rt; - struct sockaddr_in *sin; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&rt, 0, sizeof(rt)); - - sin = (struct sockaddr_in *)&rt.rt_dst; - sin->sin_family = AF_INET; - if (strcmp(dst, "default") == 0) { - sin->sin_addr.s_addr = INADDR_ANY; - } else { - if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - if (gateway) { - sin = (struct sockaddr_in *)&rt.rt_gateway; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - rt.rt_flags |= RTF_GATEWAY; - } - - if (mask) { - sin = (struct sockaddr_in *)&rt.rt_genmask; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - rt.rt_flags |= RTF_UP; - if (dev) - rt.rt_dev = (char *)dev; - if (metric >= 0) - rt.rt_metric = metric + 1; - - if (ioctl(sock, SIOCADDRT, &rt) < 0) { - close(sock); - return -1; - } - - close(sock); - return 0; + struct rtentry rt; + struct sockaddr_in *sin; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&rt, 0, sizeof(rt)); + + sin = (struct sockaddr_in *)&rt.rt_dst; + sin->sin_family = AF_INET; + if (strcmp(dst, "default") == 0) { + sin->sin_addr.s_addr = INADDR_ANY; + } else { + if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + } + + if (gateway) { + sin = (struct sockaddr_in *)&rt.rt_gateway; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + rt.rt_flags |= RTF_GATEWAY; + } + + if (mask) { + sin = (struct sockaddr_in *)&rt.rt_genmask; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + } + + rt.rt_flags |= RTF_UP; + if (dev) + rt.rt_dev = (char *)dev; + if (metric >= 0) + rt.rt_metric = metric + 1; + + if (ioctl(sock, SIOCADDRT, &rt) < 0) { + close(sock); + return -1; + } + + close(sock); + return 0; } int net_del_route(const char *dst, const char *gateway, const char *mask, const char *dev, int metric) { - struct rtentry rt; - struct sockaddr_in *sin; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&rt, 0, sizeof(rt)); - - sin = (struct sockaddr_in *)&rt.rt_dst; - sin->sin_family = AF_INET; - if (strcmp(dst, "default") == 0) { - sin->sin_addr.s_addr = INADDR_ANY; - } else { - if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - if (gateway) { - sin = (struct sockaddr_in *)&rt.rt_gateway; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - rt.rt_flags |= RTF_GATEWAY; - } - - if (mask) { - sin = (struct sockaddr_in *)&rt.rt_genmask; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - rt.rt_flags |= RTF_UP; - if (dev) - rt.rt_dev = (char *)dev; - if (metric >= 0) - rt.rt_metric = metric + 1; - - if (ioctl(sock, SIOCDELRT, &rt) < 0) { - close(sock); - return -1; - } - - close(sock); - return 0; + struct rtentry rt; + struct sockaddr_in *sin; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&rt, 0, sizeof(rt)); + + sin = (struct sockaddr_in *)&rt.rt_dst; + sin->sin_family = AF_INET; + if (strcmp(dst, "default") == 0) { + sin->sin_addr.s_addr = INADDR_ANY; + } else { + if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + } + + if (gateway) { + sin = (struct sockaddr_in *)&rt.rt_gateway; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + rt.rt_flags |= RTF_GATEWAY; + } + + if (mask) { + sin = (struct sockaddr_in *)&rt.rt_genmask; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + } + + rt.rt_flags |= RTF_UP; + if (dev) + rt.rt_dev = (char *)dev; + if (metric >= 0) + rt.rt_metric = metric + 1; + + if (ioctl(sock, SIOCDELRT, &rt) < 0) { + close(sock); + return -1; + } + + close(sock); + return 0; } int net_flush_addrs(const char *dev) { - struct NetInterface *ifaces = NULL; - int count = 0, i, r = 0; - - if (net_get_interfaces(&ifaces, &count) < 0) - return -1; - - for (i = 0; i < count; i++) { - if (strcmp(ifaces[i].name, dev) == 0) { - if (ifaces[i].has_ipv4) { - char addr_str[16]; - struct sockaddr_in *sin = &ifaces[i].ipv4_addr; - inet_ntop(AF_INET, &sin->sin_addr, addr_str, sizeof(addr_str)); - if (net_del_addr(dev, addr_str, -1) < 0) - r = -1; - } - } - } - free(ifaces); - return r; + struct NetInterface *ifaces = NULL; + int count = 0, i, r = 0; + + if (net_get_interfaces(&ifaces, &count) < 0) + return -1; + + for (i = 0; i < count; i++) { + if (strcmp(ifaces[i].name, dev) == 0) { + if (ifaces[i].has_ipv4) { + char addr_str[16]; + struct sockaddr_in *sin = &ifaces[i].ipv4_addr; + inet_ntop(AF_INET, &sin->sin_addr, addr_str, sizeof(addr_str)); + if (net_del_addr(dev, addr_str, -1) < 0) + r = -1; + } + } + } + free(ifaces); + return r; } int net_set_name(const char *name, const char *newname) { #ifdef __linux__ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - strlcpy(ifr.ifr_newname, newname, sizeof(ifr.ifr_newname)); - if (ioctl(sock, SIOCSIFNAME, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + strlcpy(ifr.ifr_newname, newname, sizeof(ifr.ifr_newname)); + if (ioctl(sock, SIOCSIFNAME, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; #else - (void)name; - (void)newname; - return -1; + (void)name; + (void)newname; + return -1; #endif } diff --git a/shared/libutil/passwd.c b/shared/libutil/passwd.c @@ -1,77 +1,384 @@ /* See LICENSE file for copyright and license details. */ -#include <sys/resource.h> -#include <sys/time.h> +#include "../passwd.h" +#include "../paths.h" +#include "../text.h" +#include "../util.h" #include <errno.h> +#include <fcntl.h> #include <pwd.h> -#include <shadow.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <sys/resource.h> +#include <sys/stat.h> +#include <sys/wait.h> #include <unistd.h> -#include "../passwd.h" -#include "../text.h" -#include "../util.h" +#include "../config.h" + +#if defined(__linux__) || defined(__GLIBC__) +#include <crypt.h> +#endif + +#if defined(__linux__) && !defined(__ANDROID__) +#define HAVE_SHADOW 1 +#include <shadow.h> +#endif + +#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define HAVE_MASTER_PASSWD 1 +#endif + +int +pw_init(void) +{ + struct rlimit rlim; + + rlim.rlim_cur = 0; + rlim.rlim_max = 0; + if (setrlimit(RLIMIT_CORE, &rlim) < 0) + eprintf("setrlimit:"); + return 0; +} -/* Returns -1 on error, 0 for incorrect password - * and 1 if all went OK */ int pw_check(const struct passwd *pw, const char *pass) { - char *cryptpass, *p; - struct spwd *spw; - - p = pw->pw_passwd; - if (p[0] == '!' || p[0] == '*') { - weprintf("denied\n"); - return -1; - } - - if (pw->pw_passwd[0] == '\0') { - if (pass[0] == '\0') - return 1; - weprintf("incorrect password\n"); - return 0; - } - - if (pw->pw_passwd[0] == 'x' && pw->pw_passwd[1] == '\0') { - errno = 0; - spw = getspnam(pw->pw_name); - if (!spw) { - if (errno) - weprintf("getspnam: %s:", pw->pw_name); - else - weprintf("who are you?\n"); - return -1; - } - p = spw->sp_pwdp; - if (p[0] == '!' || p[0] == '*') { - weprintf("denied\n"); - return -1; - } - } - - cryptpass = crypt(pass, p); - if (!cryptpass) { - weprintf("crypt:"); - return -1; - } - if (strcmp(cryptpass, p) != 0) { - weprintf("incorrect password\n"); - return 0; - } - return 1; + char *cryptpass, *p; + const char *stored; + + stored = pw->pw_passwd; + if (stored[0] == '!' || stored[0] == '*') { + weprintf("denied\n"); + return -1; + } + + if (stored[0] == '\0') { + if (pass[0] == '\0') + return 1; + weprintf("incorrect password\n"); + return 0; + } + +#if defined(HAVE_SHADOW) + if (stored[0] == 'x' && stored[1] == '\0') { + struct spwd *spw; + errno = 0; + spw = getspnam(pw->pw_name); + if (!spw) { + if (errno) + weprintf("getspnam: %s:", pw->pw_name); + else + weprintf("who are you?\n"); + return -1; + } + stored = spw->sp_pwdp; + if (stored[0] == '!' || stored[0] == '*') { + weprintf("denied\n"); + return -1; + } + } +#endif + + cryptpass = crypt(pass, stored); + if (!cryptpass) { + weprintf("crypt:"); + return -1; + } + p = estrdup(cryptpass); + if (strcmp(p, stored) != 0) { + free(p); + weprintf("incorrect password\n"); + return 0; + } + free(p); + return 1; } int -pw_init(void) +pwdb_lookup(struct pwdb_entry *ent, const char *name) { - struct rlimit rlim; + struct passwd *pw; + const char *hash; - rlim.rlim_cur = 0; - rlim.rlim_max = 0; - if (setrlimit(RLIMIT_CORE, &rlim) < 0) - eprintf("setrlimit:"); - return 0; + errno = 0; + pw = getpwnam(name); + if (!pw) { + if (errno) + weprintf("getpwnam: %s:", name); + else + weprintf("who are you?\n"); + return -1; + } + + ent->name = estrdup(pw->pw_name); + ent->uid = pw->pw_uid; + ent->gid = pw->pw_gid; + hash = pw->pw_passwd; + +#if defined(HAVE_SHADOW) + if (hash[0] == 'x' && hash[1] == '\0') { + struct spwd *spw; + errno = 0; + spw = getspnam(name); + if (spw) + hash = spw->sp_pwdp; + } +#endif + + ent->hash = estrdup(hash); + return 0; +} + +static int +fill_random(void *buf, size_t n) +{ +#if defined(__linux__) + if (getentropy(buf, n) == 0) + return 0; +#endif + { + int fd; + size_t off; + fd = open(ARUU_PATH_DEVURANDOM, O_RDONLY); + if (fd < 0) { + weprintf("open /dev/urandom:"); + return -1; + } + off = 0; + while (off < n) { + ssize_t r = read(fd, (char *)buf + off, n - off); + if (r <= 0) { + close(fd); + weprintf("read /dev/urandom:"); + return -1; + } + off += (size_t)r; + } + close(fd); + } + return 0; +} + +int +pw_gensalt_cipher(char *salt, size_t salt_sz, const char *prefix, + size_t rand_len) +{ + static const char b64[] = + "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + unsigned char raw[32]; + char body[48]; + size_t i, n, body_len; + unsigned v; + int prefix_len; + + if (rand_len > sizeof(raw)) + rand_len = sizeof(raw); + if (rand_len == 0) { + salt[0] = '\0'; + return 0; + } + + prefix_len = 0; + if (prefix) { + prefix_len = snprintf(salt, salt_sz, "%s", prefix); + if (prefix_len < 0 || (size_t)prefix_len >= salt_sz) { + weprintf("snprintf:"); + return -1; + } + } + + if (fill_random(raw, rand_len) < 0) + return -1; + + body_len = (rand_len * 4 + 2) / 3; + if (body_len >= sizeof(body)) + body_len = sizeof(body) - 1; + n = 0; + for (i = 0; i + 3 <= rand_len; i += 3) { + v = (raw[i] << 16) | (raw[i+1] << 8) | raw[i+2]; + body[n++] = b64[v & 0x3f]; v >>= 6; + body[n++] = b64[v & 0x3f]; v >>= 6; + body[n++] = b64[v & 0x3f]; v >>= 6; + body[n++] = b64[v & 0x3f]; + } + if (i < rand_len) { + v = raw[i] << 16; + if (i + 1 < rand_len) + v |= raw[i+1] << 8; + body[n++] = b64[v & 0x3f]; v >>= 6; + body[n++] = b64[v & 0x3f]; v >>= 6; + if (i + 1 < rand_len) + body[n++] = b64[v & 0x3f]; + } + body[n] = '\0'; + + if ((size_t)prefix_len + n + 1 >= salt_sz) { + weprintf("salt buffer too small\n"); + return -1; + } + memcpy(salt + prefix_len, body, n + 1); + return 0; +} + +int +pw_gensalt(char *salt, size_t salt_sz) +{ + return pw_gensalt_cipher(salt, salt_sz, PW_CIPHER, 16); +} + +#if defined(HAVE_SHADOW) +static int +update_shadow(const char *name, const char *newhash) +{ + struct spwd *spw, cur; + FILE *fp, *tfp; + int wrote = 0; + char path[256]; + + snprintf(path, sizeof(path), ARUU_PATH_ETC "/tcb/%s/shadow", name); + fp = fopen(path, "r+"); + if (!fp) { + memcpy(path, ARUU_PATH_SHADOW, sizeof(ARUU_PATH_SHADOW)); + fp = fopen(path, "r+"); + } + if (!fp) { + weprintf("fopen %s:", path); + return -1; + } + + tfp = tmpfile(); + if (!tfp) { + weprintf("tmpfile:"); + fclose(fp); + return -1; + } + + while ((spw = getspent())) { + cur = *spw; + if (strcmp(cur.sp_namp, name) == 0) { + cur.sp_pwdp = (char *)newhash; + wrote = 1; + } + errno = 0; + if (putspent(&cur, tfp) == -1) { + weprintf("putspent:"); + fclose(tfp); + fclose(fp); + return -1; + } + } + if (!wrote) { + weprintf("shadow: no matching entry\n"); + fclose(tfp); + fclose(fp); + return -1; + } + fflush(tfp); + rewind(tfp); + rewind(fp); + fconcat(tfp, "tmpfile", fp, "shadow"); + ftruncate(fileno(fp), ftell(tfp)); + fclose(tfp); + { + int fd = fileno(fp); + if (fd >= 0) + fsync(fd); + } + fclose(fp); + return 0; +} +#endif + +static int +update_passwd_file(const char *path, const char *name, const char *newhash) +{ + struct passwd *pw, cur; + FILE *fp, *tfp; + int wrote = 0; + + fp = fopen(path, "r+"); + if (!fp) { + weprintf("fopen %s:", path); + return -1; + } + tfp = tmpfile(); + if (!tfp) { + weprintf("tmpfile:"); + fclose(fp); + return -1; + } + while ((pw = fgetpwent(fp))) { + cur = *pw; + if (strcmp(cur.pw_name, name) == 0) { + cur.pw_passwd = (char *)newhash; + wrote = 1; + } + errno = 0; + if (putpwent(&cur, tfp) == -1) { + weprintf("putpwent:"); + fclose(tfp); + fclose(fp); + return -1; + } + } + if (!wrote) { + weprintf("passwd: no matching entry\n"); + fclose(tfp); + fclose(fp); + return -1; + } + fflush(tfp); + rewind(tfp); + rewind(fp); + fconcat(tfp, "tmpfile", fp, path); + ftruncate(fileno(fp), ftell(tfp)); + { + int fd = fileno(fp); + if (fd >= 0) + fsync(fd); + } + fclose(tfp); + fclose(fp); + return 0; +} + +#if defined(HAVE_MASTER_PASSWD) +static int +update_master_passwd(const char *name, const char *newhash) +{ + int r; + pid_t pid; + int st; + + r = update_passwd_file(ARUU_BSD_PATH_MASTER_PASSWD, name, newhash); + if (r != 0) + return r; + pid = fork(); + if (pid == 0) { + execl(ARUU_BSD_PATH_PWD_MKDB, "pwd_mkdb", "-p", NULL); + _exit(127); + } + if (pid > 0) + waitpid(pid, &st, 0); + return 0; +} +#endif + +int +pwdb_update(const char *name, const char *newhash) +{ +#if defined(HAVE_SHADOW) + { + struct spwd *spw; + errno = 0; + spw = getspnam(name); + if (spw) + return update_shadow(name, newhash); + } +#elif defined(HAVE_MASTER_PASSWD) + return update_master_passwd(name, newhash); +#endif + return update_passwd_file(ARUU_PATH_PASSWD, name, newhash); } diff --git a/shared/libutil/proc.c b/shared/libutil/proc.c @@ -10,6 +10,7 @@ #include <unistd.h> #include "../proc.h" +#include "../paths.h" #include "../util.h" int @@ -19,7 +20,7 @@ parsecmdline(pid_t pid, char *buf, size_t siz) char path[PATH_MAX]; ssize_t n, i; - snprintf(path, sizeof(path), "/proc/%ld/cmdline", (long)pid); + snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%ld/cmdline", (long)pid); fd = open(path, O_RDONLY); if (fd < 0) return -1; @@ -48,7 +49,7 @@ parsestat(pid_t pid, struct procstat *ps) FILE *fp; size_t len; - snprintf(path, sizeof(path), "/proc/%d/stat", pid); + snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/stat", pid); if (!(fp = fopen(path, "r"))) return -1; fscanf(fp, "%d %s %c %d %d %d %d %d %u %lu %lu %lu %lu %lu %lu", @@ -78,7 +79,7 @@ parsestatus(pid_t pid, struct procstatus *pstatus) int fd; ssize_t n; - snprintf(path, sizeof(path), "/proc/%d/status", pid); + snprintf(path, sizeof(path), ARUU_LINUX_PATH_PROC "/%d/status", pid); fd = open(path, O_RDONLY); if (fd < 0) return -1; diff --git a/shared/libutil/tls.c b/shared/libutil/tls.c @@ -1,5 +1,6 @@ /* see license file for copyright and license details */ #include "../tls.h" +#include "../paths.h" #include "../util.h" #include <errno.h> @@ -13,201 +14,201 @@ #include <tls.h> struct TlsSocket { - int fd; - int is_tls; - struct tls *ctx; + int fd; + int is_tls; + struct tls *ctx; }; #elif FEATURE_USE_BEARSSL #include <bearssl.h> struct my_x509_context { - const br_x509_class *vtable; - br_x509_minimal_context minimal; + const br_x509_class *vtable; + br_x509_minimal_context minimal; }; struct TlsSocket { - int fd; - int is_tls; - br_ssl_client_context sc; - struct my_x509_context my_x509; - unsigned char iobuf[BR_SSL_BUFSIZE_BIDI]; - br_sslio_context ioc; + int fd; + int is_tls; + br_ssl_client_context sc; + struct my_x509_context my_x509; + unsigned char iobuf[BR_SSL_BUFSIZE_BIDI]; + br_sslio_context ioc; }; struct dn_accum { - unsigned char *data; - size_t len; - size_t cap; + unsigned char *data; + size_t len; + size_t cap; }; static void append_dn_callback(void *dn_ctx, const void *src, size_t len) { - struct dn_accum *accum = dn_ctx; - if (accum->len + len > accum->cap) { - accum->cap = accum->len + len + 256; - accum->data = erealloc(accum->data, accum->cap); - } - memcpy(accum->data + accum->len, src, len); - accum->len += len; + struct dn_accum *accum = dn_ctx; + if (accum->len + len > accum->cap) { + accum->cap = accum->len + len + 256; + accum->data = erealloc(accum->data, accum->cap); + } + memcpy(accum->data + accum->len, src, len); + accum->len += len; } static void my_start_chain(const br_x509_class **ctx, const char *server_name) { - struct my_x509_context *t = (struct my_x509_context *)ctx; - br_x509_minimal_vtable.start_chain((const br_x509_class **)&t->minimal, server_name); + struct my_x509_context *t = (struct my_x509_context *)ctx; + br_x509_minimal_vtable.start_chain((const br_x509_class **)&t->minimal, server_name); } static void my_start_cert(const br_x509_class **ctx, uint32_t length) { - struct my_x509_context *t = (struct my_x509_context *)ctx; - br_x509_minimal_vtable.start_cert((const br_x509_class **)&t->minimal, length); + struct my_x509_context *t = (struct my_x509_context *)ctx; + br_x509_minimal_vtable.start_cert((const br_x509_class **)&t->minimal, length); } static void my_append(const br_x509_class **ctx, const unsigned char *buf, size_t len) { - struct my_x509_context *t = (struct my_x509_context *)ctx; - br_x509_minimal_vtable.append((const br_x509_class **)&t->minimal, buf, len); + struct my_x509_context *t = (struct my_x509_context *)ctx; + br_x509_minimal_vtable.append((const br_x509_class **)&t->minimal, buf, len); } static void my_end_cert(const br_x509_class **ctx) { - struct my_x509_context *t = (struct my_x509_context *)ctx; - br_x509_minimal_vtable.end_cert((const br_x509_class **)&t->minimal); + struct my_x509_context *t = (struct my_x509_context *)ctx; + br_x509_minimal_vtable.end_cert((const br_x509_class **)&t->minimal); } static unsigned my_end_chain(const br_x509_class **ctx) { - struct my_x509_context *t = (struct my_x509_context *)ctx; - (void)br_x509_minimal_vtable.end_chain((const br_x509_class **)&t->minimal); - /* always succeed and accept certificate when check_cert is 0 */ - return 0; + struct my_x509_context *t = (struct my_x509_context *)ctx; + (void)br_x509_minimal_vtable.end_chain((const br_x509_class **)&t->minimal); + /* always succeed and accept certificate when check_cert is 0 */ + return 0; } static const br_x509_pkey * my_get_pkey(const br_x509_class *const *ctx, unsigned *usages) { - const struct my_x509_context *t = (const struct my_x509_context *)ctx; - return br_x509_minimal_vtable.get_pkey((const br_x509_class *const *)&t->minimal, usages); + const struct my_x509_context *t = (const struct my_x509_context *)ctx; + return br_x509_minimal_vtable.get_pkey((const br_x509_class *const *)&t->minimal, usages); } static const br_x509_class my_x509_vtable = { - sizeof(struct my_x509_context), - my_start_chain, - my_start_cert, - my_append, - my_end_cert, - my_end_chain, - my_get_pkey + sizeof(struct my_x509_context), + my_start_chain, + my_start_cert, + my_append, + my_end_cert, + my_end_chain, + my_get_pkey }; static int sock_read(void *ctx, unsigned char *buf, size_t len) { - int fd = *(int *)ctx; - for (;;) { - ssize_t rlen = read(fd, buf, len); - if (rlen <= 0) { - if (rlen < 0 && errno == EINTR) - continue; - return -1; - } - return (int)rlen; - } + int fd = *(int *)ctx; + for (;;) { + ssize_t rlen = read(fd, buf, len); + if (rlen <= 0) { + if (rlen < 0 && errno == EINTR) + continue; + return -1; + } + return (int)rlen; + } } static int sock_write(void *ctx, const unsigned char *buf, size_t len) { - int fd = *(int *)ctx; - for (;;) { - ssize_t wlen = write(fd, buf, len); - if (wlen <= 0) { - if (wlen < 0 && errno == EINTR) - continue; - return -1; - } - return (int)wlen; - } + int fd = *(int *)ctx; + for (;;) { + ssize_t wlen = write(fd, buf, len); + if (wlen <= 0) { + if (wlen < 0 && errno == EINTR) + continue; + return -1; + } + return (int)wlen; + } } static int b64_decode_char(char c) { - if (c >= 'A' && c <= 'Z') return c - 'A'; - if (c >= 'a' && c <= 'z') return c - 'a' + 26; - if (c >= '0' && c <= '9') return c - '0' + 52; - if (c == '+') return 62; - if (c == '/') return 63; - return -1; + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; } static size_t b64_decode(const char *src, size_t src_len, unsigned char *dst) { - size_t i, j = 0; - int val = 0, valb = -8; - for (i = 0; i < src_len; i++) { - int c = b64_decode_char(src[i]); - if (c >= 0) { - val = (val << 6) | c; - valb += 6; - if (valb >= 0) { - dst[j++] = (val >> valb) & 0xFF; - valb -= 8; - } - } - } - return j; + size_t i, j = 0; + int val = 0, valb = -8; + for (i = 0; i < src_len; i++) { + int c = b64_decode_char(src[i]); + if (c >= 0) { + val = (val << 6) | c; + valb += 6; + if (valb >= 0) { + dst[j++] = (val >> valb) & 0xFF; + valb -= 8; + } + } + } + return j; } static int decode_cert_der(const unsigned char *der, size_t der_len, br_x509_trust_anchor *ta) { - br_x509_decoder_context dc; - struct dn_accum accum = { NULL, 0, 0 }; - const br_x509_pkey *pk; - - br_x509_decoder_init(&dc, append_dn_callback, &accum); - br_x509_decoder_push(&dc, der, der_len); - if (br_x509_decoder_last_error(&dc) != 0) { - free(accum.data); - return 0; - } - pk = br_x509_decoder_get_pkey(&dc); - if (!pk) { - free(accum.data); - return 0; - } - - ta->dn.data = accum.data; - ta->dn.len = accum.len; - ta->flags = br_x509_decoder_isCA(&dc) ? BR_X509_TA_CA : 0; - ta->pkey.key_type = pk->key_type; - - if (pk->key_type == BR_KEYTYPE_RSA) { - ta->pkey.key.rsa.nlen = pk->key.rsa.nlen; - ta->pkey.key.rsa.n = emalloc(pk->key.rsa.nlen); - memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, pk->key.rsa.nlen); - ta->pkey.key.rsa.elen = pk->key.rsa.elen; - ta->pkey.key.rsa.e = emalloc(pk->key.rsa.elen); - memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, pk->key.rsa.elen); - } else if (pk->key_type == BR_KEYTYPE_EC) { - ta->pkey.key.ec.curve = pk->key.ec.curve; - ta->pkey.key.ec.qlen = pk->key.ec.qlen; - ta->pkey.key.ec.q = emalloc(pk->key.ec.qlen); - memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen); - } else { - free(accum.data); - return 0; - } - return 1; + br_x509_decoder_context dc; + struct dn_accum accum = { NULL, 0, 0 }; + const br_x509_pkey *pk; + + br_x509_decoder_init(&dc, append_dn_callback, &accum); + br_x509_decoder_push(&dc, der, der_len); + if (br_x509_decoder_last_error(&dc) != 0) { + free(accum.data); + return 0; + } + pk = br_x509_decoder_get_pkey(&dc); + if (!pk) { + free(accum.data); + return 0; + } + + ta->dn.data = accum.data; + ta->dn.len = accum.len; + ta->flags = br_x509_decoder_isCA(&dc) ? BR_X509_TA_CA : 0; + ta->pkey.key_type = pk->key_type; + + if (pk->key_type == BR_KEYTYPE_RSA) { + ta->pkey.key.rsa.nlen = pk->key.rsa.nlen; + ta->pkey.key.rsa.n = emalloc(pk->key.rsa.nlen); + memcpy(ta->pkey.key.rsa.n, pk->key.rsa.n, pk->key.rsa.nlen); + ta->pkey.key.rsa.elen = pk->key.rsa.elen; + ta->pkey.key.rsa.e = emalloc(pk->key.rsa.elen); + memcpy(ta->pkey.key.rsa.e, pk->key.rsa.e, pk->key.rsa.elen); + } else if (pk->key_type == BR_KEYTYPE_EC) { + ta->pkey.key.ec.curve = pk->key.ec.curve; + ta->pkey.key.ec.qlen = pk->key.ec.qlen; + ta->pkey.key.ec.q = emalloc(pk->key.ec.qlen); + memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen); + } else { + free(accum.data); + return 0; + } + return 1; } static br_x509_trust_anchor *tas = NULL; @@ -216,222 +217,226 @@ static size_t tas_num = 0; static void load_ca_certs(void) { - static const char *ca_paths[] = { - "/etc/ssl/certs/ca-certificates.crt", - "/etc/ssl/cert.pem", - "/etc/pki/tls/certs/ca-bundle.crt", - }; - FILE *fp = NULL; - size_t i; - char line[512]; - struct { - char *data; - size_t len; - size_t cap; - } pem = { NULL, 0, 0 }; - int in_cert = 0; - - for (i = 0; i < LEN(ca_paths); i++) { - if ((fp = fopen(ca_paths[i], "r"))) - break; - } - if (!fp) { - weprintf("no CA certificates found, TLS verification will fail\n"); - return; - } - - while (fgets(line, sizeof(line), fp)) { - if (strncmp(line, "-----BEGIN CERTIFICATE-----", 27) == 0) { - in_cert = 1; - pem.len = 0; - } else if (strncmp(line, "-----END CERTIFICATE-----", 25) == 0) { - if (in_cert) { - unsigned char *der = emalloc(pem.len); - size_t der_len = b64_decode(pem.data, pem.len, der); - br_x509_trust_anchor ta; - if (decode_cert_der(der, der_len, &ta)) { - tas = ereallocarray(tas, tas_num + 1, sizeof(*tas)); - tas[tas_num++] = ta; - } - free(der); - in_cert = 0; - } - } else if (in_cert) { - size_t llen = strlen(line); - while (llen > 0 && (line[llen-1] == '\r' || line[llen-1] == '\n')) - llen--; - if (pem.len + llen > pem.cap) { - pem.cap = pem.len + llen + 1024; - pem.data = erealloc(pem.data, pem.cap); - } - memcpy(pem.data + pem.len, line, llen); - pem.len += llen; - } - } - free(pem.data); - fclose(fp); + static const char *ca_paths[] = { + ARUU_PATH_ETC "/ssl/certs/ca-certificates.crt", + ARUU_PATH_ETC "/ssl/cert.pem", + ARUU_PATH_ETC "/pki/tls/certs/ca-bundle.crt", + }; + FILE *fp = NULL; + size_t i; + char line[512]; + struct { + char *data; + size_t len; + size_t cap; + } pem = { NULL, 0, 0 }; + int in_cert = 0; + + for (i = 0; i < LEN(ca_paths); i++) { + if ((fp = fopen(ca_paths[i], "r"))) + break; + } + if (!fp) { + weprintf("no CA certificates found, TLS verification will fail\n"); + return; + } + + while (fgets(line, sizeof(line), fp)) { + if (strncmp(line, "-----BEGIN CERTIFICATE-----", 27) == 0) { + in_cert = 1; + pem.len = 0; + } else if (strncmp(line, "-----END CERTIFICATE-----", 25) == 0) { + if (in_cert) { + unsigned char *der = emalloc(pem.len); + size_t der_len = b64_decode(pem.data, pem.len, der); + br_x509_trust_anchor ta; + if (decode_cert_der(der, der_len, &ta)) { + tas = ereallocarray(tas, tas_num + 1, sizeof(*tas)); + tas[tas_num++] = ta; + } + free(der); + in_cert = 0; + } + } else if (in_cert) { + size_t llen = strlen(line); + while (llen > 0 && (line[llen-1] == '\r' || line[llen-1] == '\n')) + llen--; + if (pem.len + llen > pem.cap) { + pem.cap = pem.len + llen + 1024; + pem.data = erealloc(pem.data, pem.cap); + } + memcpy(pem.data + pem.len, line, llen); + pem.len += llen; + } + } + free(pem.data); + fclose(fp); } #else struct TlsSocket { - int fd; - int is_tls; + int fd; + int is_tls; }; #endif struct TlsSocket * tls_connect(int fd, const char *host, int check_cert, int is_tls) { - struct TlsSocket *s; + struct TlsSocket *s; - s = emalloc(sizeof(*s)); - s->fd = fd; - s->is_tls = is_tls; + s = emalloc(sizeof(*s)); + s->fd = fd; + s->is_tls = is_tls; - if (!is_tls) - return s; + if (!is_tls) + return s; +#if !FEATURE_USE_LIBRESSL && !FEATURE_USE_BEARSSL && !FEATURE_USE_OPENSSL + (void)host; + (void)check_cert; +#endif #if FEATURE_USE_LIBRESSL - { - struct tls_config *cfg; - - s->ctx = tls_client(); - if (!s->ctx) { - weprintf("tls_client failed\n"); - free(s); - return NULL; - } - cfg = tls_config_new(); - if (!cfg) { - weprintf("tls_config_new failed\n"); - tls_free(s->ctx); - free(s); - return NULL; - } - if (!check_cert) { - tls_config_insecure_noverifycert(cfg); - tls_config_insecure_noverifyname(cfg); - } - if (tls_configure(s->ctx, cfg) < 0) { - weprintf("tls_configure: %s\n", tls_error(s->ctx)); - tls_config_free(cfg); - tls_free(s->ctx); - free(s); - return NULL; - } - tls_config_free(cfg); - - if (tls_connect_socket(s->ctx, fd, host) < 0) { - weprintf("tls_connect_socket: %s\n", tls_error(s->ctx)); - tls_free(s->ctx); - free(s); - return NULL; - } - } + { + struct tls_config *cfg; + + s->ctx = tls_client(); + if (!s->ctx) { + weprintf("tls_client failed\n"); + free(s); + return NULL; + } + cfg = tls_config_new(); + if (!cfg) { + weprintf("tls_config_new failed\n"); + tls_free(s->ctx); + free(s); + return NULL; + } + if (!check_cert) { + tls_config_insecure_noverifycert(cfg); + tls_config_insecure_noverifyname(cfg); + } + if (tls_configure(s->ctx, cfg) < 0) { + weprintf("tls_configure: %s\n", tls_error(s->ctx)); + tls_config_free(cfg); + tls_free(s->ctx); + free(s); + return NULL; + } + tls_config_free(cfg); + + if (tls_connect_socket(s->ctx, fd, host) < 0) { + weprintf("tls_connect_socket: %s\n", tls_error(s->ctx)); + tls_free(s->ctx); + free(s); + return NULL; + } + } #elif FEATURE_USE_BEARSSL - { - signal(SIGPIPE, SIG_IGN); - - if (check_cert) { - static int ca_loaded = 0; - if (!ca_loaded) { - load_ca_certs(); - ca_loaded = 1; - } - br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, tas, tas_num); - } else { - br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, NULL, 0); - s->my_x509.vtable = &my_x509_vtable; - br_ssl_engine_set_x509(&s->sc.eng, &s->my_x509.vtable); - } - - br_ssl_engine_set_buffer(&s->sc.eng, s->iobuf, sizeof(s->iobuf), 1); - br_ssl_client_reset(&s->sc, host, 0); - br_sslio_init(&s->ioc, &s->sc.eng, sock_read, &s->fd, sock_write, &s->fd); - - if (br_sslio_flush(&s->ioc) < 0) { - weprintf("TLS handshake failed with %s\n", host); - free(s); - return NULL; - } - } + { + signal(SIGPIPE, SIG_IGN); + + if (check_cert) { + static int ca_loaded = 0; + if (!ca_loaded) { + load_ca_certs(); + ca_loaded = 1; + } + br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, tas, tas_num); + } else { + br_ssl_client_init_full(&s->sc, &s->my_x509.minimal, NULL, 0); + s->my_x509.vtable = &my_x509_vtable; + br_ssl_engine_set_x509(&s->sc.eng, &s->my_x509.vtable); + } + + br_ssl_engine_set_buffer(&s->sc.eng, s->iobuf, sizeof(s->iobuf), 1); + br_ssl_client_reset(&s->sc, host, 0); + br_sslio_init(&s->ioc, &s->sc.eng, sock_read, &s->fd, sock_write, &s->fd); + + if (br_sslio_flush(&s->ioc) < 0) { + weprintf("TLS handshake failed with %s\n", host); + free(s); + return NULL; + } + } #else - weprintf("TLS not supported, compile with FEATURE_USE_LIBRESSL or FEATURE_USE_BEARSSL\n"); - free(s); - return NULL; + weprintf("TLS not supported, compile with FEATURE_USE_LIBRESSL or FEATURE_USE_BEARSSL\n"); + free(s); + return NULL; #endif - return s; + return s; } ssize_t tls_read(struct TlsSocket *s, void *buf, size_t len) { - if (!s->is_tls) { - for (;;) { - ssize_t r = read(s->fd, buf, len); - if (r < 0 && errno == EINTR) - continue; - return r; - } - } + if (!s->is_tls) { + for (;;) { + ssize_t r = read(s->fd, buf, len); + if (r < 0 && errno == EINTR) + continue; + return r; + } + } #if FEATURE_USE_LIBRESSL - for (;;) { - ssize_t r = tls_read(s->ctx, buf, len); - if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) - continue; - return r; - } + for (;;) { + ssize_t r = tls_read(s->ctx, buf, len); + if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) + continue; + return r; + } #elif FEATURE_USE_BEARSSL - return br_sslio_read(&s->ioc, buf, len); + return br_sslio_read(&s->ioc, buf, len); #else - return -1; + return -1; #endif } ssize_t tls_write(struct TlsSocket *s, const void *buf, size_t len) { - if (!s->is_tls) { - for (;;) { - ssize_t r = write(s->fd, buf, len); - if (r < 0 && errno == EINTR) - continue; - return r; - } - } + if (!s->is_tls) { + for (;;) { + ssize_t r = write(s->fd, buf, len); + if (r < 0 && errno == EINTR) + continue; + return r; + } + } #if FEATURE_USE_LIBRESSL - for (;;) { - ssize_t r = tls_write(s->ctx, buf, len); - if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) - continue; - return r; - } + for (;;) { + ssize_t r = tls_write(s->ctx, buf, len); + if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) + continue; + return r; + } #elif FEATURE_USE_BEARSSL - { - int r = br_sslio_write_all(&s->ioc, buf, len); - if (r < 0) - return -1; - if (br_sslio_flush(&s->ioc) < 0) - return -1; - return len; - } + { + int r = br_sslio_write_all(&s->ioc, buf, len); + if (r < 0) + return -1; + if (br_sslio_flush(&s->ioc) < 0) + return -1; + return len; + } #else - return -1; + return -1; #endif } void tls_close(struct TlsSocket *s, int close_fd) { - if (s->is_tls) { + if (s->is_tls) { #if FEATURE_USE_LIBRESSL - tls_close(s->ctx); - tls_free(s->ctx); + tls_close(s->ctx); + tls_free(s->ctx); #elif FEATURE_USE_BEARSSL - br_sslio_close(&s->ioc); + br_sslio_close(&s->ioc); #endif - } - if (close_fd) - close(s->fd); - free(s); + } + if (close_fd) + close(s->fd); + free(s); } diff --git a/shared/libutil/tty.c b/shared/libutil/tty.c @@ -11,88 +11,89 @@ #include <string.h> #include <unistd.h> +#include "../paths.h" #include "../util.h" void devtotty(int dev, int *tty_maj, int *tty_min) { - *tty_maj = (dev >> 8) & 0xfff; - *tty_min = (dev & 0xff) | ((dev >> 12) & 0xfff00); + *tty_maj = (dev >> 8) & 0xfff; + *tty_min = (dev & 0xff) | ((dev >> 12) & 0xfff00); } int ttytostr(int tty_maj, int tty_min, char *str, size_t n) { - struct stat sb; - struct dirent *dp; - DIR *dirp; - char path[PATH_MAX]; - int fd; - int r = 0; + struct stat sb; + struct dirent *dp; + DIR *dirp; + char path[PATH_MAX]; + int fd; + int r = 0; - switch (tty_maj) { - case 136: - snprintf(str, n, "pts/%d", tty_min); - return 0; - case 4: - snprintf(str, n, "tty%d", tty_min); - return 0; - default: - str[0] = '?'; - str[1] = '\0'; - break; - } + switch (tty_maj) { + case 136: + snprintf(str, n, "pts/%d", tty_min); + return 0; + case 4: + snprintf(str, n, "tty%d", tty_min); + return 0; + default: + str[0] = '?'; + str[1] = '\0'; + break; + } - dirp = opendir("/dev"); - if (!dirp) { - weprintf("opendir /dev:"); - return -1; - } + dirp = opendir("/dev"); + if (!dirp) { + weprintf("opendir /dev:"); + return -1; + } - while ((dp = readdir(dirp))) { - if (!strcmp(dp->d_name, ".") || - !strcmp(dp->d_name, "..")) - continue; + while ((dp = readdir(dirp))) { + if (!strcmp(dp->d_name, ".") || + !strcmp(dp->d_name, "..")) + continue; - if (strlcpy(path, "/dev/", sizeof(path)) >= sizeof(path)) { - weprintf("path too long\n"); - r = -1; - goto err0; - } - if (strlcat(path, dp->d_name, sizeof(path)) >= sizeof(path)) { - weprintf("path too long\n"); - r = -1; - goto err0; - } + if (strlcpy(path, ARUU_PATH_DEV "/", sizeof(path)) >= sizeof(path)) { + weprintf("path too long\n"); + r = -1; + goto err0; + } + if (strlcat(path, dp->d_name, sizeof(path)) >= sizeof(path)) { + weprintf("path too long\n"); + r = -1; + goto err0; + } - if (stat(path, &sb) < 0) { - weprintf("stat %s:", path); - r = -1; - goto err0; - } + if (stat(path, &sb) < 0) { + weprintf("stat %s:", path); + r = -1; + goto err0; + } - if ((int)major(sb.st_rdev) == tty_maj && - (int)minor(sb.st_rdev) == tty_min) { - fd = open(path, O_RDONLY | O_NONBLOCK); - if (fd < 0) - continue; - if (isatty(fd)) { - strlcpy(str, dp->d_name, n); - close(fd); - break; - } else { - close(fd); - r = -1; - goto err0; - } - } - } + if ((int)major(sb.st_rdev) == tty_maj && + (int)minor(sb.st_rdev) == tty_min) { + fd = open(path, O_RDONLY | O_NONBLOCK); + if (fd < 0) + continue; + if (isatty(fd)) { + strlcpy(str, dp->d_name, n); + close(fd); + break; + } else { + close(fd); + r = -1; + goto err0; + } + } + } err0: - if (closedir(dirp) < 0) { - weprintf("closedir /dev:"); - r = -1; - } + if (closedir(dirp) < 0) { + weprintf("closedir /dev:"); + r = -1; + } - return r; + return r; } diff --git a/shared/libutil/wexec.c b/shared/libutil/wexec.c @@ -0,0 +1,343 @@ +/* See LICENSE file for copyright and license details. */ +#include "../config.h" +#include "../wexec.h" +#include "../paths.h" +#include "../util.h" + +#include <errno.h> +#include <signal.h> +#include <stdlib.h> +#include <string.h> +#include <sys/wait.h> +#include <unistd.h> + +#define MAX_BUILTINS 128 +#define MAX_POPEN 32 + +struct builtin { + const char *name; + wexec_fn fn; +}; + +static struct builtin builtins[MAX_BUILTINS]; +static int nbuiltins; + +struct popen_entry { + FILE *fp; + pid_t pid; +}; + +static struct popen_entry popen_tab[MAX_POPEN]; +static int npopen; + +int +wpopen_track(FILE *fp, pid_t pid) +{ + if (npopen >= MAX_POPEN) + return -1; + popen_tab[npopen].fp = fp; + popen_tab[npopen].pid = pid; + npopen++; + return 0; +} + +pid_t +wpopen_untrack(FILE *fp) +{ + int i; + pid_t pid = -1; + for (i = 0; i < npopen; i++) { + if (popen_tab[i].fp == fp) { + pid = popen_tab[i].pid; + popen_tab[i] = popen_tab[npopen - 1]; + npopen--; + break; + } + } + return pid; +} + +int +wexec_register(const char *name, wexec_fn fn) +{ + int i; + for (i = 0; i < nbuiltins; i++) { + if (strcmp(builtins[i].name, name) == 0) + return -1; + } + if (nbuiltins >= MAX_BUILTINS) + return -1; + builtins[nbuiltins].name = name; + builtins[nbuiltins].fn = fn; + nbuiltins++; + return 0; +} + +int +wexec_is_builtin(const char *name) +{ + int i; + for (i = 0; i < nbuiltins; i++) { + if (strcmp(builtins[i].name, name) == 0) + return 1; + } + return 0; +} + +#if FEATURE_INPROC_EXEC +static int +call_builtin(const char *name, char *const *argv) +{ + int i, argc; + char **p; + + argc = 0; + for (p = (char **)argv; *p; p++) + argc++; + for (i = 0; i < nbuiltins; i++) { + if (strcmp(builtins[i].name, name) == 0) { + fflush(stdout); + fflush(stderr); + return builtins[i].fn(argc, (char **)argv); + } + } + return -1; +} +#endif + +static int +fork_exec(const char *path, char *const *argv, int use_path) +{ + pid_t pid; + int st; + + pid = fork(); + if (pid < 0) { + weprintf("fork:"); + return -1; + } + if (pid == 0) { + if (use_path) + execvp(path, argv); + else + execv(path, argv); + _exit(127); + } + if (waitpid(pid, &st, 0) < 0) { + weprintf("waitpid:"); + return -1; + } + if (WIFEXITED(st)) + return WEXITSTATUS(st); + if (WIFSIGNALED(st)) + return 128 + WTERMSIG(st); + return -1; +} + +int +wexecvp(const char *name, char *const *argv) +{ +#if FEATURE_INPROC_EXEC + if (wexec_is_builtin(name)) { + fflush(stdout); + fflush(stderr); + return call_builtin(name, argv); + } +#endif + return fork_exec(name, argv, 1); +} + +int +wexecv(const char *path, char *const *argv) +{ +#if FEATURE_INPROC_EXEC + { + const char *base = strrchr(path, '/'); + base = base ? base + 1 : path; + if (wexec_is_builtin(base)) { + fflush(stdout); + fflush(stderr); + return call_builtin(base, argv); + } + } +#endif + return fork_exec(path, argv, 0); +} + +FILE * +wpopen(const char *name, char *const *argv, const char *mode) +{ + int pfd[2]; + pid_t pid; + int parent_end, child_end; + char *sh_argv[4]; + + if (pipe(pfd) < 0) { + weprintf("pipe:"); + return NULL; + } + + if (*mode == 'r') { + parent_end = pfd[0]; + child_end = pfd[1]; + } else { + parent_end = pfd[1]; + child_end = pfd[0]; + } + + pid = fork(); + if (pid < 0) { + weprintf("fork:"); + close(pfd[0]); + close(pfd[1]); + return NULL; + } + + if (pid == 0) { + close(parent_end); + if (child_end != (*mode == 'r' ? STDOUT_FILENO : STDIN_FILENO)) { + dup2(child_end, *mode == 'r' ? STDOUT_FILENO : STDIN_FILENO); + close(child_end); + } + if (argv) { +#if FEATURE_INPROC_EXEC + if (wexec_is_builtin(name)) { + int argc; + char **p; + argc = 0; + for (p = (char **)argv; *p; p++) + argc++; + call_builtin(name, argv); + fflush(stdout); + fflush(stderr); + _exit(0); + } +#endif + execvp(name, argv); + _exit(127); + } else { + sh_argv[0] = "sh"; + sh_argv[1] = "-c"; + sh_argv[2] = (char *)name; + sh_argv[3] = NULL; +#if FEATURE_INPROC_EXEC + if (wexec_is_builtin("sh")) { + call_builtin("sh", sh_argv); + fflush(stdout); + fflush(stderr); + _exit(0); + } +#endif + execvp("sh", sh_argv); + _exit(127); + } + } + + close(child_end); + { + FILE *fp = fdopen(parent_end, mode); + if (!fp) { + weprintf("fdopen:"); + close(parent_end); + kill(pid, SIGTERM); + waitpid(pid, NULL, 0); + return NULL; + } + if (wpopen_track(fp, pid) < 0) { + fclose(fp); + kill(pid, SIGTERM); + waitpid(pid, NULL, 0); + return NULL; + } + return fp; + } +} + +int +wpclose(FILE *fp) +{ + int st; + pid_t pid; + + pid = wpopen_untrack(fp); + if (fclose(fp) == EOF) + weprintf("fclose:"); + if (pid < 0) + return -1; + if (waitpid(pid, &st, 0) < 0) { + weprintf("waitpid:"); + return -1; + } + if (WIFEXITED(st)) + return WEXITSTATUS(st); + if (WIFSIGNALED(st)) + return 128 + WTERMSIG(st); + return -1; +} + +int +wsystem(const char *cmd) +{ +#if FEATURE_INPROC_EXEC + if (wexec_is_builtin("sh")) { + char *sh_argv[4]; + sh_argv[0] = "sh"; + sh_argv[1] = "-c"; + sh_argv[2] = (char *)cmd; + sh_argv[3] = NULL; + return wexecvp("sh", sh_argv); + } +#endif + { + char *sh_argv[4]; + int ret; + sh_argv[0] = "sh"; + sh_argv[1] = "-c"; + sh_argv[2] = (char *)cmd; + sh_argv[3] = NULL; + ret = fork_exec("sh", sh_argv, 1); + return ret; + } +} + +void +wexecvp_self(const char *name, char *const *argv) +{ +#if FEATURE_INPROC_EXEC + if (wexec_is_builtin(name)) { + int ret; + fflush(stdout); + fflush(stderr); + ret = call_builtin(name, argv); + fflush(stdout); + fflush(stderr); + exit(ret); + } +#endif + execvp(name, argv); + weprintf("execvp %s:", name); + exit((errno == ENOENT) ? 127 : 126); +} + +void +wexecv_self(const char *path, char *const *argv) +{ +#if FEATURE_INPROC_EXEC + { + const char *base = strrchr(path, '/'); + base = base ? base + 1 : path; + if (wexec_is_builtin(base)) { + int ret; + fflush(stdout); + fflush(stderr); + ret = call_builtin(base, argv); + fflush(stdout); + fflush(stderr); + exit(ret); + } + } +#endif + execv(path, argv); + weprintf("execv %s:", path); + exit((errno == ENOENT) ? 127 : 126); +} diff --git a/shared/passwd.h b/shared/passwd.h @@ -1,4 +1,25 @@ /* See LICENSE file for copyright and license details. */ -/* passwd.c */ -int pw_check(const struct passwd *, const char *); +#ifndef ARUU_PASSWD_H +#define ARUU_PASSWD_H + +#include <pwd.h> +#include <sys/types.h> + +struct pwdb_entry { + char *name; + char *hash; + uid_t uid; + gid_t gid; +}; + int pw_init(void); +int pw_check(const struct passwd *pw, const char *pass); +int pwdb_lookup(struct pwdb_entry *ent, const char *name); + +#define PW_SALT_MAX 64 +int pw_gensalt(char *salt, size_t salt_sz); +int pw_gensalt_cipher(char *salt, size_t salt_sz, const char *prefix, + size_t rand_len); +int pwdb_update(const char *name, const char *newhash); + +#endif diff --git a/shared/paths.h b/shared/paths.h @@ -0,0 +1,96 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef ARUU_PATHS_H +#define ARUU_PATHS_H + +/* + * portable paths. override at compile time for non-FHS systems: + * -DARUU_PATH_ETC="/config" + * + * OS-specific paths (procfs, sysfs) are prefixed ARUU_LINUX_PATH_* + * and only defined under __linux__. a util that reads /proc/modules + * will fail to compile on BSD because ARUU_LINUX_PATH_PROC is not + * defined there. this is intentional: the BSD code path must use + * a different mechanism (sysctl, getmntinfo, etc) + */ + +#ifndef ARUU_PATH_ETC +#define ARUU_PATH_ETC "/etc" +#endif + +#ifndef ARUU_PATH_VAR +#define ARUU_PATH_VAR "/var" +#endif + +#ifndef ARUU_PATH_DEV +#define ARUU_PATH_DEV "/dev" +#endif + +#ifndef ARUU_PATH_RUN +#define ARUU_PATH_RUN "/run" +#endif + +#ifndef ARUU_PATH_TMP +#define ARUU_PATH_TMP "/tmp" +#endif + +#ifndef ARUU_PATH_BIN +#define ARUU_PATH_BIN "/bin" +#endif + +#ifndef ARUU_PATH_SBIN +#define ARUU_PATH_SBIN "/sbin" +#endif + +#ifndef ARUU_PATH_USR_BIN +#define ARUU_PATH_USR_BIN "/usr/bin" +#endif + +#ifndef ARUU_PATH_USR_SBIN +#define ARUU_PATH_USR_SBIN "/usr/sbin" +#endif + +#define ARUU_PATH_PASSWD ARUU_PATH_ETC "/passwd" +#define ARUU_PATH_SHADOW ARUU_PATH_ETC "/shadow" +#define ARUU_PATH_GROUP ARUU_PATH_ETC "/group" +#define ARUU_PATH_DEVNULL ARUU_PATH_DEV "/null" +#define ARUU_PATH_DEVURANDOM ARUU_PATH_DEV "/urandom" +#define ARUU_PATH_DEVRANDOM ARUU_PATH_DEV "/random" +#define ARUU_PATH_DEVTTY ARUU_PATH_DEV "/tty" +#define ARUU_PATH_DEVCONSOLE ARUU_PATH_DEV "/console" +#define ARUU_PATH_UTMP ARUU_PATH_RUN "/utmp" +#define ARUU_PATH_WTMP ARUU_PATH_VAR "/log/wtmp" +#define ARUU_PATH_BTMP ARUU_PATH_VAR "/log/btmp" +#define ARUU_PATH_LASTLOG ARUU_PATH_VAR "/log/lastlog" +#define ARUU_PATH_BSHELL ARUU_PATH_BIN "/sh" +#define ARUU_PATH_STDPATH ARUU_PATH_BIN ":/usr/bin" +#define ARUU_PATH_DEFPATH ARUU_PATH_BIN ":/usr/bin" + +#if defined(__linux__) +#define ARUU_LINUX_PATH_PROC "/proc" +#define ARUU_LINUX_PATH_SYS "/sys" +#define ARUU_LINUX_PATH_PROC_MOUNTS ARUU_LINUX_PATH_PROC "/mounts" +#define ARUU_LINUX_PATH_PROC_PARTITIONS ARUU_LINUX_PATH_PROC "/partitions" +#define ARUU_LINUX_PATH_PROC_MEMINFO ARUU_LINUX_PATH_PROC "/meminfo" +#define ARUU_LINUX_PATH_PROC_LOADAVG ARUU_LINUX_PATH_PROC "/loadavg" +#define ARUU_LINUX_PATH_PROC_CMDLINE ARUU_LINUX_PATH_PROC "/cmdline" +#define ARUU_LINUX_PATH_PROC_VERSION ARUU_LINUX_PATH_PROC "/version" +#define ARUU_LINUX_PATH_PROC_MODULES ARUU_LINUX_PATH_PROC "/modules" +#define ARUU_LINUX_PATH_PROC_SYS ARUU_LINUX_PATH_PROC "/sys" +#define ARUU_LINUX_PATH_SYS_MODULE ARUU_LINUX_PATH_SYS "/module" +#define ARUU_LINUX_PATH_SYS_BLOCK ARUU_LINUX_PATH_SYS "/block" +#define ARUU_LINUX_PATH_SYS_CLASS_NET ARUU_LINUX_PATH_SYS "/class/net" +#define ARUU_LINUX_PATH_SYS_KERNEL ARUU_LINUX_PATH_SYS "/kernel" +#define ARUU_LINUX_PATH_SYS_BUS_USB ARUU_LINUX_PATH_SYS "/bus/usb/devices" +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +/* BSD systems do not have procfs or sysfs. utils that need this data + * must use sysctl(3), getmntinfo(3), or kvm(3) instead */ +#else +#error "paths.h: unsupported platform. define ARUU_LINUX_PATH_* or ARUU_BSD_PATH_* manually" +#endif + +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) +#define ARUU_BSD_PATH_MASTER_PASSWD ARUU_PATH_ETC "/master.passwd" +#define ARUU_BSD_PATH_PWD_MKDB ARUU_PATH_USR_SBIN "/pwd_mkdb" +#endif + +#endif diff --git a/shared/util.h b/shared/util.h @@ -116,45 +116,45 @@ int ttytostr(int, int, char *, size_t); #endif struct NetStats { - unsigned long long rx_bytes; - unsigned long long rx_packets; - unsigned long long rx_errs; - unsigned long long rx_drop; - unsigned long long tx_bytes; - unsigned long long tx_packets; - unsigned long long tx_errs; - unsigned long long tx_drop; + unsigned long long rx_bytes; + unsigned long long rx_packets; + unsigned long long rx_errs; + unsigned long long rx_drop; + unsigned long long tx_bytes; + unsigned long long tx_packets; + unsigned long long tx_errs; + unsigned long long tx_drop; }; struct NetInterface { - char name[IFNAMSIZ]; - unsigned int flags; - int mtu; - int metric; - unsigned char mac[6]; - int has_mac; - - /* ipv4 addresses */ - struct sockaddr_in ipv4_addr; - int has_ipv4; - struct sockaddr_in ipv4_mask; - struct sockaddr_in ipv4_brd; - - /* ipv6 addresses */ - struct sockaddr_in6 ipv6_addr; - int has_ipv6; - unsigned int ipv6_scope; - unsigned int ipv6_prefix; + char name[IFNAMSIZ]; + unsigned int flags; + int mtu; + int metric; + unsigned char mac[6]; + int has_mac; + + /* ipv4 addresses */ + struct sockaddr_in ipv4_addr; + int has_ipv4; + struct sockaddr_in ipv4_mask; + struct sockaddr_in ipv4_brd; + + /* ipv6 addresses */ + struct sockaddr_in6 ipv6_addr; + int has_ipv6; + unsigned int ipv6_scope; + unsigned int ipv6_prefix; }; struct MemInfo { - unsigned long long total; - unsigned long long free; - unsigned long long shared; - unsigned long long buffers; - unsigned long long cached; - unsigned long long totalswap; - unsigned long long freeswap; + unsigned long long total; + unsigned long long free; + unsigned long long shared; + unsigned long long buffers; + unsigned long long cached; + unsigned long long totalswap; + unsigned long long freeswap; }; int net_get_interfaces(struct NetInterface **, int *); diff --git a/shared/wexec.h b/shared/wexec.h @@ -0,0 +1,27 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef ARUU_WEXEC_H +#define ARUU_WEXEC_H + +#include <stdio.h> +#include <sys/types.h> + +typedef int (*wexec_fn)(int argc, char **argv); + +int wexec_register(const char *name, wexec_fn fn); +int wexec_is_builtin(const char *name); + +int wexecvp(const char *name, char *const *argv); +int wexecv(const char *path, char *const *argv); + +FILE *wpopen(const char *name, char *const *argv, const char *mode); +int wpclose(FILE *fp); + +int wsystem(const char *cmd); + +void wexecvp_self(const char *name, char *const *argv); +void wexecv_self(const char *path, char *const *argv); + +int wpopen_track(FILE *fp, pid_t pid); +pid_t wpopen_untrack(FILE *fp); + +#endif