aruu

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

commit cae0536930ff7b7ba48bee54dc415c6f88cfdbbc
parent 25e5f43a0b2e6836862c194d87d277fb2317486c
Author: xplshn <anto@xplshn.com.ar>
Date:   Tue, 18 Aug 2026 17:14:54 -0300

working login, passwd, fdisk, ld, as, cc1, ip, ifconfig, b3sum

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

Diffstat:
M.gitignore | 15++++++++++++++-
MMakefile | 2+-
Mbuild.cfg | 47+++++++++++++++++++++++++++++++----------------
Mcmd/dev/ninqu/expand.c | 18+++++++++---------
Mcmd/dev/ninqu/gate.c | 2+-
Mcmd/dev/ninqu/main.c | 2+-
Mcmd/dev/ninqu/ninja.c | 20++++++++++----------
Mcmd/dev/ninqu/ninqu.h | 2+-
Mcmd/dev/ninqu/parse.c | 18+++++++++---------
Mcmd/dev/ninqu/resolve.c | 8++++----
Mcmd/extra/b3sum.c | 4571+------------------------------------------------------------------------------
Mcmd/extra/blkid.c | 2+-
Acmd/extra/dc.c | 2223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/extra/fdisk.c | 217++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Acmd/extra/install.c | 269+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/extra/lsblk.c | 2+-
Acmd/extra/pgrep.c | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/extra/sync.c | 6+++---
Mcmd/extra/yap/commands.c | 216++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/display.c | 204++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/getcomm.c | 84++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/getline.c | 170++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/help.c | 32++++++++++++++++----------------
Mcmd/extra/yap/keys.c | 54+++++++++++++++++++++++++++---------------------------
Mcmd/extra/yap/machine.c | 70+++++++++++++++++++++++++++++++++++-----------------------------------
Mcmd/extra/yap/main.c | 52++++++++++++++++++++++++++--------------------------
Mcmd/extra/yap/options.c | 18+++++++++---------
Mcmd/extra/yap/output.c | 14+++++++-------
Mcmd/extra/yap/pattern.c | 2+-
Mcmd/extra/yap/process.c | 26+++++++++++++-------------
Mcmd/extra/yap/prompt.c | 24++++++++++++------------
Mcmd/extra/yap/term.c | 72++++++++++++++++++++++++++++++++++++------------------------------------
Mcmd/linux/blkdiscard.c | 2+-
Mcmd/linux/chvt.c | 2+-
Mcmd/linux/ctrlaltdel.c | 2+-
Mcmd/linux/eject.c | 2+-
Mcmd/linux/freeramdisk.c | 2+-
Mcmd/linux/fsfreeze.c | 6+++---
Mcmd/linux/hwclock.c | 4++--
Mcmd/linux/lsusb.c | 2+-
Mcmd/linux/mkswap.c | 6+++---
Mcmd/linux/modprobe.c | 40++++++++++++++++++++--------------------
Mcmd/linux/mount.c | 6+++---
Mcmd/linux/mountpoint.c | 2+-
Mcmd/linux/pivot_root.c | 2+-
Mcmd/linux/readahead.c | 2+-
Mcmd/linux/swaplabel.c | 2+-
Mcmd/linux/swapoff.c | 2+-
Mcmd/linux/swapon.c | 2+-
Mcmd/linux/switch_root.c | 6+++---
Mcmd/linux/sysctl.c | 2+-
Mcmd/linux/tunctl.c | 2+-
Mcmd/linux/umount.c | 2+-
Mcmd/linux/unshare.c | 2+-
Mcmd/linux/vtallow.c | 2+-
Mcmd/net/host.c | 2+-
Mcmd/net/httpd.c | 2+-
Mcmd/net/ifconfig.c | 2+-
Mcmd/net/ip.c | 22+++++++++++++++++-----
Mcmd/net/netcat.c | 2+-
Mcmd/net/ping.c | 2+-
Mcmd/net/sdhcp.c | 8++++----
Mcmd/net/tftp.c | 2+-
Mcmd/net/wget.c | 46+++++++++++++++++++++++++++++++++-------------
Mcmd/posix/awk/awk.h | 78+++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/posix/awk/b.c | 340++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/awk/lex.c | 56++++++++++++++++++++++++++++----------------------------
Mcmd/posix/awk/lib.c | 116++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/awk/main.c | 68++++++++++++++++++++++++++++++++++----------------------------------
Mcmd/posix/awk/maketab.c | 54+++++++++++++++++++++++++++---------------------------
Mcmd/posix/awk/math.c | 46+++++++++++++++++++++++-----------------------
Mcmd/posix/awk/parse.c | 52++++++++++++++++++++++++++--------------------------
Mcmd/posix/awk/proto.h | 46+++++++++++++++++++++++-----------------------
Mcmd/posix/awk/run.c | 264++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/awk/tran.c | 118++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/basename.c | 2+-
Mcmd/posix/bc.y | 269+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcmd/posix/cal.c | 16++++++++--------
Mcmd/posix/cat.c | 4++--
Mcmd/posix/chgrp.c | 2+-
Mcmd/posix/chmod.c | 6+++---
Mcmd/posix/chown.c | 2+-
Mcmd/posix/cksum.c | 2+-
Mcmd/posix/cmp.c | 2+-
Mcmd/posix/comm.c | 2+-
Mcmd/posix/cp.c | 2+-
Mcmd/posix/cut.c | 31++++++++++++++++---------------
Mcmd/posix/date.c | 2+-
Mcmd/posix/dd.c | 24++++++++++++++++++++----
Mcmd/posix/df.c | 2+-
Mcmd/posix/diff.c | 4++--
Mcmd/posix/dirname.c | 2+-
Mcmd/posix/du.c | 2+-
Mcmd/posix/echo.c | 2+-
Mcmd/posix/ed.c | 56++++++++++++++++++++++++++++----------------------------
Mcmd/posix/env.c | 2+-
Mcmd/posix/expand.c | 2+-
Mcmd/posix/expr.c | 4++--
Mcmd/posix/false.c | 2+-
Mcmd/posix/find.c | 144++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/fold.c | 2+-
Mcmd/posix/getconf.c | 2+-
Mcmd/posix/head.c | 2+-
Mcmd/posix/id.c | 4++--
Mcmd/posix/join.c | 10+++++-----
Mcmd/posix/kill.c | 4++--
Mcmd/posix/link.c | 2+-
Mcmd/posix/ln.c | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcmd/posix/logger.c | 2+-
Mcmd/posix/logname.c | 2+-
Mcmd/posix/make/main.c | 20++++++++++----------
Mcmd/posix/make/parser.c | 36++++++++++++++++++------------------
Mcmd/posix/mesg.c | 2+-
Mcmd/posix/mkdir.c | 2+-
Mcmd/posix/mkfifo.c | 2+-
Mcmd/posix/mv.c | 2+-
Mcmd/posix/nice.c | 2+-
Mcmd/posix/nl.c | 2+-
Mcmd/posix/nohup.c | 2+-
Mcmd/posix/od.c | 24++++++++++++++++++++----
Mcmd/posix/paste.c | 2+-
Mcmd/posix/patch.c | 7++++---
Mcmd/posix/pathchk.c | 20++++++++++----------
Mcmd/posix/pax.c | 4++--
Mcmd/posix/printf.c | 2+-
Mcmd/posix/ps.c | 22+++++++++++-----------
Mcmd/posix/pwd.c | 2+-
Mcmd/posix/readlink.c | 2+-
Mcmd/posix/renice.c | 2+-
Mcmd/posix/rm.c | 2+-
Mcmd/posix/rmdir.c | 2+-
Mcmd/posix/sed.c | 226++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/alias.c | 48++++++++++++++++++++++++------------------------
Mcmd/posix/sh/alias.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/arith.h | 32++++++++++++++++----------------
Mcmd/posix/sh/arith_yacc.c | 46+++++++++++++++++++++++-----------------------
Mcmd/posix/sh/arith_yacc.h | 40++++++++++++++++++++--------------------
Mcmd/posix/sh/arith_yylex.c | 40++++++++++++++++++++--------------------
Mcmd/posix/sh/bltin.h | 42+++++++++++++++++++++---------------------
Mcmd/posix/sh/cd.c | 94++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/cd.h | 32++++++++++++++++----------------
Mcmd/posix/sh/easter.c | 14+++++++-------
Mcmd/posix/sh/echo.c | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/error.c | 86++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/error.h | 54+++++++++++++++++++++++++++---------------------------
Mcmd/posix/sh/eval.c | 230++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/eval.h | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/exec.c | 144++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/exec.h | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/expand.c | 180++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/expand.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/input.c | 120++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/input.h | 42+++++++++++++++++++++---------------------
Mcmd/posix/sh/jobs.c | 148++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/jobs.h | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/kill.c | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/lineedit.c | 42+++++++++++++++++++++---------------------
Mcmd/posix/sh/mail.c | 44++++++++++++++++++++++----------------------
Mcmd/posix/sh/mail.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/main.c | 90++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/main.h | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/memalloc.c | 92++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/memalloc.h | 46+++++++++++++++++++++++-----------------------
Mcmd/posix/sh/miscbltin.c | 120++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/mknodes.c | 46+++++++++++++++++++++++-----------------------
Mcmd/posix/sh/mksyntax.c | 72++++++++++++++++++++++++++++++++++++------------------------------------
Mcmd/posix/sh/mystring.c | 50+++++++++++++++++++++++++-------------------------
Mcmd/posix/sh/mystring.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/options.c | 130++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/options.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/output.c | 54+++++++++++++++++++++++++++---------------------------
Mcmd/posix/sh/output.h | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/parser.c | 400++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/parser.h | 54+++++++++++++++++++++++++++---------------------------
Mcmd/posix/sh/printf.c | 80++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/redir.c | 70+++++++++++++++++++++++++++++++++++-----------------------------------
Mcmd/posix/sh/redir.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/sh_cdefs.h | 18+++++++++---------
Mcmd/posix/sh/shell.h | 50+++++++++++++++++++++++++-------------------------
Mcmd/posix/sh/show.c | 40++++++++++++++++++++--------------------
Mcmd/posix/sh/show.h | 32++++++++++++++++----------------
Mcmd/posix/sh/test.c | 56++++++++++++++++++++++++++++----------------------------
Mcmd/posix/sh/trap.c | 130++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/trap.h | 36++++++++++++++++++------------------
Mcmd/posix/sh/var.c | 160++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/var.h | 50+++++++++++++++++++++++++-------------------------
Mcmd/posix/sleep.c | 2+-
Mcmd/posix/sort.c | 18+++++++++---------
Mcmd/posix/split.c | 2+-
Mcmd/posix/tail.c | 10+++++-----
Mcmd/posix/tee.c | 2+-
Mcmd/posix/test.c | 2+-
Mcmd/posix/time.c | 2+-
Mcmd/posix/touch.c | 4++--
Mcmd/posix/tr.c | 4++--
Mcmd/posix/true.c | 2+-
Mcmd/posix/tsort.c | 2+-
Mcmd/posix/tty.c | 2+-
Mcmd/posix/uname.c | 2+-
Mcmd/posix/unexpand.c | 2+-
Mcmd/posix/uniq.c | 2+-
Mcmd/posix/unlink.c | 2+-
Mcmd/posix/uudecode.c | 4++--
Mcmd/posix/uuencode.c | 2+-
Mcmd/posix/wc.c | 2+-
Mcmd/posix/who.c | 2+-
Mcmd/posix/xargs.c | 4++--
Mcmd/pseudo/base64.c | 2+-
Mcmd/pseudo/chroot.c | 2+-
Mcmd/pseudo/clear.c | 2+-
Mcmd/pseudo/cols.c | 2+-
Mcmd/pseudo/cron.c | 6+++---
Mcmd/pseudo/diff3.c | 2+-
Mcmd/pseudo/dmesg.c | 2+-
Mcmd/pseudo/fallocate.c | 2+-
Mcmd/pseudo/flock.c | 2+-
Mcmd/pseudo/free.c | 2+-
Mcmd/pseudo/getty.c | 6+++---
Acmd/pseudo/gzip.c | 715+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/pseudo/halt.c | 2+-
Mcmd/pseudo/hostname.c | 2+-
Acmd/pseudo/install.c | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/pseudo/killall5.c | 2+-
Mcmd/pseudo/last.c | 2+-
Mcmd/pseudo/lastlog.c | 4++--
Dcmd/pseudo/login.c | 138-------------------------------------------------------------------------------
Mcmd/pseudo/md5sum.c | 2+-
Dcmd/pseudo/mkpasswd.c | 138-------------------------------------------------------------------------------
Mcmd/pseudo/mktemp.c | 2+-
Mcmd/pseudo/nologin.c | 2+-
Acmd/pseudo/nproc.c | 41+++++++++++++++++++++++++++++++++++++++++
Mcmd/pseudo/pagesize.c | 2+-
Mcmd/pseudo/pidof.c | 4++--
Mcmd/pseudo/printenv.c | 2+-
Mcmd/pseudo/pwdx.c | 2+-
Mcmd/pseudo/respawn.c | 2+-
Mcmd/pseudo/rev.c | 2+-
Mcmd/pseudo/seq.c | 2+-
Mcmd/pseudo/setsid.c | 2+-
Mcmd/pseudo/sha1sum.c | 2+-
Mcmd/pseudo/sha224sum.c | 2+-
Mcmd/pseudo/sha256sum.c | 2+-
Mcmd/pseudo/sha384sum.c | 2+-
Mcmd/pseudo/sha512-224sum.c | 2+-
Mcmd/pseudo/sha512-256sum.c | 2+-
Mcmd/pseudo/sha512sum.c | 2+-
Mcmd/pseudo/sponge.c | 2+-
Mcmd/pseudo/tar.c | 26+++++++++++++-------------
Mcmd/pseudo/truncate.c | 2+-
Mcmd/pseudo/uptime.c | 2+-
Mcmd/pseudo/watch.c | 2+-
Mcmd/pseudo/which.c | 2+-
Mcmd/pseudo/whoami.c | 2+-
Dcmd/pseudo/xinstall.c | 214-------------------------------------------------------------------------------
Mcmd/pseudo/yes.c | 2+-
Acmd/xsi/login.c | 202+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/xsi/mknod.c | 2+-
Acmd/xsi/mkpasswd.c | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/xsi/passwd.c | 212+++++++++++++++++++++++++++++++++++++++++++++++++------------------------------
Mcmd/xsi/su.c | 159+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mninqu.rules | 631++++++++++++++++++++++++++++++++++++++++++++++---------------------------------
Mscripts/genbox.sh | 19++++++++-----------
Mscripts/genconfig.sh | 48++++++++++++++++++++++++------------------------
Mscripts/getconf.sh | 2+-
Mscripts/mkman/main.go | 2+-
Mscripts/mkman/parse.go | 10+++++-----
Mscripts/mkman/txt.go | 6+++---
Mshared/arg.h | 4++--
Mshared/compat.h | 2+-
Mshared/config.h | 2+-
Mshared/crypt.h | 2+-
Mshared/diffutil.h | 2+-
Mshared/diskutil.h | 2+-
Mshared/fs.h | 2+-
Ashared/libatomic/atomic_x64.s | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libblake3/blake3.c | 4525+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libblake3/blake3.h | 43+++++++++++++++++++++++++++++++++++++++++++
Ashared/libint128/int128_x64.s | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/libredline/redline.c | 2+-
Ashared/libtcutil/ar/archive.c | 220+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/ar/archive.h | 37+++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/elf/elfutil.c | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/elf/elfutil.h | 26++++++++++++++++++++++++++
Ashared/libtcutil/table.c | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/table.h | 46++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/tcutil.c | 1055+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libtcutil/tcutil.h | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/libutf/fgetrune.c | 2+-
Mshared/libutf/fputrune.c | 2+-
Mshared/libutf/isalnumrune.c | 2+-
Mshared/libutf/isalpharune.c | 2+-
Mshared/libutf/isblankrune.c | 2+-
Mshared/libutf/iscntrlrune.c | 2+-
Mshared/libutf/isdigitrune.c | 2+-
Mshared/libutf/isgraphrune.c | 2+-
Mshared/libutf/isprintrune.c | 2+-
Mshared/libutf/ispunctrune.c | 2+-
Mshared/libutf/isspacerune.c | 2+-
Mshared/libutf/istitlerune.c | 2+-
Mshared/libutf/isxdigitrune.c | 2+-
Mshared/libutf/lowerrune.c | 2+-
Mshared/libutf/rune.c | 24++++++++++++------------
Mshared/libutf/runetype.c | 22+++++++++++-----------
Mshared/libutf/runetype.h | 22+++++++++++-----------
Mshared/libutf/upperrune.c | 2+-
Mshared/libutf/utf.c | 20++++++++++----------
Mshared/libutf/utftorunestr.c | 2+-
Mshared/libutil/agetcwd.c | 2+-
Mshared/libutil/agetline.c | 2+-
Mshared/libutil/apathmax.c | 2+-
Mshared/libutil/concat.c | 2+-
Mshared/libutil/confirm.c | 2+-
Mshared/libutil/cp.c | 2+-
Mshared/libutil/crypt.c | 2+-
Mshared/libutil/diffutil.c | 2+-
Mshared/libutil/diskutil.c | 6++++--
Mshared/libutil/ealloc.c | 2+-
Mshared/libutil/enmasse.c | 2+-
Mshared/libutil/eprintf.c | 2+-
Mshared/libutil/estrtod.c | 2+-
Mshared/libutil/estrtol.c | 2+-
Mshared/libutil/estrtoul.c | 2+-
Mshared/libutil/explicit_bzero.c | 2+-
Mshared/libutil/fconcat.c | 2+-
Mshared/libutil/fnck.c | 2+-
Mshared/libutil/fshut.c | 12++++++------
Mshared/libutil/getlines.c | 2+-
Ashared/libutil/hexval.c | 14++++++++++++++
Mshared/libutil/human.c | 2+-
Mshared/libutil/linecmp.c | 2+-
Mshared/libutil/memmem.c | 30+++++++++++++++---------------
Mshared/libutil/mkdirp.c | 2+-
Mshared/libutil/mode.c | 2+-
Mshared/libutil/parseoffset.c | 5++++-
Mshared/libutil/passwd.c | 20++++++++++++++++++--
Mshared/libutil/proc.c | 4++--
Mshared/libutil/putword.c | 2+-
Mshared/libutil/reallocarray.c | 10+++++-----
Mshared/libutil/recurse.c | 2+-
Mshared/libutil/recurse_dir.c | 2+-
Mshared/libutil/rm.c | 2+-
Mshared/libutil/sig.c | 2+-
Mshared/libutil/strcasestr.c | 18+++++++++---------
Mshared/libutil/strlcat.c | 20++++++++++----------
Mshared/libutil/strlcpy.c | 20++++++++++----------
Mshared/libutil/strnsubst.c | 18+++++++++---------
Mshared/libutil/strsep.c | 18+++++++++---------
Mshared/libutil/strtonum.c | 12++++++------
Mshared/libutil/tty.c | 2+-
Mshared/libutil/unescape.c | 2+-
Mshared/libutil/wexec.c | 13++++++++-----
Mshared/libutil/writeall.c | 2+-
Mshared/passwd.h | 2+-
Mshared/paths.h | 18++++++++++++------
Mshared/proc.h | 2+-
Mshared/queue.h | 126++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mshared/reboot.h | 20++++++++++----------
Mshared/rtc.h | 8++++----
Mshared/sha224.h | 2+-
Mshared/sha384.h | 2+-
Mshared/sha512-224.h | 2+-
Mshared/sha512-256.h | 2+-
Mshared/sig.h | 2+-
Mshared/text.h | 2+-
Mshared/tls.h | 4++--
Mshared/utf.h | 20++++++++++----------
Mshared/util.h | 8+++++++-
Mshared/wexec.h | 2+-
368 files changed, 16005 insertions(+), 9529 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -29,12 +29,25 @@ cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h -# build system generated files +# build system generated files (genconfig.sh and ninqu) scripts/mk/config.mk scripts/mk/config.kv +scripts/mk/config.set +scripts/mk/features.h scripts/mk/rules.mk +shared/libutil/nofork_list.h deps.mk +# compiler dependency files +*.d + +# python bytecode +__pycache__/ +*.pyc + +# generated man pages +man/man*/ + # ninja backend generator output and state build.ninja .ninja_log diff --git a/Makefile b/Makefile @@ -52,7 +52,7 @@ $(NINQU): $(NINQU_SRC) cmd/dev/ninqu/ninqu.h scripts/mk/config.set $(NINQU_LIB_S FORCE: # ninqu generates build.ninja if ninja/samu is available and execs that -# instead of running its own backend, but you can use make BACKEND=internal +# instead of running its own backend, but you can use make backend=internal # to force the internal one to be used anyways %: $(NINQU) FORCE $(NINQU) $(JOBS) $@ diff --git a/build.cfg b/build.cfg @@ -1,11 +1,11 @@ # posix: POSIX 2024 PRESET_FEATURES=all -# subset of: posix xsi net pseudo extra linux dev -PRESET_UTILS="posix xsi net pseudo extra linux" +# subset of: posix xsi net pseudo extra linux dev +PRESET_UTILS="posix xsi net pseudo extra linux dev" # installation paths -VERSION=2026-06-08T05-53-UTC-03 +VERSION=2026-08-09T03-56-UTC-03 PREFIX=/usr/local MANPREFIX=/usr/local/share/man @@ -13,12 +13,12 @@ MANPREFIX=/usr/local/share/man CC=cc CFLAGS="-std=c99 -Wall -Wextra -pedantic" LDFLAGS="" -LDLIBS="-lcrypt -lresolv" +LDLIBS="" AR=ar ARFLAGS="rc" RANLIB=ranlib -# --- preset expansion: do not edit below --- +# preset expansion: do not edit below case "$PRESET_FEATURES" in posix) @@ -52,6 +52,11 @@ posix) FEATURE_DEPMOD_ALIAS=0; FEATURE_DEPMOD_SYMBOLS=0 FEATURE_TAR_TTY_SAFE=0; FEATURE_TAR_NOFOLLOW=0 FEATURE_READLINK_REALPATH=0; FEATURE_UMOUNT_OPTIONS=0 + FEATURE_LN_RELATIVE=0 + FEATURE_LN_NO_TARGET_DIR=0 + FEATURE_BC_QUIET=0 + FEATURE_BC_MULTICHAR=0 + FEATURE_BC_ESCAPES=0 FEATURE_TAR_TO_STDOUT=0; FEATURE_TAR_KEEP_OLD=0 FEATURE_TAR_STRIP_COMPONENTS=0; FEATURE_TAR_FILES_FROM=0 FEATURE_TAR_EXCLUDE_FROM=0; FEATURE_IP_ROUTE_ADD_DEL=0 @@ -87,6 +92,11 @@ common) FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1 FEATURE_TAR_TTY_SAFE=1; FEATURE_TAR_NOFOLLOW=1 FEATURE_READLINK_REALPATH=1; FEATURE_UMOUNT_OPTIONS=1 + FEATURE_LN_RELATIVE=1 + FEATURE_LN_NO_TARGET_DIR=1 + FEATURE_BC_QUIET=1 + FEATURE_BC_MULTICHAR=1 + FEATURE_BC_ESCAPES=1 FEATURE_TAR_TO_STDOUT=1; FEATURE_TAR_KEEP_OLD=1 FEATURE_TAR_STRIP_COMPONENTS=1; FEATURE_TAR_FILES_FROM=1 FEATURE_TAR_EXCLUDE_FROM=1; FEATURE_IP_ROUTE_ADD_DEL=1 @@ -124,6 +134,11 @@ all) FEATURE_DEPMOD_ALIAS=1; FEATURE_DEPMOD_SYMBOLS=1 FEATURE_TAR_TTY_SAFE=1; FEATURE_TAR_NOFOLLOW=1 FEATURE_READLINK_REALPATH=1; FEATURE_UMOUNT_OPTIONS=1 + FEATURE_LN_RELATIVE=1 + FEATURE_LN_NO_TARGET_DIR=1 + FEATURE_BC_QUIET=1 + FEATURE_BC_MULTICHAR=1 + FEATURE_BC_ESCAPES=1 FEATURE_TAR_TO_STDOUT=1; FEATURE_TAR_KEEP_OLD=1 FEATURE_TAR_STRIP_COMPONENTS=1; FEATURE_TAR_FILES_FROM=1 FEATURE_TAR_EXCLUDE_FROM=1; FEATURE_IP_ROUTE_ADD_DEL=1 @@ -154,37 +169,37 @@ for _p in $PRESET_UTILS; do done unset _p -# --- per-item overrides (after preset expansion) --- -# 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 +# per-item overrides (after preset expansion) +# 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_NOEXEC: when set to 1, wexec/wpopen/wsystem can execute registered # tool mains directly inside the forked child process (skipping execve) -# This is equivalent to Busybox noexec applet support -# This applies to ALL commands contained within aruu-box, you may also +# this is equivalent to busybox noexec applet support +# this applies to ALL commands contained within aruu-box, you may also # specify if some specific command is not an attack vector to also be nofork # via enabling FEATURE_NOFORK=1 and specifying those commands in NOFORK_LIST # -#FEATURE_NOEXEC=1 +# FEATURE_NOEXEC=1 # # FEATURE_NOEXEC_OVERRIDE: only meaningful when FEATURE_NOEXEC=1 # when set to 1, ARUU_NOEXEC=0 in the environment forces fork+exec at runtime # -#FEATURE_NOEXEC_OVERRIDE=1 +# FEATURE_NOEXEC_OVERRIDE=1 # # FEATURE_NOFORK: when set to 1, wexecvp/wexecv can run simple commands # (like cat, echo, pwd, test) directly in the current process without spawning -# a subprocess (noexec+nofork). This is equivalent to Busybox nofork applet support +# a subprocess (noexec+nofork). this is equivalent to busybox nofork applet support # -#FEATURE_NOFORK=1 +# FEATURE_NOFORK=1 # # FEATURE_NOFORK_OVERRIDE: only meaningful when FEATURE_NOFORK=1 # when set to 1, ARUU_NOFORK=0 in the environment forces fork for nofork commands # even tho they will still not do execvp() call at runtime # unless FEATURE_NOEXEC_OVERRIDE was enabled at build time and ARUU_NOEXEC=0 # -#FEATURE_NOFORK_OVERRIDE=1 +# FEATURE_NOFORK_OVERRIDE=1 # # NOFORK_LIST: list of builtins that can run without fork (noexec+nofork) # @@ -246,5 +261,5 @@ CPPFLAGS_TLS=$(echo "$CPPFLAGS_TLS" | xargs) LDFLAGS_TLS=$(echo "$LDFLAGS_TLS" | xargs) LDLIBS_TLS=$(echo "$LDLIBS_TLS" | xargs) -# Makes Ninqu try them in this order: +# makes ninqu try them in this order: NINJA_TRY="${NINJA_TRY:-samu,ninja}" diff --git a/cmd/dev/ninqu/expand.c b/cmd/dev/ninqu/expand.c @@ -270,14 +270,14 @@ expand_rule(const char *name) int r_literal = rule_is_literal(r); /* run a codegen producer before globbing only when its own - * output feeds this rules glob, so a step like POSIX_BC_C - * (produces cmd/posix/bc.c) finishes before glob_all() looks - * for cmd/posix/bc.c. anything else in extra_deps (a library to - * link, a header some other rule includes) never needs to run - * here, expand_rule() on it just registers its instances so - * the resolve_input_token() pass in finalize_inst() can wire up - * dep_rule_names for backend scheduling. skipped in - * summary mode since -S must not execute */ + * output feeds this rules glob, so a step like POSIX_BC_C + * (produces cmd/posix/bc.c) finishes before glob_all() looks + * for cmd/posix/bc.c. anything else in extra_deps (a library to + * link, a header some other rule includes) never needs to run + * here, expand_rule() on it just registers its instances so + * the resolve_input_token() pass in finalize_inst() can wire up + * dep_rule_names for backend scheduling. skipped in + * summary mode since -S must not execute */ if (!summary_mode) { for (j = 0; j < r->extra_deps.n; j++) { char *tok = kv_expand(r->extra_deps.v[j]); @@ -368,7 +368,7 @@ expand_rule(const char *name) struct KvStore ov; /* non-glob rules have no MATCH/DIR/BASE to expose, so the - * overlay only carries IN/OUT for build_cmd */ + * overlay only carries IN/OUT for build_cmd */ setup_inst(inst, r); memset(&ov, 0, sizeof ov); local_overlay = &ov; diff --git a/cmd/dev/ninqu/gate.c b/cmd/dev/ninqu/gate.c @@ -116,7 +116,7 @@ gate_eval(struct Gate *g) return 0; } -/* expand every $(...) so a gate like build_$(BASESTEM) resolves +/* expand every $(...) so a gate like build_$(basestem) resolves * against the active overlay before evaluation */ struct Gate * gate_materialize(struct Gate *g) diff --git a/cmd/dev/ninqu/main.c b/cmd/dev/ninqu/main.c @@ -120,7 +120,7 @@ main(int argc, char *argv[]) return failed_any ? 1 : 0; } - /* BACKEND=internal forces executor. otherwise generate file and exec backend binary */ + /* backend=internal forces executor. otherwise generate file and exec backend binary */ if (strcmp(kv_get_or("BACKEND", "auto"), "internal") != 0) { char *bin; const struct Backend *be = backend_resolve(&bin); diff --git a/cmd/dev/ninqu/ninja.c b/cmd/dev/ninqu/ninja.c @@ -52,11 +52,11 @@ fprint_shell_word_plain(FILE *f, const char *s) * so neither lets a real newline survive inside the value. POSIX * single quotes cannot help either, there is no escape processing * inside them, so a backslash-n written between quotes stays two - * literal characters, not a newline, once the shell reads it back. + * literal characters, not a newline, once the shell reads it back * * the fix is to not carry the newline in quoted text at all: emit * a command substitution that runs the word through `printf '%b'`, - * whose %b directive is POSIX-specified to expand backslash escapes + * whose %b directive is posix-specified to expand backslash escapes * (including \n) in its argument at runtime. the argument to printf * is itself single-quoted using the same rules as the plain case, * plus doubling any backslash so it survives as data rather than @@ -82,9 +82,9 @@ fprint_shell_word(FILE *f, const char *s) } /* wrapped in double quotes so the shell treats the substitutions - * result as one word instead of splitting it on whitespace, which - * is exactly what an unquoted $(...) would do to a multi-line - * result */ + * result as one word instead of splitting it on whitespace, which + * is exactly what an unquoted $(...) would do to a multi-line + * result */ fputs("\"$$(printf '%b' '", f); for (; *s; s++) { if (*s == '\'') @@ -220,17 +220,17 @@ emit_command(FILE *f, struct Inst *inst) * inst_stale() never consults dep_inst for staleness either, only * (in)/(stale_extra), so mirroring that as a plain (not order-only) * prerequisite list is what makes ninjas own mtime check agree - * with ninqus. + * with ninqus * * ninja only knows build outputs, never ninqus rule/group/meta - * names, so `ninja LIBUTIL` (what the Makefile forwards $@ as) has + * names, so `ninja LIBUTIL` (what the makefile forwards $@ as) has * nothing to resolve against on its own. wanted carries the literal * command-line words ninqu itself was invoked with, one phony alias * per word makes that name buildable too. when more than one target * was requested in the same invocation every alias points at the * whole combined closure rather than just its own slice, since * insts[] no longer remembers which instance came from which wanted - * name, thats fine for the Makefiles own use (always one target + * name, thats fine for the makefiles own use (always one target * per invocation), just slightly conservative for a multi-target * `ninqu -G ninja a b` run */ void @@ -292,8 +292,8 @@ emit_ninja(const char *path, struct StrList *wanted) char depbuf[1024]; const char *depout = inst_target(dep, inst->dep_inst[k], depbuf, sizeof depbuf); /* a rule ref that is also a real (dep ...) input already - * forces both order and staleness, listing it again as - * order-only is pure noise */ + * forces both order and staleness, listing it again as + * order-only is pure noise */ if (sl_has(&inst->in, depout) || sl_has(&inst->stale_extra, depout)) continue; if (!printed_bar) { diff --git a/cmd/dev/ninqu/ninqu.h b/cmd/dev/ninqu/ninqu.h @@ -95,7 +95,7 @@ void lex_swallow_dollar(struct SLex *lx, char *buf, size_t *blen, size_ void lex_string(struct SLex *lx, char *buf, size_t bsz); const char *find_dollar_close(const char *inner); -/* gate: (not X) | (and X...) | (or X...) | bare var */ +/* gate: (not x) | (and x...) | (or x...) | bare var */ enum GKind { G_TRUE, G_VAR, G_NOT, G_AND, G_OR }; struct Gate { diff --git a/cmd/dev/ninqu/parse.c b/cmd/dev/ninqu/parse.c @@ -27,7 +27,7 @@ sole_atom(struct SNode *node, const char *msg) } /* a dep operand is a bare atom, a (rule NAME) stored as @NAME, or - * an (after X...) whose operands are order-only */ + * an (after x...) whose operands are order-only */ static void parse_dep_item(struct SNode *item, struct StrList *hard, struct StrList *ord, int allow_after) { @@ -158,10 +158,10 @@ process_rule_body(struct Rule *r, const char *name, struct SNode *form, int star apply_rule_clause(r, name, form->kids[i]); } -/* (if EXPR clause...) splices its clauses in when EXPR is true. - * reuses the gate grammar so there is one condition language. +/* (if EXPR clause...) splices its clauses in when EXPR is true + * reuses the gate grammar so there is one condition language * a $(...) in the condition is rejected: splicing per glob match - * would mean deferring cmd/dep construction, which no rule needs. + * would mean deferring cmd/dep construction, which no rule needs * use (gate ...) on a separate rule for a per-instance condition */ static void apply_if_clause(struct Rule *r, const char *name, struct SNode *clause) @@ -247,13 +247,13 @@ apply_rule_clause(struct Rule *r, const char *name, struct SNode *clause) ); } else if (strcmp(h, "group") == 0) { /* display-only: shows up in (query rules) output, no effect on - * resolution. (member ...) below is the enforcing one. the two - * are separate because several rules used (group ...) this way - * before namespacing existed */ + * resolution. (member ...) below is the enforcing one. the two + * are separate because several rules used (group ...) this way + * before namespacing existed */ strlcpy(r->group_name, sole_atom(clause, "(group NAME) takes one name"), sizeof r->group_name); } else if (strcmp(h, "member") == 0) { /* (member GROUP [ALIAS]) hides the bare name from the command - * line. ALIAS defaults to the rule own name */ + * line. ALIAS defaults to the rule own name */ if (clause->nkids < 2 || clause->nkids > 3 || clause->kids[1]->kind != S_ATOM) eprintf("manifest: rule %s: (member GROUP [ALIAS]) needs a group name\n", name); strlcpy(r->member_of, clause->kids[1]->atom, sizeof r->member_of); @@ -384,7 +384,7 @@ parse_set(struct SNode *form) kv_set_manifest(form->kids[1]->atom, form->kids[2]->atom); } -/* (list) and (append) keep a space-joined string in the kv store. +/* (list) and (append) keep a space-joined string in the kv store * a $(NAME) alone in a command splits back into argv entries */ static void parse_list_or_append(struct SNode *form, int append) diff --git a/cmd/dev/ninqu/resolve.c b/cmd/dev/ninqu/resolve.c @@ -101,8 +101,8 @@ resolve_member_path(const char *w) return r; } -/* META.TARGET applies META overrides then resolves TARGET. - * META alone applies META then falls back to (group default). +/* META.TARGET applies META overrides then resolves TARGET + * META alone applies META then falls back to (group default) * anything else is a plain group or rule name */ void resolve_wanted(const char *w) @@ -140,8 +140,8 @@ resolve_wanted(const char *w) } /* a rule that declared (member ...) does not resolve by bare name - * from the command line, only through GROUP/ALIAS or transitively - * via its owning group ref list */ + * from the command line, only through GROUP/ALIAS or transitively + * via its owning group ref list */ { struct Rule *br = rule_find(w); if (br && br->member_of[0]) diff --git a/cmd/extra/b3sum.c b/cmd/extra/b3sum.c @@ -1,4557 +1,12 @@ -/* See LICENSE file for copyright and license details. */ - -#if defined(__x86_64__) && (defined(__clang__) || (defined(__GNUC__) && !defined(__TINYC__))) -#define BLAKE3_X86_SIMD 1 -#else -#define BLAKE3_X86_SIMD 0 -#endif - -#include "arg.h" -#include "util.h" - -#include <assert.h> -#if BLAKE3_X86_SIMD -#include <immintrin.h> -#endif -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#define BLAKE3_VERSION_STRING "1.5.0" -#define BLAKE3_KEY_LEN 32 -#define BLAKE3_OUT_LEN 32 -#define BLAKE3_BLOCK_LEN 64 -#define BLAKE3_CHUNK_LEN 1024 -#define BLAKE3_MAX_DEPTH 54 - -#if BLAKE3_X86_SIMD -#define MAX_SIMD_DEGREE 16 -#else -#define MAX_SIMD_DEGREE 1 -#endif - -#define MAX_SIMD_DEGREE_OR_2 (MAX_SIMD_DEGREE > 2 ? MAX_SIMD_DEGREE : 2) - -enum Blake3Flags { - CHUNK_START = 1 << 0, - CHUNK_END = 1 << 1, - PARENT = 1 << 2, - ROOT = 1 << 3, - KEYED_HASH = 1 << 4, - DERIVE_KEY_CONTEXT = 1 << 5, - DERIVE_KEY_MATERIAL = 1 << 6 -}; - -struct Blake3ChunkState { - uint32_t cv[8]; - uint64_t chunk_counter; - uint8_t buf[BLAKE3_BLOCK_LEN]; - uint8_t buf_len; - uint8_t blocks_compressed; - uint8_t flags; -}; - -struct Blake3Hasher { - uint32_t key[8]; - struct Blake3ChunkState chunk; - uint8_t cv_stack_len; - uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN]; -}; - -void blake3_hasher_update(struct Blake3Hasher *self, const void *input, size_t input_len); -void blake3_hasher_finalize(const struct Blake3Hasher *self, uint8_t *out, size_t out_len); - -struct Output { - uint32_t input_cv[8]; - uint64_t counter; - uint8_t block[BLAKE3_BLOCK_LEN]; - uint8_t block_len; - uint8_t flags; -}; - -static const uint32_t IV[8] = { - 0x6A09E667UL, - 0xBB67AE85UL, - 0x3C6EF372UL, - 0xA54FF53AUL, - 0x510E527FUL, - 0x9B05688CUL, - 0x1F83D9ABUL, - 0x5BE0CD19UL -}; - -static const uint8_t MSG_SCHEDULE[7][16] = { - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, - {2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8}, - {3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1}, - {10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6}, - {12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4}, - {9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7}, - {11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13}, -}; - -static inline uint32_t -load32(const void *src) -{ - const uint8_t *p = (const uint8_t *)src; - - return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) | ((uint32_t)(p[2]) << 16) - | ((uint32_t)(p[3]) << 24); -} - -static inline void -store32(void *dst, uint32_t w) -{ - uint8_t *p = (uint8_t *)dst; - - p[0] = (uint8_t)(w >> 0); - p[1] = (uint8_t)(w >> 8); - p[2] = (uint8_t)(w >> 16); - p[3] = (uint8_t)(w >> 24); -} - -static inline void -store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8]) -{ - store32(&bytes_out[0 * 4], cv_words[0]); - store32(&bytes_out[1 * 4], cv_words[1]); - store32(&bytes_out[2 * 4], cv_words[2]); - store32(&bytes_out[3 * 4], cv_words[3]); - store32(&bytes_out[4 * 4], cv_words[4]); - store32(&bytes_out[5 * 4], cv_words[5]); - store32(&bytes_out[6 * 4], cv_words[6]); - store32(&bytes_out[7 * 4], cv_words[7]); -} - -static inline uint32_t -counter_low(uint64_t counter) -{ - return (uint32_t)counter; -} - -static inline uint32_t -counter_high(uint64_t counter) -{ - return (uint32_t)(counter >> 32); -} - -/* forward declarations */ -#if BLAKE3_X86_SIMD -void blake3_compress_in_place_sse2( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -); -void blake3_compress_xof_sse2( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -); -void blake3_hash_many_sse2( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); - -void blake3_compress_in_place_sse41( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -); -void blake3_compress_xof_sse41( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -); -void blake3_hash_many_sse41( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); - -void blake3_hash_many_avx2( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); - -void blake3_compress_in_place_avx512( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -); -void blake3_compress_xof_avx512( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -); -void blake3_hash_many_avx512( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); -#endif - -void blake3_compress_in_place_portable( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -); -void blake3_compress_xof_portable( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -); -void blake3_hash_many_portable( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); - -void blake3_compress_in_place( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -); -void blake3_compress_xof( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -); -void blake3_hash_many( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -); - -/* portable implementations */ -static inline uint32_t -rotr32(uint32_t w, uint32_t c) -{ - return (w >> c) | (w << (32 - c)); -} - -static inline void -g_portable(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y) -{ - state[a] = state[a] + state[b] + x; - state[d] = rotr32(state[d] ^ state[a], 16); - state[c] = state[c] + state[d]; - state[b] = rotr32(state[b] ^ state[c], 12); - state[a] = state[a] + state[b] + y; - state[d] = rotr32(state[d] ^ state[a], 8); - state[c] = state[c] + state[d]; - state[b] = rotr32(state[b] ^ state[c], 7); -} - -static inline void -round_fn_portable(uint32_t state[16], const uint32_t *msg, size_t round) -{ - const uint8_t *schedule = MSG_SCHEDULE[round]; - - g_portable(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]); - g_portable(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]); - g_portable(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]); - g_portable(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]); - - g_portable(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]); - g_portable(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]); - g_portable(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]); - g_portable(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]); -} - -static inline void -compress_pre_portable( - uint32_t state[16], - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - uint32_t block_words[16]; - - block_words[0] = load32(block + 4 * 0); - block_words[1] = load32(block + 4 * 1); - block_words[2] = load32(block + 4 * 2); - block_words[3] = load32(block + 4 * 3); - block_words[4] = load32(block + 4 * 4); - block_words[5] = load32(block + 4 * 5); - block_words[6] = load32(block + 4 * 6); - block_words[7] = load32(block + 4 * 7); - block_words[8] = load32(block + 4 * 8); - block_words[9] = load32(block + 4 * 9); - block_words[10] = load32(block + 4 * 10); - block_words[11] = load32(block + 4 * 11); - block_words[12] = load32(block + 4 * 12); - block_words[13] = load32(block + 4 * 13); - block_words[14] = load32(block + 4 * 14); - block_words[15] = load32(block + 4 * 15); - - state[0] = cv[0]; - state[1] = cv[1]; - state[2] = cv[2]; - state[3] = cv[3]; - state[4] = cv[4]; - state[5] = cv[5]; - state[6] = cv[6]; - state[7] = cv[7]; - state[8] = IV[0]; - state[9] = IV[1]; - state[10] = IV[2]; - state[11] = IV[3]; - state[12] = counter_low(counter); - state[13] = counter_high(counter); - state[14] = (uint32_t)block_len; - state[15] = (uint32_t)flags; - - round_fn_portable(state, &block_words[0], 0); - round_fn_portable(state, &block_words[0], 1); - round_fn_portable(state, &block_words[0], 2); - round_fn_portable(state, &block_words[0], 3); - round_fn_portable(state, &block_words[0], 4); - round_fn_portable(state, &block_words[0], 5); - round_fn_portable(state, &block_words[0], 6); -} - -void -blake3_compress_in_place_portable( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - uint32_t state[16]; - - compress_pre_portable(state, cv, block, block_len, counter, flags); - cv[0] = state[0] ^ state[8]; - cv[1] = state[1] ^ state[9]; - cv[2] = state[2] ^ state[10]; - cv[3] = state[3] ^ state[11]; - cv[4] = state[4] ^ state[12]; - cv[5] = state[5] ^ state[13]; - cv[6] = state[6] ^ state[14]; - cv[7] = state[7] ^ state[15]; -} - -void -blake3_compress_xof_portable( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -) -{ - uint32_t state[16]; - - compress_pre_portable(state, cv, block, block_len, counter, flags); - - store32(&out[0 * 4], state[0] ^ state[8]); - store32(&out[1 * 4], state[1] ^ state[9]); - store32(&out[2 * 4], state[2] ^ state[10]); - store32(&out[3 * 4], state[3] ^ state[11]); - store32(&out[4 * 4], state[4] ^ state[12]); - store32(&out[5 * 4], state[5] ^ state[13]); - store32(&out[6 * 4], state[6] ^ state[14]); - store32(&out[7 * 4], state[7] ^ state[15]); - store32(&out[8 * 4], state[8] ^ cv[0]); - store32(&out[9 * 4], state[9] ^ cv[1]); - store32(&out[10 * 4], state[10] ^ cv[2]); - store32(&out[11 * 4], state[11] ^ cv[3]); - store32(&out[12 * 4], state[12] ^ cv[4]); - store32(&out[13 * 4], state[13] ^ cv[5]); - store32(&out[14 * 4], state[14] ^ cv[6]); - store32(&out[15 * 4], state[15] ^ cv[7]); -} - -static inline void -hash_one_portable( - const uint8_t *input, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t out[BLAKE3_OUT_LEN] -) -{ - uint32_t cv[8]; - uint8_t block_flags; - - memcpy(cv, key, BLAKE3_KEY_LEN); - block_flags = flags | flags_start; - while (blocks > 0) { - if (blocks == 1) { - block_flags |= flags_end; - } - blake3_compress_in_place_portable(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); - input = &input[BLAKE3_BLOCK_LEN]; - blocks -= 1; - block_flags = flags; - } - store_cv_words(out, cv); -} - -void -blake3_hash_many_portable( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -) -{ - while (num_inputs > 0) { - hash_one_portable(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out); - if (increment_counter) { - counter += 1; - } - inputs += 1; - num_inputs -= 1; - out = &out[BLAKE3_OUT_LEN]; - } -} - -/* cpu features detection */ -enum { SSE2 = 1 << 0, SSE41 = 1 << 1, AVX2 = 1 << 2, AVX512 = 1 << 3 }; - -static int blake3_cpu_features = 0; -static int blake3_cpu_detected = 0; - -#if BLAKE3_X86_SIMD -#include <cpuid.h> - -static void -blake3_cpuid(uint32_t out[4], uint32_t id, uint32_t sid) -{ - __cpuid_count(id, sid, out[0], out[1], out[2], out[3]); -} - -static uint64_t -blake3_xgetbv(void) -{ - uint32_t eax, edx; - - __asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(0)); - return ((uint64_t)edx << 32) | eax; -} -#endif - -static void -blake3_detect_cpu_features(void) -{ -#if BLAKE3_X86_SIMD - enum { EAX, EBX, ECX, EDX }; - uint32_t regs[4]; - uint64_t xcr0; - int features = 0; - - blake3_cpuid(regs, 1, 0); - if (regs[EDX] & (1UL << 26)) - features |= SSE2; - if (regs[ECX] & (1UL << 19)) - features |= SSE41; - /* osxsave */ - if (regs[ECX] & (1UL << 27)) { - blake3_cpuid(regs, 0, 0); - if (regs[EAX] >= 7) { - blake3_cpuid(regs, 7, 0); - xcr0 = blake3_xgetbv(); - /* avx2 and xcr0 sse, avx */ - if ((regs[EBX] & (1UL << 5)) && (xcr0 & 0x06) == 0x06) - features |= AVX2; - /* avx512f, avx512vl and xcr0 opmask, zmm_hi256, - * hi16_zmm */ - if ((regs[EBX] & (1UL << 31 | 1UL << 16)) && (xcr0 & 0xe0) == 0xe0) - features |= AVX512; - } - } - blake3_cpu_features = features; -#endif - blake3_cpu_detected = 1; -} - -#if BLAKE3_X86_SIMD -__attribute__((constructor)) static void -blake3_init_cpu(void) -{ - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); -} -#endif - -#if BLAKE3_X86_SIMD -#if defined(__clang__) -#pragma clang attribute push(__attribute__((target("sse2"))), apply_to = function) -#elif defined(__GNUC__) -#pragma GCC push_options -#pragma GCC target("sse2") -#endif -#define DEGREE_SSE2 4 - -#define _mm_shuffle_ps2(a, b, c) \ - (_mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c)))) - -static inline __m128i -loadu_sse2(const uint8_t src[16]) -{ - return _mm_loadu_si128((const __m128i *)src); -} - -static inline void -storeu_sse2(__m128i src, uint8_t dest[16]) -{ - _mm_storeu_si128((__m128i *)dest, src); -} - -static inline __m128i -addv_sse2(__m128i a, __m128i b) -{ - return _mm_add_epi32(a, b); -} - -static inline __m128i -xorv_sse2(__m128i a, __m128i b) -{ - return _mm_xor_si128(a, b); -} - -static inline __m128i -set1_sse2(uint32_t x) -{ - return _mm_set1_epi32((int32_t)x); -} - -static inline __m128i -set4_sse2(uint32_t a, uint32_t b, uint32_t c, uint32_t d) -{ - return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); -} - -static inline __m128i -rot16_sse2(__m128i x) -{ - return _mm_shufflehi_epi16(_mm_shufflelo_epi16(x, 0xB1), 0xB1); -} - -static inline __m128i -rot12_sse2(__m128i x) -{ - return xorv_sse2(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12)); -} - -static inline __m128i -rot8_sse2(__m128i x) -{ - return xorv_sse2(_mm_srli_epi32(x, 8), _mm_slli_epi32(x, 32 - 8)); -} - -static inline __m128i -rot7_sse2(__m128i x) -{ - return xorv_sse2(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7)); -} - -static inline void -g1_sse2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = addv_sse2(addv_sse2(*row0, m), *row1); - *row3 = xorv_sse2(*row3, *row0); - *row3 = rot16_sse2(*row3); - *row2 = addv_sse2(*row2, *row3); - *row1 = xorv_sse2(*row1, *row2); - *row1 = rot12_sse2(*row1); -} - -static inline void -g2_sse2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = addv_sse2(addv_sse2(*row0, m), *row1); - *row3 = xorv_sse2(*row3, *row0); - *row3 = rot8_sse2(*row3); - *row2 = addv_sse2(*row2, *row3); - *row1 = xorv_sse2(*row1, *row2); - *row1 = rot7_sse2(*row1); -} - -static inline void -diagonalize_sse2(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); -} - -static inline void -undiagonalize_sse2(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); -} - -static inline __m128i -blend_epi16_sse2(__m128i a, __m128i b, const int16_t imm8) -{ - const __m128i bits = _mm_set_epi16(0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01); - __m128i mask = _mm_set1_epi16(imm8); - - mask = _mm_and_si128(mask, bits); - mask = _mm_cmpeq_epi16(mask, bits); - return _mm_or_si128(_mm_and_si128(mask, b), _mm_andnot_si128(mask, a)); -} - -static inline void -compress_pre_sse2( - __m128i rows[4], - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i m0, m1, m2, m3; - __m128i t0, t1, t2, t3, tt; - - rows[0] = loadu_sse2((uint8_t *)&cv[0]); - rows[1] = loadu_sse2((uint8_t *)&cv[4]); - rows[2] = set4_sse2(IV[0], IV[1], IV[2], IV[3]); - rows[3] = - set4_sse2(counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags); - - m0 = loadu_sse2(&block[sizeof(__m128i) * 0]); - m1 = loadu_sse2(&block[sizeof(__m128i) * 1]); - m2 = loadu_sse2(&block[sizeof(__m128i) * 2]); - m3 = loadu_sse2(&block[sizeof(__m128i) * 3]); - - /* round 1 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 2 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 3 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 4 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 5 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 6 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 7 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = blend_epi16_sse2(tt, t1, 0xCC); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse2(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = blend_epi16_sse2(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); -} - -void -blake3_compress_in_place_sse2( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i rows[4]; - - compress_pre_sse2(rows, cv, block, block_len, counter, flags); - storeu_sse2(xorv_sse2(rows[0], rows[2]), (uint8_t *)&cv[0]); - storeu_sse2(xorv_sse2(rows[1], rows[3]), (uint8_t *)&cv[4]); -} - -void -blake3_compress_xof_sse2( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out_buf[64] -) -{ - __m128i rows[4]; - - compress_pre_sse2(rows, cv, block, block_len, counter, flags); - storeu_sse2(xorv_sse2(rows[0], rows[2]), &out_buf[0]); - storeu_sse2(xorv_sse2(rows[1], rows[3]), &out_buf[16]); - storeu_sse2(xorv_sse2(rows[2], loadu_sse2((uint8_t *)&cv[0])), &out_buf[32]); - storeu_sse2(xorv_sse2(rows[3], loadu_sse2((uint8_t *)&cv[4])), &out_buf[48]); -} - -static inline void -round_fn_sse2(__m128i v[16], __m128i m[16], size_t r) -{ - v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = addv_sse2(v[0], v[4]); - v[1] = addv_sse2(v[1], v[5]); - v[2] = addv_sse2(v[2], v[6]); - v[3] = addv_sse2(v[3], v[7]); - v[12] = xorv_sse2(v[12], v[0]); - v[13] = xorv_sse2(v[13], v[1]); - v[14] = xorv_sse2(v[14], v[2]); - v[15] = xorv_sse2(v[15], v[3]); - v[12] = rot16_sse2(v[12]); - v[13] = rot16_sse2(v[13]); - v[14] = rot16_sse2(v[14]); - v[15] = rot16_sse2(v[15]); - v[8] = addv_sse2(v[8], v[12]); - v[9] = addv_sse2(v[9], v[13]); - v[10] = addv_sse2(v[10], v[14]); - v[11] = addv_sse2(v[11], v[15]); - v[4] = xorv_sse2(v[4], v[8]); - v[5] = xorv_sse2(v[5], v[9]); - v[6] = xorv_sse2(v[6], v[10]); - v[7] = xorv_sse2(v[7], v[11]); - v[4] = rot12_sse2(v[4]); - v[5] = rot12_sse2(v[5]); - v[6] = rot12_sse2(v[6]); - v[7] = rot12_sse2(v[7]); - v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = addv_sse2(v[0], v[4]); - v[1] = addv_sse2(v[1], v[5]); - v[2] = addv_sse2(v[2], v[6]); - v[3] = addv_sse2(v[3], v[7]); - v[12] = xorv_sse2(v[12], v[0]); - v[13] = xorv_sse2(v[13], v[1]); - v[14] = xorv_sse2(v[14], v[2]); - v[15] = xorv_sse2(v[15], v[3]); - v[12] = rot8_sse2(v[12]); - v[13] = rot8_sse2(v[13]); - v[14] = rot8_sse2(v[14]); - v[15] = rot8_sse2(v[15]); - v[8] = addv_sse2(v[8], v[12]); - v[9] = addv_sse2(v[9], v[13]); - v[10] = addv_sse2(v[10], v[14]); - v[11] = addv_sse2(v[11], v[15]); - v[4] = xorv_sse2(v[4], v[8]); - v[5] = xorv_sse2(v[5], v[9]); - v[6] = xorv_sse2(v[6], v[10]); - v[7] = xorv_sse2(v[7], v[11]); - v[4] = rot7_sse2(v[4]); - v[5] = rot7_sse2(v[5]); - v[6] = rot7_sse2(v[6]); - v[7] = rot7_sse2(v[7]); - - v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = addv_sse2(v[0], v[5]); - v[1] = addv_sse2(v[1], v[6]); - v[2] = addv_sse2(v[2], v[7]); - v[3] = addv_sse2(v[3], v[4]); - v[15] = xorv_sse2(v[15], v[0]); - v[12] = xorv_sse2(v[12], v[1]); - v[13] = xorv_sse2(v[13], v[2]); - v[14] = xorv_sse2(v[14], v[3]); - v[15] = rot16_sse2(v[15]); - v[12] = rot16_sse2(v[12]); - v[13] = rot16_sse2(v[13]); - v[14] = rot16_sse2(v[14]); - v[10] = addv_sse2(v[10], v[15]); - v[11] = addv_sse2(v[11], v[12]); - v[8] = addv_sse2(v[8], v[13]); - v[9] = addv_sse2(v[9], v[14]); - v[5] = xorv_sse2(v[5], v[10]); - v[6] = xorv_sse2(v[6], v[11]); - v[7] = xorv_sse2(v[7], v[8]); - v[4] = xorv_sse2(v[4], v[9]); - v[5] = rot12_sse2(v[5]); - v[6] = rot12_sse2(v[6]); - v[7] = rot12_sse2(v[7]); - v[4] = rot12_sse2(v[4]); - v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = addv_sse2(v[0], v[5]); - v[1] = addv_sse2(v[1], v[6]); - v[2] = addv_sse2(v[2], v[7]); - v[3] = addv_sse2(v[3], v[4]); - v[15] = xorv_sse2(v[15], v[0]); - v[12] = xorv_sse2(v[12], v[1]); - v[13] = xorv_sse2(v[13], v[2]); - v[14] = xorv_sse2(v[14], v[3]); - v[15] = rot8_sse2(v[15]); - v[12] = rot8_sse2(v[12]); - v[13] = rot8_sse2(v[13]); - v[14] = rot8_sse2(v[14]); - v[10] = addv_sse2(v[10], v[15]); - v[11] = addv_sse2(v[11], v[12]); - v[8] = addv_sse2(v[8], v[13]); - v[9] = addv_sse2(v[9], v[14]); - v[5] = xorv_sse2(v[5], v[10]); - v[6] = xorv_sse2(v[6], v[11]); - v[7] = xorv_sse2(v[7], v[8]); - v[4] = xorv_sse2(v[4], v[9]); - v[5] = rot7_sse2(v[5]); - v[6] = rot7_sse2(v[6]); - v[7] = rot7_sse2(v[7]); - v[4] = rot7_sse2(v[4]); -} - -static inline void -transpose_vecs_sse2(__m128i vecs[DEGREE_SSE2]) -{ - __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]); - __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]); - __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]); - __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]); - - __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01); - __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01); - __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23); - __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23); - - vecs[0] = abcd_0; - vecs[1] = abcd_1; - vecs[2] = abcd_2; - vecs[3] = abcd_3; -} - -static inline void -transpose_msg_vecs_sse2(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) -{ - size_t i; - - out_msg[0] = loadu_sse2(&inputs[0][block_offset + 0 * sizeof(__m128i)]); - out_msg[1] = loadu_sse2(&inputs[1][block_offset + 0 * sizeof(__m128i)]); - out_msg[2] = loadu_sse2(&inputs[2][block_offset + 0 * sizeof(__m128i)]); - out_msg[3] = loadu_sse2(&inputs[3][block_offset + 0 * sizeof(__m128i)]); - out_msg[4] = loadu_sse2(&inputs[0][block_offset + 1 * sizeof(__m128i)]); - out_msg[5] = loadu_sse2(&inputs[1][block_offset + 1 * sizeof(__m128i)]); - out_msg[6] = loadu_sse2(&inputs[2][block_offset + 1 * sizeof(__m128i)]); - out_msg[7] = loadu_sse2(&inputs[3][block_offset + 1 * sizeof(__m128i)]); - out_msg[8] = loadu_sse2(&inputs[0][block_offset + 2 * sizeof(__m128i)]); - out_msg[9] = loadu_sse2(&inputs[1][block_offset + 2 * sizeof(__m128i)]); - out_msg[10] = loadu_sse2(&inputs[2][block_offset + 2 * sizeof(__m128i)]); - out_msg[11] = loadu_sse2(&inputs[3][block_offset + 2 * sizeof(__m128i)]); - out_msg[12] = loadu_sse2(&inputs[0][block_offset + 3 * sizeof(__m128i)]); - out_msg[13] = loadu_sse2(&inputs[1][block_offset + 3 * sizeof(__m128i)]); - out_msg[14] = loadu_sse2(&inputs[2][block_offset + 3 * sizeof(__m128i)]); - out_msg[15] = loadu_sse2(&inputs[3][block_offset + 3 * sizeof(__m128i)]); - - for (i = 0; i < 4; i++) { - _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); - } - transpose_vecs_sse2(&out_msg[0]); - transpose_vecs_sse2(&out_msg[4]); - transpose_vecs_sse2(&out_msg[8]); - transpose_vecs_sse2(&out_msg[12]); -} - -static inline void -load_counters_sse2(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) -{ - const __m128i mask = _mm_set1_epi32(-increment_counter); - const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); - const __m128i add1 = _mm_and_si128(mask, add0); - __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); - __m128i carry = _mm_cmpgt_epi32( - _mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), _mm_xor_si128(l, _mm_set1_epi32(0x80000000)) - ); - __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); - - *out_lo = l; - *out_hi = h; -} - -void -blake3_hash4_sse2( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m128i h_vecs[8]; - __m128i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_sse2(key[0]); - h_vecs[1] = set1_sse2(key[1]); - h_vecs[2] = set1_sse2(key[2]); - h_vecs[3] = set1_sse2(key[3]); - h_vecs[4] = set1_sse2(key[4]); - h_vecs[5] = set1_sse2(key[5]); - h_vecs[6] = set1_sse2(key[6]); - h_vecs[7] = set1_sse2(key[7]); - - load_counters_sse2(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m128i block_len_vec; - __m128i block_flags_vec; - __m128i msg_vecs[16]; - __m128i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_sse2(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_sse2(block_flags); - transpose_msg_vecs_sse2(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_sse2(IV[0]); - v[9] = set1_sse2(IV[1]); - v[10] = set1_sse2(IV[2]); - v[11] = set1_sse2(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn_sse2(v, msg_vecs, 0); - round_fn_sse2(v, msg_vecs, 1); - round_fn_sse2(v, msg_vecs, 2); - round_fn_sse2(v, msg_vecs, 3); - round_fn_sse2(v, msg_vecs, 4); - round_fn_sse2(v, msg_vecs, 5); - round_fn_sse2(v, msg_vecs, 6); - - h_vecs[0] = xorv_sse2(v[0], v[8]); - h_vecs[1] = xorv_sse2(v[1], v[9]); - h_vecs[2] = xorv_sse2(v[2], v[10]); - h_vecs[3] = xorv_sse2(v[3], v[11]); - h_vecs[4] = xorv_sse2(v[4], v[12]); - h_vecs[5] = xorv_sse2(v[5], v[13]); - h_vecs[6] = xorv_sse2(v[6], v[14]); - h_vecs[7] = xorv_sse2(v[7], v[15]); - - block_flags = flags; - } - - transpose_vecs_sse2(&h_vecs[0]); - transpose_vecs_sse2(&h_vecs[4]); - storeu_sse2(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); - storeu_sse2(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); - storeu_sse2(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); - storeu_sse2(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); - storeu_sse2(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); - storeu_sse2(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); - storeu_sse2(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); - storeu_sse2(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); -} - -static inline void -hash_one_sse2( - const uint8_t *input, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t out_bytes[BLAKE3_OUT_LEN] -) -{ - uint32_t cv[8]; - uint8_t block_flags; - - memcpy(cv, key, BLAKE3_KEY_LEN); - block_flags = flags | flags_start; - while (blocks > 0) { - if (blocks == 1) { - block_flags |= flags_end; - } - blake3_compress_in_place_sse2(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); - input = &input[BLAKE3_BLOCK_LEN]; - blocks -= 1; - block_flags = flags; - } - memcpy(out_bytes, cv, BLAKE3_OUT_LEN); -} - -void -blake3_hash_many_sse2( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - while (num_inputs >= DEGREE_SSE2) { - blake3_hash4_sse2( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += DEGREE_SSE2; - } - inputs += DEGREE_SSE2; - num_inputs -= DEGREE_SSE2; - out_bytes = &out_bytes[DEGREE_SSE2 * BLAKE3_OUT_LEN]; - } - while (num_inputs > 0) { - hash_one_sse2(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); - if (increment_counter) { - counter += 1; - } - inputs += 1; - num_inputs -= 1; - out_bytes = &out_bytes[BLAKE3_OUT_LEN]; - } -} -#if defined(__clang__) -#pragma clang attribute pop -#elif defined(__GNUC__) -#pragma GCC pop_options -#endif - -#if defined(__clang__) -#pragma clang attribute push(__attribute__((target("sse4.1"))), apply_to = function) -#elif defined(__GNUC__) -#pragma GCC push_options -#pragma GCC target("sse4.1") -#endif -#define DEGREE_SSE41 4 - -#define _mm_shuffle_ps2_sse41(a, b, c) \ - (_mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c)))) - -static inline __m128i -loadu_sse41(const uint8_t src[16]) -{ - return _mm_loadu_si128((const __m128i *)src); -} - -static inline void -storeu_sse41(__m128i src, uint8_t dest[16]) -{ - _mm_storeu_si128((__m128i *)dest, src); -} - -static inline __m128i -addv_sse41(__m128i a, __m128i b) -{ - return _mm_add_epi32(a, b); -} - -static inline __m128i -xorv_sse41(__m128i a, __m128i b) -{ - return _mm_xor_si128(a, b); -} - -static inline __m128i -set1_sse41(uint32_t x) -{ - return _mm_set1_epi32((int32_t)x); -} - -static inline __m128i -set4_sse41(uint32_t a, uint32_t b, uint32_t c, uint32_t d) -{ - return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); -} - -static inline __m128i -rot16_sse41(__m128i x) -{ - return _mm_shuffle_epi8(x, _mm_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2)); -} - -static inline __m128i -rot12_sse41(__m128i x) -{ - return xorv_sse41(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12)); -} - -static inline __m128i -rot8_sse41(__m128i x) -{ - return _mm_shuffle_epi8(x, _mm_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1)); -} - -static inline __m128i -rot7_sse41(__m128i x) -{ - return xorv_sse41(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7)); -} - -static inline void -g1_sse41(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = addv_sse41(addv_sse41(*row0, m), *row1); - *row3 = xorv_sse41(*row3, *row0); - *row3 = rot16_sse41(*row3); - *row2 = addv_sse41(*row2, *row3); - *row1 = xorv_sse41(*row1, *row2); - *row1 = rot12_sse41(*row1); -} - -static inline void -g2_sse41(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = addv_sse41(addv_sse41(*row0, m), *row1); - *row3 = xorv_sse41(*row3, *row0); - *row3 = rot8_sse41(*row3); - *row2 = addv_sse41(*row2, *row3); - *row1 = xorv_sse41(*row1, *row2); - *row1 = rot7_sse41(*row1); -} - -static inline void -diagonalize_sse41(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); -} - -static inline void -undiagonalize_sse41(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); -} - -static inline void -compress_pre_sse41( - __m128i rows[4], - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i m0, m1, m2, m3; - __m128i t0, t1, t2, t3, tt; - - rows[0] = loadu_sse41((uint8_t *)&cv[0]); - rows[1] = loadu_sse41((uint8_t *)&cv[4]); - rows[2] = set4_sse41(IV[0], IV[1], IV[2], IV[3]); - rows[3] = - set4_sse41(counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags); - - m0 = loadu_sse41(&block[sizeof(__m128i) * 0]); - m1 = loadu_sse41(&block[sizeof(__m128i) * 1]); - m2 = loadu_sse41(&block[sizeof(__m128i) * 2]); - m3 = loadu_sse41(&block[sizeof(__m128i) * 3]); - - /* round 1 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 2 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 3 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 4 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 5 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 6 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 7 */ - t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); - t1 = _mm_blend_epi16(tt, t1, 0xCC); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_sse41(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - tt = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); - g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - tt = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); - g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); -} - -void -blake3_compress_in_place_sse41( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i rows[4]; - - compress_pre_sse41(rows, cv, block, block_len, counter, flags); - storeu_sse41(xorv_sse41(rows[0], rows[2]), (uint8_t *)&cv[0]); - storeu_sse41(xorv_sse41(rows[1], rows[3]), (uint8_t *)&cv[4]); -} - -void -blake3_compress_xof_sse41( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out_buf[64] -) -{ - __m128i rows[4]; - - compress_pre_sse41(rows, cv, block, block_len, counter, flags); - storeu_sse41(xorv_sse41(rows[0], rows[2]), &out_buf[0]); - storeu_sse41(xorv_sse41(rows[1], rows[3]), &out_buf[16]); - storeu_sse41(xorv_sse41(rows[2], loadu_sse41((uint8_t *)&cv[0])), &out_buf[32]); - storeu_sse41(xorv_sse41(rows[3], loadu_sse41((uint8_t *)&cv[4])), &out_buf[48]); -} - -static inline void -round_fn_sse41(__m128i v[16], __m128i m[16], size_t r) -{ - v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = addv_sse41(v[0], v[4]); - v[1] = addv_sse41(v[1], v[5]); - v[2] = addv_sse41(v[2], v[6]); - v[3] = addv_sse41(v[3], v[7]); - v[12] = xorv_sse41(v[12], v[0]); - v[13] = xorv_sse41(v[13], v[1]); - v[14] = xorv_sse41(v[14], v[2]); - v[15] = xorv_sse41(v[15], v[3]); - v[12] = rot16_sse41(v[12]); - v[13] = rot16_sse41(v[13]); - v[14] = rot16_sse41(v[14]); - v[15] = rot16_sse41(v[15]); - v[8] = addv_sse41(v[8], v[12]); - v[9] = addv_sse41(v[9], v[13]); - v[10] = addv_sse41(v[10], v[14]); - v[11] = addv_sse41(v[11], v[15]); - v[4] = xorv_sse41(v[4], v[8]); - v[5] = xorv_sse41(v[5], v[9]); - v[6] = xorv_sse41(v[6], v[10]); - v[7] = xorv_sse41(v[7], v[11]); - v[4] = rot12_sse41(v[4]); - v[5] = rot12_sse41(v[5]); - v[6] = rot12_sse41(v[6]); - v[7] = rot12_sse41(v[7]); - v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = addv_sse41(v[0], v[4]); - v[1] = addv_sse41(v[1], v[5]); - v[2] = addv_sse41(v[2], v[6]); - v[3] = addv_sse41(v[3], v[7]); - v[12] = xorv_sse41(v[12], v[0]); - v[13] = xorv_sse41(v[13], v[1]); - v[14] = xorv_sse41(v[14], v[2]); - v[15] = xorv_sse41(v[15], v[3]); - v[12] = rot8_sse41(v[12]); - v[13] = rot8_sse41(v[13]); - v[14] = rot8_sse41(v[14]); - v[15] = rot8_sse41(v[15]); - v[8] = addv_sse41(v[8], v[12]); - v[9] = addv_sse41(v[9], v[13]); - v[10] = addv_sse41(v[10], v[14]); - v[11] = addv_sse41(v[11], v[15]); - v[4] = xorv_sse41(v[4], v[8]); - v[5] = xorv_sse41(v[5], v[9]); - v[6] = xorv_sse41(v[6], v[10]); - v[7] = xorv_sse41(v[7], v[11]); - v[4] = rot7_sse41(v[4]); - v[5] = rot7_sse41(v[5]); - v[6] = rot7_sse41(v[6]); - v[7] = rot7_sse41(v[7]); - - v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = addv_sse41(v[0], v[5]); - v[1] = addv_sse41(v[1], v[6]); - v[2] = addv_sse41(v[2], v[7]); - v[3] = addv_sse41(v[3], v[4]); - v[15] = xorv_sse41(v[15], v[0]); - v[12] = xorv_sse41(v[12], v[1]); - v[13] = xorv_sse41(v[13], v[2]); - v[14] = xorv_sse41(v[14], v[3]); - v[15] = rot16_sse41(v[15]); - v[12] = rot16_sse41(v[12]); - v[13] = rot16_sse41(v[13]); - v[14] = rot16_sse41(v[14]); - v[10] = addv_sse41(v[10], v[15]); - v[11] = addv_sse41(v[11], v[12]); - v[8] = addv_sse41(v[8], v[13]); - v[9] = addv_sse41(v[9], v[14]); - v[5] = xorv_sse41(v[5], v[10]); - v[6] = xorv_sse41(v[6], v[11]); - v[7] = xorv_sse41(v[7], v[8]); - v[4] = xorv_sse41(v[4], v[9]); - v[5] = rot12_sse41(v[5]); - v[6] = rot12_sse41(v[6]); - v[7] = rot12_sse41(v[7]); - v[4] = rot12_sse41(v[4]); - v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = addv_sse41(v[0], v[5]); - v[1] = addv_sse41(v[1], v[6]); - v[2] = addv_sse41(v[2], v[7]); - v[3] = addv_sse41(v[3], v[4]); - v[15] = xorv_sse41(v[15], v[0]); - v[12] = xorv_sse41(v[12], v[1]); - v[13] = xorv_sse41(v[13], v[2]); - v[14] = xorv_sse41(v[14], v[3]); - v[15] = rot8_sse41(v[15]); - v[12] = rot8_sse41(v[12]); - v[13] = rot8_sse41(v[13]); - v[14] = rot8_sse41(v[14]); - v[10] = addv_sse41(v[10], v[15]); - v[11] = addv_sse41(v[11], v[12]); - v[8] = addv_sse41(v[8], v[13]); - v[9] = addv_sse41(v[9], v[14]); - v[5] = xorv_sse41(v[5], v[10]); - v[6] = xorv_sse41(v[6], v[11]); - v[7] = xorv_sse41(v[7], v[8]); - v[4] = xorv_sse41(v[4], v[9]); - v[5] = rot7_sse41(v[5]); - v[6] = rot7_sse41(v[6]); - v[7] = rot7_sse41(v[7]); - v[4] = rot7_sse41(v[4]); -} - -static inline void -transpose_vecs_sse41(__m128i vecs[DEGREE_SSE41]) -{ - __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]); - __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]); - __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]); - __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]); - - __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01); - __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01); - __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23); - __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23); - - vecs[0] = abcd_0; - vecs[1] = abcd_1; - vecs[2] = abcd_2; - vecs[3] = abcd_3; -} - -static inline void -transpose_msg_vecs_sse41(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) -{ - size_t i; - - out_msg[0] = loadu_sse41(&inputs[0][block_offset + 0 * sizeof(__m128i)]); - out_msg[1] = loadu_sse41(&inputs[1][block_offset + 0 * sizeof(__m128i)]); - out_msg[2] = loadu_sse41(&inputs[2][block_offset + 0 * sizeof(__m128i)]); - out_msg[3] = loadu_sse41(&inputs[3][block_offset + 0 * sizeof(__m128i)]); - out_msg[4] = loadu_sse41(&inputs[0][block_offset + 1 * sizeof(__m128i)]); - out_msg[5] = loadu_sse41(&inputs[1][block_offset + 1 * sizeof(__m128i)]); - out_msg[6] = loadu_sse41(&inputs[2][block_offset + 1 * sizeof(__m128i)]); - out_msg[7] = loadu_sse41(&inputs[3][block_offset + 1 * sizeof(__m128i)]); - out_msg[8] = loadu_sse41(&inputs[0][block_offset + 2 * sizeof(__m128i)]); - out_msg[9] = loadu_sse41(&inputs[1][block_offset + 2 * sizeof(__m128i)]); - out_msg[10] = loadu_sse41(&inputs[2][block_offset + 2 * sizeof(__m128i)]); - out_msg[11] = loadu_sse41(&inputs[3][block_offset + 2 * sizeof(__m128i)]); - out_msg[12] = loadu_sse41(&inputs[0][block_offset + 3 * sizeof(__m128i)]); - out_msg[13] = loadu_sse41(&inputs[1][block_offset + 3 * sizeof(__m128i)]); - out_msg[14] = loadu_sse41(&inputs[2][block_offset + 3 * sizeof(__m128i)]); - out_msg[15] = loadu_sse41(&inputs[3][block_offset + 3 * sizeof(__m128i)]); - - for (i = 0; i < 4; i++) { - _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); - } - transpose_vecs_sse41(&out_msg[0]); - transpose_vecs_sse41(&out_msg[4]); - transpose_vecs_sse41(&out_msg[8]); - transpose_vecs_sse41(&out_msg[12]); -} - -static inline void -load_counters_sse41(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) -{ - const __m128i mask = _mm_set1_epi32(-increment_counter); - const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); - const __m128i add1 = _mm_and_si128(mask, add0); - __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); - __m128i carry = _mm_cmpgt_epi32( - _mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), _mm_xor_si128(l, _mm_set1_epi32(0x80000000)) - ); - __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); - - *out_lo = l; - *out_hi = h; -} - -void -blake3_hash4_sse41( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m128i h_vecs[8]; - __m128i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_sse41(key[0]); - h_vecs[1] = set1_sse41(key[1]); - h_vecs[2] = set1_sse41(key[2]); - h_vecs[3] = set1_sse41(key[3]); - h_vecs[4] = set1_sse41(key[4]); - h_vecs[5] = set1_sse41(key[5]); - h_vecs[6] = set1_sse41(key[6]); - h_vecs[7] = set1_sse41(key[7]); - - load_counters_sse41(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m128i block_len_vec; - __m128i block_flags_vec; - __m128i msg_vecs[16]; - __m128i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_sse41(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_sse41(block_flags); - transpose_msg_vecs_sse41(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_sse41(IV[0]); - v[9] = set1_sse41(IV[1]); - v[10] = set1_sse41(IV[2]); - v[11] = set1_sse41(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn_sse41(v, msg_vecs, 0); - round_fn_sse41(v, msg_vecs, 1); - round_fn_sse41(v, msg_vecs, 2); - round_fn_sse41(v, msg_vecs, 3); - round_fn_sse41(v, msg_vecs, 4); - round_fn_sse41(v, msg_vecs, 5); - round_fn_sse41(v, msg_vecs, 6); - - h_vecs[0] = xorv_sse41(v[0], v[8]); - h_vecs[1] = xorv_sse41(v[1], v[9]); - h_vecs[2] = xorv_sse41(v[2], v[10]); - h_vecs[3] = xorv_sse41(v[3], v[11]); - h_vecs[4] = xorv_sse41(v[4], v[12]); - h_vecs[5] = xorv_sse41(v[5], v[13]); - h_vecs[6] = xorv_sse41(v[6], v[14]); - h_vecs[7] = xorv_sse41(v[7], v[15]); - - block_flags = flags; - } - - transpose_vecs_sse41(&h_vecs[0]); - transpose_vecs_sse41(&h_vecs[4]); - storeu_sse41(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); - storeu_sse41(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); - storeu_sse41(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); - storeu_sse41(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); - storeu_sse41(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); - storeu_sse41(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); - storeu_sse41(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); - storeu_sse41(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); -} - -static inline void -hash_one_sse41( - const uint8_t *input, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t out_bytes[BLAKE3_OUT_LEN] -) -{ - uint32_t cv[8]; - uint8_t block_flags; - - memcpy(cv, key, BLAKE3_KEY_LEN); - block_flags = flags | flags_start; - while (blocks > 0) { - if (blocks == 1) { - block_flags |= flags_end; - } - blake3_compress_in_place_sse41(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); - input = &input[BLAKE3_BLOCK_LEN]; - blocks -= 1; - block_flags = flags; - } - memcpy(out_bytes, cv, BLAKE3_OUT_LEN); -} - -void -blake3_hash_many_sse41( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - while (num_inputs >= DEGREE_SSE41) { - blake3_hash4_sse41( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += DEGREE_SSE41; - } - inputs += DEGREE_SSE41; - num_inputs -= DEGREE_SSE41; - out_bytes = &out_bytes[DEGREE_SSE41 * BLAKE3_OUT_LEN]; - } - while (num_inputs > 0) { - hash_one_sse41(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); - if (increment_counter) { - counter += 1; - } - inputs += 1; - num_inputs -= 1; - out_bytes = &out_bytes[BLAKE3_OUT_LEN]; - } -} -#if defined(__clang__) -#pragma clang attribute pop -#elif defined(__GNUC__) -#pragma GCC pop_options -#endif - -#if defined(__clang__) -#pragma clang attribute push(__attribute__((target("avx2"))), apply_to = function) -#elif defined(__GNUC__) -#pragma GCC push_options -#pragma GCC target("avx2") -#endif -#define DEGREE_AVX2 8 - -static inline __m256i -loadu_avx2(const uint8_t src[32]) -{ - return _mm256_loadu_si256((const __m256i *)src); -} - -static inline void -storeu_avx2(__m256i src, uint8_t dest[32]) -{ - _mm256_storeu_si256((__m256i *)dest, src); -} - -static inline __m256i -addv_avx2(__m256i a, __m256i b) -{ - return _mm256_add_epi32(a, b); -} - -static inline __m256i -xorv_avx2(__m256i a, __m256i b) -{ - return _mm256_xor_si256(a, b); -} - -static inline __m256i -set1_avx2(uint32_t x) -{ - return _mm256_set1_epi32((int32_t)x); -} - -static inline __m256i -rot16_avx2(__m256i x) -{ - return _mm256_shuffle_epi8( - x, - _mm256_set_epi8( - 13, - 12, - 15, - 14, - 9, - 8, - 11, - 10, - 5, - 4, - 7, - 6, - 1, - 0, - 3, - 2, - 13, - 12, - 15, - 14, - 9, - 8, - 11, - 10, - 5, - 4, - 7, - 6, - 1, - 0, - 3, - 2 - ) - ); -} - -static inline __m256i -rot12_avx2(__m256i x) -{ - return _mm256_or_si256(_mm256_srli_epi32(x, 12), _mm256_slli_epi32(x, 32 - 12)); -} - -static inline __m256i -rot8_avx2(__m256i x) -{ - return _mm256_shuffle_epi8( - x, - _mm256_set_epi8( - 12, - 15, - 14, - 13, - 8, - 11, - 10, - 9, - 4, - 7, - 6, - 5, - 0, - 3, - 2, - 1, - 12, - 15, - 14, - 13, - 8, - 11, - 10, - 9, - 4, - 7, - 6, - 5, - 0, - 3, - 2, - 1 - ) - ); -} - -static inline __m256i -rot7_avx2(__m256i x) -{ - return _mm256_or_si256(_mm256_srli_epi32(x, 7), _mm256_slli_epi32(x, 32 - 7)); -} - -static inline void -round_fn_avx2(__m256i v[16], __m256i m[16], size_t r) -{ - v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = addv_avx2(v[0], v[4]); - v[1] = addv_avx2(v[1], v[5]); - v[2] = addv_avx2(v[2], v[6]); - v[3] = addv_avx2(v[3], v[7]); - v[12] = xorv_avx2(v[12], v[0]); - v[13] = xorv_avx2(v[13], v[1]); - v[14] = xorv_avx2(v[14], v[2]); - v[15] = xorv_avx2(v[15], v[3]); - v[12] = rot16_avx2(v[12]); - v[13] = rot16_avx2(v[13]); - v[14] = rot16_avx2(v[14]); - v[15] = rot16_avx2(v[15]); - v[8] = addv_avx2(v[8], v[12]); - v[9] = addv_avx2(v[9], v[13]); - v[10] = addv_avx2(v[10], v[14]); - v[11] = addv_avx2(v[11], v[15]); - v[4] = xorv_avx2(v[4], v[8]); - v[5] = xorv_avx2(v[5], v[9]); - v[6] = xorv_avx2(v[6], v[10]); - v[7] = xorv_avx2(v[7], v[11]); - v[4] = rot12_avx2(v[4]); - v[5] = rot12_avx2(v[5]); - v[6] = rot12_avx2(v[6]); - v[7] = rot12_avx2(v[7]); - v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = addv_avx2(v[0], v[4]); - v[1] = addv_avx2(v[1], v[5]); - v[2] = addv_avx2(v[2], v[6]); - v[3] = addv_avx2(v[3], v[7]); - v[12] = xorv_avx2(v[12], v[0]); - v[13] = xorv_avx2(v[13], v[1]); - v[14] = xorv_avx2(v[14], v[2]); - v[15] = xorv_avx2(v[15], v[3]); - v[12] = rot8_avx2(v[12]); - v[13] = rot8_avx2(v[13]); - v[14] = rot8_avx2(v[14]); - v[15] = rot8_avx2(v[15]); - v[8] = addv_avx2(v[8], v[12]); - v[9] = addv_avx2(v[9], v[13]); - v[10] = addv_avx2(v[10], v[14]); - v[11] = addv_avx2(v[11], v[15]); - v[4] = xorv_avx2(v[4], v[8]); - v[5] = xorv_avx2(v[5], v[9]); - v[6] = xorv_avx2(v[6], v[10]); - v[7] = xorv_avx2(v[7], v[11]); - v[4] = rot7_avx2(v[4]); - v[5] = rot7_avx2(v[5]); - v[6] = rot7_avx2(v[6]); - v[7] = rot7_avx2(v[7]); - - v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = addv_avx2(v[0], v[5]); - v[1] = addv_avx2(v[1], v[6]); - v[2] = addv_avx2(v[2], v[7]); - v[3] = addv_avx2(v[3], v[4]); - v[15] = xorv_avx2(v[15], v[0]); - v[12] = xorv_avx2(v[12], v[1]); - v[13] = xorv_avx2(v[13], v[2]); - v[14] = xorv_avx2(v[14], v[3]); - v[15] = rot16_avx2(v[15]); - v[12] = rot16_avx2(v[12]); - v[13] = rot16_avx2(v[13]); - v[14] = rot16_avx2(v[14]); - v[10] = addv_avx2(v[10], v[15]); - v[11] = addv_avx2(v[11], v[12]); - v[8] = addv_avx2(v[8], v[13]); - v[9] = addv_avx2(v[9], v[14]); - v[5] = xorv_avx2(v[5], v[10]); - v[6] = xorv_avx2(v[6], v[11]); - v[7] = xorv_avx2(v[7], v[8]); - v[4] = xorv_avx2(v[4], v[9]); - v[5] = rot12_avx2(v[5]); - v[6] = rot12_avx2(v[6]); - v[7] = rot12_avx2(v[7]); - v[4] = rot12_avx2(v[4]); - v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = addv_avx2(v[0], v[5]); - v[1] = addv_avx2(v[1], v[6]); - v[2] = addv_avx2(v[2], v[7]); - v[3] = addv_avx2(v[3], v[4]); - v[15] = xorv_avx2(v[15], v[0]); - v[12] = xorv_avx2(v[12], v[1]); - v[13] = xorv_avx2(v[13], v[2]); - v[14] = xorv_avx2(v[14], v[3]); - v[15] = rot8_avx2(v[15]); - v[12] = rot8_avx2(v[12]); - v[13] = rot8_avx2(v[13]); - v[14] = rot8_avx2(v[14]); - v[10] = addv_avx2(v[10], v[15]); - v[11] = addv_avx2(v[11], v[12]); - v[8] = addv_avx2(v[8], v[13]); - v[9] = addv_avx2(v[9], v[14]); - v[5] = xorv_avx2(v[5], v[10]); - v[6] = xorv_avx2(v[6], v[11]); - v[7] = xorv_avx2(v[7], v[8]); - v[4] = xorv_avx2(v[4], v[9]); - v[5] = rot7_avx2(v[5]); - v[6] = rot7_avx2(v[6]); - v[7] = rot7_avx2(v[7]); - v[4] = rot7_avx2(v[4]); -} - -static inline void -transpose_vecs_avx2(__m256i vecs[DEGREE_AVX2]) -{ - __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]); - __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]); - __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]); - __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]); - __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]); - __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]); - __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]); - __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]); - - __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145); - __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145); - __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367); - __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367); - __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145); - __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145); - __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367); - __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367); - - vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20); - vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20); - vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20); - vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20); - vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31); - vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31); - vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31); - vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31); -} - -static inline void -transpose_msg_vecs_avx2(const uint8_t *const *inputs, size_t block_offset, __m256i out_msg[16]) -{ - size_t i; - - out_msg[0] = loadu_avx2(&inputs[0][block_offset + 0 * sizeof(__m256i)]); - out_msg[1] = loadu_avx2(&inputs[1][block_offset + 0 * sizeof(__m256i)]); - out_msg[2] = loadu_avx2(&inputs[2][block_offset + 0 * sizeof(__m256i)]); - out_msg[3] = loadu_avx2(&inputs[3][block_offset + 0 * sizeof(__m256i)]); - out_msg[4] = loadu_avx2(&inputs[4][block_offset + 0 * sizeof(__m256i)]); - out_msg[5] = loadu_avx2(&inputs[5][block_offset + 0 * sizeof(__m256i)]); - out_msg[6] = loadu_avx2(&inputs[6][block_offset + 0 * sizeof(__m256i)]); - out_msg[7] = loadu_avx2(&inputs[7][block_offset + 0 * sizeof(__m256i)]); - out_msg[8] = loadu_avx2(&inputs[0][block_offset + 1 * sizeof(__m256i)]); - out_msg[9] = loadu_avx2(&inputs[1][block_offset + 1 * sizeof(__m256i)]); - out_msg[10] = loadu_avx2(&inputs[2][block_offset + 1 * sizeof(__m256i)]); - out_msg[11] = loadu_avx2(&inputs[3][block_offset + 1 * sizeof(__m256i)]); - out_msg[12] = loadu_avx2(&inputs[4][block_offset + 1 * sizeof(__m256i)]); - out_msg[13] = loadu_avx2(&inputs[5][block_offset + 1 * sizeof(__m256i)]); - out_msg[14] = loadu_avx2(&inputs[6][block_offset + 1 * sizeof(__m256i)]); - out_msg[15] = loadu_avx2(&inputs[7][block_offset + 1 * sizeof(__m256i)]); - - for (i = 0; i < 8; i++) { - _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); - } - transpose_vecs_avx2(&out_msg[0]); - transpose_vecs_avx2(&out_msg[8]); -} - -static inline void -load_counters_avx2(uint64_t counter, int increment_counter, __m256i *out_lo, __m256i *out_hi) -{ - const __m256i mask = _mm256_set1_epi32(-increment_counter); - const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); - const __m256i add1 = _mm256_and_si256(mask, add0); - __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1); - __m256i carry = _mm256_xor_si256(add1, _mm256_set1_epi32(0x80000000)); - __m256i comp = _mm256_xor_si256(l, _mm256_set1_epi32(0x80000000)); - __m256i gt = _mm256_cmpgt_epi32(carry, comp); - __m256i h = _mm256_sub_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), gt); - - *out_lo = l; - *out_hi = h; -} - -void -blake3_hash8_avx2( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m256i h_vecs[8]; - __m256i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_avx2(key[0]); - h_vecs[1] = set1_avx2(key[1]); - h_vecs[2] = set1_avx2(key[2]); - h_vecs[3] = set1_avx2(key[3]); - h_vecs[4] = set1_avx2(key[4]); - h_vecs[5] = set1_avx2(key[5]); - h_vecs[6] = set1_avx2(key[6]); - h_vecs[7] = set1_avx2(key[7]); - - load_counters_avx2(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m256i block_len_vec; - __m256i block_flags_vec; - __m256i msg_vecs[16]; - __m256i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_avx2(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_avx2(block_flags); - transpose_msg_vecs_avx2(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_avx2(IV[0]); - v[9] = set1_avx2(IV[1]); - v[10] = set1_avx2(IV[2]); - v[11] = set1_avx2(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn_avx2(v, msg_vecs, 0); - round_fn_avx2(v, msg_vecs, 1); - round_fn_avx2(v, msg_vecs, 2); - round_fn_avx2(v, msg_vecs, 3); - round_fn_avx2(v, msg_vecs, 4); - round_fn_avx2(v, msg_vecs, 5); - round_fn_avx2(v, msg_vecs, 6); - - h_vecs[0] = xorv_avx2(v[0], v[8]); - h_vecs[1] = xorv_avx2(v[1], v[9]); - h_vecs[2] = xorv_avx2(v[2], v[10]); - h_vecs[3] = xorv_avx2(v[3], v[11]); - h_vecs[4] = xorv_avx2(v[4], v[12]); - h_vecs[5] = xorv_avx2(v[5], v[13]); - h_vecs[6] = xorv_avx2(v[6], v[14]); - h_vecs[7] = xorv_avx2(v[7], v[15]); - - block_flags = flags; - } - - transpose_vecs_avx2(h_vecs); - storeu_avx2(h_vecs[0], &out_bytes[0 * sizeof(__m256i)]); - storeu_avx2(h_vecs[1], &out_bytes[1 * sizeof(__m256i)]); - storeu_avx2(h_vecs[2], &out_bytes[2 * sizeof(__m256i)]); - storeu_avx2(h_vecs[3], &out_bytes[3 * sizeof(__m256i)]); - storeu_avx2(h_vecs[4], &out_bytes[4 * sizeof(__m256i)]); - storeu_avx2(h_vecs[5], &out_bytes[5 * sizeof(__m256i)]); - storeu_avx2(h_vecs[6], &out_bytes[6 * sizeof(__m256i)]); - storeu_avx2(h_vecs[7], &out_bytes[7 * sizeof(__m256i)]); -} - -void -blake3_hash_many_avx2( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - while (num_inputs >= DEGREE_AVX2) { - blake3_hash8_avx2( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += DEGREE_AVX2; - } - inputs += DEGREE_AVX2; - num_inputs -= DEGREE_AVX2; - out_bytes = &out_bytes[DEGREE_AVX2 * BLAKE3_OUT_LEN]; - } - blake3_hash_many_sse41( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out_bytes - ); -} -#if defined(__clang__) -#pragma clang attribute pop -#elif defined(__GNUC__) -#pragma GCC pop_options -#endif - -#if defined(__clang__) -#pragma clang attribute push(__attribute__((target("avx512f,avx512vl"))), apply_to = function) -#elif defined(__GNUC__) -#pragma GCC push_options -#pragma GCC target("avx512f,avx512vl") -#endif -static inline __m128i -loadu_128_avx512(const uint8_t src[16]) -{ - return _mm_loadu_si128((const __m128i *)src); -} - -static inline __m256i -loadu_256_avx512(const uint8_t src[32]) -{ - return _mm256_loadu_si256((const __m256i *)src); -} - -static inline __m512i -loadu_512_avx512(const uint8_t src[64]) -{ - return _mm512_loadu_si512((const __m512i *)src); -} - -static inline void -storeu_128_avx512(__m128i src, uint8_t dest[16]) -{ - _mm_storeu_si128((__m128i *)dest, src); -} - -static inline void -storeu_256_avx512(__m256i src, uint8_t dest[32]) -{ - _mm256_storeu_si256((__m256i *)dest, src); -} - -static inline __m128i -add_128_avx512(__m128i a, __m128i b) -{ - return _mm_add_epi32(a, b); -} - -static inline __m256i -add_256_avx512(__m256i a, __m256i b) -{ - return _mm256_add_epi32(a, b); -} - -static inline __m512i -add_512_avx512(__m512i a, __m512i b) -{ - return _mm512_add_epi32(a, b); -} - -static inline __m128i -xor_128_avx512(__m128i a, __m128i b) -{ - return _mm_xor_si128(a, b); -} - -static inline __m256i -xor_256_avx512(__m256i a, __m256i b) -{ - return _mm256_xor_si256(a, b); -} - -static inline __m512i -xor_512_avx512(__m512i a, __m512i b) -{ - return _mm512_xor_si512(a, b); -} - -static inline __m128i -set1_128_avx512(uint32_t x) -{ - return _mm_set1_epi32((int32_t)x); -} - -static inline __m256i -set1_256_avx512(uint32_t x) -{ - return _mm256_set1_epi32((int32_t)x); -} - -static inline __m512i -set1_512_avx512(uint32_t x) -{ - return _mm512_set1_epi32((int32_t)x); -} - -static inline __m128i -set4_avx512(uint32_t a, uint32_t b, uint32_t c, uint32_t d) -{ - return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); -} - -static inline __m128i -rot16_128_avx512(__m128i x) -{ - return _mm_ror_epi32(x, 16); -} - -static inline __m256i -rot16_256_avx512(__m256i x) -{ - return _mm256_ror_epi32(x, 16); -} - -static inline __m512i -rot16_512_avx512(__m512i x) -{ - return _mm512_ror_epi32(x, 16); -} - -static inline __m128i -rot12_128_avx512(__m128i x) -{ - return _mm_ror_epi32(x, 12); -} - -static inline __m256i -rot12_256_avx512(__m256i x) -{ - return _mm256_ror_epi32(x, 12); -} - -static inline __m512i -rot12_512_avx512(__m512i x) -{ - return _mm512_ror_epi32(x, 12); -} - -static inline __m128i -rot8_128_avx512(__m128i x) -{ - return _mm_ror_epi32(x, 8); -} - -static inline __m256i -rot8_256_avx512(__m256i x) -{ - return _mm256_ror_epi32(x, 8); -} - -static inline __m512i -rot8_512_avx512(__m512i x) -{ - return _mm512_ror_epi32(x, 8); -} - -static inline __m128i -rot7_128_avx512(__m128i x) -{ - return _mm_ror_epi32(x, 7); -} - -static inline __m256i -rot7_256_avx512(__m256i x) -{ - return _mm256_ror_epi32(x, 7); -} - -static inline __m512i -rot7_512_avx512(__m512i x) -{ - return _mm512_ror_epi32(x, 7); -} - -static inline void -g1_avx512(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = add_128_avx512(add_128_avx512(*row0, m), *row1); - *row3 = xor_128_avx512(*row3, *row0); - *row3 = rot16_128_avx512(*row3); - *row2 = add_128_avx512(*row2, *row3); - *row1 = xor_128_avx512(*row1, *row2); - *row1 = rot12_128_avx512(*row1); -} - -static inline void -g2_avx512(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) -{ - *row0 = add_128_avx512(add_128_avx512(*row0, m), *row1); - *row3 = xor_128_avx512(*row3, *row0); - *row3 = rot8_128_avx512(*row3); - *row2 = add_128_avx512(*row2, *row3); - *row1 = xor_128_avx512(*row1, *row2); - *row1 = rot7_128_avx512(*row1); -} - -static inline void -diagonalize_avx512(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); -} - -static inline void -undiagonalize_avx512(__m128i *row0, __m128i *row2, __m128i *row3) -{ - *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); - *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); - *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); -} - -static inline void -compress_pre_avx512( - __m128i rows[4], - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i m0, m1, m2, m3; - __m128i t0, t1, t2, t3; - - rows[0] = loadu_128_avx512((const uint8_t *)&cv[0]); - rows[1] = loadu_128_avx512((const uint8_t *)&cv[4]); - rows[2] = set4_avx512(IV[0], IV[1], IV[2], IV[3]); - rows[3] = set4_avx512( - counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags - ); - - m0 = loadu_128_avx512(&block[sizeof(__m128i) * 0]); - m1 = loadu_128_avx512(&block[sizeof(__m128i) * 1]); - m2 = loadu_128_avx512(&block[sizeof(__m128i) * 2]); - m3 = loadu_128_avx512(&block[sizeof(__m128i) * 3]); - - /* round 1 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 2 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 3 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 4 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 5 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 6 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); - m0 = t0; - m1 = t1; - m2 = t2; - m3 = t3; - - /* round 7 */ - t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); - t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); - t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); - t1 = _mm_blend_epi16(m0, t1, 0xCC); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); - diagonalize_avx512(&rows[0], &rows[2], &rows[3]); - t2 = _mm_unpacklo_epi64(m3, m1); - t2 = _mm_blend_epi16(t2, m2, 0xC0); - t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); - g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); - t3 = _mm_unpackhi_epi32(m1, m3); - t3 = _mm_unpacklo_epi32(m2, t3); - t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); - g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); - undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); -} - -void -blake3_compress_in_place_avx512( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - __m128i rows[4]; - - compress_pre_avx512(rows, cv, block, block_len, counter, flags); - storeu_128_avx512(xor_128_avx512(rows[0], rows[2]), (uint8_t *)&cv[0]); - storeu_128_avx512(xor_128_avx512(rows[1], rows[3]), (uint8_t *)&cv[4]); -} - -void -blake3_compress_xof_avx512( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out_buf[64] -) -{ - __m128i rows[4]; - - compress_pre_avx512(rows, cv, block, block_len, counter, flags); - storeu_128_avx512(xor_128_avx512(rows[0], rows[2]), &out_buf[0]); - storeu_128_avx512(xor_128_avx512(rows[1], rows[3]), &out_buf[16]); - storeu_128_avx512( - xor_128_avx512(rows[2], loadu_128_avx512((const uint8_t *)&cv[0])), &out_buf[32] - ); - storeu_128_avx512( - xor_128_avx512(rows[3], loadu_128_avx512((const uint8_t *)&cv[4])), &out_buf[48] - ); -} - -static inline void -round_fn4_avx512(__m128i v[16], __m128i m[16], size_t r) -{ - v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = add_128_avx512(v[0], v[4]); - v[1] = add_128_avx512(v[1], v[5]); - v[2] = add_128_avx512(v[2], v[6]); - v[3] = add_128_avx512(v[3], v[7]); - v[12] = xor_128_avx512(v[12], v[0]); - v[13] = xor_128_avx512(v[13], v[1]); - v[14] = xor_128_avx512(v[14], v[2]); - v[15] = xor_128_avx512(v[15], v[3]); - v[12] = rot16_128_avx512(v[12]); - v[13] = rot16_128_avx512(v[13]); - v[14] = rot16_128_avx512(v[14]); - v[15] = rot16_128_avx512(v[15]); - v[8] = add_128_avx512(v[8], v[12]); - v[9] = add_128_avx512(v[9], v[13]); - v[10] = add_128_avx512(v[10], v[14]); - v[11] = add_128_avx512(v[11], v[15]); - v[4] = xor_128_avx512(v[4], v[8]); - v[5] = xor_128_avx512(v[5], v[9]); - v[6] = xor_128_avx512(v[6], v[10]); - v[7] = xor_128_avx512(v[7], v[11]); - v[4] = rot12_128_avx512(v[4]); - v[5] = rot12_128_avx512(v[5]); - v[6] = rot12_128_avx512(v[6]); - v[7] = rot12_128_avx512(v[7]); - v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = add_128_avx512(v[0], v[4]); - v[1] = add_128_avx512(v[1], v[5]); - v[2] = add_128_avx512(v[2], v[6]); - v[3] = add_128_avx512(v[3], v[7]); - v[12] = xor_128_avx512(v[12], v[0]); - v[13] = xor_128_avx512(v[13], v[1]); - v[14] = xor_128_avx512(v[14], v[2]); - v[15] = xor_128_avx512(v[15], v[3]); - v[12] = rot8_128_avx512(v[12]); - v[13] = rot8_128_avx512(v[13]); - v[14] = rot8_128_avx512(v[14]); - v[15] = rot8_128_avx512(v[15]); - v[8] = add_128_avx512(v[8], v[12]); - v[9] = add_128_avx512(v[9], v[13]); - v[10] = add_128_avx512(v[10], v[14]); - v[11] = add_128_avx512(v[11], v[15]); - v[4] = xor_128_avx512(v[4], v[8]); - v[5] = xor_128_avx512(v[5], v[9]); - v[6] = xor_128_avx512(v[6], v[10]); - v[7] = xor_128_avx512(v[7], v[11]); - v[4] = rot7_128_avx512(v[4]); - v[5] = rot7_128_avx512(v[5]); - v[6] = rot7_128_avx512(v[6]); - v[7] = rot7_128_avx512(v[7]); - - v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = add_128_avx512(v[0], v[5]); - v[1] = add_128_avx512(v[1], v[6]); - v[2] = add_128_avx512(v[2], v[7]); - v[3] = add_128_avx512(v[3], v[4]); - v[15] = xor_128_avx512(v[15], v[0]); - v[12] = xor_128_avx512(v[12], v[1]); - v[13] = xor_128_avx512(v[13], v[2]); - v[14] = xor_128_avx512(v[14], v[3]); - v[15] = rot16_128_avx512(v[15]); - v[12] = rot16_128_avx512(v[12]); - v[13] = rot16_128_avx512(v[13]); - v[14] = rot16_128_avx512(v[14]); - v[10] = add_128_avx512(v[10], v[15]); - v[11] = add_128_avx512(v[11], v[12]); - v[8] = add_128_avx512(v[8], v[13]); - v[9] = add_128_avx512(v[9], v[14]); - v[5] = xor_128_avx512(v[5], v[10]); - v[6] = xor_128_avx512(v[6], v[11]); - v[7] = xor_128_avx512(v[7], v[8]); - v[4] = xor_128_avx512(v[4], v[9]); - v[5] = rot12_128_avx512(v[5]); - v[6] = rot12_128_avx512(v[6]); - v[7] = rot12_128_avx512(v[7]); - v[4] = rot12_128_avx512(v[4]); - v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = add_128_avx512(v[0], v[5]); - v[1] = add_128_avx512(v[1], v[6]); - v[2] = add_128_avx512(v[2], v[7]); - v[3] = add_128_avx512(v[3], v[4]); - v[15] = xor_128_avx512(v[15], v[0]); - v[12] = xor_128_avx512(v[12], v[1]); - v[13] = xor_128_avx512(v[13], v[2]); - v[14] = xor_128_avx512(v[14], v[3]); - v[15] = rot8_128_avx512(v[15]); - v[12] = rot8_128_avx512(v[12]); - v[13] = rot8_128_avx512(v[13]); - v[14] = rot8_128_avx512(v[14]); - v[10] = add_128_avx512(v[10], v[15]); - v[11] = add_128_avx512(v[11], v[12]); - v[8] = add_128_avx512(v[8], v[13]); - v[9] = add_128_avx512(v[9], v[14]); - v[5] = xor_128_avx512(v[5], v[10]); - v[6] = xor_128_avx512(v[6], v[11]); - v[7] = xor_128_avx512(v[7], v[8]); - v[4] = xor_128_avx512(v[4], v[9]); - v[5] = rot7_128_avx512(v[5]); - v[6] = rot7_128_avx512(v[6]); - v[7] = rot7_128_avx512(v[7]); - v[4] = rot7_128_avx512(v[4]); -} - -static inline void -round_fn8_avx512(__m256i v[16], __m256i m[16], size_t r) -{ - v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = add_256_avx512(v[0], v[4]); - v[1] = add_256_avx512(v[1], v[5]); - v[2] = add_256_avx512(v[2], v[6]); - v[3] = add_256_avx512(v[3], v[7]); - v[12] = xor_256_avx512(v[12], v[0]); - v[13] = xor_256_avx512(v[13], v[1]); - v[14] = xor_256_avx512(v[14], v[2]); - v[15] = xor_256_avx512(v[15], v[3]); - v[12] = rot16_256_avx512(v[12]); - v[13] = rot16_256_avx512(v[13]); - v[14] = rot16_256_avx512(v[14]); - v[15] = rot16_256_avx512(v[15]); - v[8] = add_256_avx512(v[8], v[12]); - v[9] = add_256_avx512(v[9], v[13]); - v[10] = add_256_avx512(v[10], v[14]); - v[11] = add_256_avx512(v[11], v[15]); - v[4] = xor_256_avx512(v[4], v[8]); - v[5] = xor_256_avx512(v[5], v[9]); - v[6] = xor_256_avx512(v[6], v[10]); - v[7] = xor_256_avx512(v[7], v[11]); - v[4] = rot12_256_avx512(v[4]); - v[5] = rot12_256_avx512(v[5]); - v[6] = rot12_256_avx512(v[6]); - v[7] = rot12_256_avx512(v[7]); - v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = add_256_avx512(v[0], v[4]); - v[1] = add_256_avx512(v[1], v[5]); - v[2] = add_256_avx512(v[2], v[6]); - v[3] = add_256_avx512(v[3], v[7]); - v[12] = xor_256_avx512(v[12], v[0]); - v[13] = xor_256_avx512(v[13], v[1]); - v[14] = xor_256_avx512(v[14], v[2]); - v[15] = xor_256_avx512(v[15], v[3]); - v[12] = rot8_256_avx512(v[12]); - v[13] = rot8_256_avx512(v[13]); - v[14] = rot8_256_avx512(v[14]); - v[15] = rot8_256_avx512(v[15]); - v[8] = add_256_avx512(v[8], v[12]); - v[9] = add_256_avx512(v[9], v[13]); - v[10] = add_256_avx512(v[10], v[14]); - v[11] = add_256_avx512(v[11], v[15]); - v[4] = xor_256_avx512(v[4], v[8]); - v[5] = xor_256_avx512(v[5], v[9]); - v[6] = xor_256_avx512(v[6], v[10]); - v[7] = xor_256_avx512(v[7], v[11]); - v[4] = rot7_256_avx512(v[4]); - v[5] = rot7_256_avx512(v[5]); - v[6] = rot7_256_avx512(v[6]); - v[7] = rot7_256_avx512(v[7]); - - v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = add_256_avx512(v[0], v[5]); - v[1] = add_256_avx512(v[1], v[6]); - v[2] = add_256_avx512(v[2], v[7]); - v[3] = add_256_avx512(v[3], v[4]); - v[15] = xor_256_avx512(v[15], v[0]); - v[12] = xor_256_avx512(v[12], v[1]); - v[13] = xor_256_avx512(v[13], v[2]); - v[14] = xor_256_avx512(v[14], v[3]); - v[15] = rot16_256_avx512(v[15]); - v[12] = rot16_256_avx512(v[12]); - v[13] = rot16_256_avx512(v[13]); - v[14] = rot16_256_avx512(v[14]); - v[10] = add_256_avx512(v[10], v[15]); - v[11] = add_256_avx512(v[11], v[12]); - v[8] = add_256_avx512(v[8], v[13]); - v[9] = add_256_avx512(v[9], v[14]); - v[5] = xor_256_avx512(v[5], v[10]); - v[6] = xor_256_avx512(v[6], v[11]); - v[7] = xor_256_avx512(v[7], v[8]); - v[4] = xor_256_avx512(v[4], v[9]); - v[5] = rot12_256_avx512(v[5]); - v[6] = rot12_256_avx512(v[6]); - v[7] = rot12_256_avx512(v[7]); - v[4] = rot12_256_avx512(v[4]); - v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = add_256_avx512(v[0], v[5]); - v[1] = add_256_avx512(v[1], v[6]); - v[2] = add_256_avx512(v[2], v[7]); - v[3] = add_256_avx512(v[3], v[4]); - v[15] = xor_256_avx512(v[15], v[0]); - v[12] = xor_256_avx512(v[12], v[1]); - v[13] = xor_256_avx512(v[13], v[2]); - v[14] = xor_256_avx512(v[14], v[3]); - v[15] = rot8_256_avx512(v[15]); - v[12] = rot8_256_avx512(v[12]); - v[13] = rot8_256_avx512(v[13]); - v[14] = rot8_256_avx512(v[14]); - v[10] = add_256_avx512(v[10], v[15]); - v[11] = add_256_avx512(v[11], v[12]); - v[8] = add_256_avx512(v[8], v[13]); - v[9] = add_256_avx512(v[9], v[14]); - v[5] = xor_256_avx512(v[5], v[10]); - v[6] = xor_256_avx512(v[6], v[11]); - v[7] = xor_256_avx512(v[7], v[8]); - v[4] = xor_256_avx512(v[4], v[9]); - v[5] = rot7_256_avx512(v[5]); - v[6] = rot7_256_avx512(v[6]); - v[7] = rot7_256_avx512(v[7]); - v[4] = rot7_256_avx512(v[4]); -} - -static inline void -round_fn16_avx512(__m512i v[16], __m512i m[16], size_t r) -{ - v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); - v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); - v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); - v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); - v[0] = add_512_avx512(v[0], v[4]); - v[1] = add_512_avx512(v[1], v[5]); - v[2] = add_512_avx512(v[2], v[6]); - v[3] = add_512_avx512(v[3], v[7]); - v[12] = xor_512_avx512(v[12], v[0]); - v[13] = xor_512_avx512(v[13], v[1]); - v[14] = xor_512_avx512(v[14], v[2]); - v[15] = xor_512_avx512(v[15], v[3]); - v[12] = rot16_512_avx512(v[12]); - v[13] = rot16_512_avx512(v[13]); - v[14] = rot16_512_avx512(v[14]); - v[15] = rot16_512_avx512(v[15]); - v[8] = add_512_avx512(v[8], v[12]); - v[9] = add_512_avx512(v[9], v[13]); - v[10] = add_512_avx512(v[10], v[14]); - v[11] = add_512_avx512(v[11], v[15]); - v[4] = xor_512_avx512(v[4], v[8]); - v[5] = xor_512_avx512(v[5], v[9]); - v[6] = xor_512_avx512(v[6], v[10]); - v[7] = xor_512_avx512(v[7], v[11]); - v[4] = rot12_512_avx512(v[4]); - v[5] = rot12_512_avx512(v[5]); - v[6] = rot12_512_avx512(v[6]); - v[7] = rot12_512_avx512(v[7]); - v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); - v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); - v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); - v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); - v[0] = add_512_avx512(v[0], v[4]); - v[1] = add_512_avx512(v[1], v[5]); - v[2] = add_512_avx512(v[2], v[6]); - v[3] = add_512_avx512(v[3], v[7]); - v[12] = xor_512_avx512(v[12], v[0]); - v[13] = xor_512_avx512(v[13], v[1]); - v[14] = xor_512_avx512(v[14], v[2]); - v[15] = xor_512_avx512(v[15], v[3]); - v[12] = rot8_512_avx512(v[12]); - v[13] = rot8_512_avx512(v[13]); - v[14] = rot8_512_avx512(v[14]); - v[15] = rot8_512_avx512(v[15]); - v[8] = add_512_avx512(v[8], v[12]); - v[9] = add_512_avx512(v[9], v[13]); - v[10] = add_512_avx512(v[10], v[14]); - v[11] = add_512_avx512(v[11], v[15]); - v[4] = xor_512_avx512(v[4], v[8]); - v[5] = xor_512_avx512(v[5], v[9]); - v[6] = xor_512_avx512(v[6], v[10]); - v[7] = xor_512_avx512(v[7], v[11]); - v[4] = rot7_512_avx512(v[4]); - v[5] = rot7_512_avx512(v[5]); - v[6] = rot7_512_avx512(v[6]); - v[7] = rot7_512_avx512(v[7]); - - v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); - v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); - v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); - v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); - v[0] = add_512_avx512(v[0], v[5]); - v[1] = add_512_avx512(v[1], v[6]); - v[2] = add_512_avx512(v[2], v[7]); - v[3] = add_512_avx512(v[3], v[4]); - v[15] = xor_512_avx512(v[15], v[0]); - v[12] = xor_512_avx512(v[12], v[1]); - v[13] = xor_512_avx512(v[13], v[2]); - v[14] = xor_512_avx512(v[14], v[3]); - v[15] = rot16_512_avx512(v[15]); - v[12] = rot16_512_avx512(v[12]); - v[13] = rot16_512_avx512(v[13]); - v[14] = rot16_512_avx512(v[14]); - v[10] = add_512_avx512(v[10], v[15]); - v[11] = add_512_avx512(v[11], v[12]); - v[8] = add_512_avx512(v[8], v[13]); - v[9] = add_512_avx512(v[9], v[14]); - v[5] = xor_512_avx512(v[5], v[10]); - v[6] = xor_512_avx512(v[6], v[11]); - v[7] = xor_512_avx512(v[7], v[8]); - v[4] = xor_512_avx512(v[4], v[9]); - v[5] = rot12_512_avx512(v[5]); - v[6] = rot12_512_avx512(v[6]); - v[7] = rot12_512_avx512(v[7]); - v[4] = rot12_512_avx512(v[4]); - v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); - v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); - v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); - v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); - v[0] = add_512_avx512(v[0], v[5]); - v[1] = add_512_avx512(v[1], v[6]); - v[2] = add_512_avx512(v[2], v[7]); - v[3] = add_512_avx512(v[3], v[4]); - v[15] = xor_512_avx512(v[15], v[0]); - v[12] = xor_512_avx512(v[12], v[1]); - v[13] = xor_512_avx512(v[13], v[2]); - v[14] = xor_512_avx512(v[14], v[3]); - v[15] = rot8_512_avx512(v[15]); - v[12] = rot8_512_avx512(v[12]); - v[13] = rot8_512_avx512(v[13]); - v[14] = rot8_512_avx512(v[14]); - v[10] = add_512_avx512(v[10], v[15]); - v[11] = add_512_avx512(v[11], v[12]); - v[8] = add_512_avx512(v[8], v[13]); - v[9] = add_512_avx512(v[9], v[14]); - v[5] = xor_512_avx512(v[5], v[10]); - v[6] = xor_512_avx512(v[6], v[11]); - v[7] = xor_512_avx512(v[7], v[8]); - v[4] = xor_512_avx512(v[4], v[9]); - v[5] = rot7_512_avx512(v[5]); - v[6] = rot7_512_avx512(v[6]); - v[7] = rot7_512_avx512(v[7]); - v[4] = rot7_512_avx512(v[4]); -} - -#define LO_IMM8 0x88 -#define HI_IMM8 0xdd - -static inline __m512i -unpack_lo_128_avx512(__m512i a, __m512i b) -{ - return _mm512_shuffle_i32x4(a, b, LO_IMM8); -} - -static inline __m512i -unpack_hi_128_avx512(__m512i a, __m512i b) -{ - return _mm512_shuffle_i32x4(a, b, HI_IMM8); -} - -static inline void -transpose_vecs_512_avx512(__m512i vecs[16]) -{ - __m512i ab_0 = _mm512_unpacklo_epi32(vecs[0], vecs[1]); - __m512i ab_2 = _mm512_unpackhi_epi32(vecs[0], vecs[1]); - __m512i cd_0 = _mm512_unpacklo_epi32(vecs[2], vecs[3]); - __m512i cd_2 = _mm512_unpackhi_epi32(vecs[2], vecs[3]); - __m512i ef_0 = _mm512_unpacklo_epi32(vecs[4], vecs[5]); - __m512i ef_2 = _mm512_unpackhi_epi32(vecs[4], vecs[5]); - __m512i gh_0 = _mm512_unpacklo_epi32(vecs[6], vecs[7]); - __m512i gh_2 = _mm512_unpackhi_epi32(vecs[6], vecs[7]); - __m512i ij_0 = _mm512_unpacklo_epi32(vecs[8], vecs[9]); - __m512i ij_2 = _mm512_unpackhi_epi32(vecs[8], vecs[9]); - __m512i kl_0 = _mm512_unpacklo_epi32(vecs[10], vecs[11]); - __m512i kl_2 = _mm512_unpackhi_epi32(vecs[10], vecs[11]); - __m512i mn_0 = _mm512_unpacklo_epi32(vecs[12], vecs[13]); - __m512i mn_2 = _mm512_unpackhi_epi32(vecs[12], vecs[13]); - __m512i op_0 = _mm512_unpacklo_epi32(vecs[14], vecs[15]); - __m512i op_2 = _mm512_unpackhi_epi32(vecs[14], vecs[15]); - - __m512i abcd_0 = _mm512_unpacklo_epi64(ab_0, cd_0); - __m512i abcd_1 = _mm512_unpackhi_epi64(ab_0, cd_0); - __m512i abcd_2 = _mm512_unpacklo_epi64(ab_2, cd_2); - __m512i abcd_3 = _mm512_unpackhi_epi64(ab_2, cd_2); - __m512i efgh_0 = _mm512_unpacklo_epi64(ef_0, gh_0); - __m512i efgh_1 = _mm512_unpackhi_epi64(ef_0, gh_0); - __m512i efgh_2 = _mm512_unpacklo_epi64(ef_2, gh_2); - __m512i efgh_3 = _mm512_unpackhi_epi64(ef_2, gh_2); - __m512i ijkl_0 = _mm512_unpacklo_epi64(ij_0, kl_0); - __m512i ijkl_1 = _mm512_unpackhi_epi64(ij_0, kl_0); - __m512i ijkl_2 = _mm512_unpacklo_epi64(ij_2, kl_2); - __m512i ijkl_3 = _mm512_unpackhi_epi64(ij_2, kl_2); - __m512i mnop_0 = _mm512_unpacklo_epi64(mn_0, op_0); - __m512i mnop_1 = _mm512_unpackhi_epi64(mn_0, op_0); - __m512i mnop_2 = _mm512_unpacklo_epi64(mn_2, op_2); - __m512i mnop_3 = _mm512_unpackhi_epi64(mn_2, op_2); - - __m512i abcdefgh_0 = unpack_lo_128_avx512(abcd_0, efgh_0); - __m512i abcdefgh_1 = unpack_lo_128_avx512(abcd_1, efgh_1); - __m512i abcdefgh_2 = unpack_lo_128_avx512(abcd_2, efgh_2); - __m512i abcdefgh_3 = unpack_lo_128_avx512(abcd_3, efgh_3); - __m512i abcdefgh_4 = unpack_hi_128_avx512(abcd_0, efgh_0); - __m512i abcdefgh_5 = unpack_hi_128_avx512(abcd_1, efgh_1); - __m512i abcdefgh_6 = unpack_hi_128_avx512(abcd_2, efgh_2); - __m512i abcdefgh_7 = unpack_hi_128_avx512(abcd_3, efgh_3); - __m512i ijklmnop_0 = unpack_lo_128_avx512(ijkl_0, mnop_0); - __m512i ijklmnop_1 = unpack_lo_128_avx512(ijkl_1, mnop_1); - __m512i ijklmnop_2 = unpack_lo_128_avx512(ijkl_2, mnop_2); - __m512i ijklmnop_3 = unpack_lo_128_avx512(ijkl_3, mnop_3); - __m512i ijklmnop_4 = unpack_hi_128_avx512(ijkl_0, mnop_0); - __m512i ijklmnop_5 = unpack_hi_128_avx512(ijkl_1, mnop_1); - __m512i ijklmnop_6 = unpack_hi_128_avx512(ijkl_2, mnop_2); - __m512i ijklmnop_7 = unpack_hi_128_avx512(ijkl_3, mnop_3); - - vecs[0] = unpack_lo_128_avx512(abcdefgh_0, ijklmnop_0); - vecs[1] = unpack_lo_128_avx512(abcdefgh_1, ijklmnop_1); - vecs[2] = unpack_lo_128_avx512(abcdefgh_2, ijklmnop_2); - vecs[3] = unpack_lo_128_avx512(abcdefgh_3, ijklmnop_3); - vecs[4] = unpack_lo_128_avx512(abcdefgh_4, ijklmnop_4); - vecs[5] = unpack_lo_128_avx512(abcdefgh_5, ijklmnop_5); - vecs[6] = unpack_lo_128_avx512(abcdefgh_6, ijklmnop_6); - vecs[7] = unpack_lo_128_avx512(abcdefgh_7, ijklmnop_7); - vecs[8] = unpack_hi_128_avx512(abcdefgh_0, ijklmnop_0); - vecs[9] = unpack_hi_128_avx512(abcdefgh_1, ijklmnop_1); - vecs[10] = unpack_hi_128_avx512(abcdefgh_2, ijklmnop_2); - vecs[11] = unpack_hi_128_avx512(abcdefgh_3, ijklmnop_3); - vecs[12] = unpack_hi_128_avx512(abcdefgh_4, ijklmnop_4); - vecs[13] = unpack_hi_128_avx512(abcdefgh_5, ijklmnop_5); - vecs[14] = unpack_hi_128_avx512(abcdefgh_6, ijklmnop_6); - vecs[15] = unpack_hi_128_avx512(abcdefgh_7, ijklmnop_7); -} - -static inline void -transpose_msg_vecs16_avx512(const uint8_t *const *inputs, size_t block_offset, __m512i out_msg[16]) -{ - size_t i; - - out_msg[0] = loadu_512_avx512(&inputs[0][block_offset]); - out_msg[1] = loadu_512_avx512(&inputs[1][block_offset]); - out_msg[2] = loadu_512_avx512(&inputs[2][block_offset]); - out_msg[3] = loadu_512_avx512(&inputs[3][block_offset]); - out_msg[4] = loadu_512_avx512(&inputs[4][block_offset]); - out_msg[5] = loadu_512_avx512(&inputs[5][block_offset]); - out_msg[6] = loadu_512_avx512(&inputs[6][block_offset]); - out_msg[7] = loadu_512_avx512(&inputs[7][block_offset]); - out_msg[8] = loadu_512_avx512(&inputs[8][block_offset]); - out_msg[9] = loadu_512_avx512(&inputs[9][block_offset]); - out_msg[10] = loadu_512_avx512(&inputs[10][block_offset]); - out_msg[11] = loadu_512_avx512(&inputs[11][block_offset]); - out_msg[12] = loadu_512_avx512(&inputs[12][block_offset]); - out_msg[13] = loadu_512_avx512(&inputs[13][block_offset]); - out_msg[14] = loadu_512_avx512(&inputs[14][block_offset]); - out_msg[15] = loadu_512_avx512(&inputs[15][block_offset]); - - for (i = 0; i < 16; i++) { - _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); - } - transpose_vecs_512_avx512(out_msg); -} - -static inline void -load_counters16_avx512(uint64_t counter, int increment_counter, __m512i *out_lo, __m512i *out_hi) -{ - const __m512i mask = _mm512_set1_epi32(-increment_counter); - const __m512i deltas = _mm512_set_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - const __m512i masked_deltas = _mm512_and_si512(deltas, mask); - const __m512i low_words = _mm512_add_epi32(_mm512_set1_epi32((int32_t)counter), masked_deltas); - const __m512i carries = - _mm512_srli_epi32(_mm512_andnot_si512(low_words, _mm512_set1_epi32((int32_t)counter)), 31); - const __m512i high_words = _mm512_add_epi32(_mm512_set1_epi32((int32_t)(counter >> 32)), carries); - - *out_lo = low_words; - *out_hi = high_words; -} - -void -blake3_hash16_avx512( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m512i h_vecs[8]; - __m512i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_512_avx512(key[0]); - h_vecs[1] = set1_512_avx512(key[1]); - h_vecs[2] = set1_512_avx512(key[2]); - h_vecs[3] = set1_512_avx512(key[3]); - h_vecs[4] = set1_512_avx512(key[4]); - h_vecs[5] = set1_512_avx512(key[5]); - h_vecs[6] = set1_512_avx512(key[6]); - h_vecs[7] = set1_512_avx512(key[7]); - - load_counters16_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m512i block_len_vec; - __m512i block_flags_vec; - __m512i msg_vecs[16]; - __m512i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_512_avx512(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_512_avx512(block_flags); - transpose_msg_vecs16_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_512_avx512(IV[0]); - v[9] = set1_512_avx512(IV[1]); - v[10] = set1_512_avx512(IV[2]); - v[11] = set1_512_avx512(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn16_avx512(v, msg_vecs, 0); - round_fn16_avx512(v, msg_vecs, 1); - round_fn16_avx512(v, msg_vecs, 2); - round_fn16_avx512(v, msg_vecs, 3); - round_fn16_avx512(v, msg_vecs, 4); - round_fn16_avx512(v, msg_vecs, 5); - round_fn16_avx512(v, msg_vecs, 6); - - h_vecs[0] = xor_512_avx512(v[0], v[8]); - h_vecs[1] = xor_512_avx512(v[1], v[9]); - h_vecs[2] = xor_512_avx512(v[2], v[10]); - h_vecs[3] = xor_512_avx512(v[3], v[11]); - h_vecs[4] = xor_512_avx512(v[4], v[12]); - h_vecs[5] = xor_512_avx512(v[5], v[13]); - h_vecs[6] = xor_512_avx512(v[6], v[14]); - h_vecs[7] = xor_512_avx512(v[7], v[15]); - - block_flags = flags; - } - - __m512i padded[16] = { - h_vecs[0], - h_vecs[1], - h_vecs[2], - h_vecs[3], - h_vecs[4], - h_vecs[5], - h_vecs[6], - h_vecs[7], - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - set1_512_avx512(0), - }; - transpose_vecs_512_avx512(padded); - _mm256_mask_storeu_epi32( - &out_bytes[0 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[0]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[1 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[1]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[2 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[2]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[3 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[3]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[4 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[4]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[5 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[5]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[6 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[6]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[7 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[7]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[8 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[8]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[9 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[9]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[10 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[10]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[11 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[11]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[12 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[12]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[13 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[13]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[14 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[14]) - ); - _mm256_mask_storeu_epi32( - &out_bytes[15 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[15]) - ); -} - -static inline void -transpose_msg_vecs8_avx512(const uint8_t *const *inputs, size_t block_offset, __m256i out_msg[16]) -{ - out_msg[0] = loadu_256_avx512(&inputs[0][block_offset]); - out_msg[1] = loadu_256_avx512(&inputs[1][block_offset]); - out_msg[2] = loadu_256_avx512(&inputs[2][block_offset]); - out_msg[3] = loadu_256_avx512(&inputs[3][block_offset]); - out_msg[4] = loadu_256_avx512(&inputs[4][block_offset]); - out_msg[5] = loadu_256_avx512(&inputs[5][block_offset]); - out_msg[6] = loadu_256_avx512(&inputs[6][block_offset]); - out_msg[7] = loadu_256_avx512(&inputs[7][block_offset]); - out_msg[8] = loadu_256_avx512(&inputs[0][block_offset + 32]); - out_msg[9] = loadu_256_avx512(&inputs[1][block_offset + 32]); - out_msg[10] = loadu_256_avx512(&inputs[2][block_offset + 32]); - out_msg[11] = loadu_256_avx512(&inputs[3][block_offset + 32]); - out_msg[12] = loadu_256_avx512(&inputs[4][block_offset + 32]); - out_msg[13] = loadu_256_avx512(&inputs[5][block_offset + 32]); - out_msg[14] = loadu_256_avx512(&inputs[6][block_offset + 32]); - out_msg[15] = loadu_256_avx512(&inputs[7][block_offset + 32]); - - transpose_vecs_avx2(out_msg); -} - -static inline void -load_counters8_avx512(uint64_t counter, int increment_counter, __m256i *out_lo, __m256i *out_hi) -{ - const __m256i mask = _mm256_set1_epi32(-increment_counter); - const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); - const __m256i add1 = _mm256_and_si256(mask, add0); - __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1); - __m256i carry = - _mm256_srli_epi32(_mm256_andnot_si256(l, _mm256_set1_epi32((int32_t)counter)), 31); - __m256i h = _mm256_add_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), carry); - - *out_lo = l; - *out_hi = h; -} - -void -blake3_hash8_avx512( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m256i h_vecs[8]; - __m256i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_256_avx512(key[0]); - h_vecs[1] = set1_256_avx512(key[1]); - h_vecs[2] = set1_256_avx512(key[2]); - h_vecs[3] = set1_256_avx512(key[3]); - h_vecs[4] = set1_256_avx512(key[4]); - h_vecs[5] = set1_256_avx512(key[5]); - h_vecs[6] = set1_256_avx512(key[6]); - h_vecs[7] = set1_256_avx512(key[7]); - - load_counters8_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m256i block_len_vec; - __m256i block_flags_vec; - __m256i msg_vecs[16]; - __m256i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_256_avx512(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_256_avx512(block_flags); - transpose_msg_vecs8_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_256_avx512(IV[0]); - v[9] = set1_256_avx512(IV[1]); - v[10] = set1_256_avx512(IV[2]); - v[11] = set1_256_avx512(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn8_avx512(v, msg_vecs, 0); - round_fn8_avx512(v, msg_vecs, 1); - round_fn8_avx512(v, msg_vecs, 2); - round_fn8_avx512(v, msg_vecs, 3); - round_fn8_avx512(v, msg_vecs, 4); - round_fn8_avx512(v, msg_vecs, 5); - round_fn8_avx512(v, msg_vecs, 6); - - h_vecs[0] = xor_256_avx512(v[0], v[8]); - h_vecs[1] = xor_256_avx512(v[1], v[9]); - h_vecs[2] = xor_256_avx512(v[2], v[10]); - h_vecs[3] = xor_256_avx512(v[3], v[11]); - h_vecs[4] = xor_256_avx512(v[4], v[12]); - h_vecs[5] = xor_256_avx512(v[5], v[13]); - h_vecs[6] = xor_256_avx512(v[6], v[14]); - h_vecs[7] = xor_256_avx512(v[7], v[15]); - - block_flags = flags; - } - - transpose_vecs_avx2(h_vecs); - storeu_256_avx512(h_vecs[0], &out_bytes[0 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[1], &out_bytes[1 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[2], &out_bytes[2 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[3], &out_bytes[3 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[4], &out_bytes[4 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[5], &out_bytes[5 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[6], &out_bytes[6 * sizeof(__m256i)]); - storeu_256_avx512(h_vecs[7], &out_bytes[7 * sizeof(__m256i)]); -} - -static inline void -transpose_msg_vecs4_avx512(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) -{ - out_msg[0] = loadu_128_avx512(&inputs[0][block_offset]); - out_msg[1] = loadu_128_avx512(&inputs[1][block_offset]); - out_msg[2] = loadu_128_avx512(&inputs[2][block_offset]); - out_msg[3] = loadu_128_avx512(&inputs[3][block_offset]); - out_msg[4] = loadu_128_avx512(&inputs[0][block_offset + 16]); - out_msg[5] = loadu_128_avx512(&inputs[1][block_offset + 16]); - out_msg[6] = loadu_128_avx512(&inputs[2][block_offset + 16]); - out_msg[7] = loadu_128_avx512(&inputs[3][block_offset + 16]); - out_msg[8] = loadu_128_avx512(&inputs[0][block_offset + 32]); - out_msg[9] = loadu_128_avx512(&inputs[1][block_offset + 32]); - out_msg[10] = loadu_128_avx512(&inputs[2][block_offset + 32]); - out_msg[11] = loadu_128_avx512(&inputs[3][block_offset + 32]); - out_msg[12] = loadu_128_avx512(&inputs[0][block_offset + 48]); - out_msg[13] = loadu_128_avx512(&inputs[1][block_offset + 48]); - out_msg[14] = loadu_128_avx512(&inputs[2][block_offset + 48]); - out_msg[15] = loadu_128_avx512(&inputs[3][block_offset + 48]); - - transpose_vecs_sse2(out_msg); -} - -static inline void -load_counters4_avx512(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) -{ - const __m128i mask = _mm_set1_epi32(-increment_counter); - const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); - const __m128i add1 = _mm_and_si128(mask, add0); - __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); - __m128i carry = _mm_srli_epi32(_mm_andnot_si128(l, _mm_set1_epi32((int32_t)counter)), 31); - __m128i h = _mm_add_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); - - *out_lo = l; - *out_hi = h; -} - -void -blake3_hash4_avx512( - const uint8_t *const *inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - __m128i h_vecs[8]; - __m128i counter_low_vec, counter_high_vec; - uint8_t block_flags; - size_t block; - - h_vecs[0] = set1_128_avx512(key[0]); - h_vecs[1] = set1_128_avx512(key[1]); - h_vecs[2] = set1_128_avx512(key[2]); - h_vecs[3] = set1_128_avx512(key[3]); - h_vecs[4] = set1_128_avx512(key[4]); - h_vecs[5] = set1_128_avx512(key[5]); - h_vecs[6] = set1_128_avx512(key[6]); - h_vecs[7] = set1_128_avx512(key[7]); - - load_counters4_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); - block_flags = flags | flags_start; - - for (block = 0; block < blocks; block++) { - __m128i block_len_vec; - __m128i block_flags_vec; - __m128i msg_vecs[16]; - __m128i v[16]; - - if (block + 1 == blocks) { - block_flags |= flags_end; - } - block_len_vec = set1_128_avx512(BLAKE3_BLOCK_LEN); - block_flags_vec = set1_128_avx512(block_flags); - transpose_msg_vecs4_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); - - v[0] = h_vecs[0]; - v[1] = h_vecs[1]; - v[2] = h_vecs[2]; - v[3] = h_vecs[3]; - v[4] = h_vecs[4]; - v[5] = h_vecs[5]; - v[6] = h_vecs[6]; - v[7] = h_vecs[7]; - v[8] = set1_128_avx512(IV[0]); - v[9] = set1_128_avx512(IV[1]); - v[10] = set1_128_avx512(IV[2]); - v[11] = set1_128_avx512(IV[3]); - v[12] = counter_low_vec; - v[13] = counter_high_vec; - v[14] = block_len_vec; - v[15] = block_flags_vec; - - round_fn4_avx512(v, msg_vecs, 0); - round_fn4_avx512(v, msg_vecs, 1); - round_fn4_avx512(v, msg_vecs, 2); - round_fn4_avx512(v, msg_vecs, 3); - round_fn4_avx512(v, msg_vecs, 4); - round_fn4_avx512(v, msg_vecs, 5); - round_fn4_avx512(v, msg_vecs, 6); - - h_vecs[0] = xor_128_avx512(v[0], v[8]); - h_vecs[1] = xor_128_avx512(v[1], v[9]); - h_vecs[2] = xor_128_avx512(v[2], v[10]); - h_vecs[3] = xor_128_avx512(v[3], v[11]); - h_vecs[4] = xor_128_avx512(v[4], v[12]); - h_vecs[5] = xor_128_avx512(v[5], v[13]); - h_vecs[6] = xor_128_avx512(v[6], v[14]); - h_vecs[7] = xor_128_avx512(v[7], v[15]); - - block_flags = flags; - } - - transpose_vecs_sse2(h_vecs); - storeu_128_avx512(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); - storeu_128_avx512(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); -} - -static inline void -hash_one_avx512( - const uint8_t *input, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t out_bytes[BLAKE3_OUT_LEN] -) -{ - uint32_t cv[8]; - uint8_t block_flags; - - memcpy(cv, key, BLAKE3_KEY_LEN); - block_flags = flags | flags_start; - while (blocks > 0) { - if (blocks == 1) { - block_flags |= flags_end; - } - blake3_compress_in_place_avx512(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); - input = &input[BLAKE3_BLOCK_LEN]; - blocks -= 1; - block_flags = flags; - } - memcpy(out_bytes, cv, BLAKE3_OUT_LEN); -} - -void -blake3_hash_many_avx512( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out_bytes -) -{ - while (num_inputs >= 16) { - blake3_hash16_avx512( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += 16; - } - inputs += 16; - num_inputs -= 16; - out_bytes = &out_bytes[16 * BLAKE3_OUT_LEN]; - } - while (num_inputs >= 8) { - blake3_hash8_avx512( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += 8; - } - inputs += 8; - num_inputs -= 8; - out_bytes = &out_bytes[8 * BLAKE3_OUT_LEN]; - } - while (num_inputs >= 4) { - blake3_hash4_avx512( - inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes - ); - if (increment_counter) { - counter += 4; - } - inputs += 4; - num_inputs -= 4; - out_bytes = &out_bytes[4 * BLAKE3_OUT_LEN]; - } - while (num_inputs > 0) { - hash_one_avx512(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); - if (increment_counter) { - counter += 1; - } - inputs += 1; - num_inputs -= 1; - out_bytes = &out_bytes[BLAKE3_OUT_LEN]; - } -} -#if defined(__clang__) -#pragma clang attribute pop -#elif defined(__GNUC__) -#pragma GCC pop_options -#endif -#endif - -/* dispatch functions */ -void -blake3_compress_in_place( - uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ -#if BLAKE3_X86_SIMD - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); - if (blake3_cpu_features & AVX512) { - blake3_compress_in_place_avx512(cv, block, block_len, counter, flags); - return; - } - if (blake3_cpu_features & SSE41) { - blake3_compress_in_place_sse41(cv, block, block_len, counter, flags); - return; - } - if (blake3_cpu_features & SSE2) { - blake3_compress_in_place_sse2(cv, block, block_len, counter, flags); - return; - } -#endif - blake3_compress_in_place_portable(cv, block, block_len, counter, flags); -} - -void -blake3_compress_xof( - const uint32_t cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags, - uint8_t out[64] -) -{ -#if BLAKE3_X86_SIMD - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); - if (blake3_cpu_features & AVX512) { - blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out); - return; - } - if (blake3_cpu_features & SSE41) { - blake3_compress_xof_sse41(cv, block, block_len, counter, flags, out); - return; - } - if (blake3_cpu_features & SSE2) { - blake3_compress_xof_sse2(cv, block, block_len, counter, flags, out); - return; - } -#endif - blake3_compress_xof_portable(cv, block, block_len, counter, flags, out); -} - -void -blake3_hash_many( - const uint8_t *const *inputs, - size_t num_inputs, - size_t blocks, - const uint32_t key[8], - uint64_t counter, - int increment_counter, - uint8_t flags, - uint8_t flags_start, - uint8_t flags_end, - uint8_t *out -) -{ -#if BLAKE3_X86_SIMD - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); - if (blake3_cpu_features & AVX512) { - blake3_hash_many_avx512( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out - ); - return; - } - if (blake3_cpu_features & AVX2) { - blake3_hash_many_avx2( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out - ); - return; - } - if (blake3_cpu_features & SSE41) { - blake3_hash_many_sse41( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out - ); - return; - } - if (blake3_cpu_features & SSE2) { - blake3_hash_many_sse2( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out - ); - return; - } -#endif - blake3_hash_many_portable( - inputs, - num_inputs, - blocks, - key, - counter, - increment_counter, - flags, - flags_start, - flags_end, - out - ); -} - -size_t -blake3_simd_degree(void) -{ -#if BLAKE3_X86_SIMD - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); - if (blake3_cpu_features & AVX512) - return 16; - if (blake3_cpu_features & AVX2) - return 8; - if (blake3_cpu_features & SSE41) - return 4; - if (blake3_cpu_features & SSE2) - return 4; -#endif - return 1; -} - -/* core hasher implementation */ -const char * -blake3_version(void) -{ - return BLAKE3_VERSION_STRING; -} - -static inline void -chunk_state_init(struct Blake3ChunkState *self, const uint32_t key[8], uint8_t flags) -{ - memcpy(self->cv, key, BLAKE3_KEY_LEN); - self->chunk_counter = 0; - memset(self->buf, 0, BLAKE3_BLOCK_LEN); - self->buf_len = 0; - self->blocks_compressed = 0; - self->flags = flags; -} - -static inline void -chunk_state_reset(struct Blake3ChunkState *self, const uint32_t key[8], uint64_t chunk_counter) -{ - memcpy(self->cv, key, BLAKE3_KEY_LEN); - self->chunk_counter = chunk_counter; - self->blocks_compressed = 0; - memset(self->buf, 0, BLAKE3_BLOCK_LEN); - self->buf_len = 0; -} - -static inline size_t -chunk_state_len(const struct Blake3ChunkState *self) -{ - return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) + ((size_t)self->buf_len); -} - -static inline size_t -chunk_state_fill_buf(struct Blake3ChunkState *self, const uint8_t *input, size_t input_len) -{ - size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len); - uint8_t *dest; - - if (take > input_len) { - take = input_len; - } - dest = self->buf + ((size_t)self->buf_len); - memcpy(dest, input, take); - self->buf_len += (uint8_t)take; - return take; -} - -static inline uint8_t -chunk_state_maybe_start_flag(const struct Blake3ChunkState *self) -{ - if (self->blocks_compressed == 0) { - return CHUNK_START; - } else { - return 0; - } -} - -static inline struct Output -make_output( - const uint32_t input_cv[8], - const uint8_t block[BLAKE3_BLOCK_LEN], - uint8_t block_len, - uint64_t counter, - uint8_t flags -) -{ - struct Output ret; - - memcpy(ret.input_cv, input_cv, 32); - memcpy(ret.block, block, BLAKE3_BLOCK_LEN); - ret.block_len = block_len; - ret.counter = counter; - ret.flags = flags; - return ret; -} - -static inline void -output_chaining_value(const struct Output *self, uint8_t cv[32]) -{ - uint32_t cv_words[8]; - - memcpy(cv_words, self->input_cv, 32); - blake3_compress_in_place(cv_words, self->block, self->block_len, self->counter, self->flags); - store_cv_words(cv, cv_words); -} - -static inline void -output_root_bytes(const struct Output *self, uint64_t seek, uint8_t *out, size_t out_len) -{ - uint64_t output_block_counter = seek / 64; - size_t offset_within_block = seek % 64; - uint8_t wide_buf[64]; - size_t available_bytes; - size_t memcpy_len; - - while (out_len > 0) { - blake3_compress_xof( - self->input_cv, - self->block, - self->block_len, - output_block_counter, - self->flags | ROOT, - wide_buf - ); - available_bytes = 64 - offset_within_block; - if (out_len > available_bytes) { - memcpy_len = available_bytes; - } else { - memcpy_len = out_len; - } - memcpy(out, wide_buf + offset_within_block, memcpy_len); - out += memcpy_len; - out_len -= memcpy_len; - output_block_counter += 1; - offset_within_block = 0; - } -} - -static inline void -chunk_state_update(struct Blake3ChunkState *self, const uint8_t *input, size_t input_len) -{ - size_t take; - - if (self->buf_len > 0) { - take = chunk_state_fill_buf(self, input, input_len); - input += take; - input_len -= take; - if (input_len > 0) { - blake3_compress_in_place( - self->cv, - self->buf, - BLAKE3_BLOCK_LEN, - self->chunk_counter, - self->flags | chunk_state_maybe_start_flag(self) - ); - self->blocks_compressed += 1; - self->buf_len = 0; - memset(self->buf, 0, BLAKE3_BLOCK_LEN); - } - } - - while (input_len > BLAKE3_BLOCK_LEN) { - blake3_compress_in_place( - self->cv, - input, - BLAKE3_BLOCK_LEN, - self->chunk_counter, - self->flags | chunk_state_maybe_start_flag(self) - ); - self->blocks_compressed += 1; - input += BLAKE3_BLOCK_LEN; - input_len -= BLAKE3_BLOCK_LEN; - } - - take = chunk_state_fill_buf(self, input, input_len); - input += take; - input_len -= take; -} - -static inline struct Output -chunk_state_output(const struct Blake3ChunkState *self) -{ - uint8_t block_flags = self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END; - - return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter, block_flags); -} - -static inline struct Output -parent_output(const uint8_t block[BLAKE3_BLOCK_LEN], const uint32_t key[8], uint8_t flags) -{ - return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT); -} - -static unsigned int -highest_one(uint64_t x) -{ -#if defined(__GNUC__) || defined(__clang__) - return 63 ^ __builtin_clzll(x); -#else - unsigned int c = 0; - if (x & 0xffffffff00000000ULL) { - x >>= 32; - c += 32; - } - if (x & 0x00000000ffff0000ULL) { - x >>= 16; - c += 16; - } - if (x & 0x000000000000ff00ULL) { - x >>= 8; - c += 8; - } - if (x & 0x00000000000000f0ULL) { - x >>= 4; - c += 4; - } - if (x & 0x000000000000000cULL) { - x >>= 2; - c += 2; - } - if (x & 0x0000000000000002ULL) { - c += 1; - } - return c; -#endif -} - -static inline uint64_t -round_down_to_power_of_2(uint64_t x) -{ - return 1ULL << highest_one(x | 1); -} - -static inline size_t -left_len(size_t content_len) -{ - size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN; - - return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN; -} - -static inline size_t -compress_chunks_parallel( - const uint8_t *input, - size_t input_len, - const uint32_t key[8], - uint64_t chunk_counter, - uint8_t flags, - uint8_t *out -) -{ - const uint8_t *chunks_array[MAX_SIMD_DEGREE]; - size_t input_position = 0; - size_t chunks_array_len = 0; - - assert(0 < input_len); - assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN); - - while (input_len - input_position >= BLAKE3_CHUNK_LEN) { - chunks_array[chunks_array_len] = &input[input_position]; - input_position += BLAKE3_CHUNK_LEN; - chunks_array_len += 1; - } - - blake3_hash_many( - chunks_array, - chunks_array_len, - BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, - key, - chunk_counter, - 1, - flags, - CHUNK_START, - CHUNK_END, - out - ); - - if (input_len > input_position) { - uint64_t counter = chunk_counter + (uint64_t)chunks_array_len; - struct Blake3ChunkState chunk_state; - struct Output output; - - chunk_state_init(&chunk_state, key, flags); - chunk_state.chunk_counter = counter; - chunk_state_update(&chunk_state, &input[input_position], input_len - input_position); - output = chunk_state_output(&chunk_state); - output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]); - return chunks_array_len + 1; - } else { - return chunks_array_len; - } -} - -static inline size_t -compress_parents_parallel( - const uint8_t *child_chaining_values, - size_t num_chaining_values, - const uint32_t key[8], - uint8_t flags, - uint8_t *out -) -{ - const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2]; - size_t parents_array_len = 0; - - assert(2 <= num_chaining_values); - assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2); - - while (num_chaining_values - (2 * parents_array_len) >= 2) { - parents_array[parents_array_len] = - &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN]; - parents_array_len += 1; - } - - blake3_hash_many(parents_array, parents_array_len, 1, key, 0, 0, flags | PARENT, 0, 0, out); - - if (num_chaining_values > 2 * parents_array_len) { - memcpy( - &out[parents_array_len * BLAKE3_OUT_LEN], - &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN], - BLAKE3_OUT_LEN - ); - return parents_array_len + 1; - } else { - return parents_array_len; - } -} - -static inline size_t -blake3_compress_subtree_wide( - const uint8_t *input, - size_t input_len, - const uint32_t key[8], - uint64_t chunk_counter, - uint8_t flags, - uint8_t *out -) -{ - size_t degree; - - if (input_len <= (size_t)blake3_simd_degree() * BLAKE3_CHUNK_LEN) { - return compress_chunks_parallel(input, input_len, key, chunk_counter, flags, out); - } - - degree = blake3_simd_degree(); - if (degree > 1) { - size_t child_len = round_down_to_power_of_2(input_len - 1) / degree; - size_t cvs_written = 0; - - if (child_len < BLAKE3_CHUNK_LEN) { - child_len = BLAKE3_CHUNK_LEN; - } - - while (input_len > 0) { - size_t take = child_len; - size_t sub_cvs; - - if (take > input_len) { - take = input_len; - } - sub_cvs = blake3_compress_subtree_wide( - input, take, key, chunk_counter, flags, &out[cvs_written * BLAKE3_OUT_LEN] - ); - cvs_written += sub_cvs; - chunk_counter += take / BLAKE3_CHUNK_LEN; - input += take; - input_len -= take; - } - - while (cvs_written > 2) { - cvs_written = compress_parents_parallel(out, cvs_written, key, flags, out); - } - return cvs_written; - } else { - /* fallback when simd degree is 1 */ - size_t left = left_len(input_len); - size_t right = input_len - left; - size_t left_cvs = blake3_compress_subtree_wide(input, left, key, chunk_counter, flags, out); - size_t right_cvs = blake3_compress_subtree_wide( - input + left, - right, - key, - chunk_counter + (left / BLAKE3_CHUNK_LEN), - flags, - &out[left_cvs * BLAKE3_OUT_LEN] - ); - - return left_cvs + right_cvs; - } -} - -static void -compress_subtree_to_parent_node( - const uint8_t *input, - size_t input_len, - const uint32_t key[8], - uint64_t chunk_counter, - uint8_t flags, - uint8_t out[2 * BLAKE3_OUT_LEN] -) -{ - uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN]; - size_t num_cvs = - blake3_compress_subtree_wide(input, input_len, key, chunk_counter, flags, cv_array); - - assert(num_cvs >= 2); - while (num_cvs > 2) { - num_cvs = compress_parents_parallel(cv_array, num_cvs, key, flags, cv_array); - } - memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); -} - -static inline void -hasher_init_base(struct Blake3Hasher *self, const uint32_t key[8], uint8_t flags) -{ - memcpy(self->key, key, BLAKE3_KEY_LEN); - chunk_state_init(&self->chunk, key, flags); - self->cv_stack_len = 0; -} - -void -blake3_hasher_init(struct Blake3Hasher *self) -{ - if (!blake3_cpu_detected) - blake3_detect_cpu_features(); - hasher_init_base(self, IV, 0); -} - -static inline void -load_key_words(const uint8_t key[BLAKE3_KEY_LEN], uint32_t key_words[8]) -{ - key_words[0] = load32(&key[0 * 4]); - key_words[1] = load32(&key[1 * 4]); - key_words[2] = load32(&key[2 * 4]); - key_words[3] = load32(&key[3 * 4]); - key_words[4] = load32(&key[4 * 4]); - key_words[5] = load32(&key[5 * 4]); - key_words[6] = load32(&key[6 * 4]); - key_words[7] = load32(&key[7 * 4]); -} - -void -blake3_hasher_init_keyed(struct Blake3Hasher *self, const uint8_t key[BLAKE3_KEY_LEN]) -{ - uint32_t key_words[8]; - - load_key_words(key, key_words); - hasher_init_base(self, key_words, KEYED_HASH); -} - -void -blake3_hasher_init_derive_key_raw( - struct Blake3Hasher *self, const void *context, size_t context_len -) -{ - struct Blake3Hasher context_hasher; - uint8_t context_key[BLAKE3_KEY_LEN]; - uint32_t context_key_words[8]; - - hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT); - blake3_hasher_update(&context_hasher, context, context_len); - blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN); - load_key_words(context_key, context_key_words); - hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL); -} - -static inline unsigned int -popcnt(uint64_t x) -{ -#if defined(__GNUC__) || defined(__clang__) - return __builtin_popcountll(x); -#else - unsigned int count = 0; - while (x != 0) { - count += 1; - x &= x - 1; - } - return count; -#endif -} - -void -blake3_hasher_init_derive_key(struct Blake3Hasher *self, const char *context) -{ - blake3_hasher_init_derive_key_raw(self, context, strlen(context)); -} - -static inline void -hasher_merge_cv_stack(struct Blake3Hasher *self, uint64_t total_len) -{ - size_t post_merge_stack_len = (size_t)popcnt(total_len); - - while (self->cv_stack_len > post_merge_stack_len) { - uint8_t *parent_node = &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN]; - struct Output output = parent_output(parent_node, self->key, self->chunk.flags); - - output_chaining_value(&output, parent_node); - self->cv_stack_len -= 1; - } -} - -static inline void -hasher_push_cv(struct Blake3Hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN], uint64_t chunk_counter) -{ - hasher_merge_cv_stack(self, chunk_counter); - memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv, BLAKE3_OUT_LEN); - self->cv_stack_len += 1; -} - -void -blake3_hasher_update(struct Blake3Hasher *self, const void *input, size_t input_len) -{ - const uint8_t *input_bytes; - - if (input_len == 0) { - return; - } - - input_bytes = (const uint8_t *)input; - - if (chunk_state_len(&self->chunk) > 0) { - size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk); - - if (take > input_len) { - take = input_len; - } - chunk_state_update(&self->chunk, input_bytes, take); - input_bytes += take; - input_len -= take; - if (input_len > 0) { - struct Output output = chunk_state_output(&self->chunk); - uint8_t chunk_cv[32]; - - output_chaining_value(&output, chunk_cv); - hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter); - chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1); - } else { - return; - } - } - - while (input_len > BLAKE3_CHUNK_LEN) { - size_t subtree_len = round_down_to_power_of_2(input_len); - uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN; - uint64_t subtree_chunks; - - while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) { - subtree_len /= 2; - } - subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN; - if (subtree_len <= BLAKE3_CHUNK_LEN) { - struct Blake3ChunkState chunk_state; - struct Output output; - uint8_t cv[BLAKE3_OUT_LEN]; - - chunk_state_init(&chunk_state, self->key, self->chunk.flags); - chunk_state.chunk_counter = self->chunk.chunk_counter; - chunk_state_update(&chunk_state, input_bytes, subtree_len); - output = chunk_state_output(&chunk_state); - output_chaining_value(&output, cv); - hasher_push_cv(self, cv, chunk_state.chunk_counter); - } else { - uint8_t cv_pair[2 * BLAKE3_OUT_LEN]; - - compress_subtree_to_parent_node( - input_bytes, subtree_len, self->key, self->chunk.chunk_counter, self->chunk.flags, cv_pair - ); - hasher_push_cv(self, cv_pair, self->chunk.chunk_counter); - hasher_push_cv( - self, &cv_pair[BLAKE3_OUT_LEN], self->chunk.chunk_counter + (subtree_chunks / 2) - ); - } - self->chunk.chunk_counter += subtree_chunks; - input_bytes += subtree_len; - input_len -= subtree_len; - } - - if (input_len > 0) { - chunk_state_update(&self->chunk, input_bytes, input_len); - hasher_merge_cv_stack(self, self->chunk.chunk_counter); - } -} - -void -blake3_hasher_finalize_seek( - const struct Blake3Hasher *self, uint64_t seek, uint8_t *out, size_t out_len -) -{ - struct Output output; - size_t cvs_remaining; - - if (out_len == 0) { - return; - } - - if (self->cv_stack_len == 0) { - output = chunk_state_output(&self->chunk); - output_root_bytes(&output, seek, out, out_len); - return; - } - - if (chunk_state_len(&self->chunk) > 0) { - cvs_remaining = self->cv_stack_len; - output = chunk_state_output(&self->chunk); - } else { - cvs_remaining = self->cv_stack_len - 2; - output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key, self->chunk.flags); - } - - while (cvs_remaining > 0) { - uint8_t parent_block[BLAKE3_BLOCK_LEN]; - - cvs_remaining -= 1; - memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32); - output_chaining_value(&output, &parent_block[32]); - output = parent_output(parent_block, self->key, self->chunk.flags); - } - output_root_bytes(&output, seek, out, out_len); -} - -void -blake3_hasher_finalize(const struct Blake3Hasher *self, uint8_t *out, size_t out_len) -{ - blake3_hasher_finalize_seek(self, 0, out, out_len); -} +/* see LICENSE file for copyright and license details */ +#include "arg.h" +#include "util.h" +#include "../../shared/libblake3/blake3.h" -void -blake3_hasher_reset(struct Blake3Hasher *self) -{ - chunk_state_reset(&self->chunk, self->key, 0); - self->cv_stack_len = 0; -} +#include <stdio.h> +#include <stdlib.h> +#include <string.h> -/* utility implementation */ static unsigned char *out; static size_t outlen = BLAKE3_OUT_LEN; @@ -4599,18 +54,6 @@ sum(const char *name, FILE *file) } static int -hexval(int c) -{ - if ('0' <= c && c <= '9') - return c - '0'; - if ('a' <= c && c <= 'f') - return c - 'a' + 10; - if ('A' <= c && c <= 'F') - return c - 'A' + 10; - return -1; -} - -static int checkfile(const char *name, const char *mode, const char *str, unsigned char *out_buf, size_t len) { FILE *file; diff --git a/cmd/extra/blkid.c b/cmd/extra/blkid.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "diskutil.h" #include "util.h" diff --git a/cmd/extra/dc.c b/cmd/extra/dc.c @@ -0,0 +1,2223 @@ +/* see LICENSE file for copyright and license details */ + +#include "arg.h" +#include "util.h" + +#include <assert.h> +#include <ctype.h> +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <setjmp.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define NDIGITS 10 +#define REGSIZ 16 +#define HASHSIZ 128 + +enum { + NVAL, + STR, + NUM, +}; + +enum { + NE, + LE, + GE, +}; + +struct num { + int begin; + int scale; + int room; + signed char *buf, *wp, *rp; +}; + +struct digit { + int val; + struct digit *next; +}; + +struct val { + int type; + union { + struct num *n; + char *s; + } u; + + struct val *next; +}; + +struct ary { + int n; + struct val *buf; + struct ary *next; +}; + +struct reg { + char *name; + struct val val; + struct ary ary; + struct reg *next; +}; + +struct input { + FILE *fp; + char *buf; + size_t n; + char *s; + struct input *next; +}; + +static struct val *stack; +static jmp_buf env; +static struct input *input; +static struct reg *htbl[HASHSIZ]; + +static signed char onestr[] = {1, 0}; +static struct num zero, one = {.buf = onestr, .wp = onestr + 1}; +static char digits[] = "0123456789ABCDEF."; + +static int scale, ibase = 10, obase = 10; +static int iflag; +static int col; + +/* this dc implementation follows the description of dc found in the paper + * DC - an interactive desk calculator, by robert morris and lorinda cherry */ + +/* error is not called from the implementation of the + * arithmetic functions because that can drive to memory + * leaks very easily */ +static void +error(char *fmt, ...) +{ + va_list va; + + va_start(va, fmt); + xvprintf(fmt, va); + putc('\n', stderr); + va_end(va); + + longjmp(env, 1); +} + +static void +freenum(struct num *num) +{ + if (!num) + return; + free(num->buf); + free(num); +} + +static struct num * +moreroom(struct num *num, int more) +{ + int ro, wo, room; + signed char *p; + + ro = num->rp - num->buf; + wo = num->wp - num->buf; + room = num->room; + + if (room > INT_MAX - more) + eprintf("out of memory\n"); + + room = room + more; + if (room < NDIGITS) + room = NDIGITS; + p = erealloc(num->buf, room); + num->buf = p; + num->rp = p + ro; + num->wp = p + wo; + num->room = room; + + return num; +} + +static struct num * +grow(struct num *num) +{ + return moreroom(num, NDIGITS); +} + +static struct num * +expand(struct num *num, int min) +{ + if (min < num->room) + return num; + return moreroom(num, min - num->room); +} + +static struct num * +newnum(int room) +{ + struct num *num = emalloc(sizeof(*num)); + + num->rp = num->wp = num->buf = NULL; + num->begin = num->room = num->scale = 0; + + return moreroom(num, room); +} + +static struct num * +zeronum(int ndigits) +{ + struct num *num = newnum(ndigits); + + num->wp = num->buf + ndigits; + memset(num->buf, 0, ndigits); + + return num; +} + +static struct num * +wrdigit(struct num *num, int d) +{ + if (num->wp == &num->buf[num->room]) + grow(num); + *num->wp++ = d; + + return num; +} + +static int +rddigit(struct num *num) +{ + if (num->rp == num->wp) + return -1; + return *num->rp++; +} + +static int +peek(struct num *num) +{ + if (num->rp == num->wp) + return -1; + return *num->rp; +} + +static struct num * +poke(struct num *num, unsigned d) +{ + if (num->rp == &num->buf[num->room]) + grow(num); + if (num->rp == num->wp) + num->wp++; + *num->rp = d; + + return num; +} + +static int +begin(struct num *num) +{ + return num->begin != 0; +} + +static int +first(struct num *num) +{ + num->begin = 0; + num->rp = num->buf; + return num->rp != num->wp; +} + +static int +last(struct num *num) +{ + if (num->wp != num->buf) { + num->begin = 0; + num->rp = num->wp - 1; + return 1; + } + num->begin = 1; + return 0; +} + +static int +prev(struct num *num) +{ + if (num->rp > num->buf) { + --num->rp; + return 1; + } + num->begin = 1; + return 0; +} + +static int +next(struct num *num) +{ + if (num->rp != num->wp + 1) { + ++num->rp; + return 1; + } + return 0; +} + +static void +numtrunc(struct num *num) +{ + num->wp = num->rp; + if (num->rp != num->buf) + num->rp--; +} + +static int +more(struct num *num) +{ + return (num->rp != num->wp); +} + +static int +length(struct num *num) +{ + return num->wp - num->buf; +} + +static int +tell(struct num *num) +{ + return num->rp - num->buf; +} + +static void +seek(struct num *num, int pos) +{ + num->rp = num->buf + pos; +} + +static void +rshift(struct num *num, int n) +{ + int diff; + + diff = length(num) - n; + if (diff < 0) { + first(num); + numtrunc(num); + return; + } + + memmove(num->buf, num->buf + n, diff); + num->rp = num->buf + diff; + numtrunc(num); +} + +static void +lshift(struct num *num, int n) +{ + int len; + + len = length(num); + expand(num, len + n); + memmove(num->buf + n, num->buf, len); + memset(num->buf, 0, n); + num->wp += n; +} + +static struct num * +chsign(struct num *num) +{ + int val, d, carry; + + carry = 0; + for (first(num); more(num); next(num)) { + d = peek(num); + val = 100 - d - carry; + + carry = 1; + if (val >= 100) { + val -= 100; + carry = 0; + } + poke(num, val); + } + + prev(num); + if (carry != 0) { + if (peek(num) == 99) + poke(num, -1); + else + wrdigit(num, -1); + } else { + if (peek(num) == 0) + numtrunc(num); + } + + return num; +} + +static struct num * +copy(struct num *num) +{ + struct num *p; + int len = length(num); + + p = newnum(len); + memcpy(p->buf, num->buf, len); + p->wp = p->buf + len; + p->rp = p->buf; + p->scale = num->scale; + + return p; +} + +static int +negative(struct num *num) +{ + return last(num) && peek(num) == -1; +} + +static struct num * +norm(struct num *n) +{ + /* trailing 0 */ + for (last(n); peek(n) == 0; numtrunc(n)) + ; + + if (negative(n)) { + for (prev(n); peek(n) == 99; prev(n)) { + poke(n, -1); + next(n); + numtrunc(n); + } + } + + /* adjust scale for 0 case */ + if (length(n) == 0) + n->scale = 0; + return n; +} + +static struct num * +mulnto(struct num *src, struct num *dst, int n) +{ + div_t dd; + int d, carry; + + first(dst); + numtrunc(dst); + + carry = 0; + for (first(src); more(src); next(src)) { + d = peek(src) * n + carry; + dd = div(d, 100); + carry = dd.quot; + wrdigit(dst, dd.rem); + } + + if (carry) + wrdigit(dst, carry); + return dst; +} + +static struct num * +muln(struct num *num, int n) +{ + div_t dd; + int d, carry; + + carry = 0; + for (first(num); more(num); next(num)) { + d = peek(num) * n + carry; + dd = div(d, 100); + carry = dd.quot; + poke(num, dd.rem); + } + + if (carry) + wrdigit(num, carry); + return num; +} + +static int +divn(struct num *num, int n) +{ + div_t dd; + int val, carry; + + carry = 0; + for (last(num); !begin(num); prev(num)) { + val = carry * 100 + peek(num); + dd = div(val, n); + poke(num, dd.quot); + carry = dd.rem; + } + norm(num); + + return carry; +} + +static void +div10(struct num *num, int n) +{ + div_t dd = div(n, 2); + + if (dd.rem == 1) + divn(num, 10); + + rshift(num, dd.quot); +} + +static void +mul10(struct num *num, int n) +{ + div_t dd = div(n, 2); + + if (dd.rem == 1) + muln(num, 10); + + lshift(num, dd.quot); +} + +static void +align(struct num *a, struct num *b) +{ + int d; + struct num *max, *min; + + d = a->scale - b->scale; + if (d == 0) { + return; + } else if (d > 0) { + min = b; + max = a; + } else { + min = a; + max = b; + } + + d = abs(d); + mul10(min, d); + min->scale += d; + + assert(min->scale == max->scale); +} + +static struct num * +addn(struct num *num, int val) +{ + int d, carry = val; + + for (first(num); carry; next(num)) { + d = more(num) ? peek(num) : 0; + d += carry; + carry = 0; + + if (d >= 100) { + carry = 1; + d -= 100; + } + poke(num, d); + } + + return num; +} + +static struct num * +reverse(struct num *num) +{ + int d; + signed char *p, *q; + + for (p = num->buf, q = num->wp - 1; p < q; ++p, --q) { + d = *p; + *p = *q; + *q = d; + } + + return num; +} + +static struct num * +addnum(struct num *a, struct num *b) +{ + struct num *c; + int len, alen, blen, carry, da, db, sum; + + align(a, b); + alen = length(a); + blen = length(b); + len = (alen > blen) ? alen : blen; + c = newnum(len); + + first(a); + first(b); + carry = 0; + while (len-- > 0) { + da = (more(a)) ? rddigit(a) : 0; + db = (more(b)) ? rddigit(b) : 0; + + sum = da + db + carry; + if (sum >= 100) { + carry = 1; + sum -= 100; + } else if (sum < 0) { + carry = -1; + sum += 100; + } else { + carry = 0; + } + + wrdigit(c, sum); + } + + if (carry) + wrdigit(c, carry); + c->scale = a->scale; + + return norm(c); +} + +static struct num * +subnum(struct num *a, struct num *b) +{ + struct num *tmp, *sum; + + tmp = chsign(copy(b)); + sum = addnum(a, tmp); + freenum(tmp); + + return sum; +} + +static struct num * +mulnum(struct num *a, struct num *b) +{ + struct num shadow, *c, *ca, *cb; + int pos, prod, carry, dc, db, da, sc; + int asign = negative(a), bsign = negative(b); + + c = zeronum(length(a) + length(b) + 1); + c->scale = a->scale + b->scale; + sc = (a->scale > b->scale) ? a->scale : b->scale; + + ca = a; + if (asign) + ca = chsign(copy(ca)); + cb = b; + if (bsign) + cb = chsign(copy(cb)); + + /* avoid aliasing problems when called from expnum */ + if (ca == cb) { + shadow = *cb; + b = cb = &shadow; + } + + for (first(cb); more(cb); next(cb)) { + div_t d; + + carry = 0; + db = peek(cb); + + pos = tell(c); + for (first(ca); more(ca); next(ca)) { + da = peek(ca); + dc = peek(c); + prod = da * db + dc + carry; + d = div(prod, 100); + carry = d.quot; + poke(c, d.rem); + next(c); + } + + for (; carry > 0; carry = d.quot) { + dc = peek(c) + carry; + d = div(dc, 100); + poke(c, d.rem); + next(c); + } + seek(c, pos + 1); + } + norm(c); + + if (sc < scale) + sc = scale; + sc = c->scale - sc; + if (sc > 0) { + div10(c, sc); + c->scale -= sc; + } + + if (ca != a) + freenum(ca); + if (cb != b) + freenum(cb); + + if (asign ^ bsign) + chsign(c); + return c; +} + +/* the divmod function is implemented following the algorithm + * from the plan9 version that is not exactly like the one described + * in the paper. a lot of magic here */ +static struct num * +divmod(struct num *odivd, struct num *odivr, struct num **remp) +{ + struct num *acc, *divd, *divr, *res; + int divsign, remsign; + int under, magic, ndig, diff; + int d, q, carry, divcarry; + long dr, dd, cc; + + divr = odivr; + acc = copy(&zero); + divd = copy(odivd); + res = zeronum(length(odivd)); + + under = divcarry = divsign = remsign = 0; + + if (length(divr) == 0) { + weprintf("divide by 0\n"); + goto ret; + } + + divsign = negative(divd); + if (divsign) + chsign(divd); + + remsign = negative(divr); + if (remsign) + divr = chsign(copy(divr)); + + diff = length(divd) - length(divr); + + seek(res, diff + 1); + last(divd); + last(divr); + + wrdigit(divd, 0); + + dr = peek(divr); + magic = dr < 10; + dr = dr * 100 + (prev(divr) ? peek(divr) : 0); + if (magic) { + dr = dr * 100 + (prev(divr) ? peek(divr) : 0); + dr *= 2; + dr /= 25; + } + + for (ndig = 0; diff >= 0; ++ndig) { + last(divd); + dd = peek(divd); + dd = dd * 100 + (prev(divd) ? peek(divd) : 0); + dd = dd * 100 + (prev(divd) ? peek(divd) : 0); + cc = dr; + + if (diff == 0) + dd++; + else + cc++; + + if (magic) + dd *= 8; + + q = dd / cc; + under = 0; + if (q > 0 && dd % cc < 8 && magic) { + q--; + under = 1; + } + + mulnto(divr, acc, q); + + /* subtract acc from dividend at offset position */ + first(acc); + carry = 0; + for (seek(divd, diff); more(divd); next(divd)) { + d = peek(divd); + d = d - (more(acc) ? rddigit(acc) : 0) - carry; + carry = 0; + if (d < 0) { + d += 100; + carry = 1; + } + poke(divd, d); + } + divcarry = carry; + + /* store quotient digit */ + prev(res); + poke(res, q); + + /* handle borrow propagation */ + last(divd); + d = peek(divd); + if ((d != 0) && (diff != 0)) { + prev(divd); + d = peek(divd) + 100; + poke(divd, d); + } + + /* shorten dividend for next iteration */ + if (--diff >= 0) + divd->wp--; + } + + /* if we have an underflow then we have to adjust + * the remaining and the result */ + if (under) { + struct num *p = subnum(divd, divr); + if (negative(p)) { + freenum(p); + } else { + freenum(divd); + poke(res, q + 1); + divd = p; + } + } + + if (divcarry) { + struct num *p; + + poke(res, q - 1); + poke(divd, -1); + p = addnum(divr, divd); + freenum(divd); + divd = p; + } + + divcarry = 0; + for (first(res); more(res); next(res)) { + d = peek(res) + divcarry; + divcarry = 0; + if (d >= 100) { + d -= 100; + divcarry = 1; + } + poke(res, d); + } + +ret: + if (divsign) + chsign(divd); + if (divsign ^ remsign) + chsign(res); + + if (remp) { + divd->scale = odivd->scale; + *remp = norm(divd); + } else { + freenum(divd); + } + + if (divr != odivr) + freenum(divr); + + freenum(acc); + + res->scale = odivd->scale - odivr->scale; + if (res->scale < 0) + res->scale = 0; + + return norm(res); +} + +static int +divscale(struct num *divd, struct num *divr) +{ + int diff; + + if (length(divr) == 0) { + weprintf("divide by 0\n"); + return 0; + } + + diff = scale + divr->scale - divd->scale; + + if (diff > 0) { + mul10(divd, diff); + divd->scale += diff; + } else if (diff < 0) { + mul10(divr, -diff); + divr->scale += -diff; + } + + return 1; +} + +static struct num * +divnum(struct num *a, struct num *b) +{ + struct num *r; + int siga, sigb; + + siga = negative(a); + if (siga) + chsign(a); + + sigb = negative(b); + if (sigb) + chsign(b); + + if (!divscale(a, b)) + return copy(&zero); + + r = divmod(a, b, NULL); + if (siga ^ sigb) + chsign(r); + return r; +} + +static struct num * +modnum(struct num *a, struct num *b) +{ + struct num *mod, *c; + int siga, sigb; + + siga = negative(a); + if (siga) + chsign(a); + + sigb = negative(b); + if (sigb) + chsign(b); + + if (!divscale(a, b)) + return copy(&zero); + + c = divmod(a, b, &mod); + freenum(c); + + if (siga) + chsign(mod); + + return mod; +} + +static struct num * +expnum(struct num *base, struct num *exp) +{ + int neg, d; + struct num *res, *fact, *e, *tmp1, *tmp2; + + res = copy(&one); + if (length(exp) == 0) + return res; + + e = copy(exp); + if ((neg = negative(exp)) != 0) + chsign(e); + + if (e->scale > 0) { + div10(e, e->scale); + e->scale = 0; + } + + fact = copy(base); + while (length(e) > 0) { + first(e); + d = peek(e); + if (d % 2 == 1) { + tmp1 = mulnum(res, fact); + freenum(res); + res = tmp1; + } + + /* square fact */ + tmp1 = mulnum(fact, fact); + freenum(fact); + fact = tmp1; + + divn(e, 2); + } + freenum(fact); + freenum(e); + + /* handle negative exponent: 1 / res */ + if (neg) { + tmp2 = divnum(tmp1 = copy(&one), res); + freenum(tmp1); + freenum(res); + res = tmp2; + } + + return res; +} + +/* compare two numbers: returns <0 if a<b, 0 if a==b, >0 if a>b */ +static int +cmpnum(struct num *a, struct num *b) +{ + struct num *diff; + int result; + + diff = subnum(a, b); + if (length(diff) == 0) + result = 0; + else if (negative(diff)) + result = -1; + else + result = 1; + freenum(diff); + + return result; +} + +/* integer square root of a small integer (0-9999) + * used for initial guess in newton's method */ +static int +isqrt(int n) +{ + int x, x1; + + if (n <= 0) + return 0; + if (n == 1) + return 1; + + x = n; + x1 = (x + 1) / 2; + while (x1 < x) { + x = x1; + x1 = (x + n / x) / 2; + } + return x; +} + +/* square root using newton's method: x_{n+1} = (x_n + y/x_n) / 2 + * + * key insight: sqrt(a * 10^(2n)) = sqrt(a) * 10^n + * so we scale up the input to get the desired output precision + * + * to compute sqrt with scale decimal places of precision: + * 1. scale up y by 10^(2*scale + 2) (extra 2 for guard digits) + * 2. compute integer sqrt + * 3. result has (scale + 1) decimal places, numtrunc to scale */ +static struct num * +sqrtnum(struct num *oy) +{ + struct num *y, *x, *xprev, *q, *sum; + int top, ysc, iter; + + if (length(oy) == 0) + return copy(&zero); + + if (negative(oy)) { + weprintf("square root of negative number\n"); + return copy(&zero); + } + + y = copy(oy); + ysc = 2 * scale + 2 - y->scale; + if (ysc > 0) + mul10(y, ysc); + ysc = 2 * scale + 2; + + /* make scale even (so sqrt gives integer result) */ + if (ysc % 2 == 1) { + muln(y, 10); + ysc++; + } + y->scale = 0; + + last(y); + top = peek(y); + if (prev(y) && length(y) > 1) + top = top * 100 + peek(y); + + x = newnum(0); + wrdigit(x, isqrt(top)); + x->scale = 0; + + /* scale up the initial guess to match the magnitude of y */ + lshift(x, (length(y) - 1) / 2); + + /* newton iteration: x = (x + y/x) / 2 */ + xprev = NULL; + for (iter = 0; iter < 1000; iter++) { + q = divmod(y, x, NULL); + sum = addnum(x, q); + freenum(q); + divn(sum, 2); + + /* check for convergence: sum == x or sum == prev */ + if (cmpnum(sum, x) == 0) { + freenum(sum); + break; + } + if (xprev != NULL && cmpnum(sum, xprev) == 0) { + /* oscillating, pick smaller */ + if (cmpnum(x, sum) < 0) { + freenum(sum); + } else { + freenum(x); + x = sum; + } + break; + } + + freenum(xprev); + xprev = x; + x = sum; + } + freenum(xprev); + freenum(y); + + /* truncate to desired scale */ + x->scale = ysc / 2; + if (x->scale > scale) { + int diff = x->scale - scale; + div10(x, diff); + x->scale = scale; + } + + return norm(x); +} + +static struct num * +tonum(void) +{ + char *s, *t, *end, *dot; + struct num *num, *denom, *numer, *frac, *q, *rem; + int sign, d, ch, nfrac; + + s = input->s; + num = newnum(0); + sign = 0; + if (*s == '_') { + sign = 1; + ++s; + } + + dot = NULL; + for (t = s; (ch = *t) > 0 || ch <= UCHAR_MAX; ++t) { + if (!strchr(digits, ch)) + break; + if (ch == '.') { + if (dot) + break; + dot = t; + } + } + input->s = end = t; + + /* parse integer part: process digits left-to-right + * for each digit: num = num * ibase + digit */ + for (t = s; t < (dot ? dot : end); ++t) { + d = strchr(digits, *t) - digits; + muln(num, ibase); + addn(num, d); + } + norm(num); + + if (!dot) + goto ret; + + /* convert fractional digits + * algorithm: for digits d[0], d[1], ..., d[n-1] after '.' + * value = d[0]/ibase + d[1]/ibase^2 + ... + d[n-1]/ibase^n + * + * numerator = d[0]*ibase^(n-1) + d[1]*ibase^(n-2) + ... + d[n-1] + * denominator = ibase^n + * then extract decimal digits by repeated: num*100/denom */ + denom = copy(&one); + numer = copy(&zero); + for (t = dot + 1; t < end; ++t) { + d = strchr(digits, *t) - digits; + muln(denom, ibase); + muln(numer, ibase); + addn(numer, d); + } + + nfrac = end - dot - 1; + frac = newnum(0); + d = 0; + while (frac->scale < nfrac || length(numer) > 0) { + muln(numer, 100); + q = divmod(numer, denom, &rem); + freenum(numer); + + d = first(q) ? peek(q) : 0; + wrdigit(frac, d); + freenum(q); + numer = rem; + frac->scale += 2; + } + reverse(frac); + + /* trim to exact input scale for odd nfrac */ + if (frac->scale > nfrac && d % 10 == 0) { + divn(frac, 10); + frac->scale--; + } + + freenum(numer); + freenum(denom); + + q = addnum(num, frac); + freenum(num); + freenum(frac); + num = q; + +ret: + if (sign) + chsign(num); + return num; +} + +static void +prchr(int ch) +{ + if (col >= 69) { + putchar('\\'); + putchar('\n'); + col = 0; + } + putchar(ch); + col++; +} + +static void +printd(int d, int base, int space) +{ + int w, n; + + if (base <= 16) { + prchr(digits[d]); + } else { + if (space) + prchr(' '); + + for (w = 1, n = base - 1; n >= 10; n /= 10) + w++; + + if (col + w > 69) { + putchar('\\'); + putchar('\n'); + col = 0; + } + col += printf("%0*d", w, d); + } +} + +static void +pushdigit(struct digit **l, int val) +{ + struct digit *it = emalloc(sizeof(*it)); + + it->next = *l; + it->val = val; + *l = it; +} + +static int +popdigit(struct digit **l) +{ + int val; + struct digit *next, *it = *l; + + if (it == NULL) + return -1; + + val = it->val; + next = it->next; + free(it); + *l = next; + return val; +} + +static void +printnum(struct num *onum, int base) +{ + struct digit *sp; + int sc, i, sign, n; + struct num *num, *inte, *frac, *opow; + + col = 0; + if (length(onum) == 0) { + prchr('0'); + return; + } + + num = copy(onum); + if ((sign = negative(num)) != 0) + chsign(num); + + sc = num->scale; + if (num->scale % 2 == 1) { + muln(num, 10); + num->scale++; + } + inte = copy(num); + rshift(inte, num->scale / 2); + inte->scale = 0; + frac = subnum(num, inte); + + sp = NULL; + for (i = 0; length(inte) > 0; ++i) + pushdigit(&sp, divn(inte, base)); + if (sign) + prchr('-'); + while (i-- > 0) + printd(popdigit(&sp), base, 1); + assert(sp == NULL); + + if (num->scale == 0) + goto ret; + + /* print fractional part by repeated multiplication by base + * we maintain the fraction as: frac / 10^scale + * + * algorithm: + * 1. multiply frac by base + * 2. output integer part (frac / 10^scale) + * 3. keep fractional part (frac % 10^scale) */ + prchr('.'); + + opow = copy(&one); + mul10(opow, num->scale); + + for (n = 0; n < sc; ++n) { + int d; + struct num *q, *rem; + + muln(frac, base); + q = divmod(frac, opow, &rem); + d = first(q) ? peek(q) : 0; + freenum(frac); + freenum(q); + frac = rem; + printd(d, base, n > 0); + } + freenum(opow); + +ret: + freenum(num); + freenum(inte); + freenum(frac); +} + +static int +moreinput(void) +{ + struct input *ip; + +repeat: + if (!input) + return 0; + + if (input->buf != NULL && *input->s != '\0') + return 1; + + if (input->fp) { + if (getline(&input->buf, &input->n, input->fp) >= 0) { + input->s = input->buf; + return 1; + } + if (ferror(input->fp)) { + eprintf("reading from file:"); + exit(1); + } + fclose(input->fp); + } + + ip = input; + input = ip->next; + free(ip->buf); + free(ip); + goto repeat; +} + +static void +addinput(FILE *fp, char *s) +{ + struct input *ip; + + assert((!fp && !s) == 0); + + ip = emalloc(sizeof(*ip)); + ip->next = input; + ip->fp = fp; + ip->n = 0; + ip->s = ip->buf = s; + input = ip; +} + +static void +delinput(int cmd, int n) +{ + if (n < 0) + error("Q command requires a number >= 0"); + while (n-- > 0) { + if (cmd == 'Q' && !input->next) + error("Q command argument exceeded string execution depth"); + if (input->fp) + fclose(input->fp); + free(input->buf); + input = input->next; + if (!input) + exit(0); + } +} + +static void +push(struct val v) +{ + struct val *p = emalloc(sizeof(struct val)); + + *p = v; + p->next = stack; + stack = p; +} + +static void +needstack(int n) +{ + struct val *vp; + + for (vp = stack; n > 0 && vp; vp = vp->next) + --n; + if (n > 0) + error("stack empty"); +} + +static struct val +pop(void) +{ + struct val v; + + if (!stack) + error("stack empty"); + v = *stack; + free(stack); + stack = v.next; + v.next = NULL; + + return v; +} + +static struct num * +popnum(void) +{ + struct val v = pop(); + + if (v.type != NUM) { + free(v.u.s); + error("non-numeric value"); + } + return v.u.n; +} + +static void +pushnum(struct num *num) +{ + push((struct val){.type = NUM, .u.n = num}); +} + +static void +pushstr(char *s) +{ + push((struct val){.type = STR, .u.s = s}); +} + +static void +arith(struct num *(*fn)(struct num *, struct num *)) +{ + struct num *a, *b, *c; + + needstack(2); + b = popnum(); + a = popnum(); + c = (*fn)(a, b); + freenum(a); + freenum(b); + pushnum(c); +} + +static void +pushdivmod(void) +{ + struct num *a, *b, *q, *rem; + + needstack(2); + b = popnum(); + a = popnum(); + + if (!divscale(a, b)) { + q = copy(&zero); + rem = copy(&zero); + } else { + q = divmod(a, b, &rem); + } + + pushnum(q); + pushnum(rem); + freenum(a); + freenum(b); +} + +static int +popint(void) +{ + struct num *num; + int r = -1, n, d; + + num = popnum(); + if (negative(num)) + goto ret; + + /* discard fraction part */ + div10(num, num->scale); + + n = 0; + for (last(num); !begin(num); prev(num)) { + if (n > INT_MAX / 100) + goto ret; + n *= 100; + d = peek(num); + if (n > INT_MAX - d) + goto ret; + n += d; + } + r = n; + +ret: + freenum(num); + return r; +} + +static void +pushint(int n) +{ + div_t dd; + struct num *num; + + num = newnum(0); + for (; n > 0; n = dd.quot) { + dd = div(n, 100); + wrdigit(num, dd.rem); + } + pushnum(num); +} + +static void +printval(struct val v) +{ + if (v.type == STR) + fputs(v.u.s, stdout); + else + printnum(v.u.n, obase); +} + +static struct val +dupval(struct val v) +{ + struct val nv; + + switch (nv.type = v.type) { + case STR: + nv.u.s = estrdup(v.u.s); + break; + case NUM: + nv.u.n = copy(v.u.n); + break; + case NVAL: + nv.type = NUM; + nv.u.n = copy(&zero); + break; + } + nv.next = NULL; + + return nv; +} + +static void +freeval(struct val v) +{ + if (v.type == STR) + free(v.u.s); + else if (v.type == NUM) + freenum(v.u.n); +} + +static void +dumpstack(void) +{ + struct val *vp; + + for (vp = stack; vp; vp = vp->next) { + printval(*vp); + putchar('\n'); + } +} + +static void +clearstack(void) +{ + struct val *vp, *next; + + for (vp = stack; vp; vp = next) { + next = vp->next; + freeval(*vp); + free(vp); + } + stack = NULL; +} + +static void +dupstack(void) +{ + struct val v; + + push(v = pop()); + push(dupval(v)); +} + +static void +deepstack(void) +{ + int n; + struct val *vp; + + n = 0; + for (vp = stack; vp; vp = vp->next) { + if (n == INT_MAX) + error("stack depth does not fit in a integer"); + ++n; + } + pushint(n); +} + +static void +pushfrac(void) +{ + struct val v = pop(); + + if (v.type == STR) + pushint(0); + else + pushint(v.u.n->scale); + freeval(v); +} + +static void +pushlen(void) +{ + int n; + struct num *num; + struct val v = pop(); + + if (v.type == STR) { + n = strlen(v.u.s); + } else { + num = v.u.n; + if (length(num) == 0) { + n = 1; + } else { + n = length(num) * 2; + n -= last(num) ? peek(num) < 10 : 0; + } + } + pushint(n); + freeval(v); +} + +static void +setibase(void) +{ + int n = popint(); + + if (n < 2 || n > 16) + error("input base must be an integer between 2 and 16"); + ibase = n; +} + +static void +setobase(void) +{ + int n = popint(); + + if (n < 2) + error("output base must be an integer greater than 1"); + obase = n; +} + +static char * +string(char *dst, int *np) +{ + int n, ch; + + n = np ? *np : 0; + for (;;) { + ch = *input->s++; + + switch (ch) { + case '\0': + /* the read above already stepped input->s one past this + * buffer's own terminator; moreinput()'s own fast path + * dereferences input->s directly on the assumption it is + * always in bounds, so it has to be backed up first or that + * check reads one byte past the allocation */ + --input->s; + if (!moreinput()) + exit(0); + break; + case '\\': + if (*input->s == '[') { + dst = erealloc(dst, n + 1); + dst[n++] = *input->s++; + break; + } + goto copy; + case ']': + if (!np) { + dst = erealloc(dst, n + 1); + dst[n] = '\0'; + return dst; + } + case '[': + default: + copy: + dst = erealloc(dst, n + 1); + dst[n++] = ch; + if (ch == '[') + dst = string(dst, &n); + if (ch == ']') { + *np = n; + return dst; + } + } + } +} + +static void +setscale(void) +{ + int n = popint(); + + if (n < 0) + error("scale must be a nonnegative integer"); + scale = n; +} + +static unsigned +hash(char *name) +{ + int c; + unsigned h = 5381; + + while ((c = *name++)) + h = h * 33 ^ c; + + return h; +} + +static struct reg * +lookup(char *name) +{ + struct reg *rp; + int h = hash(name) & (HASHSIZ - 1); + + for (rp = htbl[h]; rp; rp = rp->next) { + if (strcmp(name, rp->name) == 0) + return rp; + } + + rp = emalloc(sizeof(*rp)); + rp->next = htbl[h]; + htbl[h] = rp; + rp->name = estrdup(name); + + rp->val.type = NVAL; + rp->val.next = NULL; + + rp->ary.n = 0; + rp->ary.buf = NULL; + rp->ary.next = NULL; + + return rp; +} + +static char * +regname(void) +{ + int delim, ch; + char *s; + static char name[REGSIZ]; + + ch = *input->s++; + if (!iflag || (ch != '<' && ch != '"')) { + name[0] = ch; + name[1] = '\0'; + return name; + } + + if ((delim = ch) == '<') + delim = '>'; + + for (s = name; s < &name[REGSIZ]; ++s) { + ch = *input->s++; + if (ch == '\0' || ch == delim) { + *s = '\0'; + if (ch == '>') { + name[0] = atoi(name); + name[1] = '\0'; + } + return name; + } + *s = ch; + } + + error("identifier too long"); +} + +static void +popreg(void) +{ + int i; + struct val *vnext; + struct ary *anext; + char *s = regname(); + struct reg *rp = lookup(s); + + if (rp->val.type == NVAL) + error("stack register '%s' (%o) is empty", s, s[0]); + + push(rp->val); + vnext = rp->val.next; + if (!vnext) { + rp->val.type = NVAL; + } else { + rp->val = *vnext; + free(vnext); + } + + for (i = 0; i < rp->ary.n; ++i) + freeval(rp->ary.buf[i]); + free(rp->ary.buf); + + anext = rp->ary.next; + if (!anext) { + rp->ary.n = 0; + rp->ary.buf = NULL; + } else { + rp->ary = *anext; + free(anext); + } +} + +static void +pushreg(void) +{ + struct val v; + struct val *vp; + struct ary *ap; + struct reg *rp = lookup(regname()); + + v = pop(); + + vp = emalloc(sizeof(struct val)); + *vp = rp->val; + rp->val = v; + rp->val.next = vp; + + ap = emalloc(sizeof(struct ary)); + *ap = rp->ary; + rp->ary.n = 0; + rp->ary.buf = NULL; + rp->ary.next = ap; +} + +static struct val * +aryidx(void) +{ + int n; + int i; + struct val *vp; + struct reg *rp = lookup(regname()); + struct ary *ap = &rp->ary; + + n = popint(); + if (n < 0) + error("array index must fit in a positive integer"); + + if (n >= ap->n) { + ap->buf = ereallocarray(ap->buf, n + 1, sizeof(struct val)); + for (i = ap->n; i <= n; ++i) + ap->buf[i].type = NVAL; + ap->n = n + 1; + } + return &ap->buf[n]; +} + +static void +aryget(void) +{ + struct val *vp = aryidx(); + + push(dupval(*vp)); +} + +static void +aryset(void) +{ + struct val val, *vp = aryidx(); + + val = pop(); + freeval(*vp); + *vp = val; +} + +static void +execmacro(void) +{ + int ch; + struct val v = pop(); + + assert(v.type != NVAL); + if (v.type == NUM) { + push(v); + return; + } + + if (input->fp) { + addinput(NULL, v.u.s); + return; + } + + for (ch = *input->s; ch > 0 && ch <= UCHAR_MAX; ch = *input->s) { + if (!isspace(ch)) + break; + ++input->s; + } + + /* check for tail recursion */ + if (ch == '\0' && strcmp(input->buf, v.u.s) == 0) { + free(input->buf); + input->buf = input->s = v.u.s; + return; + } + + addinput(NULL, v.u.s); +} + +static void +relational(int ch) +{ + int r; + char *s; + struct num *a, *b; + struct reg *rp = lookup(regname()); + + needstack(2); + a = popnum(); + b = popnum(); + r = cmpnum(a, b); + freenum(a); + freenum(b); + + switch (ch) { + case '>': + r = r > 0; + break; + case '<': + r = r < 0; + break; + case '=': + r = r == 0; + break; + case LE: + r = r <= 0; + break; + case GE: + r = r >= 0; + break; + case NE: + r = r != 0; + break; + default: + abort(); + } + + if (!r) + return; + + push(dupval(rp->val)); + execmacro(); +} + +static void +printbytes(void) +{ + struct num *num; + struct val v = pop(); + + if (v.type == STR) { + fputs(v.u.s, stdout); + } else { + num = v.u.n; + div10(num, num->scale); + num->scale = 0; + printnum(num, 100); + } + freeval(v); +} + +/* bc's own spawn() repurposes fd 0 as the read end of the pipe + * carrying its generated code, and dups the real, original stdin to + * fd 3 first so this command still has somewhere real to read from; + * standalone dc (fd 3 never opened) falls back to its own real stdin */ +static FILE * +readsrc(void) +{ + static FILE *fp; + static int tried; + + if (!tried) { + tried = 1; + if (fcntl(3, F_GETFD) >= 0) + fp = fdopen(3, "r"); + if (!fp) + fp = stdin; + } + return fp; +} + +static void +eval(void) +{ + int ch; + char *s; + struct num *num; + size_t siz; + struct val v1, v2; + struct reg *rp; + + if (setjmp(env)) + return; + + for (s = input->s; (ch = *s) != '\0'; ++s) { + if (ch < 0 || ch > UCHAR_MAX || !isspace(ch)) + break; + } + input->s = s + (ch != '\0'); + + switch (ch) { + case '\0': + break; + case 'n': + v1 = pop(); + printval(v1); + freeval(v1); + break; + case 'p': + v1 = pop(); + printval(v1); + putchar('\n'); + push(v1); + break; + case 'P': + printbytes(); + break; + case 'f': + dumpstack(); + break; + case '+': + arith(addnum); + break; + case '-': + arith(subnum); + break; + case '*': + arith(mulnum); + break; + case '/': + arith(divnum); + break; + case '%': + arith(modnum); + break; + case '^': + arith(expnum); + break; + case '~': + pushdivmod(); + break; + case 'v': + num = popnum(); + pushnum(sqrtnum(num)); + freenum(num); + break; + case 'c': + clearstack(); + break; + case 'd': + dupstack(); + break; + case 'r': + needstack(2); + v1 = pop(); + v2 = pop(); + push(v1); + push(v2); + break; + case 'S': + pushreg(); + break; + case 'L': + popreg(); + break; + case 's': + rp = lookup(regname()); + v1 = pop(); + freeval(rp->val); + rp->val.u = v1.u; + rp->val.type = v1.type; + break; + case 'l': + rp = lookup(regname()); + push(dupval(rp->val)); + break; + case 'i': + setibase(); + break; + case 'o': + setobase(); + break; + case 'k': + setscale(); + break; + case 'I': + pushint(ibase); + break; + case 'O': + pushint(obase); + break; + case 'K': + pushint(scale); + break; + case '[': + pushstr(string(NULL, NULL)); + break; + case 'x': + execmacro(); + break; + case '!': + switch (*input->s++) { + case '<': + ch = GE; + break; + case '>': + ch = LE; + break; + case '=': + ch = NE; + break; + default: + system(input->s - 1); + goto discard; + } + case '>': + case '<': + case '=': + relational(ch); + break; + case '?': + /* real dc executes the line as commands rather than pushing it + * as a string: bc's own read() relies on exactly this, since a + * bare number is already a complete, valid command that pushes + * itself */ + s = NULL; + if (getline(&s, &siz, readsrc()) > 0) { + addinput(NULL, s); + } else { + free(s); + if (ferror(readsrc())) + eprintf("reading from file\n"); + } + break; + case 'q': + delinput('q', 2); + break; + case 'Q': + delinput('Q', popint()); + break; + case 'Z': + pushlen(); + break; + case 'X': + pushfrac(); + break; + case 'z': + deepstack(); + break; + case '#': + discard: + while (*input->s) + ++input->s; + break; + case ':': + aryset(); + break; + case ';': + aryget(); + break; + default: + if (!strchr(digits, ch)) + error("'%c' (%#o) unimplemented", ch, ch); + case '_': + --input->s; + pushnum(tonum()); + break; + } +} + +static void +dc(char *fname) +{ + FILE *fp; + + if (strcmp(fname, "-") == 0) { + fp = stdin; + } else { + if ((fp = fopen(fname, "r")) == NULL) + eprintf("opening '%s':", fname); + } + addinput(fp, NULL); + + while (moreinput()) + eval(); + + free(input); + input = NULL; +} + +static void +usage(void) +{ + eprintf("usage: dc [-i] [file ...]\n"); +} + +// ?man dc: an arbitrary-precision reverse-polish desk calculator +// ?man arguments: [file ...] +// ?man dc reads and executes commands from each file in turn, then +// ?man from standard input +int +main(int argc, char *argv[]) +{ + ARGBEGIN + { + // ?man -i: enable extended (multi-character) register names + case 'i': + iflag = 1; + break; + default: + usage(); + } + ARGEND + + while (*argv) + dc(*argv++); + dc("-"); + + return 0; +} diff --git a/cmd/extra/fdisk.c b/cmd/extra/fdisk.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "diskutil.h" #include "util.h" @@ -6,6 +6,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <unistd.h> struct MbrPartition { @@ -121,6 +122,151 @@ crc32(uint32_t crc, const void *buf, size_t len) return crc; } +/* short two-byte codes match gdisk/sgdisk's own convention, since + * every caller already writing "-t ef00" etc against those tools + * expects the same codes here */ +static const struct { + const char *code; + uint8_t guid[16]; +} gpt_type_table[] = { + /* ef00: efi system partition */ + {"ef00", + {0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11, 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, + 0x3b} }, + /* ef02: bios boot partition */ + {"ef02", + {0x48, 0x61, 0x68, 0x21, 0x49, 0x64, 0x6f, 0x6e, 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, + 0x49} }, + /* 8200: linux swap */ + {"8200", + {0x6d, 0xfd, 0x57, 0x06, 0xab, 0xa4, 0xc4, 0x43, 0x84, 0xe5, 0x09, 0x33, 0xc8, 0x4b, 0x4f, + 0x4f} }, + /* 8300: linux filesystem data */ + {"8300", + {0xaf, 0x3d, 0xc6, 0x0f, 0x84, 0x83, 0x72, 0x47, 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, + 0xe4} }, +}; +#define GPT_TYPE_TABLE_LEN (int)(sizeof(gpt_type_table) / sizeof(gpt_type_table[0])) + +/* canonical XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX form: the first three + * groups store little-endian, the last two store big-endian, the same + * mixed layout every other GUID field in this file already uses */ +static int +parse_guid_string(const char *s, uint8_t out[16]) +{ + static const int group_len[5] = {8, 4, 4, 4, 12}; + static const int group_le[5] = {1, 1, 1, 0, 0}; + int g, i, hi, lo, byte_idx = 0; + const char *p = s; + + for (g = 0; g < 5; g++) { + uint8_t bytes[6]; + int nbytes = group_len[g] / 2; + for (i = 0; i < nbytes; i++) { + hi = hexval(p[i * 2]); + lo = hexval(p[i * 2 + 1]); + if (hi < 0 || lo < 0) + return -1; + bytes[i] = (uint8_t)((hi << 4) | lo); + } + if (group_le[g]) { + for (i = nbytes - 1; i >= 0; i--) + out[byte_idx++] = bytes[i]; + } else { + for (i = 0; i < nbytes; i++) + out[byte_idx++] = bytes[i]; + } + p += group_len[g]; + if (g < 4) { + if (*p != '-') + return -1; + p++; + } + } + return *p == '\0' ? 0 : -1; +} + +/* opt_type is a short gdisk-style code (see gpt_type_table above), a + * full canonical GUID string, or unset: unset (or unrecognized, with + * a warning) keeps the long-standing default of "linux filesystem + * data", matching what every caller got before -t existed */ +static void +gpt_type_guid(const char *type, uint8_t out[16]) +{ + int i; + + if (type) { + for (i = 0; i < GPT_TYPE_TABLE_LEN; i++) { + if (strcasecmp(type, gpt_type_table[i].code) == 0) { + memcpy(out, gpt_type_table[i].guid, 16); + return; + } + } + if (parse_guid_string(type, out) == 0) + return; + weprintf("unrecognized GPT type '%s', using linux filesystem data\n", type); + } + memcpy(out, gpt_type_table[GPT_TYPE_TABLE_LEN - 1].guid, 16); +} + +/* resolves -b for a GPT add: a plain sector number, or 0/unset for + * the first free sector right after every existing partition's own + * end_lba (gpt_hdr.first_usable if the table is still empty), the + * same "0 means auto-place" convention gdisk-family tools already use */ +static uint64_t +gpt_resolve_start(struct GptHeader *hdr, struct GptPartition *parts, const char *s) +{ + uint32_t i; + uint64_t next = hdr->first_usable; + + if (s && strcmp(s, "0") != 0) + return (uint64_t)estrtoul(s, 10); + + for (i = 0; i < hdr->num_parts; i++) { + if (parts[i].start_lba == 0 && parts[i].end_lba == 0) + continue; + if (parts[i].end_lba + 1 > next) + next = parts[i].end_lba + 1; + } + return next; +} + +/* resolves -e for a GPT add: a plain sector number, 0/unset for the + * disk's own last usable sector, or +SIZE for a size relative to the + * already-resolved start */ +static uint64_t +gpt_resolve_end(struct GptHeader *hdr, size_t sec_size, uint64_t start, const char *s) +{ + off_t size_bytes; + uint64_t sectors; + + if (!s || strcmp(s, "0") == 0) + return hdr->last_usable; + if (s[0] == '+') { + size_bytes = parseoffset(s + 1); + if (size_bytes < 0) + eprintf("fdisk: malformed size '%s'\n", s); + sectors = ((uint64_t)size_bytes + sec_size - 1) / sec_size; + return start + sectors - 1; + } + return (uint64_t)estrtoul(s, 10); +} + +/* GPT partition names are UTF-16LE, 36 code units, null-padded: every + * caller so far only ever needs a plain ASCII label, so this widens + * each byte rather than pulling in a real UTF-8 decoder for it */ +static void +gpt_set_name(uint16_t name[36], const char *s) +{ + size_t i; + + memset(name, 0, 36 * sizeof(uint16_t)); + if (!s) + return; + for (i = 0; i < 35 && s[i]; i++) + name[i] = (uint16_t)(unsigned char)s[i]; +} + static int opt_list = 0; static int opt_print = 0; static int opt_init_gpt = 0; @@ -130,16 +276,17 @@ static int opt_add = 0; static int opt_del = 0; static int opt_part_idx = -1; static int opt_part_is_letter = 0; -static uint64_t opt_start = 0; -static uint64_t opt_end = 0; +static const char *opt_start_str = NULL; +static const char *opt_end_str = NULL; static const char *opt_type = NULL; +static const char *opt_name = NULL; static void usage(void) { eprintf( "usage: %s [-l] [-p] [-g] [-m] [-s] [-a] [-d] [-n index] [-b " - "start] [-e end] [-t type] [device]\n", + "start] [-e end] [-t type] [-c name] [device]\n", argv0 ); } @@ -445,6 +592,8 @@ do_fdisk(const char *path) int idx; int has_gpt = 0; int has_bsd = 0; + uint64_t bsd_start, bsd_end; + uint64_t mbr_start, mbr_end; if (blockdev_open(&dev, path, 1) < 0) { weprintf("cannot open %s:", path); @@ -542,25 +691,11 @@ do_fdisk(const char *path) blockdev_close(&dev); return -1; } - gp = &gpt_parts[opt_part_idx - 1]; - gp->start_lba = opt_start; - gp->end_lba = opt_end; - gp->type_guid[0] = 0xAF; - gp->type_guid[1] = 0x3D; - gp->type_guid[2] = 0xC6; - gp->type_guid[3] = 0x0F; - gp->type_guid[4] = 0x83; - gp->type_guid[5] = 0x84; - gp->type_guid[6] = 0x72; - gp->type_guid[7] = 0x47; - gp->type_guid[8] = 0x8E; - gp->type_guid[9] = 0x79; - gp->type_guid[10] = 0x3D; - gp->type_guid[11] = 0x69; - gp->type_guid[12] = 0xD8; - gp->type_guid[13] = 0x47; - gp->type_guid[14] = 0x7D; - gp->type_guid[15] = 0xE4; + gp = &gpt_parts[opt_part_idx - 1]; + gp->start_lba = gpt_resolve_start(&gpt_hdr, gpt_parts, opt_start_str); + gp->end_lba = gpt_resolve_end(&gpt_hdr, dev.sec_size, gp->start_lba, opt_end_str); + gpt_type_guid(opt_type, gp->type_guid); + gpt_set_name(gp->name, opt_name); if (gpt_write(&dev, &gpt_hdr, gpt_parts) < 0) { weprintf("cannot update GPT on %s:", path); @@ -590,9 +725,11 @@ do_fdisk(const char *path) return -1; } bp = &bsd_lp.d_partitions[idx]; - bp->offset = (uint32_t)opt_start; - bp->offset_h = (uint16_t)(opt_start >> 32); - size = opt_end - opt_start + 1; + bsd_start = opt_start_str ? (uint64_t)estrtoul(opt_start_str, 10) : 0; + bsd_end = opt_end_str ? (uint64_t)estrtoul(opt_end_str, 10) : 0; + bp->offset = (uint32_t)bsd_start; + bp->offset_h = (uint16_t)(bsd_start >> 32); + size = bsd_end - bsd_start + 1; bp->size = (uint32_t)size; bp->size_h = (uint16_t)(size >> 32); bp->fstype = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 7; @@ -624,8 +761,10 @@ do_fdisk(const char *path) return -1; } mp = &mbr.parts[opt_part_idx - 1]; - mp->start_lba = (uint32_t)opt_start; - mp->size = (uint32_t)(opt_end - opt_start + 1); + mbr_start = opt_start_str ? (uint64_t)estrtoul(opt_start_str, 10) : 0; + mbr_end = opt_end_str ? (uint64_t)estrtoul(opt_end_str, 10) : 0; + mp->start_lba = (uint32_t)mbr_start; + mp->size = (uint32_t)(mbr_end - mbr_start + 1); mp->type = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 0x83; mbr.sig[0] = 0x55; mbr.sig[1] = 0xAA; @@ -724,8 +863,8 @@ do_fdisk(const char *path) // ?man fdisk: partition table manipulator // ?man arguments: [-l] [-p] [-g] [-m] [-s] [-a] [-d] [-n index] [-b start] [-e -// end] [-t type] [device] ?man fdisk performs partition table operations for -// MBR, GPT and BSD disklabels +// end] [-t type] [-c name] [device] ?man fdisk performs partition table +// operations for MBR, GPT and BSD disklabels int main(int argc, char *argv[]) { @@ -773,18 +912,26 @@ main(int argc, char *argv[]) } break; } - // ?man -b:starting sector LBA + // ?man -b:starting sector LBA, or 0 for right after the last + // ?man partition already on the disk case 'b': - opt_start = (uint64_t)estrtoul(EARGF(usage()), 10); + opt_start_str = EARGF(usage()); break; - // ?man -e:ending sector LBA + // ?man -e:ending sector LBA, 0 for the disk's last usable + // ?man sector, or +SIZE (K/M/G/T, e.g. +512M) for a size + // ?man relative to the start case 'e': - opt_end = (uint64_t)estrtoul(EARGF(usage()), 10); + opt_end_str = EARGF(usage()); break; - // ?man -t:partition type (MBR/BSD hex or GPT string) + // ?man -t:partition type: MBR/BSD hex, or for GPT a gdisk-style + // ?man code (ef00, ef02, 8200, 8300) or a full GUID string case 't': opt_type = EARGF(usage()); break; + // ?man -c:GPT partition name, ignored for MBR/BSD + case 'c': + opt_name = EARGF(usage()); + break; default: usage(); } diff --git a/cmd/extra/install.c b/cmd/extra/install.c @@ -0,0 +1,269 @@ +/* see LICENSE file for copyright and license details */ +#include <sys/stat.h> +#include <sys/types.h> + +#include <errno.h> +#include <fcntl.h> +#include <grp.h> +#include <libgen.h> +#include <limits.h> +#include <pwd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "fs.h" +#include "util.h" +#include "wexec.h" + +static int dflag, Dflag, pflag, sflag; +static mode_t mode = 0755; +static uid_t uid = (uid_t)-1; +static gid_t gid = (gid_t)-1; +static int status; + +static void +usage(void) +{ + eprintf( + "usage: %s [-Dps] [-o owner] [-g group] [-m mode] [-t dir] source ... dest\n" + " %s -d [-Dp] [-o owner] [-g group] [-m mode] dir ...\n", + argv0, + argv0 + ); +} + +static void +lookup_owner(const char *owner, const char *group) +{ + struct passwd *pw; + struct group *gr; + + if (owner) { + errno = 0; + pw = getpwnam(owner); + if (pw) { + uid = pw->pw_uid; + } else { + if (errno) + eprintf("getpwnam %s:", owner); + uid = (uid_t)estrtonum(owner, 0, UINT_MAX); + } + } + if (group) { + errno = 0; + gr = getgrnam(group); + if (gr) { + gid = gr->gr_gid; + } else { + if (errno) + eprintf("getgrnam %s:", group); + gid = (gid_t)estrtonum(group, 0, UINT_MAX); + } + } +} + +static void +chown_if_requested(const char *path) +{ + if (uid == (uid_t)-1 && gid == (gid_t)-1) + return; + if (chown(path, uid, gid) < 0) { + weprintf("chown %s:", path); + status = 1; + } +} + +static void +preserve_time(const char *src, const char *dst) +{ + struct stat st; + struct timespec times[2]; + + if (stat(src, &st) < 0) { + weprintf("stat %s:", src); + status = 1; + return; + } + times[0] = st.st_atim; + times[1] = st.st_mtim; + if (utimensat(AT_FDCWD, dst, times, 0) < 0) { + weprintf("utimensat %s:", dst); + status = 1; + } +} + +static void +strip_binary(const char *path) +{ + char *args[] = {"strip", "-p", (char *)path, NULL}; + + if (wexecvp("strip", args) != 0) { + weprintf("strip %s:", path); + status = 1; + } +} + +// leading path components of dst, not dst itself +static void +make_leading_dirs(const char *dst) +{ + char buf[PATH_MAX]; + char *dir; + + estrlcpy(buf, dst, sizeof(buf)); + dir = dirname(buf); + if (mkdirp(dir, 0755, 0755) < 0 && errno != EEXIST) { + weprintf("mkdir %s:", dir); + status = 1; + } +} + +static void +install_dirs(char **argv) +{ + for (; *argv; argv++) { + if (mkdirp(*argv, mode, 0755) < 0 && errno != EEXIST) { + weprintf("mkdir %s:", *argv); + status = 1; + continue; + } + if (chmod(*argv, mode) < 0) { + weprintf("chmod %s:", *argv); + status = 1; + } + chown_if_requested(*argv); + } +} + +static void +install_one(const char *src, const char *dst) +{ + if (Dflag) + make_leading_dirs(dst); + + cp_fflag = 1; + cp_pflag = 0; + cp_rflag = 0; + cp_follow = 'L'; + cp(src, dst, 0); + if (cp_status) { + status = 1; + return; + } + + if (sflag) + strip_binary(dst); + + if (chmod(dst, mode) < 0) { + weprintf("chmod %s:", dst); + status = 1; + } + chown_if_requested(dst); + if (pflag) + preserve_time(src, dst); +} + +// ?man install: copy files and set attributes +// ?man arguments: source ... dest +// ?man install copies each source to dest, or into dest when dest is a +// ?man directory or -t is given, then applies mode/owner/group; with +// ?man -d, every argument is a directory to create instead +int +main(int argc, char *argv[]) +{ + const char *owner = NULL, *group = NULL, *modestr = NULL, *targetdir = NULL; + const char *dest; + struct stat st; + int isdir; + int i; + + ARGBEGIN + { + // ?man -c: ignored; accepted for compatibility with older install callers + case 'c': + break; + // ?man -d: create directories instead of installing files + case 'd': + dflag = 1; + break; + // ?man -D: create dest's leading directories before installing + case 'D': + Dflag = 1; + break; + // ?man -p: preserve source modification and access times + case 'p': + pflag = 1; + break; + // ?man -s: strip the installed file's symbol table + case 's': + sflag = 1; + break; + // ?man -o:owner set the installed file's owner (name or uid) + case 'o': + owner = EARGF(usage()); + break; + // ?man -g:group set the installed file's group (name or gid) + case 'g': + group = EARGF(usage()); + break; + // ?man -m:mode set the installed file's permissions + case 'm': + modestr = EARGF(usage()); + break; + // ?man -t:dir install every source into dir + case 't': + targetdir = EARGF(usage()); + break; + default: + usage(); + } + ARGEND; + + if (argc < 1 || (dflag && (targetdir || sflag))) + usage(); + if (modestr) + mode = parsemode(modestr, 0, 0); + lookup_owner(owner, group); + + if (dflag) { + install_dirs(argv); + goto shut; + } + + if (targetdir) { + isdir = 1; + dest = targetdir; + if (Dflag && mkdirp(targetdir, 0755, 0755) < 0 && errno != EEXIST) { + weprintf("mkdir %s:", targetdir); + status = 1; + } + } else { + if (argc < 2) + usage(); + dest = argv[--argc]; + isdir = stat(dest, &st) == 0 && S_ISDIR(st.st_mode); + if (!isdir && argc > 1) + eprintf("%s: not a directory\n", dest); + } + + for (i = 0; i < argc; i++) { + if (isdir) { + char buf[PATH_MAX], nb[PATH_MAX]; + const char *base; + + estrlcpy(nb, argv[i], sizeof(nb)); + base = basename(nb); + estrlcpy(buf, dest, sizeof(buf)); + estrlcat(buf, "/", sizeof(buf)); + estrlcat(buf, base, sizeof(buf)); + install_one(argv[i], buf); + } else { + install_one(argv[i], dest); + } + } + +shut: + return fshut(stdout, "<stdout>") || status; +} diff --git a/cmd/extra/lsblk.c b/cmd/extra/lsblk.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "diskutil.h" #include "util.h" diff --git a/cmd/extra/pgrep.c b/cmd/extra/pgrep.c @@ -0,0 +1,247 @@ +/* see LICENSE file for copyright and license details */ +#include <sys/types.h> + +#include <errno.h> +#include <libgen.h> +#include <limits.h> +#include <pwd.h> +#include <regex.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "paths.h" +#include "proc.h" +#include "util.h" + +enum { + PGREP_fflag = 1 << 0, /* match against full cmdline, not just comm */ + PGREP_lflag = 1 << 1, /* list pid and comm */ + PGREP_aflag = 1 << 2, /* list pid and full cmdline */ + PGREP_xflag = 1 << 3, /* require an exact match */ + PGREP_vflag = 1 << 4, /* invert: print non-matching pids */ + PGREP_cflag = 1 << 5, /* print a match count, not the pids */ +}; + +struct hit { + pid_t pid; + unsigned long long starttime; +}; + +static int flags; +static regex_t preg; +static uid_t user_uid; +static int have_user; +static pid_t self; +static struct hit *hits; +static size_t nhits, hitscap; +static int count; + +// newest/oldest are mutually exclusive with each other and with +// printing every match as it is found, so they buffer every match +// instead of streaming it: 0 means "print as found" +enum { PGREP_NONE = 0, PGREP_NEWEST, PGREP_OLDEST }; +static int select_mode; + +static int +matches(const char *target) +{ + regmatch_t m; + int r; + + r = regexec(&preg, target, 1, &m, 0); + if (r != 0) + return 0; + if (flags & PGREP_xflag) + return m.rm_so == 0 && (size_t)m.rm_eo == strlen(target); + return 1; +} + +static void +record(pid_t pid, unsigned long long starttime) +{ + if (nhits == hitscap) { + hitscap = hitscap ? hitscap * 2 : 64; + hits = ereallocarray(hits, hitscap, sizeof(*hits)); + } + hits[nhits].pid = pid; + hits[nhits].starttime = starttime; + nhits++; +} + +static void +show(pid_t pid, const char *comm) +{ + char cmdline[BUFSIZ]; + + count++; + if (flags & PGREP_cflag) + return; + if (flags & PGREP_aflag) { + if (parsecmdline(pid, cmdline, sizeof(cmdline)) < 0) + printf("%d %s\n", pid, comm); + else + printf("%d %s\n", pid, cmdline); + } else if (flags & PGREP_lflag) { + printf("%d %s\n", pid, comm); + } else { + printf("%d\n", pid); + } +} + +static void +pgrepr(const char *file) +{ + char path[PATH_MAX], *p; + struct procstat ps; + struct procstatus pstatus; + char cmdline[BUFSIZ]; + const char *target; + pid_t pid; + int matched; + + if (strlcpy(path, file, sizeof(path)) >= sizeof(path)) + eprintf("path too long\n"); + p = basename(path); + if (pidfile(p) == 0) + return; + pid = estrtol(p, 10); + if (pid == self) + return; + if (parsestat(pid, &ps) < 0) + return; + + if (have_user) { + if (parsestatus(pid, &pstatus) < 0) + return; + if (pstatus.euid != user_uid) + return; + } + + if (flags & PGREP_fflag) { + if (parsecmdline(pid, cmdline, sizeof(cmdline)) < 0) + target = ps.comm; + else + target = cmdline; + } else { + target = ps.comm; + } + + matched = matches(target); + if (flags & PGREP_vflag) + matched = !matched; + if (!matched) + return; + + if (select_mode != PGREP_NONE) + record(pid, ps.starttime); + else + show(pid, ps.comm); +} + +static void +usage(void) +{ + eprintf("usage: %s [-flaxvc] [-u user] [-n | -o] pattern\n", argv0); +} + +// ?man pgrep: list processes by name +// ?man arguments: pattern +// ?man pgrep matches pattern, a POSIX extended regular expression, +// ?man against each running process's name (or full command line +// ?man with -f) and prints the pid of every match, one per line +int +main(int argc, char *argv[]) +{ + char namebuf[PATH_MAX]; + struct procstat ps; + struct passwd *pw; + const char *user = NULL; + size_t i, pick; + + ARGBEGIN + { + // ?man -f: match the full command line instead of just the name + case 'f': + flags |= PGREP_fflag; + break; + // ?man -l: list the matched name alongside each pid + case 'l': + flags |= PGREP_lflag; + break; + // ?man -a: list the full command line alongside each pid + case 'a': + flags |= PGREP_aflag; + break; + // ?man -x: require pattern to match the whole name or cmdline + case 'x': + flags |= PGREP_xflag; + break; + // ?man -v: invert the match, printing non-matching pids + case 'v': + flags |= PGREP_vflag; + break; + // ?man -c: print a count of matches instead of their pids + case 'c': + flags |= PGREP_cflag; + break; + // ?man -u:user only match processes owned by user (name or uid) + case 'u': + user = EARGF(usage()); + break; + // ?man -n{sel}: select only the most recently started match + case 'n': + select_mode = PGREP_NEWEST; + break; + // ?man -o{sel}: select only the oldest match + case 'o': + select_mode = PGREP_OLDEST; + break; + default: + usage(); + } + ARGEND; + + if (argc != 1) + usage(); + + if (user) { + errno = 0; + pw = getpwnam(user); + if (pw) { + user_uid = pw->pw_uid; + } else { + if (errno) + eprintf("getpwnam %s:", user); + user_uid = (uid_t)estrtonum(user, 0, UINT_MAX); + } + have_user = 1; + } + + eregcomp(&preg, argv[0], REG_EXTENDED); + + self = getpid(); + recurse_dir(ARUU_LINUX_PATH_PROC, pgrepr); + + if (select_mode != PGREP_NONE && nhits > 0) { + pick = 0; + for (i = 1; i < nhits; i++) { + if (select_mode == PGREP_NEWEST ? hits[i].starttime > hits[pick].starttime + : hits[i].starttime < hits[pick].starttime) + pick = i; + } + if (parsestat(hits[pick].pid, &ps) == 0) + strlcpy(namebuf, ps.comm, sizeof(namebuf)); + else + namebuf[0] = '\0'; + show(hits[pick].pid, namebuf); + } + + if (flags & PGREP_cflag) + printf("%d\n", count); + + if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) + return 2; + return count > 0 ? 0 : 1; +} diff --git a/cmd/extra/sync.c b/cmd/extra/sync.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> #include "arg.h" @@ -6,8 +6,8 @@ // ?man sync: flush disk cache // ?man synopsis: -// ?man The sync utility invokes sync(2) to flush all unwritten changes to disk. -// This is usually done before shutting down, rebooting or halting. ?man ## SEE +// ?man The sync utility invokes sync(2) to flush all unwritten changes to disk +// this is usually done before shutting down, rebooting or halting. ?man ## SEE // ALSO ?man fsync(2), sync(2) static void diff --git a/cmd/extra/yap/commands.c b/cmd/extra/yap/commands.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "commands.h" #include "assert.h" @@ -17,9 +17,9 @@ #include "prompt.h" #include "term.h" -static long lastcount; /* Save last count for '.' command */ -static int lastcomm; /* Save last command for '.' command */ -static int searchdir; /* Direction of last search */ +static long lastcount; /* save last count for '.' command */ +static int lastcomm; /* save last command for '.' command */ +static int searchdir; /* direction of last search */ static int do_nocomm(long cnt); static void do_search(char *str, long cnt, int dir); @@ -59,14 +59,14 @@ static int do_quit(long cnt); static int do_nocomm(long cnt) -{ /* Do nothing */ +{ /* do nothing */ (void)cnt; return 0; } int do_chkm(long cnt) -{ /* Change key map */ +{ /* change key map */ struct keymap *p; (void)cnt; @@ -80,7 +80,7 @@ do_chkm(long cnt) } /* - * Perform searches + * perform searches */ static void @@ -91,19 +91,19 @@ do_search(char *str, long cnt, int dir) if (str) { /* - * We have to get a pattern, which we have to prompt for - * with the string "str". - */ + * we have to get a pattern, which we have to prompt for + * with the string "str" + */ if ((p = readline(str)) == 0) { /* - * User cancelled command - */ + * user cancelled command + */ return; } if ((p = re_comp(p))) { /* - * There was an error in the pattern - */ + * there was an error in the pattern + */ error(p); return; } @@ -119,17 +119,17 @@ do_search(char *str, long cnt, int dir) p = getline(lineno, 0); if (interrupt) return; - if (!p) { /* End of file reached */ + if (!p) { /* end of file reached */ error("pattern not found"); return; } if (re_exec(p) && --cnt <= 0) { /* - * We found the pattern, and we found it often enough. - * Pity that we still don't know where the match is. - * We only know the linenumber. So, we just hope the - * following will at least bring it on the screen ... - */ + * we found the pattern, and we found it often enough + * pity that we still dont know where the match is + * we only know the linenumber. so, we just hope the + * following will at least bring it on the screen ... + */ (void)display(lineno, 0, pagesize, 0); (void)scrollb(2, 0); redraw(0); @@ -141,20 +141,20 @@ do_search(char *str, long cnt, int dir) static int do_fsearch(long cnt) -{ /* Forward search */ +{ /* forward search */ do_search("/", cnt, 1); return 0; } static int do_bsearch(long cnt) -{ /* Backward search */ +{ /* backward search */ do_search("?", cnt, -1); return 0; } /* - * Repeat last search in direction "dir" + * repeat last search in direction "dir" */ static int @@ -180,14 +180,14 @@ n_or_rn_search(long cnt, int dir) static int do_nsearch(long cnt) -{ /* Repeat search in same direction */ +{ /* repeat search in same direction */ n_or_rn_search(cnt, searchdir); return 0; } static int do_rnsearch(long cnt) -{ /* Repeat search in opposite direction */ +{ /* repeat search in opposite direction */ n_or_rn_search(cnt, -searchdir); return 0; } @@ -209,10 +209,10 @@ shell_command(int esc_ch, long cnt) putline(TI); if (!p) { /* - * Avoid double redraw. - * After a "startcomm", a redraw will - * take place anyway. - */ + * avoid double redraw + * after a "startcomm", a redraw will + * take place anyway + */ redraw(1); } } @@ -222,27 +222,27 @@ shell_command(int esc_ch, long cnt) static int do_shell(long cnt) -{ /* Execute a shell escape */ +{ /* execute a shell escape */ return shell_command('!', cnt); } static int do_pipe(long cnt) -{ /* Execute a shell escape */ +{ /* execute a shell escape */ return shell_command('|', cnt); } static int do_writefile(long cnt) -{ /* Write input to a file */ +{ /* write input to a file */ char *p; int fd; (void)cnt; if ((p = readline("Filename: ")) == 0 || !*p) { /* - * No file name given - */ + * no file name given + */ return 0; } if ((fd = open(p, O_CREAT | O_EXCL | O_WRONLY, 0644)) < 0) { @@ -283,14 +283,14 @@ wrt_fd(int fd) static int do_absolute(long cnt) -{ /* Go to linenumber "cnt" */ +{ /* go to linenumber "cnt" */ - if (!getline(cnt, 0)) { /* Not there or interrupt */ + if (!getline(cnt, 0)) { /* not there or interrupt */ if (!interrupt) { /* - * User did'nt give an interrupt, so the line number - * was too high. Go to the last line. - */ + * user did'nt give an interrupt, so the line number + * was too high. go to the last line + */ do_lline(cnt); } return 0; @@ -301,9 +301,9 @@ do_absolute(long cnt) static int do_visit(long cnt) -{ /* Visit a file */ +{ /* visit a file */ char *p; - static char fn[128]; /* Keep file name */ + static char fn[128]; /* keep file name */ (void)cnt; if ((p = readline("Filename: ")) == 0) { @@ -314,8 +314,8 @@ do_visit(long cnt) visitfile(fn); } else { /* - * User typed a return. Visit the current file - */ + * user typed a return. visit the current file + */ if (!(p = filenames[filecount])) { error("No current file"); return 0; @@ -328,15 +328,15 @@ do_visit(long cnt) static int do_error(long cnt) -{ /* Called when user types wrong key sequence */ +{ /* called when user types wrong key sequence */ (void)cnt; error(currmap->k_help); return 0; } /* - * Interface routine for displaying previous screen, - * depending on cflag. + * interface routine for displaying previous screen, + * depending on cflag */ static int @@ -347,17 +347,17 @@ prev_screen(int sz, int really) retval = scrollb(sz - 1, really && cflag); if (really && !cflag) { /* - * The previous call did not display anything, but at least we - * know where to start - */ + * the previous call did not display anything, but at least we + * know where to start + */ return display(scr_info.firstline, scr_info.nf, sz, 1); } return retval; } /* - * Interface routine for displaying the next screen, - * dependent on cflag. + * interface routine for displaying the next screen, + * dependent on cflag */ static int @@ -399,15 +399,15 @@ page_size(unsigned cnt) static int do_forward(long cnt) -{ /* Display next page */ +{ /* display next page */ int i; i = page_size((unsigned)cnt); if (status & EOFILE) { /* - * May seem strange, but actually a visit to the next file - * has already been done here - */ + * may seem strange, but actually a visit to the next file + * has already been done here + */ (void)display(1L, 0, i, 1); return 0; } @@ -430,11 +430,11 @@ do_backward(long cnt) return 0; } /* - * The next part is a bit clumsy. - * We want to display the last page of the previous file (for which - * a visit has already been done), but the pagesize may temporarily - * be different because the command had a count - */ + * the next part is a bit clumsy + * we want to display the last page of the previous file (for which + * a visit has already been done), but the pagesize may temporarily + * be different because the command had a count + */ temp = pagesize; pagesize = i; do_lline(cnt); @@ -444,7 +444,7 @@ do_backward(long cnt) static int do_firstline(long cnt) -{ /* Go to start of input */ +{ /* go to start of input */ (void)cnt; do_absolute(1L); return 0; @@ -452,24 +452,24 @@ do_firstline(long cnt) static int do_lline(long cnt) -{ /* Go to end of input */ +{ /* go to end of input */ int i = 0; int j = pagesize - 1; if ((cnt = to_lastline()) < 0) { /* - * Interrupted by the user - */ + * interrupted by the user + */ return 0; } /* - * Display the page such that only the last line of the page is - * a "~", independant of the pagesize - */ + * display the page such that only the last line of the page is + * a "~", independant of the pagesize + */ while (!(display(cnt, i, j, 0) & EOFILE)) { /* - * The last line could of course be very long ... - */ + * the last line could of course be very long ... + */ i += j; } (void)scrollb(j - scr_info.tail->cnt, 0); @@ -479,9 +479,9 @@ do_lline(long cnt) static int do_lf(long cnt) -{ /* Display next line, or go to line */ +{ /* display next line, or go to line */ - if (cnt) { /* Go to line */ + if (cnt) { /* go to line */ do_absolute(cnt); return 0; } @@ -491,9 +491,9 @@ do_lf(long cnt) static int do_upline(long cnt) -{ /* Display previous line, or go to line */ +{ /* display previous line, or go to line */ - if (cnt) { /* Go to line */ + if (cnt) { /* go to line */ do_absolute(cnt); return 0; } @@ -503,9 +503,9 @@ do_upline(long cnt) static int do_skiplines(long cnt) -{ /* Skip lines forwards */ +{ /* skip lines forwards */ - /* Should be interruptable ... */ + /* should be interruptable ... */ (void)scrollf((int)(cnt + maxpagesize - 1), 0); redraw(0); return 0; @@ -513,9 +513,9 @@ do_skiplines(long cnt) static int do_bskiplines(long cnt) -{ /* Skip lines backwards */ +{ /* skip lines backwards */ - /* Should be interruptable ... */ + /* should be interruptable ... */ (void)scrollb((int)(cnt + pagesize - 1), 0); redraw(0); return 0; @@ -523,7 +523,7 @@ do_bskiplines(long cnt) static int do_fscreens(long cnt) -{ /* Skip screens forwards */ +{ /* skip screens forwards */ do { if ((next_screen(pagesize, 0) & EOFILE) || interrupt) @@ -535,7 +535,7 @@ do_fscreens(long cnt) static int do_bscreens(long cnt) -{ /* Skip screens backwards */ +{ /* skip screens backwards */ do { if ((prev_screen(pagesize, 0) & START) || interrupt) @@ -557,7 +557,7 @@ scro_size(unsigned cnt) static int do_f_scroll(long cnt) -{ /* Scroll forwards */ +{ /* scroll forwards */ (void)scrollf(scro_size((unsigned)cnt), 1); return 0; @@ -565,7 +565,7 @@ do_f_scroll(long cnt) static int do_b_scroll(long cnt) -{ /* Scroll backwards */ +{ /* scroll backwards */ (void)scrollb(scro_size((unsigned)cnt), 1); return 0; @@ -573,7 +573,7 @@ do_b_scroll(long cnt) static int do_previousfile(long cnt) -{ /* Visit previous file */ +{ /* visit previous file */ if (nextfile(-(int)cnt)) { error("No (Nth) previous file"); @@ -585,7 +585,7 @@ do_previousfile(long cnt) static int do_nextfile(long cnt) -{ /* Visit next file */ +{ /* visit next file */ if (nextfile((int)cnt)) { error("No (Nth) next file"); @@ -603,7 +603,7 @@ do_quit(long cnt) } /* - * The next array is initialized, sorted on the first element of the structs, + * the next array is initialized, sorted on the first element of the structs, * so that we can perform binary search */ struct commands commands[] = { @@ -658,8 +658,8 @@ struct commands commands[] = { }; /* - * Lookup string "s" in the commands array, and return index. - * return 0 if not found. + * lookup string "s" in the commands array, and return index + * return 0 if not found */ int @@ -671,8 +671,8 @@ lookup(char *s) u = &commands[sizeof(commands) / sizeof(*u) - 1]; do { /* - * Perform binary search - */ + * perform binary search + */ m = l + (u - l) / 2; if (strcmp(s, m->c_cmd) > 0) l = m + 1; @@ -684,10 +684,10 @@ lookup(char *s) return 0; } -/*ARGSUSED*/ +/* ARGSUSED */ static int do_lcomm(long cnt) -{ /* Repeat last command */ +{ /* repeat last command */ (void)cnt; if (!lastcomm) { @@ -699,7 +699,7 @@ do_lcomm(long cnt) } /* - * Execute a command, with optional count "count". + * execute a command, with optional count "count" */ void @@ -713,15 +713,15 @@ do_comm(int comm, long count) flags = pcomm->c_flags; /* - * Check the command. - * If the last line of the file is displayed and the command goes - * forwards and does'nt have the ability to go to the next file, it - * is an error. - * If the first line of the file is displayed and the command goes - * backwards and does'nt have the ability to go to the previous file, - * it is an error. - * Also check wether we need the next or previous file. If so, get it. - */ + * check the command + * if the last line of the file is displayed and the command goes + * forwards and does'nt have the ability to go to the next file, it + * is an error + * if the first line of the file is displayed and the command goes + * backwards and does'nt have the ability to go to the previous file, + * it is an error + * also check wether we need the next or previous file. if so, get it + */ if ((status & EOFILE) && (flags & AHEAD)) { if (qflag || !(flags & TONEXTFILE)) return; @@ -735,8 +735,8 @@ do_comm(int comm, long count) quit(); } /* - * Does the command stick around for LASTCOMM? - */ + * does the command stick around for LASTCOMM? + */ if (flags & STICKY) { lastcomm = comm; lastcount = count; @@ -746,8 +746,8 @@ do_comm(int comm, long count) count = 1; } else { /* - * Does the command adapt the screensize? - */ + * does the command adapt the screensize? + */ if (flags & SCREENSIZE_ADAPT) { temp = maxpagesize; if ((unsigned)count < (unsigned)temp) { @@ -760,8 +760,8 @@ do_comm(int comm, long count) pagesize = temp; } /* - * Does the command adapt the scrollsize? - */ + * does the command adapt the scrollsize? + */ if (flags & SCROLLSIZE_ADAPT) { temp = maxpagesize - 1; if ((unsigned)count < (unsigned)temp) { @@ -772,7 +772,7 @@ do_comm(int comm, long count) } } /* - * Now execute the command. - */ + * now execute the command + */ (*(pcomm->c_func))(count); } diff --git a/cmd/extra/yap/display.c b/cmd/extra/yap/display.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "display.h" #include "assert.h" @@ -28,7 +28,7 @@ static int decode_cell(const char *s, const char **next, int *width, int *is_u int wcwidth(wchar_t wc); /* - * Fill n lines of the screen, each with "str". + * fill n lines of the screen, each with "str" */ static void @@ -40,7 +40,7 @@ fillscr(char *str, int n) } /* - * Skip "n" screenlines of line "p", and return what's left of it. + * skip "n" screenlines of line "p", and return what's left of it */ static char * @@ -54,9 +54,9 @@ skiplines(char *p, int n) } /* - * Redraw screen. - * "n" = 1 if it is a real redraw, 0 if one page must be displayed. - * It is also called when yap receives a stop signal. + * redraw screen + * "n" = 1 if it is a real redraw, 0 if one page must be displayed + * it is also called when yap receives a stop signal */ void @@ -73,10 +73,10 @@ redraw(int n) } /* - * Compute return value for the routines "display" and "scrollf". - * This return value indicates wether we are at the end of file - * or at the start, or both. - * "s" contains that part of the last line that was not displayed. + * compute return value for the routines "display" and "scrollf" + * this return value indicates wether we are at the end of file + * or at the start, or both + * "s" contains that part of the last line that was not displayed */ static int @@ -97,10 +97,10 @@ compretval(const char *s) } /* - * Display nlines, starting at line n, not displaying the first - * nd screenlines of n. - * If reallydispl = 0, the actual displaying is not performed, - * only the computing associated with it is done. + * display nlines, starting at line n, not displaying the first + * nd screenlines of n + * if reallydispl = 0, the actual displaying is not performed, + * only the computing associated with it is done */ int @@ -109,11 +109,11 @@ display(long n, int nd, int nlines, int reallydispl) struct scr_info *s = &scr_info; char *p; /* pointer to line to be displayed */ - if (startcomm) { /* No displaying on a command from the - * yap command line. In this case, displaying - * will be done after executing the command, - * by a redraw. - */ + if (startcomm) { /* no displaying on a command from the + * yap command line. in this case, displaying + * will be done after executing the command, + * by a redraw + */ reallydispl = 0; } if (!n) { @@ -135,8 +135,8 @@ display(long n, int nd, int nlines, int reallydispl) } } /* - * Now, do computations and display - */ + * now, do computations and display + */ s->currentpos = 0; s->nf = nd; s->head = s->tail; @@ -145,15 +145,15 @@ display(long n, int nd, int nlines, int reallydispl) p = skiplines(getline(n, 1), nd); while (nlines && p) { /* - * While there is room, - * and there is something left to display ... - */ + * while there is room, + * and there is something left to display ... + */ (s->tail->cnt)++; nlines--; if (*(p = do_line(p, reallydispl)) == '\0') { /* - * File-line finished, get next one ... - */ + * file-line finished, get next one ... + */ p = getline(++n, 1); if (nlines && p) { s->tail = s->tail->next; @@ -173,7 +173,7 @@ display(long n, int nd, int nlines, int reallydispl) } /* - * Scroll forwards n lines. + * scroll forwards n lines */ int @@ -185,37 +185,37 @@ scrollf(int n, int reallydispl) int i; /* - * First, find out how many screenlines of the last line were already - * on the screen, and possibly above it. - */ + * first, find out how many screenlines of the last line were already + * on the screen, and possibly above it + */ if (n <= 0 || (status & EOFILE)) return status; if (startcomm) reallydispl = 0; /* - * Find out where to begin displaying - */ + * find out where to begin displaying + */ i = s->tail->cnt; if ((ll = s->lastline) == s->firstline) i += s->nf; p = skiplines(getline(ll, 1), i); /* - * Now, place the cursor at the first free line - */ + * now, place the cursor at the first free line + */ if (reallydispl && !stupid) { clrbline(); mgoto(s->currentpos); } /* - * Now display lines, keeping track of which lines are on the screen. - */ - while (n-- > 0) { /* There are still rows to be displayed */ - if (!*p) { /* End of line, get next one */ + * now display lines, keeping track of which lines are on the screen + */ + while (n-- > 0) { /* there are still rows to be displayed */ + if (!*p) { /* end of line, get next one */ if (!(p = getline(++ll, 1))) { /* - * No lines left. At end of file - */ + * no lines left. at end of file + */ break; } s->tail = s->tail->next; @@ -224,16 +224,16 @@ scrollf(int n, int reallydispl) } if (s->currentpos >= maxpagesize) { /* - * No room, delete first screen-line - */ + * no room, delete first screen-line + */ s->currentpos--; s->nf++; if (--(s->head->cnt) == 0) { /* - * The first file-line on the screen is wiped - * out completely; update administration - * accordingly. - */ + * the first file-line on the screen is wiped + * out completely; update administration + * accordingly + */ s->nf = 0; s->head = s->head->next; assert(s->head->cnt > 0); @@ -246,14 +246,14 @@ scrollf(int n, int reallydispl) } /* - * Scroll back n lines + * scroll back n lines */ int scrollb(int n, int reallydispl) { struct scr_info *s = &scr_info; - char *p; /* Holds string to be displayed */ + char *p; /* holds string to be displayed */ int i; int count; long ln; /* a line number */ @@ -261,8 +261,8 @@ scrollb(int n, int reallydispl) int cannotscroll; /* stupid or no insert-line */ /* - * First, find out where to start - */ + * first, find out where to start + */ if ((count = n) <= 0 || (status & START)) return status; if (startcomm) @@ -270,31 +270,31 @@ scrollb(int n, int reallydispl) cannotscroll = stupid || (!*AL && !*SR); ln = s->firstline; nodispl = s->nf; - while (count) { /* While scrolling back ... */ + while (count) { /* while scrolling back ... */ i = nodispl; if (i) { /* - * There were screen-lines of s->firstline that were not - * displayed. - * We can use them now, but only "count" of them. - */ + * there were screen-lines of s->firstline that were not + * displayed + * we can use them now, but only "count" of them + */ if (i > count) i = count; s->currentpos += i; nodispl -= i; count -= i; - } else { /* Get previous line */ + } else { /* get previous line */ if (ln == 1) - break; /* isn't there ... */ + break; /* isnt there ... */ p = getline(--ln, 1); /* - * Make it the first line of the screen and compute - * how many screenlines it takes. These lines are not - * displayed, but nodispl is set to this count, so - * that it will be nonzero next time around - */ + * make it the first line of the screen and compute + * how many screenlines it takes. these lines are not + * displayed, but nodispl is set to this count, so + * that it will be nonzero next time around + */ nodispl = 0; - do { /* Find out how many screenlines */ + do { /* find out how many screenlines */ nodispl++; p = skiplines(p, 1); } while (*p); @@ -306,33 +306,33 @@ scrollb(int n, int reallydispl) if (reallydispl && hardcopy) i = n; /* - * Now that we know where to start, we can use "display" to do the - * rest of the computing for us, and maybe even the displaying ... - */ + * now that we know where to start, we can use "display" to do the + * rest of the computing for us, and maybe even the displaying ... + */ i = display(ln, nodispl, i, reallydispl && cannotscroll); if (cannotscroll || !reallydispl) { /* - * Yes, "display" did the displaying, or we did'nt have to - * display at all. - * I like it, but the user obviously does not. - * Let him buy another (smarter) terminal ... - */ + * yes, "display" did the displaying, or we did'nt have to + * display at all + * i like it, but the user obviously does not + * let him buy another (smarter) terminal ... + */ return i; } /* - * Now, all we have to do is the displaying. And we are dealing with - * a smart terminal (it can insert lines or scroll back). - */ + * now, all we have to do is the displaying. and we are dealing with + * a smart terminal (it can insert lines or scroll back) + */ home(); /* - * Insert lines all at once - */ + * insert lines all at once + */ for (i = n; i; i--) { if (DB && *CE) { /* - * Grumble..., terminal retains lines below, so we have - * to clear the lines that we push off the screen - */ + * grumble..., terminal retains lines below, so we have + * to clear the lines that we push off the screen + */ clrbline(); home(); } @@ -354,8 +354,8 @@ scrollb(int n, int reallydispl) } /* - * Process a line. - * If reallydispl > 0 then display it. + * process a line + * if reallydispl > 0 then display it */ static char * @@ -397,13 +397,13 @@ do_line(char *str, int reallydispl) } if (uc < ' ' && (cell_len = match(str, &c2, sppat)) > 0) { /* - * We found a string that matches, and thus must be - * echoed literally - */ + * we found a string that matches, and thus must be + * echoed literally + */ if ((pos - c2) <= 0) { /* - * It did not fit - */ + * it did not fit + */ break; } pos -= c2; @@ -438,8 +438,8 @@ do_line(char *str, int reallydispl) } do_ul = 1; /* - * Find underline sequences ... - */ + * find underline sequences ... + */ if (is_underscore && *cursor == '\b' && *(cursor + 1) != '\0') { cell_start = cursor + 1; cell_len = decode_cell(cell_start, &next, &cell_width, &is_underscore); @@ -519,9 +519,9 @@ do_line(char *str, int reallydispl) pos -= cell_width; if (reallydispl && do_ul && *UC && cell_width == 1 && pos > 0) { /* - * Underlining apparently is done one - * character at a time. - */ + * underlining apparently is done one + * character at a time + */ flush_display_buffer(buf, &p); backspace(); underchar(); @@ -537,13 +537,13 @@ do_line(char *str, int reallydispl) putline("\r\n"); } /* - * The next should be here! I.e. it may not be before printing - * the newline. This has to do with XN. We don't know exactly - * WHEN the terminal will stop ignoring the newline. - * I have for example a terminal (Ampex a230) that will - * continue to ignore the newline after a clear to end of line - * sequence, but not after an end_underline sequence. - */ + * the next should be here! i.e. it may not be before printing + * the newline. this has to do with XN. we dont know exactly + * WHEN the terminal will stop ignoring the newline + * i have for example a terminal (ampex a230) that will + * continue to ignore the newline after a clear to end of line + * sequence, but not after an end_underline sequence + */ if (lastmode) { end_underline(); } @@ -628,7 +628,7 @@ decode_cell(const char *s, const char **next, int *width, int *is_underscore) /* ARGSUSED */ int setmark(long cnt) -{ /* Set a mark on the current page */ +{ /* set a mark on the current page */ struct scr_info *p = &scr_info; (void)cnt; @@ -640,7 +640,7 @@ setmark(long cnt) /* ARGSUSED */ int tomark(long cnt) -{ /* Go to the mark */ +{ /* go to the mark */ struct scr_info *p = &scr_info; (void)cnt; @@ -651,7 +651,7 @@ tomark(long cnt) /* ARGSUSED */ int exgmark(long cnt) -{ /* Exchange mark and current page */ +{ /* exchange mark and current page */ struct scr_info *p = &scr_info; long svfirst; int svnf; @@ -667,7 +667,7 @@ exgmark(long cnt) void d_clean() -{ /* Clean up */ +{ /* clean up */ struct scr_info *p = &scr_info; p->savnf = 0; diff --git a/cmd/extra/yap/getcomm.c b/cmd/extra/yap/getcomm.c @@ -1,7 +1,7 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ /* - * Command reader, also executes shell escapes + * command reader, also executes shell escapes */ #include "getcomm.h" @@ -23,8 +23,8 @@ static int killchar(int c); static void sigquit(int signo); /* - * Read a line from the terminal, doing line editing. - * The parameter s contains the prompt for the line. + * read a line from the terminal, doing line editing + * the parameter s contains the prompt for the line */ char * @@ -41,19 +41,19 @@ readline(char *s) while ((ch = getch()) != '\n' && ch != '\r') { if (ch == -1) { /* - * Can only occur because of an interrupted read. - */ + * can only occur because of an interrupted read + */ ch = erasech; interrupt = 0; } if (ch == erasech) { /* - * Erase last char - */ + * erase last char + */ if (p == buf) { /* - * There was none, so return - */ + * there was none, so return + */ return (char *)0; } pos -= killchar(*--p); @@ -62,8 +62,8 @@ readline(char *s) } if (ch == killch) { /* - * Erase the whole line - */ + * erase the whole line + */ if (!(p > buf && *(p - 1) == '\\')) { while (p > buf) { pos -= killchar(*--p); @@ -74,9 +74,9 @@ readline(char *s) } if (p > &buf[78] || pos >= COLS - 2) { /* - * Line does not fit. - * Simply refuse to make it any longer - */ + * line does not fit + * simply refuse to make it any longer + */ pos -= killchar(*--p); } *p++ = ch; @@ -95,7 +95,7 @@ readline(char *s) } /* - * Erase a character from the command line. + * erase a character from the command line */ static int @@ -112,7 +112,7 @@ killchar(int c) } /* - * Do a shell escape, after expanding '%' and '!'. + * do a shell escape, after expanding '%' and '!' */ void @@ -134,14 +134,14 @@ shellescape(char *p, int esc_char) cnt = 253; while (*p) { /* - * expand command - */ + * expand command + */ switch (*p++) { case '!': /* - * An unescaped ! expands to the previous - * command, but disappears if there is none - */ + * an unescaped ! expands to the previous + * command, but disappears if there is none + */ if (lastc != '\\') { if (*previous) { id = strlen(previous); @@ -156,9 +156,9 @@ shellescape(char *p, int esc_char) continue; case '%': /* - * An unescaped % will expand to the current - * filename, but disappears is there is none - */ + * an unescaped % will expand to the current + * filename, but disappears is there is none + */ if (lastc != '\\') { if (nopipe) { id = strlen(currentfile); @@ -184,8 +184,8 @@ shellescape(char *p, int esc_char) *p2 = '\0'; if (!stupid) { /* - * Display expanded command - */ + * display expanded command + */ cputline(comm); putline("\r\n"); } @@ -225,8 +225,8 @@ shellescape(char *p, int esc_char) } while ((lastc = wait((int *)0)) != id && lastc >= 0) { /* - * Wait for child, making sure it is the one we expected ... - */ + * wait for child, making sure it is the one we expected ... + */ } (void)signal(SIGINT, catchdel); (void)signal(SIGQUIT, sigquit); @@ -244,7 +244,7 @@ sigquit(int signo) } /* - * Get all those commands ... + * get all those commands ... */ int @@ -268,14 +268,14 @@ getcomm(long *plong) for (;;) { if (c == -1) { /* - * This should never happen, but it does, - * when the user gives a TSTP signal (^Z) or - * an interrupt while the program is trying - * to read a character from the terminal. - * In this case, the read is interrupted, so - * we end up here. - * Right, we will have to read again. - */ + * this should never happen, but it does, + * when the user gives a TSTP signal (^z) or + * an interrupt while the program is trying + * to read a character from the terminal + * in this case, the read is interrupted, so + * we end up here + * right, we will have to read again + */ if (interrupt) return 1; break; @@ -284,15 +284,15 @@ getcomm(long *plong) *p = 0; if ((i = match(buf, &j, currmap->k_mach)) > 0) { /* - * The key sequence matched. We have a command - */ + * the key sequence matched. we have a command + */ return j; } if (i == 0) return 0; /* - * We have a prefix of a command. - */ + * we have a prefix of a command + */ assert(i == FSM_ISPREFIX); c = getch(); } diff --git a/cmd/extra/yap/getline.c b/cmd/extra/yap/getline.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "getline.h" #include "assert.h" @@ -15,12 +15,12 @@ #define CHUNK 50 /* # of blockheaders allocated at a time */ /* - * Blocks are kept in an array in line-number order. Each block stores the raw - * text and the offsets of the lines parsed from it. + * blocks are kept in an array in line-number order. each block stores the raw + * text and the offsets of the lines parsed from it */ struct block { - int b_flags; /* Contains the following flags: */ + int b_flags; /* contains the following flags: */ #define PARTLY 02 /* block not filled completely (eof) */ long b_end; /* line number of last line in block */ char *b_info; /* the block */ @@ -44,16 +44,16 @@ new_block() if (!maxblocklist || !(pblock->b_flags & PARTLY)) { /* - * There is no last block, or it was filled completely, - * so allocate a new blockheader. - */ + * there is no last block, or it was filled completely, + * so allocate a new blockheader + */ int siz; pblock = blocklist; if (maxblocklist == topblocklist) { /* - * No blockheaders left. Allocate new ones - */ + * no blockheaders left. allocate new ones + */ siz = topblocklist - pblock; blocklist = pblock = (struct block *)re_alloc((char *)pblock, (unsigned)((siz + CHUNK) * sizeof(*pblock))); @@ -67,8 +67,8 @@ new_block() } if (!siz) { /* - * Create dummy header cell. - */ + * create dummy header cell + */ maxblocklist++; } } @@ -79,9 +79,9 @@ new_block() } /* - * Return the block in which line 'n' of the current file can be found. - * If "disable_interrupt" = 0, the call may be interrupted, in which - * case it returns 0. + * return the block in which line 'n' of the current file can be found + * if "disable_interrupt" = 0, the call may be interrupted, in which + * case it returns 0 */ static struct block * @@ -91,17 +91,17 @@ getblock(long n, int disable_interrupt) if (stdf < 0) { /* - * Not file descriptor, so return end of file - */ + * not file descriptor, so return end of file + */ return 0; } pblock = maxblocklist - 1; if (n < lastreadline || (n == lastreadline && !(pblock->b_flags & PARTLY))) { /* - * The line asked for has been read already. - * Perform binary search in the blocklist to find the block - * where it's in. - */ + * the line asked for has been read already + * perform binary search in the blocklist to find the block + * where its in + */ struct block *min, *mid; min = blocklist + 1; @@ -112,13 +112,13 @@ getblock(long n, int disable_interrupt) } else pblock = mid; } while (min < pblock); - /* Found, pblock is now a reference to the block wanted */ + /* found, pblock is now a reference to the block wanted */ return pblock; } /* - * The line was'nt read yet, so read blocks until found - */ + * the line was'nt read yet, so read blocks until found + */ for (;;) { if (interrupt && !disable_interrupt) return 0; @@ -128,9 +128,9 @@ getblock(long n, int disable_interrupt) } if (pblock->b_flags & PARTLY) { /* - * We did not find it, and the last block could not be - * read completely, so return 0; - */ + * we did not find it, and the last block could not be + * read completely, so return 0; + */ return 0; } } @@ -149,7 +149,7 @@ getline(long n, int disable_interrupt) } /* - * Find the last line of the input, and return its number + * find the last line of the input, and return its number */ long @@ -158,10 +158,10 @@ to_lastline() for (;;) { if (!getline(lastreadline + 1, 0)) { /* - * "lastreadline" always contains the linenumber of - * the last line read. So, if the call to getline - * succeeds, "lastreadline" is affected - */ + * "lastreadline" always contains the linenumber of + * the last line read. so, if the call to getline + * succeeds, "lastreadline" is affected + */ if (interrupt) return -1L; return lastreadline; @@ -183,8 +183,8 @@ alloc(unsigned size) } /* - * Re-allocate the memorychunk pointed to by ptr, to let it - * grow or shrink. + * re-allocate the memorychunk pointed to by ptr, to let it + * grow or shrink */ static char * @@ -203,53 +203,53 @@ static char *saved; static long filldegree; /* - * Try to read the block indicated by pblock + * try to read the block indicated by pblock */ static void nextblock(struct block *pblock) { - char *c, /* Run through pblock->b_info */ + char *c, /* run through pblock->b_info */ *c1; /* indicate end of pblock->b_info */ int *poff; /* pointer in line-offset list */ int cnt; /* # of characters read */ - unsigned siz; /* Size of allocated line-offset list */ + unsigned siz; /* size of allocated line-offset list */ static unsigned savedsiz; /* saved "siz" */ static int *savedpoff; /* saved "poff" */ static char *savedc1; /* saved "c1" */ if (pblock->b_flags & PARTLY) { /* - * The block was already partly filled. Initialize locals - * accordingly - */ + * the block was already partly filled. initialize locals + * accordingly + */ poff = savedpoff; siz = savedsiz; pblock->b_flags = 0; c1 = savedc1; if (c1 == pblock->b_info || *(c1 - 1)) { /* - * We had incremented "lastreadline" temporarily, - * because the last line could not be completely read - * last time we tried. Undo this increment - */ + * we had incremented "lastreadline" temporarily, + * because the last line could not be completely read + * last time we tried. undo this increment + */ poff--; --lastreadline; } } else { if (saved) { /* - * There were leftovers from the previous block - */ + * there were leftovers from the previous block + */ pblock->b_info = saved; c1 = savedc1; saved = 0; - } else { /* Allocate new block */ + } else { /* allocate new block */ pblock->b_info = c1 = alloc(BLOCKSIZE + 1); } /* - * Allocate some space for line-offsets - */ + * allocate some space for line-offsets + */ pblock->b_offs = poff = (int *)alloc((unsigned)(100 * sizeof(int))); siz = 99; *poff++ = 0; @@ -257,13 +257,13 @@ nextblock(struct block *pblock) c = c1; for (;;) { /* - * Read loop - */ + * read loop + */ cnt = read(stdf, c1, BLOCKSIZE - (c1 - pblock->b_info)); if (cnt < 0) { /* - * Interrupted read - */ + * interrupted read + */ if (errno == EINTR) continue; error("Could not read input file"); @@ -279,22 +279,22 @@ nextblock(struct block *pblock) assert(c <= c1); while (c < c1) { /* - * Now process the block - */ + * now process the block + */ if (*c == '\n') { /* - * Newlines are replaced by '\0', so that "getline" - * can deliver one line at a time - */ + * newlines are replaced by '\0', so that "getline" + * can deliver one line at a time + */ *c = 0; lastreadline++; /* - * Remember the line-offset - */ + * remember the line-offset + */ if (poff == pblock->b_offs + siz) { /* - * No space for it, allocate some more - */ + * no space for it, allocate some more + */ pblock->b_offs = (int *)re_alloc((char *)pblock->b_offs, (unsigned)((siz + 51) * sizeof(int))); poff = pblock->b_offs + siz; @@ -308,15 +308,15 @@ nextblock(struct block *pblock) *c = 0; if (c != pblock->b_info && *(c - 1) != 0) { /* - * The last line read does not end with a newline, so add one - */ + * the last line read does not end with a newline, so add one + */ lastreadline++; *poff++ = c - pblock->b_info + 1; if (!(pblock->b_flags & PARTLY) && *(poff - 2) != 0) { /* - * Save the started line; it will be in the next block. - * Remove the newline we added just now. - */ + * save the started line; it will be in the next block + * remove the newline we added just now + */ saved = c1 = alloc(BLOCKSIZE + 1); c = pblock->b_info + *(--poff - 1); while (*c) @@ -329,9 +329,9 @@ nextblock(struct block *pblock) pblock->b_end = lastreadline; if (pblock->b_flags & PARTLY) { /* - * Take care, that we can call "nextblock" again, to fill in - * the rest of this block - */ + * take care, that we can call "nextblock" again, to fill in + * the rest of this block + */ savedsiz = siz; savedpoff = poff; savedc1 = c; @@ -347,8 +347,8 @@ nextblock(struct block *pblock) } /* - * Called after processing a file. - * Free all core. + * called after processing a file + * free all core */ void @@ -378,7 +378,7 @@ do_clean() } /* - * Get a character. If possible, do some workahead. + * get a character. if possible, do some workahead */ int @@ -391,17 +391,17 @@ getch() flush(); if (startcomm) { /* - * Command line option command - */ + * command line option command + */ if (*startcomm) return *startcomm++; return '\n'; } if (stdf >= 0) { /* - * Make reads from the terminal non-blocking, so that - * we can see if the user typed something - */ + * make reads from the terminal non-blocking, so that + * we can see if the user typed something + */ flags = fcntl(0, F_GETFL, 0); if (flags != -1 && fcntl(0, F_SETFL, flags | O_NONBLOCK) != -1) { bytes_read = 0; @@ -417,18 +417,18 @@ getch() (nopipe || (fstat(stdf, &buf) >= 0 && buf.st_size > 0))) { /* - * Do some read ahead, after making sure there - * is input and the user did not type a command - */ + * do some read ahead, after making sure there + * is input and the user did not type a command + */ new_block(); } (void)fcntl(0, F_SETFL, flags); if (bytes_read < 0) { /* - * Could this have happened? - * I'm not sure, because the read is - * nonblocking. Can it be interrupted then? - */ + * could this have happened? + * i'm not sure, because the read is + * nonblocking. can it be interrupted then? + */ return -1; } if (bytes_read > 0) @@ -452,7 +452,7 @@ getch() } /* - * Get the position of line "ln" in the file. + * get the position of line "ln" in the file */ long diff --git a/cmd/extra/yap/help.c b/cmd/extra/yap/help.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "help.h" #include "commands.h" @@ -12,14 +12,14 @@ #include "prompt.h" #include "term.h" -static int h_cnt; /* Count # of lines */ -static struct state *origin; /* Keep track of startstate */ +static int h_cnt; /* count # of lines */ +static struct state *origin; /* keep track of startstate */ /* - * Print a key sequence. - * We arrived at an endstate. The s_next link in the state structure now + * print a key sequence + * we arrived at an endstate. the s_next link in the state structure now * leads us from "origin" to the current state, so that we can print the key - * sequence easily. + * sequence easily */ static void @@ -29,15 +29,15 @@ pr_comm() char *pb; int c; char buf[30]; - int i = 0; /* How many characters printed? */ + int i = 0; /* how many characters printed? */ pb = buf; for (;;) { c = p->s_char & 0177; if (c < ' ' || c == 0177) { /* - * Will take an extra position - */ + * will take an extra position + */ i++; } *pb++ = c; @@ -54,9 +54,9 @@ pr_comm() } /* - * Print out a description of the keymap. This is done, by temporarily using + * print out a description of the keymap. this is done, by temporarily using * the s_next field in the state structure indicate the state matching the - * next character, so that we can walk from "origin" to an endstate. + * next character, so that we can walk from "origin" to an endstate */ static void @@ -68,13 +68,13 @@ pr_mach(struct state *currstate, struct state *back) if (interrupt) break; if (back) { - save = back->s_next; /* Save original link */ + save = back->s_next; /* save original link */ back->s_next = currstate; } if (!currstate->s_match) { /* - * End state, print command - */ + * end state, print command + */ pr_comm(); putline(commands[currstate->s_cnt].c_descr); putline("\r\n"); @@ -92,10 +92,10 @@ pr_mach(struct state *currstate, struct state *back) } } -/*ARGSUSED*/ +/* ARGSUSED */ int do_help(long i) -{ /* The help command */ +{ /* the help command */ (void)i; startcomm = 0; diff --git a/cmd/extra/yap/keys.c b/cmd/extra/yap/keys.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "keys.h" #include "assert.h" @@ -17,13 +17,13 @@ red=^L:rep=.:bps=Z:bss=b:fps=z:fss=d:shl=!:tom=':top=\\^:vis=e:\ wrf=w:qui=q:qui=Q:mar=m:pip=|"; /* - * Construct an error message and return it + * construct an error message and return it */ static char * kerror(char *key, char *emess) { - static char ebuf[80]; /* Room for the error message */ + static char ebuf[80]; /* room for the error message */ (void)strcpy(ebuf, key); (void)strcat(ebuf, emess); @@ -31,41 +31,41 @@ kerror(char *key, char *emess) } /* - * Compile a keymap into commtable. Returns an error message if there + * compile a keymap into commtable. returns an error message if there * is one */ static char * compile(char *map, struct keymap *commtable) { - char *mark; /* Indicates start of mnemonic */ - char *c; /* Runs through buf */ + char *mark; /* indicates start of mnemonic */ + char *c; /* runs through buf */ int temp; char *escapes = commtable->k_esc; - char buf[10]; /* Will hold key sequence */ + char buf[10]; /* will hold key sequence */ (void)strcpy(commtable->k_help, "Illegal command"); while (*map) { c = buf; - mark = map; /* Start of mnemonic */ + mark = map; /* start of mnemonic */ while (*map && *map != '=') { map++; } if (!*map) { /* - * Mnemonic should end with '=' - */ + * mnemonic should end with '=' + */ return kerror(mark, ": Syntax error"); } *map++ = 0; while (*map) { /* - * Get key sequence - */ + * get key sequence + */ if (*map == ':') { /* - * end of key sequence - */ + * end of key sequence + */ map++; break; } @@ -73,8 +73,8 @@ compile(char *map, struct keymap *commtable) if (*c == '^' || *c == '\\') { if (!(temp = *map++)) { /* - * Escape not followed by a character - */ + * escape not followed by a character + */ return kerror(mark, ": Syntax error"); } if (*c == '^') { @@ -109,9 +109,9 @@ compile(char *map, struct keymap *commtable) assert(temp == FSM_OKE); if (!strcmp(mark, "hlp")) { /* - * Create an error message to be given when the user - * types an illegal command - */ + * create an error message to be given when the user + * types an illegal command + */ (void)strcpy(commtable->k_help, "Type "); (void)strcat(commtable->k_help, buf); (void)strcat(commtable->k_help, " for help"); @@ -122,7 +122,7 @@ compile(char *map, struct keymap *commtable) } /* - * Initialize the keymaps + * initialize the keymaps */ void @@ -133,20 +133,20 @@ initkeys() currmap = &xx[0]; othermap = &xx[1]; - p = compile(defaultmap, currmap); /* Compile default map */ + p = compile(defaultmap, currmap); /* compile default map */ assert(p == (char *)0); p = getenv("YAPKEYS"); if (p) { if (!(p = compile(p, othermap))) { /* - * No errors in user defined keymap. So, use it - */ + * no errors in user defined keymap. so, use it + */ do_chkm(0L); return; } error(p); } - othermap = 0; /* No other keymap */ + othermap = 0; /* no other keymap */ } int @@ -162,10 +162,10 @@ is_escape(int c) } static char keyset[16]; /* bitset indicating which keys are - * used - */ + * used + */ /* - * Mark key "key" as used + * mark key "key" as used */ void diff --git a/cmd/extra/yap/machine.c b/cmd/extra/yap/machine.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "machine.h" #include "assert.h" @@ -7,22 +7,22 @@ #include <ctype.h> /* - * Add part of finite state machine to recognize the string s. + * add part of finite state machine to recognize the string s */ static int addtomach(char *s, int cnt, struct state **list) { struct state *l; - int i = FSM_OKE; /* Return value */ + int i = FSM_OKE; /* return value */ int j; for (;;) { l = *list; if (!l) { /* - * Create new list element - */ + * create new list element + */ *list = l = (struct state *)alloc(sizeof(*l)); l->s_char = *s; l->s_endstate = 0; @@ -31,21 +31,21 @@ addtomach(char *s, int cnt, struct state **list) } if (l->s_char == *s) { /* - * Continue with next character - */ + * continue with next character + */ if (!*++s) { /* - * No next character - */ + * no next character + */ j = l->s_endstate; l->s_endstate = 1; if (l->s_match || j) { /* - * If the state already was an endstate, - * or has a successor, the currently - * added string is a prefix of an - * already recognized string - */ + * if the state already was an endstate, + * or has a successor, the currently + * added string is a prefix of an + * already recognized string + */ return FSM_ISPREFIX; } l->s_cnt = cnt; @@ -53,10 +53,10 @@ addtomach(char *s, int cnt, struct state **list) } if (l->s_endstate) { /* - * In this case, the currently added string has - * a prefix that is an already recognized - * string. - */ + * in this case, the currently added string has + * a prefix that is an already recognized + * string + */ i = FSM_HASPREFIX; } list = &(l->s_match); @@ -68,7 +68,7 @@ addtomach(char *s, int cnt, struct state **list) } /* - * Add a string to the FSM. + * add a string to the FSM */ int @@ -81,26 +81,26 @@ addstring(char *s, int cnt, struct state **machine) } /* - * Match string s with the finite state machine. - * If it matches, the number of characters actually matched is returned, - * and the count is put in the word pointed to by i. - * If the string is a prefix of a string that could be matched, - * FSM_ISPREFIX is returned. Otherwise, 0 is returned. + * match string s with the finite state machine + * if it matches, the number of characters actually matched is returned, + * and the count is put in the word pointed to by i + * if the string is a prefix of a string that could be matched, + * FSM_ISPREFIX is returned. otherwise, 0 is returned */ int match(char *s, int *i, struct state *mach) { - char *s1 = s; /* Walk through string */ + char *s1 = s; /* walk through string */ struct state *mach1 = 0; - /* Keep track of previous state */ + /* keep track of previous state */ while (mach && *s1) { if (mach->s_char == *s1) { /* - * Current character matches. Carry on with next - * character and next state - */ + * current character matches. carry on with next + * character and next state + */ mach1 = mach; mach = mach->s_match; s1++; @@ -110,21 +110,21 @@ match(char *s, int *i, struct state *mach) } if (!mach1) { /* - * No characters matched - */ + * no characters matched + */ return 0; } if (mach1->s_endstate) { /* - * The string matched - */ + * the string matched + */ *i = mach1->s_cnt; return s1 - s; } if (!*s1) { /* - * The string matched a prefix - */ + * the string matched a prefix + */ return FSM_ISPREFIX; } return 0; diff --git a/cmd/extra/yap/main.c b/cmd/extra/yap/main.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "main.h" #include "commands.h" @@ -53,12 +53,12 @@ main(int argc, char **argv) } /* - * Open temporary file for reading and writing. - * Panic if it fails + * open temporary file for reading and writing + * panic if it fails */ /* - * Collect initializing stuff here. + * collect initializing stuff here */ static int @@ -66,17 +66,17 @@ initialize(int x) { if (!(nopipe = x)) { /* - * Reading from pipe - */ + * reading from pipe + */ if (isatty(0)) { return 1; } - stdf = dup(0); /* Duplicate file descriptor of input */ + stdf = dup(0); /* duplicate file descriptor of input */ if (no_tty) return 0; /* - * Make sure standard input is from the terminal. - */ + * make sure standard input is from the terminal + */ (void)close(0); if (open("/dev/tty", O_RDONLY, 0) != 0) { putline("Couldn't open terminal\n"); @@ -87,9 +87,9 @@ initialize(int x) if (no_tty) return 0; /* - * Handle signals. - * Catch QUIT, DELETE and ^Z - */ + * handle signals + * catch QUIT, DELETE and ^z + */ (void)signal(SIGQUIT, SIG_IGN); (void)signal(SIGINT, catchdel); ini_terminal(); @@ -120,8 +120,8 @@ sigquit(int signo) #ifdef SIGTSTP /* - * We had a SIGTSTP signal. - * Suspend, by a call to this routine. + * we had a SIGTSTP signal + * suspend, by a call to this routine */ void @@ -132,12 +132,12 @@ suspend() (void)signal(SIGTSTP, SIG_DFL); (void)kill(0, SIGTSTP); /* - * We are not here anymore ... - * - - * - * But we arive here ... - */ + * we are not here anymore ... + * + * + * + * but we arive here ... + */ inittty(); putline(TI); flush(); @@ -145,8 +145,8 @@ suspend() } /* - * SIGTSTP signal handler. - * Just indicate that we had one, ignore further ones and return. + * SIGTSTP signal handler + * just indicate that we had one, ignore further ones and return */ static void @@ -161,8 +161,8 @@ suspsig(int signo) #endif /* - * quit : called on exit. - * I bet you guessed that much. + * quit : called on exit + * i bet you guessed that much */ int @@ -175,8 +175,8 @@ quit() } /* - * Exit, but nonvoluntarily. - * At least tell the user why. + * exit, but nonvoluntarily + * at least tell the user why */ void diff --git a/cmd/extra/yap/options.c b/cmd/extra/yap/options.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "options.h" #include "display.h" @@ -15,8 +15,8 @@ char *startcomm; static int parsopt(char *s); /* - * Read the options. Return the argv pointer following them if there were - * no errors, otherwise return 0. + * read the options. return the argv pointer following them if there were + * no errors, otherwise return 0 */ char ** @@ -31,8 +31,8 @@ readoptions(char **argv) while (*av && **av == '-') { if (parsopt(*av)) { /* - * Error in option - */ + * error in option + */ putline(*av); putline(": illegal option\n"); return (char **)0; @@ -41,8 +41,8 @@ readoptions(char **argv) } if (*av && **av == '+') { /* - * Command in command line - */ + * command in command line + */ startcomm = *av + 1; av++; } @@ -58,8 +58,8 @@ parsopt(char *s) s++; if (isdigit(*s)) { /* - * pagesize option - */ + * pagesize option + */ i = 0; do { i = i * 10 + *s++ - '0'; diff --git a/cmd/extra/yap/output.c b/cmd/extra/yap/output.c @@ -1,7 +1,7 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ /* - * Handle output to screen + * handle output to screen */ #include "output.h" @@ -17,7 +17,7 @@ static char _outbuf[OBUFSIZ]; void flush() -{ /* Flush output buffer, by writing it */ +{ /* flush output buffer, by writing it */ char *p = _outbuf; _ocnt = OBUFSIZ; @@ -28,7 +28,7 @@ flush() void nflush() -{ /* Flush output buffer, ignoring it */ +{ /* flush output buffer, ignoring it */ _ocnt = OBUFSIZ; _optr = _outbuf; @@ -43,7 +43,7 @@ fputch(int ch) void putline(char *s) -{ /* Print string s */ +{ /* print string s */ if (!s) return; @@ -53,7 +53,7 @@ putline(char *s) } /* - * A safe version of putline. All control characters are echoed as ^X + * a safe version of putline. all control characters are echoed as ^x */ void @@ -71,7 +71,7 @@ cputline(char *s) } /* - * Simple minded routine to print a number + * simple minded routine to print a number */ void diff --git a/cmd/extra/yap/pattern.c b/cmd/extra/yap/pattern.c @@ -3,7 +3,7 @@ #include <regex.h> /* - * Interface to POSIX regular expression routines. + * interface to POSIX regular expression routines */ static regex_t pattern; diff --git a/cmd/extra/yap/process.c b/cmd/extra/yap/process.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "process.h" #include "commands.h" @@ -19,10 +19,10 @@ char **filenames; char *currentfile; long maxpos; -static int nfiles; /* Number of filenames on command line */ +static int nfiles; /* number of filenames on command line */ /* - * Visit a file, file name is "fn". + * visit a file, file name is "fn" */ void @@ -32,15 +32,15 @@ visitfile(char *fn) if (stdf > 0) { /* - * Close old input file - */ + * close old input file + */ (void)close(stdf); } currentfile = fn; if ((stdf = open(fn, O_RDONLY, 0)) < 0) { error(": could not open"); maxpos = 0; - } else { /* Get size for percentage in prompt */ + } else { /* get size for percentage in prompt */ (void)fstat(stdf, &statbuf); maxpos = statbuf.st_size; } @@ -49,8 +49,8 @@ visitfile(char *fn) } /* - * process the input files, one by one. - * If there is none, input is from a pipe. + * process the input files, one by one + * if there is none, input is from a pipe */ void @@ -61,12 +61,12 @@ processfiles(int n, char **argv) if (!(nfiles = n)) { /* - * Input from pipe - */ + * input from pipe + */ currentfile = "standard-input"; /* - * Take care that *(filenames - 1) and *(filenames + 1) are 0 - */ + * take care that *(filenames - 1) and *(filenames + 1) are 0 + */ filenames = &dummies[1]; d_clean(); do_clean(); @@ -97,7 +97,7 @@ processfiles(int n, char **argv) } /* - * Get the next file the user asks for. + * get the next file the user asks for */ int diff --git a/cmd/extra/yap/prompt.c b/cmd/extra/yap/prompt.c @@ -1,4 +1,4 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ #include "prompt.h" #include "assert.h" @@ -15,7 +15,7 @@ #include "process.h" #include "term.h" -static char *errorgiven; /* Set to error message, if there is one */ +static char *errorgiven; /* set to error message, if there is one */ static char *display_basename(char *path, char *scratch, size_t scratch_size); @@ -29,7 +29,7 @@ copy(char *p, const char *ep, char *s) } /* - * display the prompt and refresh the screen. + * display the prompt and refresh the screen */ void @@ -50,8 +50,8 @@ give_prompt() } if (!stupid) { /* - * fancy prompt - */ + * fancy prompt + */ clrbline(); standout(); pb = copy(pb, &buf[255], display_basename(currentfile, filebuf, sizeof(filebuf))); @@ -62,12 +62,12 @@ give_prompt() pb = copy(pb, &buf[255], getnum(p->lastline)); } } else { - *pb++ = '\007'; /* Stupid terminal, stupid prompt */ + *pb++ = '\007'; /* stupid terminal, stupid prompt */ } if (errorgiven) { /* - * display error message - */ + * display error message + */ pb = copy(pb, &buf[255], " "); pb = copy(pb, &buf[255], errorgiven); if (stupid) { @@ -79,8 +79,8 @@ give_prompt() name = &filenames[filecount]; if (status) { /* - * indicate top and/or bottom - */ + * indicate top and/or bottom + */ if (status & START) { if (!*(name - 1)) { pb = copy(pb, &buf[255], "Top"); @@ -130,7 +130,7 @@ display_basename(char *path, char *scratch, size_t scratch_size) } /* - * Remember error message + * remember error message */ void @@ -141,7 +141,7 @@ error(char *str) void ret_to_continue() -{ /* Obvious */ +{ /* obvious */ int c; static char buf[2]; diff --git a/cmd/extra/yap/term.c b/cmd/extra/yap/term.c @@ -1,7 +1,7 @@ -/* Copyright (c) 1985 Ceriel J.H. Jacobs */ +/* copyright (c) 1985 ceriel J.H. jacobs */ /* - * Terminal handling routines, mostly initializing. + * terminal handling routines, mostly initializing */ #include "term.h" @@ -53,8 +53,8 @@ handle(cc_t *c) } /* - * Set terminal in cbreak mode. - * Also check if tabs need expanding. + * set terminal in cbreak mode + * also check if tabs need expanding */ void @@ -72,7 +72,7 @@ inittty() handle(&p->c_cc[VQUIT]); erasech = p->c_cc[VERASE]; killch = p->c_cc[VKILL]; - p->c_cc[VMIN] = 1; /* Just wait for one character */ + p->c_cc[VMIN] = 1; /* just wait for one character */ p->c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, p); } @@ -150,7 +150,7 @@ givetab() } /* - * Reset the terminal to its original state + * reset the terminal to its original state */ void @@ -162,8 +162,8 @@ resettty() } /* - * Get string terminal capability "cap". - * If not present, return an empty string. + * get string terminal capability "cap" + * if not present, return an empty string */ static char * @@ -196,7 +196,7 @@ getnumcap(char *cap) } /* - * Initialize some terminal-dependent stuff. + * initialize some terminal-dependent stuff */ void @@ -225,11 +225,11 @@ ini_terminal() panic("No terminfo entry"); } stupid = 0; - hardcopy = getflag("hc"); /* Hard copy terminal?*/ + hardcopy = getflag("hc"); /* hard copy terminal? */ if (*(s = getcap("cub1"))) { /* - * Backspace if not ^H - */ + * backspace if not ^h + */ BC = s; } UP = getcap("cuu1"); /* move up a line */ @@ -237,11 +237,11 @@ ini_terminal() CL = getcap("clear"); /* clear screen */ if (!*CL) cflag = 1; - TI = getcap("smcup"); /* Initialization for CM */ + TI = getcap("smcup"); /* initialization for CM */ TE = getcap("rmcup"); /* end for CM */ CM = getcap("cup"); /* cursor addressing */ SR = getcap("ri"); /* scroll reverse */ - AL = getcap("il"); /* Insert line */ + AL = getcap("il"); /* insert line */ SO = getcap("smso"); /* standout */ SE = getcap("rmso"); /* standend */ SG = getnumcap("xmc"); /* blanks left by attributes */ @@ -260,8 +260,8 @@ ini_terminal() mr = getcap("rev"); /* reversed video attribute */ if (!nflag) { /* - * Recognize special strings - */ + * recognize special strings + */ (void)addstring(SO, SG, &sppat); (void)addstring(SE, SG, &sppat); (void)addstring(US, UG, &sppat); @@ -284,27 +284,27 @@ ini_terminal() if (*US || uflag) UC = ""; COLS = getnumcap("cols"); /* columns on page */ - i = getnumcap("lines"); /* Lines on page */ + i = getnumcap("lines"); /* lines on page */ AM = getflag("am"); /* terminal wraps automatically? */ XN = getflag("xenl"); /* and then ignores next newline? */ DB = getflag("db"); /* terminal retains lines below */ HO = getcap("home"); if (!*HO && *CM) { - HO = tiparm(CM, 0, 0); /* Another way of getting home */ + HO = tiparm(CM, 0, 0); /* another way of getting home */ } if ((!*CE && !*AL) || !*HO || hardcopy) { cflag = stupid = 1; } if (*(s = getcap("ht"))) { /* - * Tab (other than ^I or padding) - */ + * tab (other than ^i or padding) + */ TA = s; } if (!*(ll = getcap("ll")) && *CM && i > 0) { /* - * Lower left hand corner - */ + * lower left hand corner + */ BO = tiparm(CM, i - 1, 0); } else BO = ll; @@ -331,16 +331,16 @@ ini_terminal() } /* - * The next part does not really belong here, but there it is ... - * Initialize a circular list for the screenlines. - */ + * the next part does not really belong here, but there it is ... + * initialize a circular list for the screenlines + */ scr_info.tail = lp = _X; lp1 = lp + (100 - 1); for (; lp <= lp1; lp++) { /* - * Circular doubly linked list - */ + * circular doubly linked list + */ lp->next = lp + 1; lp->prev = lp - 1; } @@ -354,7 +354,7 @@ ini_terminal() } /* - * Place cursor at start of line n. + * place cursor at start of line n */ void @@ -366,17 +366,17 @@ mgoto(int n) bottom(); else if (*CM) { /* - * Cursor addressing - */ + * cursor addressing + */ tputs(tiparm(CM, n, 0), 1, fputch); } else if (*BO && *UP && n >= (maxpagesize >> 1)) { /* - * Bottom and then up - */ + * bottom and then up + */ bottom(); while (n++ < maxpagesize) putline(UP); - } else { /* Home, and then down */ + } else { /* home, and then down */ home(); while (n--) putline("\r\n"); @@ -384,7 +384,7 @@ mgoto(int n) } /* - * Clear bottom line + * clear bottom line */ void @@ -397,8 +397,8 @@ clrbline() bottom(); if (*CE) { /* - * We can clear to end of line - */ + * we can clear to end of line + */ clrtoeol(); return; } diff --git a/cmd/linux/blkdiscard.c b/cmd/linux/blkdiscard.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/mount.h> diff --git a/cmd/linux/chvt.c b/cmd/linux/chvt.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/types.h> diff --git a/cmd/linux/ctrlaltdel.c b/cmd/linux/ctrlaltdel.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/syscall.h> diff --git a/cmd/linux/eject.c b/cmd/linux/eject.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/stat.h> diff --git a/cmd/linux/freeramdisk.c b/cmd/linux/freeramdisk.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/mount.h> diff --git a/cmd/linux/fsfreeze.c b/cmd/linux/fsfreeze.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/stat.h> @@ -11,8 +11,8 @@ #include "util.h" -#define FIFREEZE _IOWR('X', 119, int) /* Freeze */ -#define FITHAW _IOWR('X', 120, int) /* Thaw */ +#define FIFREEZE _IOWR('X', 119, int) /* freeze */ +#define FITHAW _IOWR('X', 120, int) /* thaw */ static void usage(void) diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/stat.h> @@ -155,7 +155,7 @@ main(int argc, char *argv[]) if ((rflag ^ sflag ^ wflag) == 0) eprintf("missing or incompatible function\n"); - /* Only UTC support at the moment */ + /* only UTC support at the moment */ setenv("TZ", "UTC0", 1); tzset(); diff --git a/cmd/linux/lsusb.c b/cmd/linux/lsusb.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <stdio.h> diff --git a/cmd/linux/mkswap.c b/cmd/linux/mkswap.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> @@ -73,7 +73,7 @@ main(int argc, char *argv[]) if (pages < SWAP_MIN_PAGES) eprintf("swap space needs to be at least %ldKiB\n", SWAP_MIN_PAGES * pagesize / 1024); - /* Fill up the swap header */ + /* fill up the swap header */ hdr = (struct swap_hdr *)buf; hdr->version = 1; hdr->last_page = pages - 1; @@ -81,7 +81,7 @@ main(int argc, char *argv[]) printf("Setting up swapspace version 1, size = %luKiB\n", (pages - 1) * pagesize / 1024); - /* Write out the signature page */ + /* write out the signature page */ if (write(fd, buf, pagesize) != pagesize) eprintf("unable to write signature page\n"); diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -541,11 +541,11 @@ usage(void) // ?man modprobe: add or remove modules from the Linux kernel // ?man arguments: module [symbol=value ...] -// ?man modprobe loads or removes kernel modules from the running system. +// ?man modprobe loads or removes kernel modules from the running system // ?man It reads modules.dep, modules.alias, and modules.symbols from the // appropriate ?man /lib/modules/release directory to resolve module names and -// dependencies, ?man loading prerequisites first. ?man Without -r, modprobe -// loads the named module (and any required dependencies) ?man into the kernel. +// dependencies, ?man loading prerequisites first. ?man without -r, modprobe +// loads the named module (and any required dependencies) ?man into the kernel int main(int argc, char *argv[]) { @@ -559,36 +559,36 @@ main(int argc, char *argv[]) // ?man -a: specify a option case 'a': // ?man -a: Load all modules named on the command line (rather - // than stopping after the first). + // than stopping after the first) aflag = 1; break; // ?man -r: specify r option case 'r': - // ?man -r: Remove the named modules from the kernel. - // Dependencies are not automatically removed. + // ?man -r: Remove the named modules from the kernel + // dependencies are not automatically removed rflag = 1; break; // ?man -q: specify q option case 'q': - // ?man -q: Quiet mode. Suppress error messages. + // ?man -q: Quiet mode. Suppress error messages qflag = 1; break; // ?man -v: specify v option case 'v': - // ?man -v: Verbose mode. Print each action taken. + // ?man -v: Verbose mode. Print each action taken vflag = 1; break; // ?man -l: specify l option case 'l': // ?man -l: List available modules matching the optional - // _pattern_ (a fnmatch(3) glob). + // _pattern_ (a fnmatch(3) glob) lflag = 1; break; #if FEATURE_MODPROBE_SHOW_DEPENDS // ?man -D: specify D option case 'D': // ?man -D: Print the sequence of insmod commands that would be - // used to load the module, without actually loading anything. + // used to load the module, without actually loading anything Dflag = 1; break; #endif @@ -596,7 +596,7 @@ main(int argc, char *argv[]) // ?man -b: specify b option case 'b': // ?man -b: Skip modules listed as blacklist in - // /etc/modprobe.d/. + // /etc/modprobe.d/ bflag = 1; break; #endif @@ -604,7 +604,7 @@ main(int argc, char *argv[]) // ?man -s: specify s option case 's': // ?man -s: Log messages to syslog(3) (facility LOG_DAEMON) - // instead of standard error. + // instead of standard error sflag = 1; break; #endif @@ -612,7 +612,7 @@ main(int argc, char *argv[]) // ?man -d:file: specify d option case 'd': // ?man -d dir: Use dir as the base directory for module files - // instead of /lib/modules/release. + // instead of /lib/modules/release strlist_append(&moddirs, EARGF(usage())); break; #endif @@ -640,7 +640,7 @@ main(int argc, char *argv[]) read_configs(); /* traverse all provided or default base directories for symbol, alias, - * and dependency tracking */ + * and dependency tracking */ for (pn = moddirs; pn; pn = pn->next) { if (chdir(pn->str) < 0) { pr_warn("chdir %s:", pn->str); @@ -691,24 +691,24 @@ end: // ?man ## FILES // ?man // ?man `/etc/modprobe.conf` - // ?man : Global configuration file. + // ?man : Global configuration file // ?man // ?man Files under `/etc/modprobe.d/` - // ?man : Per-module configuration snippets. + // ?man : Per-module configuration snippets // ?man // ?man `/lib/modules/`_release_`/modules.dep` - // ?man : Module dependency map generated by `depmod(8)`. + // ?man : Module dependency map generated by `depmod(8)` // ?man // ?man ## EXIT STATUS // ?man // ?man 0 - // ?man : Success. + // ?man : Success // ?man // ?man 1 - // ?man : Module not found or kernel rejected the operation. + // ?man : Module not found or kernel rejected the operation // ?man // ?man 2 - // ?man : I/O error on stdout or stdin. + // ?man : I/O error on stdout or stdin // ?man // ?man ## SEE ALSO // ?man diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/mount.h> #include <sys/stat.h> @@ -322,8 +322,8 @@ mountall: } parseopts(fsopts, &flags, data, sizeof(data)); /* if -t types specified: - * if non-match, skip - * if match and prefixed with "no", skip */ + * if non-match, skip + * if match and prefixed with "no", skip */ if (types && ((types[0] == 'n' && types[1] == 'o' && findtype(types + 2, me->mnt_type)) || (!findtype(types, me->mnt_type)))) diff --git a/cmd/linux/mountpoint.c b/cmd/linux/mountpoint.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/sysmacros.h> diff --git a/cmd/linux/pivot_root.c b/cmd/linux/pivot_root.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/syscall.h> diff --git a/cmd/linux/readahead.c b/cmd/linux/readahead.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <limits.h> diff --git a/cmd/linux/swaplabel.c b/cmd/linux/swaplabel.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/types.h> diff --git a/cmd/linux/swapoff.c b/cmd/linux/swapoff.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/swap.h> diff --git a/cmd/linux/swapon.c b/cmd/linux/swapon.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/swap.h> diff --git a/cmd/linux/switch_root.c b/cmd/linux/switch_root.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/mount.h> #include <sys/stat.h> @@ -25,7 +25,7 @@ delete_content(const char *dir, dev_t curdevice) struct stat st; struct dirent *dent; - /* don't dive into other filesystems */ + /* dont dive into other filesystems */ if (lstat(dir, &st) < 0 || st.st_dev != curdevice) return; if (!(d = opendir(dir))) @@ -90,7 +90,7 @@ main(int argc, char *argv[]) if (argc != 2 || getpid() != 1) usage(); - /* chdir to newroot and make sure it's a different fs */ + /* chdir to newroot and make sure its a different fs */ if (chdir(argv[0])) eprintf("chdir %s:", argv[0]); diff --git a/cmd/linux/sysctl.c b/cmd/linux/sysctl.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <limits.h> diff --git a/cmd/linux/tunctl.c b/cmd/linux/tunctl.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/socket.h> diff --git a/cmd/linux/umount.c b/cmd/linux/umount.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/mount.h> diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sched.h> #include <stdio.h> diff --git a/cmd/linux/vtallow.c b/cmd/linux/vtallow.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/stat.h> diff --git a/cmd/net/host.c b/cmd/net/host.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" diff --git a/cmd/net/httpd.c b/cmd/net/httpd.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" diff --git a/cmd/net/ifconfig.c b/cmd/net/ifconfig.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <arpa/inet.h> #include <ctype.h> diff --git a/cmd/net/ip.c b/cmd/net/ip.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <arpa/inet.h> #include <ctype.h> @@ -41,6 +41,16 @@ usage(void) eprintf("usage: %s [addr | link | route] [args...]\n", argv0); } +/* real ip(8) and BusyBox's own ip applet both accept any unambiguous + * prefix of an object name (ip a, ip li, ip ro, ...), not just the + * full word: obj matches full whenever it is a real, non-empty prefix */ +static int +is_object(const char *obj, const char *full) +{ + size_t len = strlen(obj); + return len > 0 && len <= strlen(full) && strncmp(obj, full, len) == 0; +} + static void parse_mac(const char *str, unsigned char mac[6]) { @@ -369,7 +379,9 @@ do_route(int argc, char *argv[]) // ?man ip: show or configure routing and devices // ?man arguments: [addr | link | route] [args ...] -// ?man configure and view network devices, routing, and tunnels +// ?man configure and view network devices, routing, and tunnels. any +// ?man unambiguous prefix of an object name works too (a, addr, l, +// ?man link, r, route) // ?man ## COMMANDS // ?man ### addr [show | list [dev <device>]] // ?man show interface addresses @@ -405,11 +417,11 @@ main(int argc, char *argv[]) obj = argv[0]; - if (strcmp(obj, "addr") == 0 || strcmp(obj, "address") == 0) { + if (is_object(obj, "address")) { return do_addr(argc - 1, argv + 1); - } else if (strcmp(obj, "link") == 0) { + } else if (is_object(obj, "link")) { return do_link(argc - 1, argv + 1); - } else if (strcmp(obj, "route") == 0) { + } else if (is_object(obj, "route")) { return do_route(argc - 1, argv + 1); } diff --git a/cmd/net/netcat.c b/cmd/net/netcat.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/socket.h> #include <sys/types.h> diff --git a/cmd/net/ping.c b/cmd/net/ping.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" diff --git a/cmd/net/sdhcp.c b/cmd/net/sdhcp.c @@ -1,5 +1,5 @@ /* sdhcp: simple DHCP client, ported from git.2f30.org/sdhcp */ -/* See LICENSE file for copyright and license details */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" #include "wexec.h" @@ -70,7 +70,7 @@ enum { OB_DNSSERVER = 6, OB_HOSTNAME = 12, OB_BADDR = 28, - /* DHCP-specific options */ + /* dhcp-specific options */ OD_IPADDR = 50, /* 0x32 */ OD_LEASE = 51, OD_OVERLOAD = 52, @@ -542,7 +542,7 @@ main(int argc, char *argv[]) ARGBEGIN { - case 'd': /* don't update /etc/resolv.conf */ + case 'd': /* dont update /etc/resolv.conf */ dflag = 0; break; case 'e': /* exec program on each lease */ @@ -551,7 +551,7 @@ main(int argc, char *argv[]) case 'f': /* stay in foreground */ fflag = 1; break; - case 'i': /* don't configure IP address */ + case 'i': /* dont configure IP address */ iflag = 0; break; default: diff --git a/cmd/net/tftp.c b/cmd/net/tftp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/socket.h> #include <sys/time.h> diff --git a/cmd/net/wget.c b/cmd/net/wget.c @@ -8,6 +8,7 @@ #include <ctype.h> #include <errno.h> #include <fcntl.h> +#include <limits.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> @@ -31,6 +32,7 @@ static int cflag = 0; static int spider = 0; static int no_check_certificate = 0; static int timeout_sec = 900; +static int tries = 20; static char *Pflag = NULL; static char *Oflag = NULL; static char *user_agent = "wget/aruu"; @@ -43,7 +45,7 @@ static void usage(void) { eprintf( - "usage: %s [-cqS] [-O file] [-P dir] [-T timeout] [-U " + "usage: %s [-cqS] [-O file] [-P dir] [-T timeout] [-t tries] [-U " "user_agent] " "[-post-data data] [-post-file file] [-header header] " "[-no-check-certificate] [-spider] url\n", @@ -102,9 +104,9 @@ parse_url(char *url, char **host, char **port, char **path, int *is_tls) char *p, *ss; *is_tls = 0; - if (strncasecmp(url, "http://", 7) == 0) { + if (strncasecmp(url, "http:// ", 7) == 0) { url += 7; - } else if (strncasecmp(url, "https://", 8) == 0) { + } else if (strncasecmp(url, "https:// ", 8) == 0) { url += 8; *is_tls = 1; } else { @@ -334,6 +336,8 @@ main(int argc, char *argv[]) long long post_len = 0; int post_fd = -1; size_t i; + int attempt; + int max_tries; ARGBEGIN { @@ -349,6 +353,10 @@ main(int argc, char *argv[]) case 'T': timeout_sec = estrtonum(EARGF(usage()), 0, 100000); break; + // ?man -t:num: set number of connection retries, 0 retries forever + case 't': + tries = estrtonum(EARGF(usage()), 0, 1000000); + break; // ?man -U:str: set User-Agent header case 'U': user_agent = EARGF(usage()); @@ -454,6 +462,9 @@ main(int argc, char *argv[]) post_len = st.st_size; } + /* wgets own -t: 0 means retry forever */ + max_tries = tries == 0 ? INT_MAX : tries; + while (!tls_sock) { if (redirects > max_redirects) eprintf("too many redirects\n"); @@ -465,14 +476,23 @@ main(int argc, char *argv[]) port = estrdup(curr_port); path = estrdup(curr_path); - sock_fd = dial(host, port); - if (sock_fd < 0) - eprintf("failed to connect to %s:%s\n", host, port); + for (attempt = 1; attempt <= max_tries; attempt++) { + sock_fd = dial(host, port); + if (sock_fd < 0) { + if (attempt == max_tries) + eprintf("failed to connect to %s:%s\n", host, port); + continue; + } + + tls_sock = tlss_connect(sock_fd, host, !no_check_certificate, is_tls); + if (!tls_sock) { + close(sock_fd); + if (attempt == max_tries) + eprintf("failed to establish TLS connection with %s\n", host); + continue; + } - tls_sock = tlss_connect(sock_fd, host, !no_check_certificate, is_tls); - if (!tls_sock) { - close(sock_fd); - eprintf("failed to establish TLS connection with %s\n", host); + break; } /* send http request */ @@ -572,18 +592,18 @@ main(int argc, char *argv[]) "header\n" ); - if (strncasecmp(loc, "http://", 7) == 0 || strncasecmp(loc, "https://", 8) == 0) { + if (strncasecmp(loc, "http:// ", 7) == 0 || strncasecmp(loc, "https://", 8) == 0) { new_url = estrdup(loc); } else if (loc[0] == '/') { new_url = emalloc(8 + strlen(host) + strlen(port) + strlen(loc) + 2); - sprintf(new_url, "%s://%s:%s%s", is_tls ? "https" : "http", host, port, loc); + sprintf(new_url, "%s:// %s:%s%s", is_tls ? "https" : "http", host, port, loc); } else { last_slash = strrchr(path, '/'); dir_len = 0; if (last_slash) dir_len = last_slash - path + 1; new_url = emalloc(8 + strlen(host) + strlen(port) + 1 + dir_len + strlen(loc) + 2); - sprintf(new_url, "%s://%s:%s/", is_tls ? "https" : "http", host, port); + sprintf(new_url, "%s:// %s:%s/", is_tls ? "https" : "http", host, port); if (dir_len > 0) strncat(new_url, path, dir_len); strcat(new_url, loc); diff --git a/cmd/posix/awk/awk.h b/cmd/posix/awk/awk.h @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #include <assert.h> #include <stddef.h> @@ -40,7 +40,7 @@ THIS SOFTWARE. typedef double Awkfloat; -/* unsigned char is more trouble than it's worth */ +/* unsigned char is more trouble than its worth */ typedef unsigned char uschar; @@ -50,14 +50,14 @@ typedef unsigned char uschar; (a) = NULL; \ } /* - * We sometimes cheat writing read-only pointers to NUL-terminate them + * we sometimes cheat writing read-only pointers to nul-terminate them * and then put back the original value */ #define setptr(ptr, a) (*(char *)(intptr_t)(ptr)) = (a) #define NN(p) \ - ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF \ - */ + ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF \ + */ #define DEBUG #ifdef DEBUG #define DPRINTF(...) \ @@ -71,12 +71,12 @@ extern enum compile_states { RUNNING, COMPILING, ERROR_PRINTING } compile_time; extern bool safe; /* false => unsafe, true => safe */ -#define RECSIZE (8 * 1024) /* sets limit on records, fields, etc., etc. */ +#define RECSIZE (8 * 1024) /* sets limit on records, fields, etc., etc */ extern int recsize; /* size of current record, orig RECSIZE */ extern size_t awk_mb_cur_max; /* max size of a multi-byte character */ -extern char EMPTY[]; /* this avoid -Wwritable-strings issues */ +extern char EMPTY[]; /* this avoid -wwritable-strings issues */ extern char **FS; extern char **RS; extern char **ORS; @@ -100,13 +100,13 @@ extern bool donerec; /* true if record is valid (no fld has changed */ extern int dbg; extern const char *patbeg; /* beginning of pattern matched */ -extern int patlen; /* length of pattern matched. set in b.c */ +extern int patlen; /* length of pattern matched. set in b.c */ -/* Cell: all information about a variable or constant */ +/* cell: all information about a variable or constant */ typedef struct Cell { - uschar ctype; /* OCELL, OBOOL, OJUMP, etc. */ - uschar csub; /* CCON, CTEMP, CFLD, etc. */ + uschar ctype; /* OCELL, OBOOL, OJUMP, etc */ + uschar csub; /* CCON, CTEMP, CFLD, etc */ char *nval; /* name, for variables only */ char *sval; /* string value */ Awkfloat fval; /* value as number */ @@ -136,7 +136,7 @@ extern Cell *rlengthloc; /* RLENGTH */ extern Cell *subseploc; /* SUBSEP */ extern Cell *symtabloc; /* SYMTAB */ -/* Cell.tval values: */ +/* cell.tval values: */ #define NUM 01 /* number value is valid */ #define STR 02 /* string value is valid */ #define DONTFREE 04 /* string space is not freeable */ @@ -164,7 +164,7 @@ extern Cell *symtabloc; /* SYMTAB */ #define FTOLOWER 13 #define FFLUSH 14 -/* Node: parse tree is made of nodes, with Cell's at bottom */ +/* node: parse tree is made of nodes, with cell's at bottom */ typedef struct Node { int ntype; @@ -184,7 +184,7 @@ extern Node *nullnode; #define OBOOL 2 #define OJUMP 3 -/* Cell subtypes: csub */ +/* cell subtypes: csub */ #define CFREE 7 #define CCOPY 6 #define CCON 5 @@ -231,14 +231,14 @@ extern int pairstack[], paircnt; #define istrue(n) ((n)->csub == BTRUE) #define istemp(n) ((n)->csub == CTEMP) #define isargument(n) ((n)->nobj == ARG) -/* #define freeable(p) (!((p)->tval & DONTFREE)) */ +/* #define freeable(p) (!((p)->tval & DONTFREE)) */ #define freeable(p) (((p)->tval & (STR | DONTFREE)) == STR) /* structures used by regular expression matching machinery, mostly b.c: */ #define NCHARS (1256 + 3) /* 256 handles 8-bit chars; 128 does 7-bit */ /* BUG: some overflows (caught) if we use 256 */ - /* watch out in match(), etc. */ + /* watch out in match(), etc */ #define HAT (NCHARS + 2) /* matches ^ in regular expr */ #define NSTATES 32 @@ -249,7 +249,7 @@ typedef struct rrow { Node *np; uschar *up; int *rp; /* rune representation of char class */ - } lval; /* because Al stores a pointer in it! */ + } lval; /* because al stores a pointer in it! */ int *lfollow; } rrow; diff --git a/cmd/posix/awk/b.c b/cmd/posix/awk/b.c @@ -1,28 +1,28 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ - -/* lasciate ogne speranza, voi ch'intrate. */ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ + +/* lasciate ogne speranza, voi ch'intrate */ #define DEBUG @@ -55,13 +55,13 @@ THIS SOFTWARE. case PLUS: \ case QUEST: -/* encoding in tree Nodes: - leaf (CCL, NCCL, CHAR, DOT, FINAL, ALL, EMPTYRE): - left is index, right contains value or pointer to value - unary (STAR, PLUS, QUEST): left is child, right is null - binary (CAT, OR): left and right are children - parent contains pointer to parent -*/ +/* encoding in tree nodes: + * leaf (CCL, NCCL, CHAR, DOT, FINAL, ALL, EMPTYRE): + * left is index, right contains value or pointer to value + * unary (STAR, PLUS, QUEST): left is child, right is null + * binary (CAT, OR): left and right are children + * parent contains pointer to parent + */ int *setvec; int *tmpset; @@ -72,10 +72,10 @@ int rlxval; static const uschar *rlxstr; static const uschar *prestr; /* current position in current re */ static const uschar *lastre; /* origin of last re */ -static const uschar *lastatom; /* origin of last Atom */ +static const uschar *lastatom; /* origin of last atom */ static const uschar *starttok; static const uschar *basestr; /* starts with original, replaced during - repetition processing */ + * repetition processing */ static const uschar *firstbasestr; static int setcnt; @@ -91,32 +91,32 @@ int nfatab = 0; /* entries in fatab */ extern int u8_nextlen(const char *s); /* utf-8 mechanism: - - For most of Awk, utf-8 strings just "work", since they look like - null-terminated sequences of 8-bit bytes. - - Functions like length(), index(), and substr() have to operate - in units of utf-8 characters. The u8_* functions in run.c - handle this. - - Regular expressions are more complicated, since the basic - mechanism of the goto table used 8-bit byte indices into the - gototab entries to compute the next state. Unicode is a lot - bigger, so the gototab entries are now structs with a character - and a next state. These are sorted by code point and binary - searched. - - Throughout the RE mechanism in b.c, utf-8 characters are - converted to their utf-32 value. This mostly shows up in - cclenter, which expands character class ranges like a-z and now - alpha-omega. The size of a gototab array is still about 256. - This should be dynamic, but for now things work ok for a single - code page of Unicode, which is the most likely case. - - The code changes are localized in run.c and b.c. I have added a - handful of functions to somewhat better hide the implementation, - but a lot more could be done. - + * + * for most of awk, utf-8 strings just "work", since they look like + * null-terminated sequences of 8-bit bytes + * + * functions like length(), index(), and substr() have to operate + * in units of utf-8 characters. the u8_* functions in run.c + * handle this + * + * regular expressions are more complicated, since the basic + * mechanism of the goto table used 8-bit byte indices into the + * gototab entries to compute the next state. unicode is a lot + * bigger, so the gototab entries are now structs with a character + * and a next state. these are sorted by code point and binary + * searched + * + * throughout the RE mechanism in b.c, utf-8 characters are + * converted to their utf-32 value. this mostly shows up in + * cclenter, which expands character class ranges like a-z and now + * alpha-omega. the size of a gototab array is still about 256 + * this should be dynamic, but for now things work ok for a single + * code page of unicode, which is the most likely case + * + * the code changes are localized in run.c and b.c. i have added a + * handful of functions to somewhat better hide the implementation, + * but a lot more could be done + * */ static int entry_cmp(const void *l, const void *r); @@ -240,9 +240,9 @@ mkdfa(const char *s, bool anchor) /* does the real work of making a dfa */ basestr = firstbasestr; p = reparse(s); p1 = op2(CAT, op2(STAR, op2(ALL, NIL, NIL), NIL), p); - /* put ALL STAR in front of reg. exp. */ + /* put ALL STAR in front of reg. exp */ p1 = op2(CAT, p1, op2(FINAL, NIL, NIL)); - /* put FINAL after reg. exp. */ + /* put FINAL after reg. exp */ poscnt = 0; penter(p1); /* enter parent pointers and leaf indices */ @@ -316,7 +316,7 @@ penter(Node *p) /* set up parent pointers and leaf indices */ break; case ZERO: break; - default: /* can't happen */ + default: /* cant happen */ FATAL("can't happen: unknown type %d in penter", type(p)); break; } @@ -340,14 +340,14 @@ freetr(Node *p) /* free parse tree */ freetr(right(p)); xfree(p); break; - default: /* can't happen */ + default: /* cant happen */ FATAL("can't happen: unknown type %d in freetr", type(p)); break; } } /* in the parsing of regular expressions, metacharacters like . have */ -/* to be seen literally; \056 is not a metacharacter. */ +/* to be seen literally; \056 is not a metacharacter */ int hexstr(const uschar **pp, int max) /* find and eval hex string at pp, return new p */ @@ -452,7 +452,7 @@ cclenter(const char *argp) /* add a character class */ p += n; if (c2 == '\\') c2 = quoted(&p); /* BUG: sets p, has to - be u8 size */ + * be u8 size */ if (c > c2) { /* empty; ignore */ bp--; i--; @@ -493,9 +493,9 @@ cclenter(const char *argp) /* add a character class */ i++; } *bp = 0; - /* DPRINTF("cclenter: in = |%s|, out = |%s|\n", op, buf); BUG: can't - * print array of int */ - /* xfree(op); BUG: what are we freeing here? */ + /* dprintf("cclenter: in = |%s|, out = |%s|\n", op, buf); BUG: cant + * print array of int */ + /* xfree(op); BUG: what are we freeing here? */ retp = (int *)calloc(bp - buf + 1, sizeof(int)); for (i = 0; i < bp - buf + 1; i++) retp[i] = buf[i]; @@ -510,7 +510,7 @@ overflo(const char *s) void cfoll(fa *f, Node *v) /* enter follow set of each leaf of vertex v into - lfollow[leaf] */ + * lfollow[leaf] */ { int i; int *p; @@ -543,7 +543,7 @@ cfoll(fa *f, Node *v) /* enter follow set of each leaf of vertex v into break; case ZERO: break; - default: /* can't happen */ + default: /* cant happen */ FATAL("can't happen: unknown type %d in cfoll", type(v)); } } @@ -591,7 +591,7 @@ first(Node *p) /* collects initially active leaves of p into setvec */ case ZERO: return 0; } - FATAL("can't happen: unknown type %d in first", type(p)); /* can't happen */ + FATAL("can't happen: unknown type %d in first", type(p)); /* cant happen */ return (-1); } @@ -646,11 +646,11 @@ resize_gototab(fa *f, int state) if (p == NULL) overflo(__func__); - // need to initialize the new memory to zero - size_t orig_size = f->gototab[state].allocated; // 2nd half of new mem is this size - memset(p + orig_size, 0, orig_size * sizeof(gtte)); // clean it out + /* need to initialize the new memory to zero */ + size_t orig_size = f->gototab[state].allocated; /* 2nd half of new mem is this size */ + memset(p + orig_size, 0, orig_size * sizeof(gtte)); /* clean it out */ - f->gototab[state].allocated = new_size; // update gototab info + f->gototab[state].allocated = new_size; /* update gototab info */ f->gototab[state].entries = p; } @@ -700,7 +700,7 @@ set_gototab(fa *f, int state, int ch, int val) /* hide gototab implementation */ f->gototab[state].inuse++; return val; } else if ((unsigned)ch > f->gototab[state].entries[f->gototab[state].inuse - 1].ch) { - // not seen yet, insert and return + /* not seen yet, insert and return */ gtt *tab = &f->gototab[state]; if (tab->inuse + 1 >= tab->allocated) resize_gototab(f, state); @@ -710,7 +710,7 @@ set_gototab(fa *f, int state, int ch, int val) /* hide gototab implementation */ f->gototab[state].inuse++; return val; } else { - // maybe we have it, maybe we don't + /* maybe we have it, maybe we dont */ gtte key; gtte *item; @@ -721,11 +721,11 @@ set_gototab(fa *f, int state, int ch, int val) /* hide gototab implementation */ ); if (item != NULL) { - // we have it, update state and return + /* we have it, update state and return */ item->state = val; return item->state; } - // otherwise, fall through to insert and reallocate. + /* otherwise, fall through to insert and reallocate */ } gtt *tab = &f->gototab[state]; @@ -820,7 +820,7 @@ pmatch(fa *f, const char *p0) /* longest match, for sub */ } while (1); q++; /* was *q++ */ if (f->out[s]) - patlen = q - p - 1; /* don't count $ */ + patlen = q - p - 1; /* dont count $ */ if (patlen >= 0) { patbeg = (const char *)p; return (1); @@ -873,7 +873,7 @@ nematch(fa *f, const char *p0) /* non-empty match, for sub */ } while (1); q++; if (f->out[s]) - patlen = q - p - 1; /* don't count $ */ + patlen = q - p - 1; /* dont count $ */ if (patlen > 0) { patbeg = (const char *)p; return (1); @@ -887,17 +887,17 @@ nematch(fa *f, const char *p0) /* non-empty match, for sub */ /* * NAME - * fnematch + * fnematch * * DESCRIPTION - * A stream-fed version of nematch which transfers characters to a - * null-terminated buffer. All characters up to and including the last - * character of the matching text or EOF are placed in the buffer. If - * a match is found, patbeg and patlen are set appropriately. + * a stream-fed version of nematch which transfers characters to a + * null-terminated buffer. all characters up to and including the last + * character of the matching text or EOF are placed in the buffer. if + * a match is found, patbeg and patlen are set appropriately * * RETURN VALUES - * false No match found. - * true Match found. + * false no match found + * true match found */ bool @@ -911,20 +911,20 @@ fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum) patlen = 0; /* - * buf <= i <= j <= k <= buf+bufsize - * - * i: origin of active substring - * j: current character - * k: destination of the next getc - */ + * buf <= i <= j <= k <= buf+bufsize + * + * i: origin of active substring + * j: current character + * k: destination of the next getc + */ i = j = k = buf; do { /* - * Call u8_rune with at least awk_mb_cur_max ahead in - * the buffer until EOF interferes. - */ + * call u8_rune with at least awk_mb_cur_max ahead in + * the buffer until EOF interferes + */ if (k - j < (int)awk_mb_cur_max) { if (k + awk_mb_cur_max > buf + bufsize) { char *obuf = buf; @@ -961,7 +961,7 @@ fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum) if (pfa->out[s]) { /* final state */ patbeg = i; patlen = j - i; - if (c == 0) /* don't count $ */ + if (c == 0) /* dont count $ */ patlen--; } @@ -980,16 +980,16 @@ fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum) if (patlen) { /* - * Under no circumstances is the last character fed to - * the automaton part of the match. It is EOF's nullbyte, - * or it sent the automaton into a state with no further - * transitions available (s==1), or both. Room for a - * terminating nullbyte is guaranteed. - * - * ungetc any chars after the end of matching text - * (except for EOF's nullbyte, if present) and null - * terminate the buffer. - */ + * under no circumstances is the last character fed to + * the automaton part of the match. it is eof's nullbyte, + * or it sent the automaton into a state with no further + * transitions available (s==1), or both. room for a + * terminating nullbyte is guaranteed + * + * ungetc any chars after the end of matching text + * (except for eof's nullbyte, if present) and null + * terminate the buffer + */ do if (*--k && ungetc(*k, f) == EOF) FATAL("unable to ungetc '%c'", *k); @@ -1010,7 +1010,7 @@ reparse(const char *p) /* parses regular expression pointed to by p */ rtok = relex(); /* GNU compatibility: an empty regexp matches anything */ if (rtok == '\0') { - /* FATAL("empty regular expression"); previous */ + /* fatal("empty regular expression"); previous */ return (op2(EMPTYRE, NIL, NIL)); } np = regexp(); @@ -1065,7 +1065,7 @@ primary(void) return (unary(op2(CHAR, NIL, NIL))); case '(': lastatom = starttok; - savelastatom = starttok - basestr; /* Retain over recursion */ + savelastatom = starttok - basestr; /* retain over recursion */ rtok = relex(); if (rtok == ')') { /* special pleading for () */ rtok = relex(); @@ -1073,7 +1073,7 @@ primary(void) } np = regexp(); if (rtok == ')') { - lastatom = basestr + savelastatom; /* Restore */ + lastatom = basestr + savelastatom; /* restore */ rtok = relex(); return (unary(np)); } else { @@ -1083,7 +1083,7 @@ primary(void) default: FATAL("illegal primary in regular expression %s at %s", lastre, prestr); } - return 0; /*NOTREACHED*/ + return 0; /* NOTREACHED */ } Node * @@ -1137,23 +1137,23 @@ unary(Node *np) } /* - * Character class definitions conformant to the POSIX locale as - * defined in IEEE P1003.1 draft 7 of June 2001, assuming the source + * character class definitions conformant to the POSIX locale as + * defined in IEEE P1003.1 draft 7 of june 2001, assuming the source * and operating character sets are both ASCII (ISO646) or supersets - * thereof. + * thereof * - * Note that to avoid overflowing the temporary buffer used in + * note that to avoid overflowing the temporary buffer used in * relex(), the expanded character class (prior to range expansion) - * must be less than twice the size of their full name. + * must be less than twice the size of their full name */ -/* Because isblank doesn't show up in any of the header files on any - * system i use, it's defined here. if some other locale has a richer +/* because isblank doesnt show up in any of the header files on any + * system i use, its defined here. if some other locale has a richer * definition of "blank", define HAS_ISBLANK and provide your own - * version. + * version * the parentheses here are an attempt to find a path through the maze - * of macro definition and/or function and/or version provided. thanks - * to nelson beebe for the suggestion; let's see if it works everywhere. + * of macro definition and/or function and/or version provided. thanks + * to nelson beebe for the suggestion; let's see if it works everywhere */ /* #define HAS_ISBLANK */ @@ -1210,17 +1210,17 @@ replace_repeat( uschar *buf = 0; int ret = 1; int init_q = (firstnum == 0); /* first added char will be ? */ - int n_q_reps = secondnum - firstnum; /* m>n, so reduce until {1,m-n} left */ + int n_q_reps = secondnum - firstnum; /* m>n, so reduce until {1,m-n} left */ int prefix_length = reptok - basestr; /* prefix includes first rep - */ - int suffix_length = strlen((const char *)reptok) - reptoklen; /* string after rep specifier */ + */ + int suffix_length = strlen((const char *)reptok) - reptoklen; /* string after rep specifier */ int size = prefix_length + suffix_length; if (firstnum > 1) { /* add room for reps 2 through firstnum */ size += atomlen * (firstnum - 1); } - /* Adjust size of buffer for special cases */ + /* adjust size of buffer for special cases */ if (special_case == REPEAT_PLUS_APPENDED) { size++; /* for the final + */ } else if (special_case == REPEAT_WITH_Q) { @@ -1230,14 +1230,14 @@ replace_repeat( } if ((buf = (uschar *)malloc(size + 1)) == NULL) FATAL("out of space in reg expr %.10s..", lastre); - memcpy(buf, basestr, prefix_length); /* copy prefix */ + memcpy(buf, basestr, prefix_length); /* copy prefix */ j = prefix_length; if (special_case == REPEAT_ZERO) { j -= atomlen; buf[j++] = '('; buf[j++] = ')'; } - for (i = 1; i < firstnum; i++) { /* copy x reps */ + for (i = 1; i < firstnum; i++) { /* copy x reps */ memcpy(&buf[j], atom, atomlen); j += atomlen; } @@ -1283,12 +1283,12 @@ repeat( return 0; /* - In general, the repetition specifier or "bound" is replaced here - by an equivalent ERE string, repeating the immediately previous atom - and appending ? and + as needed. Note that the first copy of the - atom is left in place, except in the special_case of a zero-repeat - (i.e., {0}). - */ + * in general, the repetition specifier or "bound" is replaced here + * by an equivalent ERE string, repeating the immediately previous atom + * and appending ? and + as needed. note that the first copy of the + * atom is left in place, except in the special_case of a zero-repeat + * (i.e., {0}) + */ if (secondnum < 0) { /* means {n,} -> repeat n-1 times followed by PLUS */ if (firstnum < 2) { /* 0 or 1: should be handled before you get here */ @@ -1300,17 +1300,17 @@ repeat( } } else if (firstnum == secondnum) { /* {n} or {n,n} -> simply repeat n-1 times */ if (firstnum == 0) { /* {0} or {0,0} */ - /* This case is unusual because the resulting - replacement string might actually be SMALLER than - the original ERE */ + /* this case is unusual because the resulting + * replacement string might actually be SMALLER than + * the original ERE */ return replace_repeat(reptok, reptoklen, atom, atomlen, firstnum, secondnum, REPEAT_ZERO); } else { /* (firstnum >= 1) */ return replace_repeat(reptok, reptoklen, atom, atomlen, firstnum, secondnum, REPEAT_SIMPLE); } - } else if (firstnum < secondnum) { /* {n,m} -> repeat n-1 times then alternate */ - /* x{n,m} => xx...x{1, m-n+1} => xx...x?x?x?..x? */ + } else if (firstnum < secondnum) { /* {n,m} -> repeat n-1 times then alternate */ + /* x{n,m} => xx...x{1, m-n+1} => xx...x?x?x?..x? */ return replace_repeat(reptok, reptoklen, atom, atomlen, firstnum, secondnum, REPEAT_WITH_Q); - } else { /* Error - shouldn't be here (n>m) */ + } else { /* error - shouldnt be here (n>m) */ FATAL("internal error"); } return 0; @@ -1383,7 +1383,7 @@ rescan: prestr++; } else cflag = 0; - n = 5 * strlen((const char *)prestr) + 1; /* BUG: was 2. what value? */ + n = 5 * strlen((const char *)prestr) + 1; /* BUG: was 2. what value? */ if (!adjbuf((char **)&buf, &bufsz, n, n, (char **)&bp, "relex1")) FATAL("out of space for reg expr %.10s...", lastre); for (;;) { @@ -1402,11 +1402,11 @@ rescan: ); *bp++ = c; /* } else if (c == '\n') { */ - /* FATAL("newline in character class - * %.20s...", lastre); */ + /* fatal("newline in character class + * %.20s...", lastre); */ } else if (c == '[' && *prestr == ':') { - /* POSIX char class names, Dag-Erling Smorgrav, - * des@ofug.org */ + /* POSIX char class names, dag-erling smorgrav, + * des@ofug.org */ for (cc = charclasses; cc->cc_name; cc++) if (strncmp((const char *)prestr + 1, (const char *)cc->cc_name, cc->cc_namelen) == 0) break; @@ -1414,14 +1414,14 @@ rescan: && prestr[2 + cc->cc_namelen] == ']') { prestr += cc->cc_namelen + 3; /* - * BUG: We begin at 1, instead of 0, - * since we would otherwise prematurely - * terminate the string for classes like - * [[:cntrl:]]. This means that we can't - * match the NUL character, not without - * first adapting the entire program to - * track each string's length. - */ + * BUG: we begin at 1, instead of 0, + * since we would otherwise prematurely + * terminate the string for classes like + * [[:cntrl:]]. this means that we cant + * match the NUL character, not without + * first adapting the entire program to + * track each string's length + */ for (i = 1; i <= UCHAR_MAX; i++) { if (!adjbuf((char **)&buf, &bufsz, bp - buf + 2, 100, (char **)&bp, "relex2")) FATAL( @@ -1449,11 +1449,11 @@ rescan: collate_char = *prestr++; if (*prestr == '.' && prestr[1] == ']') { prestr += 2; - /* Found it: map via locale TBD: for - now, simply return this char. This - is sufficient to pass conformance - test awk.ex 156 - */ + /* found it: map via locale TBD: for + * now, simply return this char. this + * is sufficient to pass conformance + * test awk.ex 156 + */ if (*prestr == ']') { prestr++; rlxval = collate_char; @@ -1466,11 +1466,11 @@ rescan: equiv_char = *prestr++; if (*prestr == '=' && prestr[1] == ']') { prestr += 2; - /* Found it: map via locale TBD: for now - simply return this char. This is - sufficient to pass conformance test - awk.ex 156 - */ + /* found it: map via locale TBD: for now + * simply return this char. this is + * sufficient to pass conformance test + * awk.ex 156 + */ if (*prestr == ']') { prestr++; rlxval = equiv_char; @@ -1494,13 +1494,13 @@ rescan: break; case '{': if (isdigit((int)*(prestr))) { - num = 0; /* Process as a repetition */ + num = 0; /* process as a repetition */ n = -1; m = -1; commafound = false; digitfound = false; startreptok = prestr - 1; - /* Remember start of previous atom here ? */ + /* remember start of previous atom here ? */ } else { /* just a { char, not a repetition */ rlxval = c; return CHAR; @@ -1529,7 +1529,7 @@ rescan: } } else { if (digitfound) { /* {n} same as {n,n} - */ + */ n = num; m = num; } else { /* {} */ @@ -1547,8 +1547,8 @@ rescan: /* must rescan input for next token */ goto rescan; } - /* Failed to replace: eat up {...} characters - and treat like just PLUS */ + /* failed to replace: eat up {...} characters + * and treat like just PLUS */ return PLUS; } else if (c == '\0') { FATAL("nonterminated character class %.20s", lastre); @@ -1591,7 +1591,7 @@ cgoto(fa *f, int s, int c) int *p, *q; int i, j, k; - /* assert(c == HAT || c < NCHARS); BUG: seg fault if disable test */ + /* assert(c == HAT || c < NCHARS); BUG: seg fault if disable test */ while (f->accept >= maxsetvec) { /* guessing here! */ resizesetvec(__func__); } diff --git a/cmd/posix/awk/lex.c b/cmd/posix/awk/lex.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #include "awk.h" #include "awkgram.tab.h" @@ -122,7 +122,7 @@ gettok(char **pbuf, int *psz) /* get next input token */ return c; *bp++ = c; - if (isalpha(c) || c == '_') { /* it's a varname */ + if (isalpha(c) || c == '_') { /* its a varname */ for (; (c = input()) != 0;) { if (bp - buf >= sz) if (!adjbuf(&buf, &sz, bp - buf + 2, 100, &bp, "gettok")) @@ -137,9 +137,9 @@ gettok(char **pbuf, int *psz) /* get next input token */ } *bp = 0; retc = 'a'; /* alphanumeric */ - } else { /* maybe it's a number, but could be . */ + } else { /* maybe its a number, but could be */ char *rem; - /* read input until can't be a number */ + /* read input until cant be a number */ for (; (c = input()) != 0;) { if (bp - buf >= sz) if (!adjbuf(&buf, &sz, bp - buf + 2, 100, &bp, "gettok")) @@ -484,7 +484,7 @@ string(void) *bp++ = n; break; - case 'x': /* hex \x0-9a-fA-F (exactly two) */ + case 'x': /* hex \x0-9a-fa-f (exactly two) */ { int i; @@ -514,7 +514,7 @@ string(void) break; } - case 'u': /* utf \u0-9a-fA-F (1..8) */ + case 'u': /* utf \u0-9a-fa-f (1..8) */ { int i; diff --git a/cmd/posix/awk/lib.c b/cmd/posix/awk/lib.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #define DEBUG #include "awk.h" @@ -45,7 +45,7 @@ int recsize = RECSIZE; char *fields; int fieldssize = RECSIZE; -Cell **fldtab; /* pointers to Cells */ +Cell **fldtab; /* pointers to cells */ static size_t len_inputFS = 0; static char *inputFS = NULL; /* FS at time of input, for field splitting */ @@ -118,11 +118,11 @@ initgetrec(void) /* * POSIX specifies that fields are supposed to be evaluated as if they were * split using the value of FS at the time that the record's value ($0) was - * read. + * read * - * Since field-splitting is done lazily, we save the current value of FS + * since field-splitting is done lazily, we save the current value of FS * whenever a new record is read in (implicitly or via getline), or when - * a new value is assigned to $0. + * a new value is assigned to $0 */ void savefs(void) @@ -230,7 +230,7 @@ extern int readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag); int readrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* read one record into buf */ { - int sep, c, isrec; // POTENTIAL BUG? isrec is a macro in awk.h + int sep, c, isrec; /* potential bug? isrec is a macro in awk.h */ char *rr = *pbuf, *buf = *pbuf; int bufsize = *pbufsize; char *rs = getsval(rsloc); @@ -294,11 +294,11 @@ readrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* read one record return isrec; } -/******************* +/* ****************** * loose ends here: - * \r\n should become \n - * what about bare \r? Excel uses that for embedded newlines - * can't have "" in unquoted fields, according to RFC 4180 + * \r\n should become \n + * what about bare \r? excel uses that for embedded newlines + * cant have "" in unquoted fields, according to RFC 4180 */ int @@ -312,13 +312,13 @@ readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* csv can have bool in_quote = false; sep = '\n'; /* the only separator; have to skip over \n embedded in - "..." */ + * "..." */ rr = buf; while ((c = getc(inf)) != EOF) { if (c == sep) { if (!in_quote) break; - if (rr > buf && rr[-1] == '\r') // remove \r if was \r\n + if (rr > buf && rr[-1] == '\r') /* remove \r if was \r\n */ rr--; } @@ -329,7 +329,7 @@ readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* csv can have if (c == '"') in_quote = !in_quote; } - if (c == '\n' && rr > buf && rr[-1] == '\r') // remove \r if was \r\n + if (c == '\n' && rr > buf && rr[-1] == '\r') /* remove \r if was \r\n */ rr--; if (!adjbuf(&buf, &bufsize, 1 + rr - buf, recsize, &rr, "readcsvrec 4")) @@ -342,7 +342,7 @@ readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* csv can have } char * -getargv(int n) /* get ARGV[n] */ +getargv(int n) /* get argv[n] */ { Array *ap; Cell *x; @@ -366,8 +366,8 @@ setclvar(char *s) /* set var=value from s */ Cell *q; double result; - /* commit f3d9187d4e0f02294fb1b0e31152070506314e67 broke T.argv test */ - /* I don't understand why it was changed. */ + /* commit f3d9187d4e0f02294fb1b0e31152070506314e67 broke t.argv test */ + /* i dont understand why it was changed */ for (p = s; *p != '='; p++) ; @@ -411,7 +411,7 @@ fldbld(void) /* create fields from current record */ i = 0; /* number of fields accumulated here */ if (inputFS == NULL) /* make sure we have a copy of FS */ savefs(); - if (!CSV && strlen(inputFS) > 1) { /* it's a regular expression */ + if (!CSV && strlen(inputFS) > 1) { /* its a regular expression */ i = refldbld(r, inputFS); } else if (!CSV && (sep = *inputFS) == ' ') { /* default whitespace */ for (i = 0;;) { @@ -432,7 +432,7 @@ fldbld(void) /* create fields from current record */ *fr++ = 0; } *fr = 0; - } else if (CSV) { /* CSV processing. no error handling */ + } else if (CSV) { /* CSV processing. no error handling */ if (*r != 0) { for (;;) { i++; @@ -446,11 +446,11 @@ fldbld(void) /* create fields from current record */ for (r++; *r != '\0';) { if (*r == '"' && r[1] != '\0' && r[1] == '"') { r += 2; /* doubled quote - */ + */ *fr++ = '"'; } else if (*r == '"' && (r[1] == '\0' || r[1] == ',')) { r++; /* skip over - closing quote */ + * closing quote */ break; } else { *fr++ = *r++; @@ -483,11 +483,11 @@ fldbld(void) /* create fields from current record */ fldtab[i]->tval = FLD | STR; } *fr = 0; - } else if (*r != 0) { /* if 0, it's a null field */ - /* subtle case: if length(FS) == 1 && length(RS > 0) - * \n is NOT a field separator (cf awk book 61,84). - * this variable is tested in the inner while loop. - */ + } else if (*r != 0) { /* if 0, its a null field */ + /* subtle case: if length(fs) == 1 && length(rs > 0) + * \n is NOT a field separator (cf awk book 61,84) + * this variable is tested in the inner while loop + */ int rtest = '\n'; /* normal case */ if (strlen(*RS) > 0) rtest = '\0'; @@ -590,7 +590,7 @@ growfldtab(int n) /* make new fields up to at least $n */ if (n > nf) nf = n; s = (nf + 1) * (sizeof(struct Cell *)); /* freebsd: how much do we need? */ - if (s / sizeof(struct Cell *) - 1 == (size_t)nf) /* didn't overflow */ + if (s / sizeof(struct Cell *) - 1 == (size_t)nf) /* didnt overflow */ fldtab = (Cell **)realloc(fldtab, s); else /* overflow sizeof int */ xfree(fldtab); /* make it null */ @@ -882,20 +882,20 @@ isclvar(const char *s) /* is s of form var=something ? */ /* strtod is supposed to be a proper test of what's a valid number */ /* appears to be broken in gcc on linux: thinks 0x123 is a valid FP number */ -/* wrong: violates 4.10.1.4 of ansi C standard */ +/* wrong: violates 4.10.1.4 of ansi c standard */ -/* well, not quite. As of C99, hex floating point is allowed. so this is - * a bit of a mess. We work around the mess by checking for a hexadecimal - * value and disallowing it. Similarly, we now follow gawk and allow only - * +nan, -nan, +inf, and -inf for NaN and infinity values. +/* well, not quite. as of C99, hex floating point is allowed. so this is + * a bit of a mess. we work around the mess by checking for a hexadecimal + * value and disallowing it. similarly, we now follow gawk and allow only + * +nan, -nan, +inf, and -inf for nan and infinity values */ /* - * This routine now has a more complicated interface, the main point + * this routine now has a more complicated interface, the main point * being to avoid the double conversion of a string to double, and * also to convey out, if requested, the information that the numeric - * value was a leading string or is all of the string. The latter bit - * is used in getfval(). + * value was a leading string or is all of the string. the latter bit + * is used in getfval() */ bool @@ -941,8 +941,8 @@ convert: *result = r; /* - * check for trailing stuff - */ + * check for trailing stuff + */ while (isspace((int)*ep)) ep++; diff --git a/cmd/posix/awk/main.c b/cmd/posix/awk/main.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ const char *version = "version 20260426"; @@ -112,12 +112,12 @@ fpecatch( ); } -/* Can this work with recursive calls? I don't think so. -void segvcatch(int n) -{ - FATAL("segfault. Do you have an unbounded recursive call?", n); -} -*/ +/* can this work with recursive calls? i dont think so + * void segvcatch(int n) + * { + * fatal("segfault. do you have an unbounded recursive call?", n); + * } + */ static const char * setfs(char *p) @@ -172,9 +172,9 @@ main(int argc, char *argv[]) #else (void)signal(SIGFPE, fpecatch); #endif - /*signal(SIGSEGV, segvcatch); experiment */ + /* signal(sigsegv, segvcatch); experiment */ - /* Set and keep track of the random seed */ + /* set and keep track of the random seed */ srand_seed = 1; srandom((unsigned long)srand_seed); @@ -217,7 +217,7 @@ main(int argc, char *argv[]) case 'F': /* set field separator */ fs = setfs(getarg(&argc, &argv, "no field separator")); break; - case 'v': /* -v a=1 to be done NOW. one -v for each */ + case 'v': /* -v a=1 to be done NOW. one -v for each */ vn = getarg(&argc, &argv, "no variable name"); if (isclvar(vn)) setclvar(vn); @@ -263,8 +263,8 @@ main(int argc, char *argv[]) envinit(environ); yyparse(); #if 0 - // Doing this would comply with POSIX, but is not compatible with - // other awks and with what most users expect. So comment it out. + /* doing this would comply with POSIX, but is not compatible with + * other awks and with what most users expect. so comment it out */ setlocale(LC_NUMERIC, ""); /* back to whatever it is locally */ #endif if (fs) diff --git a/cmd/posix/awk/maketab.c b/cmd/posix/awk/maketab.c @@ -1,31 +1,31 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ /* * this program makes the table to link function names - * and type indices that is used by execute() in run.c. - * it finds the indices in awkgram.tab.h, produced by bison. + * and type indices that is used by execute() in run.c + * it finds the indices in awkgram.tab.h, produced by bison */ #define _POSIX_C_SOURCE 200809L @@ -137,7 +137,7 @@ main(int argc, char *argv[]) printf("static const char * const printname[%d] = {\n", SIZE); i = 0; while (fgets(buf, sizeof buf, fp) != NULL) { - // 199 is sizeof(def) - 1 + /* 199 is sizeof(def) - 1 */ if (tokentype != TOK_ENUM) { n = sscanf(buf, "%1c %199s %199s %d", &c, def, name, &tok); if (n == 4 && c == '#' && strcmp(def, "define") == 0) { @@ -160,7 +160,7 @@ main(int argc, char *argv[]) if (tok < FIRSTTOKEN || tok > LASTTOKEN) { tokentype = TOK_UNKNOWN; /* fprintf(stderr, "maketab funny token %d %s - * ignored\n", tok, buf); */ + * ignored\n", tok, buf); */ continue; } names[tok - FIRSTTOKEN] = strdup(name); diff --git a/cmd/posix/awk/math.c b/cmd/posix/awk/math.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunknown-pragmas" diff --git a/cmd/posix/awk/parse.c b/cmd/posix/awk/parse.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #define DEBUG #include "awk.h" @@ -192,7 +192,7 @@ celltonode(Cell *a, int b) } Node * -rectonode(void) /* make $0 into a Node */ +rectonode(void) /* make $0 into a node */ { extern Cell *literal0; return op1(INDIRECT, celltonode(literal0, CUNK)); @@ -237,7 +237,7 @@ linkum(Node *a, Node *b) { Node *c; - if (errorflag) /* don't link things that are wrong */ + if (errorflag) /* dont link things that are wrong */ return a; if (a == NULL) return (b); @@ -251,7 +251,7 @@ linkum(Node *a, Node *b) void defn(Cell *v, Node *vl, Node *st) /* turn on FCN bit in definition, */ -{ /* body of function, arglist */ +{ /* body of function, arglist */ Node *p; int n; diff --git a/cmd/posix/awk/proto.h b/cmd/posix/awk/proto.h @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #include <stddef.h> #include <stdio.h> diff --git a/cmd/posix/awk/run.c b/cmd/posix/awk/run.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-parameter" @@ -52,7 +52,7 @@ static char *wide_char_to_byte_str(int rune, size_t *outlen); do { \ if (istemp(x)) \ tfree(x); \ - } while (/*CONSTCOND*/ 0) + } while (/* CONSTCOND */ 0) #else void tempfree(Cell *p) @@ -72,8 +72,8 @@ tempfree(Cell *p) /* #endif */ /* #endif */ -/* #ifndef FOPEN_MAX */ -/* #define FOPEN_MAX 40 */ /* max number of open files */ +/* #ifndef fopen_max */ +/* #define fopen_max 40 */ /* max number of open files */ /* #endif */ jmp_buf env; @@ -106,14 +106,14 @@ Node *curnode = NULL; /* the node being executed, for debugging */ /* buffer memory management */ int adjbuf(char **pbuf, int *psiz, int minlen, int quantum, char **pbptr, const char *whatrtn) -/* pbuf: address of pointer to buffer being managed - * psiz: address of buffer size variable - * minlen: minimum length of buffer needed +/* pbuf: address of pointer to buffer being managed + * psiz: address of buffer size variable + * minlen: minimum length of buffer needed * quantum: buffer size quantum - * pbptr: address of movable pointer into buffer, or 0 if none + * pbptr: address of movable pointer into buffer, or 0 if none * whatrtn: name of the calling routine if failure should cause fatal error * - * return 0 for realloc failure, !=0 for success + * return 0 for realloc failure, !=0 for success */ { if (minlen > *psiz) { @@ -167,8 +167,8 @@ execute(Node *u) /* execute a node of the parse tree */ recbld(); return (x); } - if (notlegal(a->nobj)) /* probably a Cell* but too risky to - print */ + if (notlegal(a->nobj)) /* probably a cell* but too risky to + * print */ FATAL("illegal statement"); proc = proctab[a->nobj - FIRSTTOKEN]; x = (*proc)(a->narg, a->nobj); @@ -229,7 +229,7 @@ ex1: struct Frame { /* stack frame for awk function calls */ int nargs; /* number of arguments in this call */ - Cell *fcncell; /* pointer to Cell for function */ + Cell *fcncell; /* pointer to cell for function */ Cell **args; /* pointer to array of arguments after execute */ Cell *retval; /* return value */ }; @@ -241,12 +241,12 @@ int nframe = 0; /* number of frames allocated */ struct Frame *frp = NULL; /* frame pointer. bottom level unused */ Cell * -call(Node **a, int n) /* function call. very kludgy and fragile */ +call(Node **a, int n) /* function call. very kludgy and fragile */ { static const Cell newcopycell = {OCELL, CCOPY, 0, EMPTY, 0.0, NUM | STR | DONTFREE, NULL, NULL}; int i, ncall, ndef; int freed = 0; /* handles potential double freeing when fcn & param - share a tempcell */ + * share a tempcell */ Node *x; Cell *args[NARGS], *oargs[NARGS]; /* BUG: fixed size arrays */ Cell *y, *z, *fcn; @@ -338,7 +338,7 @@ call(Node **a, int n) /* function call. very kludgy and fragile */ if (isexit(y) || isnext(y)) return y; if (freed == 0) { - tempfree(y); /* don't free twice! */ + tempfree(y); /* dont free twice! */ } z = frp->retval; /* return value */ DPRINTF("%s returns %g |%s| %o\n", s, getfval(z), getsval(z), z->tval); @@ -400,7 +400,7 @@ jump(Node **a, int n) /* break, continue, next, nextfile, return */ setsval(frp->retval, getsval(y)); else if (y->tval & NUM) setfval(frp->retval, getfval(y)); - else /* can't happen */ + else /* cant happen */ FATAL("bad type variable %d", y->tval); tempfree(y); } @@ -414,7 +414,7 @@ jump(Node **a, int n) /* break, continue, next, nextfile, return */ return (jbreak); case CONTINUE: return (jcont); - default: /* can't happen */ + default: /* cant happen */ FATAL("illegal jump type %d", n); } return 0; /* not reached */ @@ -536,7 +536,7 @@ array(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ Cell *x, *z; char *buf; - x = execute(a[0]); /* Cell* for symbol table */ + x = execute(a[0]); /* cell* for symbol table */ buf = makearraystring(a[1], __func__); if (!isarr(x)) { DPRINTF("making %s into an array\n", NN(x->nval)); @@ -559,7 +559,7 @@ awkdelete(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ { Cell *x; - x = execute(a[0]); /* Cell* for symbol table */ + x = execute(a[0]); /* cell* for symbol table */ if (x == symtabloc) { FATAL("cannot delete SYMTAB or its elements"); } @@ -607,18 +607,18 @@ intest(Node **a, int n) /* a[0] is index (list), a[1] is symtab */ /* ======== utf-8 code ========== */ /* - * Awk strings can contain ascii, random 8-bit items (eg Latin-1), - * or utf-8. u8_isutf tests whether a string starts with a valid - * utf-8 sequence, and returns 0 if not (e.g., high bit set). + * awk strings can contain ascii, random 8-bit items (eg latin-1), + * or utf-8. u8_isutf tests whether a string starts with a valid + * utf-8 sequence, and returns 0 if not (e.g., high bit set) * u8_nextlen returns length of next valid sequence, which is - * 1 for ascii, 2..4 for utf-8, or 1 for high bit non-utf. + * 1 for ascii, 2..4 for utf-8, or 1 for high bit non-utf * u8_strlen returns length of string in valid utf-8 sequences - * and/or high-bit bytes. Conversion functions go between byte - * number and character number. + * and/or high-bit bytes. conversion functions go between byte + * number and character number * - * In theory, this behaves the same as before for non-utf8 bytes. + * in theory, this behaves the same as before for non-utf8 bytes * - * Limited checking! This is a potential security hole. + * limited checking! this is a potential security hole */ /* is s the beginning of a valid utf-8 string? */ @@ -631,7 +631,7 @@ u8_isutf(const char *s) c = s[0]; if (c < 128 || awk_mb_cur_max == 1) - return 1; /* what if it's 0? */ + return 1; /* what if its 0? */ n = strlen(s); if (n >= 2 && ((c >> 5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) { @@ -649,9 +649,9 @@ u8_isutf(const char *s) return ret; } -/* Convert (prefix of) utf8 string to utf-32 rune. */ -/* Sets *rune to the value, returns the length. */ -/* No error checking: watch out. */ +/* convert (prefix of) utf8 string to utf-32 rune */ +/* sets *rune to the value, returns the length */ +/* no error checking: watch out */ int u8_rune(int *rune, const char *s) { @@ -683,7 +683,7 @@ u8_rune(int *rune, const char *s) *rune = c; ret = 1; } - return ret; /* returns one byte if sequence doesn't look like utf */ + return ret; /* returns one byte if sequence doesnt look like utf */ } /* return length of next sequence: 1 for ascii or random, 2..4 for valid utf8 */ @@ -756,7 +756,7 @@ u8_byte2char(const char *s, int bytenum) return charnum; } -/* runetochar() adapted from rune.c in the Plan 9 distribution */ +/* runetochar() adapted from rune.c in the plan 9 distribution */ enum { Runeerror = 128, /* from somewhere else */ @@ -795,14 +795,14 @@ runetochar(char *str, int c) return 1; } - /* two character sequence 00080-007FF => T2 Tx */ + /* two character sequence 00080-007FF => T2 tx */ if (c <= Rune2) { str[0] = T2 | (c >> 1 * Bitx); str[1] = Tx | (c & Maskx); return 2; } - /* three character sequence 00800-0FFFF => T3 Tx Tx */ + /* three character sequence 00800-0FFFF => T3 tx tx */ if (c > Runemax) c = Runeerror; if (c <= Rune3) { @@ -812,7 +812,7 @@ runetochar(char *str, int c) return 3; } - /* four character sequence 010000-1FFFFF => T4 Tx Tx Tx */ + /* four character sequence 010000-1FFFFF => T4 tx tx tx */ str[0] = T4 | (c >> 3 * Bitx); str[1] = Tx | ((c >> 2 * Bitx) & Maskx); str[2] = Tx | ((c >> 1 * Bitx) & Maskx); @@ -913,14 +913,14 @@ boolop(Node **a, int n) /* a[0] || a[1], a[0] && a[1], !a[0] */ return (False); else return (True); - default: /* can't happen */ + default: /* cant happen */ FATAL("unknown boolean operator %d", n); } - return 0; /*NOTREACHED*/ + return 0; /* NOTREACHED */ } Cell * -relop(Node **a, int n) /* a[0 < a[1], etc. */ +relop(Node **a, int n) /* a[0 < a[1], etc */ { int i; Cell *x, *y; @@ -974,10 +974,10 @@ relop(Node **a, int n) /* a[0 < a[1], etc. */ return (True); else return (False); - default: /* can't happen */ + default: /* cant happen */ FATAL("unknown relational operator %d", n); } - return 0; /*NOTREACHED*/ + return 0; /* NOTREACHED */ } void @@ -1027,7 +1027,7 @@ indirect(Node **a, int n) /* $( a[0] ) */ m = (int)val; tempfree(x); x = fieldadr(m); - x->ctype = OCELL; /* BUG? why are these needed? */ + x->ctype = OCELL; /* BUG? why are these needed? */ x->csub = CFLD; return (x); } @@ -1078,7 +1078,7 @@ substr(Node **a, int nnn) /* substr(a[0], a[1], a[2]) */ mb = u8_char2byte(s, m - 1); /* byte offset of start char in s */ nb = u8_char2byte(s, m - 1 + n); /* byte offset of end+1 char in s */ - temp = s[nb]; /* with thanks to John Linderman */ + temp = s[nb]; /* with thanks to john linderman */ s[nb] = '\0'; setsval(y, s + mb); s[nb] = temp; @@ -1103,7 +1103,7 @@ sindex(Node **a, int nnn) /* index(a[0], a[1]) */ for (q = p1, p2 = s2; *p2 != '\0' && *q == *p2; q++, p2++) continue; if (*p2 == '\0') { - /* v = (Awkfloat) (p1 - s1 + 1); origin 1 */ + /* v = (awkfloat) (p1 - s1 + 1); origin 1 */ /* should be a function: used in match() as well */ int i, len; @@ -1123,7 +1123,7 @@ sindex(Node **a, int nnn) /* index(a[0], a[1]) */ int has_utf8(char *s) /* return 1 if s contains any utf-8 (2 bytes or more) - character */ + * character */ { int n; @@ -1189,7 +1189,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver "of memory", os ); - /* Ignore size specifiers */ + /* ignore size specifiers */ if (strchr("hjLlqtz", *s) != NULL) { /* the ansi panoply */ t--; continue; @@ -1289,7 +1289,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver t = getsval(x); n = strlen(t); /* if simple format or no utf-8 in the string, sprintf - * works */ + * works */ if (!has_utf8(t) || strcmp(fmt, "%s") == 0) { if (fmtwd > n) n = fmtwd; @@ -1306,7 +1306,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver } /* get here if string has utf-8 chars and fmt is not - * plain %s */ + * plain %s */ /* "%-w.ps", where -, w and .p are all optional */ /* '0' before the w is a flag character */ /* fmt points at % */ @@ -1316,7 +1316,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver ljust = 1; f++; } - // flags '0' and '+' are recognized but skipped + /* flags '0' and '+' are recognized but skipped */ if (f[0] == '0') { f++; if (f[0] == '+') @@ -1335,27 +1335,27 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver } if (prec > u8_strlen(t)) prec = u8_strlen(t); - pad = wid > prec ? wid - prec : 0; // has to be >= 0 + pad = wid > prec ? wid - prec : 0; /* has to be >= 0 */ int i, k, n; - if (ljust) { // print prec chars from t, then pad blanks + if (ljust) { /* print prec chars from t, then pad blanks */ n = u8_char2byte(t, prec); for (k = 0; k < n; k++) { - // putchar(t[k]); + /* putchar(t[k]); */ *p++ = t[k]; } for (i = 0; i < pad; i++) { - // printf(" "); + /* printf(" "); */ *p++ = ' '; } - } else { // print pad blanks, then prec chars from t + } else { /* print pad blanks, then prec chars from t */ for (i = 0; i < pad; i++) { - // printf(" "); + /* printf(" "); */ *p++ = ' '; } n = u8_char2byte(t, prec); for (k = 0; k < n; k++) { - // putchar(t[k]); + /* putchar(t[k]); */ *p++ = t[k]; } } @@ -1365,17 +1365,17 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver case 'c': { /* - * If a numeric value is given, awk should just turn - * it into a character and print it: - * BEGIN { printf("%c\n", 65) } - * prints "A". - * - * But what if the numeric value is > 128 and - * represents a valid Unicode code point?!? We do - * our best to convert it back into UTF-8. If we - * can't, we output the encoding of the Unicode - * "invalid character", 0xFFFD. - */ + * if a numeric value is given, awk should just turn + * it into a character and print it: + * BEGIN { printf("%c\n", 65) } + * prints "a" + * + * but what if the numeric value is > 128 and + * represents a valid unicode code point?!? we do + * our best to convert it back into UTF-8. if we + * cant, we output the encoding of the unicode + * "invalid character", 0xfffd + */ if (isnum(x)) { int charval = (int)getfval(x); @@ -1383,13 +1383,13 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver if (charval < 128 || awk_mb_cur_max == 1) snprintf(p, BUFSZ(p), fmt, charval); else { - // possible unicode character + /* possible unicode character */ size_t count; char *bs = wide_char_to_byte_str(charval, &count); - if (bs == NULL) { // invalid character - // use unicode invalid - // character, 0xFFFD + if (bs == NULL) { /* invalid character */ + /* use unicode invalid + * character, 0xfffd */ static char invalid_char[] = "\357\277" "\275"; bs = invalid_char; @@ -1402,7 +1402,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver } else { *p++ = '\0'; /* explicit null byte */ *p = '\0'; /* next output will start - here */ + * here */ } break; } @@ -1414,14 +1414,14 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver break; } - // utf8 character, almost same song and dance as for %s + /* utf8 character, almost same song and dance as for %s */ int ljust = 0, wid = 0, prec = n, pad = 0; char *f = fmt + 1; if (f[0] == '-') { ljust = 1; f++; } - // flags '0' and '+' are recognized but skipped + /* flags '0' and '+' are recognized but skipped */ if (f[0] == '0') { f++; if (f[0] == '+') @@ -1438,21 +1438,21 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver if (f[0] == '.') { /* there is a .prec */ prec = strtol(++f, &f, 10); } - if (prec > 1) // %c --> only one character + if (prec > 1) /* %c: only one character */ prec = 1; - pad = wid > prec ? wid - prec : 0; // has to be >= 0 + pad = wid > prec ? wid - prec : 0; /* has to be >= 0 */ int i; - if (ljust) { // print one char from t, then pad blanks + if (ljust) { /* print one char from t, then pad blanks */ for (i = 0; i < n; i++) *p++ = t[i]; for (i = 0; i < pad; i++) { - // printf(" "); + /* printf(" "); */ *p++ = ' '; } - } else { // print pad blanks, then prec chars from t + } else { /* print pad blanks, then prec chars from t */ for (i = 0; i < pad; i++) { - // printf(" "); + /* printf(" "); */ *p++ = ' '; } for (i = 0; i < n; i++) @@ -1537,7 +1537,7 @@ awkprintf(Node **a, int n) /* printf */ } Cell * -arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ +arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ { Awkfloat i, j = 0; double v; @@ -1584,7 +1584,7 @@ arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ else i = pow_errcheck(i, j); break; - default: /* can't happen */ + default: /* cant happen */ FATAL("illegal arithmetic operator %d", n); } setfval(z, i); @@ -1592,7 +1592,7 @@ arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ } double -ipow(double x, int n) /* x**n. ought to be done by pow, but isn't always */ +ipow(double x, int n) /* x**n. ought to be done by pow, but isnt always */ { double v; @@ -1606,7 +1606,7 @@ ipow(double x, int n) /* x**n. ought to be done by pow, but isn't always */ } Cell * -incrdecr(Node **a, int n) /* a[0]++, etc. */ +incrdecr(Node **a, int n) /* a[0]++, etc */ { Cell *x, *z; int k; @@ -1627,8 +1627,8 @@ incrdecr(Node **a, int n) /* a[0]++, etc. */ } Cell * -assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc. */ -{ /* this is subtle; don't muck with it. */ +assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc */ +{ /* this is subtle; dont muck with it */ Cell *x, *y; Awkfloat xf, yf; double v; @@ -1637,8 +1637,8 @@ assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc. */ x = execute(a[0]); if (n == ASSIGN) { /* ordinary assignment */ if (x == y && !(x->tval & (FLD | REC)) && x != nfloc) - ; /* self-assignment: leave alone unless it's a field or - NF */ + ; /* self-assignment: leave alone unless its a field or + * NF */ else if ((y->tval & (STR | NUM)) == (STR | NUM)) { yf = getfval(y); setsval(x, getsval(y)); @@ -1794,7 +1794,7 @@ split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ } sep = *fs; ap = execute(a[1]); /* array name */ - /* BUG 7/26/22: this appears not to reset array: see C1/asplit */ + /* BUG 7/26/22: this appears not to reset array: see c1/asplit */ freesymtab(ap); DPRINTF("split: s=|%s|, a=%s, sep=|%s|\n", s, NN(ap->nval), fs); ap->tval &= ~STR; @@ -1803,7 +1803,7 @@ split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ n = 0; if (arg3type == REGEXPR && strlen((char *)((fa *)a[2])->restr) == 0) { - /* split(s, a, //); have to arrange that it looks like empty sep + /* split(s, a, // ); have to arrange that it looks like empty sep */ arg3type = 0; fs = ""; @@ -1811,7 +1811,7 @@ split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ } if (*s != '\0' && (strlen(fs) > 1 || arg3type == REGEXPR)) { /* reg expr */ fa *pfa; - if (arg3type == REGEXPR) { /* it's ready already */ + if (arg3type == REGEXPR) { /* its ready already */ pfa = (fa *)a[2]; } else { pfa = makedfa(fs, 1); @@ -1864,7 +1864,7 @@ split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ *fr++ = '"'; } else if (*s == '"' && (s[1] == '\0' || s[1] == ',')) { s++; /* skip over closing quote - */ + */ break; } else { *fr++ = *s++; @@ -2109,11 +2109,11 @@ nawk_convert(const char *s, int (*fun_c)(int), wint_t (*fun_wc)(wint_t)) (void)mbtowc(NULL, NULL, 0); /* reset internal state */ /* - * Reset internal state here too. - * Assign result to avoid a compiler warning. (Casting to void - * doesn't work.) - * Increment said variable to avoid a different warning. - */ + * reset internal state here too + * assign result to avoid a compiler warning. (casting to void + * doesnt work.) + * increment said variable to avoid a different warning + */ unused = wctomb(NULL, L'\0'); unused++; @@ -2189,7 +2189,7 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ switch (t) { case FLENGTH: if (isarr(x)) - u = ((Array *)x->sval)->nelem; /* GROT. should be function*/ + u = ((Array *)x->sval)->nelem; /* GROT. should be function */ else u = u8_strlen(getsval(x)); break; @@ -2242,13 +2242,13 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ break; case FRAND: /* random() returns numbers in [0..2^31-1] - * in order to get a number in [0, 1), divide it by 2^31 - */ + * in order to get a number in [0, 1), divide it by 2^31 + */ do { - /* exact if Awkfloat wide enough */ + /* exact if awkfloat wide enough */ u = (Awkfloat)random(); u /= 0x80000000; /* should be exact */ - } while (u >= 1.0); /* in case Awkfloat is narrow */ + } while (u >= 1.0); /* in case awkfloat is narrow */ break; case FSRAND: if (isrec(x)) /* no argument provided */ @@ -2280,7 +2280,7 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ else u = fflush(fp); break; - default: /* can't happen */ + default: /* cant happen */ FATAL("illegal function type %d", t); break; } @@ -2391,7 +2391,7 @@ openfile(int a, const char *us, bool *pnewflag) *pnewflag = false; return files[i].fp; } - if (a == FFLUSH) /* didn't find it, so don't create it! */ + if (a == FFLUSH) /* didn't find it, so dont create it! */ return NULL; for (i = 0; i < nfiles; i++) if (files[i].fp == NULL) @@ -2409,7 +2409,7 @@ openfile(int a, const char *us, bool *pnewflag) fflush(stdout); /* force a semblance of order */ - /* don't try to read or write a directory */ + /* dont try to read or write a directory */ if (a == LT || a == GT || a == APPEND) if (stat(s, &sbuf) == 0 && S_ISDIR(sbuf.st_mode)) return NULL; @@ -2426,7 +2426,7 @@ openfile(int a, const char *us, bool *pnewflag) fp = popen(s, "r"); } else if (a == LT) { /* getline <file */ fp = strcmp(s, "-") == 0 ? stdin : fopen(s, "r"); /* "-" is stdin */ - } else /* can't happen */ + } else /* cant happen */ FATAL("illegal redirection %d", a); if (fp != NULL) { files[i].fname = tostring(s); @@ -2724,18 +2724,18 @@ wide_char_to_byte_str(int rune, size_t *outlen) if (rune <= 0x0000007F) { buf[len++] = rune; } else if (rune <= 0x000007FF) { - // 110xxxxx 10xxxxxx + /* 110xxxxx 10xxxxxx */ buf[len++] = 0xC0 | (rune >> 6); buf[len++] = 0x80 | (rune & 0x3F); } else if (rune <= 0x0000FFFF) { - // 1110xxxx 10xxxxxx 10xxxxxx + /* 1110xxxx 10xxxxxx 10xxxxxx */ buf[len++] = 0xE0 | (rune >> 12); buf[len++] = 0x80 | ((rune >> 6) & 0x3F); buf[len++] = 0x80 | (rune & 0x3F); } else { - // 0x00010000 - 0x10FFFF - // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + /* 0x00010000 - 0x10ffff + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ buf[len++] = 0xF0 | (rune >> 18); buf[len++] = 0x80 | ((rune >> 12) & 0x3F); buf[len++] = 0x80 | ((rune >> 6) & 0x3F); diff --git a/cmd/posix/awk/tran.c b/cmd/posix/awk/tran.c @@ -1,26 +1,26 @@ -/**************************************************************** -Copyright (C) Lucent Technologies 1997 -All Rights Reserved - -Permission to use, copy, modify, and distribute this software and -its documentation for any purpose and without fee is hereby -granted, provided that the above copyright notice appear in all -copies and that both that the copyright notice and this -permission notice and warranty disclaimer appear in supporting -documentation, and that the name Lucent Technologies or any of -its entities not be used in advertising or publicity pertaining -to distribution of the software without specific, written prior -permission. - -LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. -IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY -SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER -IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -THIS SOFTWARE. -****************************************************************/ +/* *************************************************************** + * copyright (c) lucent technologies 1997 + * all rights reserved + * + * permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name lucent technologies or any of + * its entities not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission + * + * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY + * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE + * ************************************************************** */ #define DEBUG #include "awk.h" @@ -283,8 +283,8 @@ rehash(Array *tp) /* rehash items in small table into big one */ nsz = GROWTAB * tp->size; np = (Cell **)calloc(nsz, sizeof(*np)); - if (np == NULL) /* can't do it, but can keep running. */ - return; /* someone else will run out later. */ + if (np == NULL) /* cant do it, but can keep running */ + return; /* someone else will run out later */ for (i = 0; i < tp->size; i++) { for (cp = tp->tab[i]; cp; cp = op) { op = cp->cnext; @@ -312,7 +312,7 @@ lookup(const char *s, Array *tp) /* look for s in tp */ } Awkfloat -setfval(Cell *vp, Awkfloat f) /* set float val of a Cell */ +setfval(Cell *vp, Awkfloat f) /* set float val of a cell */ { int fldno; @@ -366,7 +366,7 @@ funnyvar(Cell *vp, const char *rw) } char * -setsval(Cell *vp, const char *s) /* set string val of a Cell */ +setsval(Cell *vp, const char *s) /* set string val of a cell */ { char *t; int fldno; @@ -401,7 +401,7 @@ setsval(Cell *vp, const char *s) /* set string val of a Cell */ if (!donerec) recbld(); } - t = s ? tostring(s) : tostring(""); /* in case it's self-assign */ + t = s ? tostring(s) : tostring(""); /* in case its self-assign */ if (freeable(vp)) xfree(vp->sval); vp->tval &= ~(NUM | DONTFREE | CONVC | CONVO); @@ -429,7 +429,7 @@ setsval(Cell *vp, const char *s) /* set string val of a Cell */ } Awkfloat -getfval(Cell *vp) /* get float val of a Cell */ +getfval(Cell *vp) /* get float val of a cell */ { if ((vp->tval & (NUM | STR)) == 0) funnyvar(vp, "read value of"); @@ -464,7 +464,7 @@ get_inf_nan(double d) } static char * -get_str_val(Cell *vp, char **fmt) /* get string val of a Cell */ +get_str_val(Cell *vp, char **fmt) /* get string val of a cell */ { char s[256]; double dtemp; @@ -478,36 +478,36 @@ get_str_val(Cell *vp, char **fmt) /* get string val of a Cell */ recbld(); /* - * ADR: This is complicated and more fragile than is desirable. - * Retrieving a string value for a number associates the string - * value with the scalar. Previously, the string value was - * sticky, meaning if converted via OFMT that became the value - * (even though POSIX wants it to be via CONVFMT). Or if CONVFMT - * changed after a string value was retrieved, the original value - * was maintained and used. Also not per POSIX. - * - * We work around this design by adding two additional flags, - * CONVC and CONVO, indicating how the string value was - * obtained (via CONVFMT or OFMT) and _also_ maintaining a copy - * of the pointer to the xFMT format string used for the - * conversion. This pointer is only read, **never** dereferenced. - * The next time we do a conversion, if it's coming from the same - * xFMT as last time, and the pointer value is different, we - * know that the xFMT format string changed, and we need to - * redo the conversion. If it's the same, we don't have to. - * - * There are also several cases where we don't do a conversion, - * such as for a field (see the checks below). - */ - - /* Don't duplicate the code for actually updating the value */ + * ADR: this is complicated and more fragile than is desirable + * retrieving a string value for a number associates the string + * value with the scalar. previously, the string value was + * sticky, meaning if converted via OFMT that became the value + * (even though POSIX wants it to be via CONVFMT). or if CONVFMT + * changed after a string value was retrieved, the original value + * was maintained and used. also not per POSIX + * + * we work around this design by adding two additional flags, + * CONVC and CONVO, indicating how the string value was + * obtained (via CONVFMT or OFMT) and _also_ maintaining a copy + * of the pointer to the xfmt format string used for the + * conversion. this pointer is only read, **never** dereferenced + * the next time we do a conversion, if its coming from the same + * xfmt as last time, and the pointer value is different, we + * know that the xfmt format string changed, and we need to + * redo the conversion. if its the same, we dont have to + * + * there are also several cases where we dont do a conversion, + * such as for a field (see the checks below) + */ + + /* dont duplicate the code for actually updating the value */ #define update_str_val(vp) \ { \ if (freeable(vp)) \ xfree(vp->sval); \ if ((p = get_inf_nan(vp->fval)) != NULL) \ strcpy(s, p); \ - else if (modf(vp->fval, &dtemp) == 0) /* it's integral */ \ + else if (modf(vp->fval, &dtemp) == 0) /* its integral */ \ snprintf(s, sizeof(s), "%.30g", vp->fval); \ else \ snprintf(s, sizeof(s), *fmt, vp->fval); \ @@ -560,13 +560,13 @@ done: } char * -getsval(Cell *vp) /* get string val of a Cell */ +getsval(Cell *vp) /* get string val of a cell */ { return get_str_val(vp, CONVFMT); } char * -getpssval(Cell *vp) /* get string val of a Cell for print */ +getpssval(Cell *vp) /* get string val of a cell for print */ { return get_str_val(vp, OFMT); } @@ -605,12 +605,12 @@ catstr(Cell *a, Cell *b) /* concatenate a and b */ FATAL("out of space concatenating %s and %s", sa, sb); snprintf(p, l, "%s%s", sa, sb); - l++; // add room for ' ' + l++; /* add room for ' ' */ char *newbuf = (char *)malloc(l); if (newbuf == NULL) FATAL("out of space concatenating %s and %s", sa, sb); - // See string() in lex.c; a string "xx" is stored in the symbol - // table as "xx ". + /* see string() in lex.c; a string "xx" is stored in the symbol + * table as "xx " */ snprintf(newbuf, l, "%s ", p); c = setsymtab(newbuf, p, 0.0, CON | STR | DONTFREE, symtab); free(p); diff --git a/cmd/posix/basename.c b/cmd/posix/basename.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <libgen.h> #include <stdio.h> diff --git a/cmd/posix/bc.y b/cmd/posix/bc.y @@ -38,7 +38,7 @@ static void quit(void); static char *code(char *, ...); static char *forcode(Macro *, char *, char *, char *, char *); static char *whilecode(Macro *, char *, char *); -static char *ifcode(Macro *, char *, char *); +static char *ifcode(Macro *, char *, char *, char *); static char *funcode(Macro *, char *, char *, char *); static char *param(char *, char *), *local(char *, char *); static char *retcode(char *); @@ -51,6 +51,7 @@ static char *ary(char *); static void writeout(char *); static char *yytext, *buff, *unwind; +static size_t buffcap; static char *filename; static FILE *filep; static int lineno, nerr, flowid; @@ -65,7 +66,7 @@ static char *dcprog = "dc"; %union { char *str; - char id[2]; + char id[16]; // matches dc's own REGSIZ: an extended register name's cap Macro *macro; } @@ -92,10 +93,14 @@ static char *dcprog = "dc"; %token OBASE %token AUTO PARAM %token PRINT +%token ELSE +%token HALT +%token READ %type <str> item statlst scolonlst %type <str> function assign nexpr expr exprstat rel stat ary cond %type <str> autolst arglst parlst +%type <str> prlst pritem %type <str> params param locals local %type <macro> def if for while @@ -134,19 +139,41 @@ statlst : {$$ = code("");} ; stat : exprstat - | PRINT expr {$$ = code("%sps.", $2);} - | PRINT STRING {$$ = code("[%s]P", $2);} - | PRINT STRING ',' expr {$$ = code("[%s]P%sps.", $2, $4);} + | PRINT prlst {$$ = $2;} | STRING {$$ = code("[%s]P", $1);} | BREAK {$$ = brkcode();} | QUIT {quit();} + | HALT {$$ = code("q");} | RETURN {$$ = retcode(code(" 0"));} - | RETURN '(' expr ')' {$$ = retcode($3);} + | RETURN expr {$$ = retcode($2);} | RETURN '(' ')' {$$ = retcode(code(" 0"));} - | while cond stat {$$ = whilecode($1, $2, $3);} - | if cond stat {$$ = ifcode($1, $2, $3);} + | while cond optnl stat {$$ = whilecode($1, $2, $4);} + | if cond optnl stat {$$ = ifcode($1, $2, $4, NULL);} + | if cond optnl stat ELSE optnl stat {$$ = ifcode($1, $2, $4, $7);} | '{' statlst '}' {$$ = $2;} - | for '(' expr ';' rel ';' expr ')' stat {$$ = forcode($1, $3, $5, $7, $9);} + | for '(' expr ';' rel ';' expr ')' optnl stat {$$ = forcode($1, $3, $5, $7, $10);} + ; + +// real scripts routinely put a while/if/for's own body on the next +// line instead of right after the condition; nothing else in this +// grammar needs a newline here, since a body wrapped in { } already +// goes through statlst, which handles its own internal newlines +optnl : + | optnl '\n' + ; + +// print takes a comma-separated list of any length, mixing strings +// and expressions freely: real scripts (the kernel's own timeconst.bc +// generator among them) routinely print three or more at once. no +// item here ever gets an automatic trailing newline of its own, +// matching real bc: whatever newlines appear come from the items +// themselves +prlst : pritem + | prlst ',' pritem {$$ = code("%s%s", $1, $3);} + ; + +pritem : expr {$$ = code("%sn", $1);} + | STRING {$$ = code("[%s]P", $1);} ; while : WHILE {$$ = macro(LOOP);} @@ -214,6 +241,7 @@ expr : nexpr nexpr : NUMBER {$$ = code(" %s", code($1));} | ID {$$ = code("l%s", var($1));} + | READ '(' ')' {$$ = code("?");} | DOT {$$ = code("l.");} | SCALE {$$ = code("K");} | IBASE {$$ = code("I");} @@ -277,21 +305,38 @@ writeout(char *s) goto err; free(s); return; - + err: eprintf("writing to dc:"); } +// grows the shared code buffer geometrically to fit at least 'need' +// bytes: a single generated dc macro (an if/else body, a print list, +// a deeply nested function) has no fixed upper bound, unlike the +// stdio-buffering constant BUFSIZ this buffer borrowed its original +// size from +static void +growbuff(size_t need) +{ + size_t newcap; + + newcap = buffcap; + while (newcap < need) + newcap *= 2; + buff = erealloc(buff, newcap); + buffcap = newcap; +} + static char * code(char *fmt, ...) { - char *s, *t; + char *t; va_list ap; - int c, len, room; + int c, len; + size_t off, room; va_start(ap, fmt); - room = BUFSIZ; - for (s = buff; *fmt; s += len) { + for (off = 0; *fmt; off += (size_t)len) { len = 1; if ((c = *fmt++) != '%') goto append; @@ -299,41 +344,41 @@ code(char *fmt, ...) switch (*fmt++) { case 'd': c = va_arg(ap, int); - len = snprintf(s, room, "%d", c); - if (len < 0 || len >= room) - goto err; + for (;;) { + room = buffcap - off; + len = snprintf(buff + off, room, "%d", c); + if (len < 0) + eprintf("unable to code requested operation\n"); + if ((size_t)len < room) + break; + growbuff(off + (size_t)len + 1); + } break; case 'c': c = va_arg(ap, int); goto append; case 's': - t = va_arg(ap, void *); + t = va_arg(ap, void *); len = strlen(t); - if (len >= room) - goto err; - memcpy(s, t, len); + if ((size_t)len >= buffcap - off) + growbuff(off + (size_t)len + 1); + memcpy(buff + off, t, len); free(t); break; case '%': append: - if (room <= 1) - goto err; - *s = c; + if (buffcap - off <= 1) + growbuff(off + 2); + buff[off] = c; break; default: abort(); } - - room -= len; } va_end(ap); - *s = '\0'; + buff[off] = '\0'; return estrdup(buff); - -err: - eprintf("unable to code requested operation\n"); - return NULL; } static Macro * @@ -493,17 +538,72 @@ whilecode(Macro *d, char *cmp, char *body) return s; } +// the trailing relational operator on a cond's own generated code +// (see the rel grammar rule) is always one of these six forms; an +// else branch runs on whichever of them means "the opposite happened" static char * -ifcode(Macro *d, char *cmp, char *body) +invertrel(char *cmp) { + size_t n = strlen(cmp); + const char *suffix; + size_t keep; char *s; + if (n >= 2 && strcmp(cmp + n - 2, "!=") == 0) { + keep = n - 2; + suffix = "="; + } else if (n >= 2 && strcmp(cmp + n - 2, "!<") == 0) { + keep = n - 2; + suffix = "<"; + } else if (n >= 2 && strcmp(cmp + n - 2, "!>") == 0) { + keep = n - 2; + suffix = ">"; + } else if (n >= 1 && cmp[n - 1] == '=') { + keep = n - 1; + suffix = "!="; + } else if (n >= 1 && cmp[n - 1] == '<') { + keep = n - 1; + suffix = "!<"; + } else if (n >= 1 && cmp[n - 1] == '>') { + keep = n - 1; + suffix = "!>"; + } else { + yyerror("cannot invert comparison for else"); + return NULL; + } + + s = emalloc(keep + strlen(suffix) + 1); + memcpy(s, cmp, keep); + strcpy(s + keep, suffix); + + return s; +} + +// an else branch's own stored body needs a register distinct from the +// then branch's d->id: nested caps how high d->id itself ever goes, +// so offsetting by it lands on a register no other nesting level, and +// no ordinary (single-letter or, under -i, named) variable, ever uses +static char * +ifcode(Macro *d, char *cmp, char *body, char *ebody) +{ + char *s, *inv; + s = code(sflag ? "[%s]s<%d>" : "[%s]s%c", body, d->id); writeout(s); - s = code(sflag ? "%s<%d> " : "%s%c ", - cmp, d->id); + if (ebody) { + s = code(sflag ? "[%s]s<%d>" : "[%s]s%c", + ebody, d->id + NESTED_MAX); + writeout(s); + + inv = invertrel(cmp); + s = code(sflag ? "%s<%d> %s<%d> " : "%s%c %s%c ", + cmp, d->id, inv, d->id + NESTED_MAX); + } else { + s = code(sflag ? "%s<%d> " : "%s%c ", + cmp, d->id); + } nested--; return s; @@ -582,6 +682,9 @@ iden(int ch) {"obase", OBASE}, {"auto", AUTO}, {"print", PRINT}, + {"else", ELSE}, + {"halt", HALT}, + {"read", READ}, {NULL} }; struct keyword *p; @@ -610,8 +713,16 @@ iden(int ch) if (p->str) return p->token; + // strict POSIX bc only ever names a variable/function with a + // single lowercase letter; every real bc script in the wild + // (the kernel's own timeconst.bc among them) freely uses + // multi-character names anyway, same as GNU bc's own default +#if !FEATURE_BC_MULTICHAR if (!sflag) yyerror("invalid keyword"); +#endif + if (strlen(yytext) >= sizeof(yylval.id)) + yyerror("identifier too long"); strcpy(yylval.id, yytext); return ID; } @@ -676,6 +787,50 @@ string(int ch) for (bp = yytext; bp < &yytext[BUFSIZ]; ++bp) { if ((ch = getc(filep)) == '"') break; +#if FEATURE_BC_ESCAPES + // strict POSIX bc has no escape sequences in a string at + // all; every real script (again, the kernel's own scripts + // among them) assumes GNU bc's \n/\t/etc, since dc's own + // string reader passes a literal byte straight through + // with nothing left to turn it into a real newline later + if (ch == '\\') { + switch (ch = getc(filep)) { + case 'a': + ch = '\a'; + break; + case 'b': + ch = '\b'; + break; + case 'f': + ch = '\f'; + break; + case 'n': + ch = '\n'; + break; + case 'r': + ch = '\r'; + break; + case 't': + ch = '\t'; + break; + case 'v': + ch = '\v'; + break; + case 'q': + // GNU bc's own escape for a literal double + // quote, needed since a bc string's own + // delimiter is " with no other way in + ch = '"'; + break; + case '\\': + case '"': + break; + default: + *bp++ = '\\'; + break; + } + } +#endif *bp = ch; } @@ -808,9 +963,27 @@ static void spawn(void) { int fds[2]; + // dc only accepts the extended, multi-character register + // syntax bc.y's own ftn()/var()/ary() emit for a non-single- + // letter name (see iden() above) when told -i: whenever this + // build can produce that syntax at all, dc always needs it +#if FEATURE_BC_MULTICHAR + char *par = "-i"; +#else char *par = sflag ? "-i" : NULL; +#endif char errmsg[] = "bc:error execing dc\n"; + // fd 0 is about to become the read end of the code pipe below, + // but dc's own "?" (bc's read()) needs the real, original stdin: + // stash it on a fixed fd dc knows to check, or read() would read + // straight out of this project's own generated dc code instead + // of whatever the user actually piped in. this has to happen + // before pipe() claims its own two fds, or dup2 here could + // clobber one of them (fd 3 is often the next one pipe() itself + // would have picked) + dup2(0, 3); + if (pipe(fds) < 0) eprintf("creating pipe:"); @@ -872,7 +1045,11 @@ bc(char *fname) static void usage(void) { +#if FEATURE_BC_QUIET + eprintf("usage: %s [-p dc][-cdlqs]\n", argv0); +#else eprintf("usage: %s [-p dc][-cdls]\n", argv0); +#endif } int @@ -892,6 +1069,11 @@ main(int argc, char *argv[]) case 'l': lflag = 1; break; +#if FEATURE_BC_QUIET + // for compat with sucky impls + case 'q': + break; +#endif case 's': sflag = 1; break; @@ -899,8 +1081,9 @@ main(int argc, char *argv[]) usage(); } ARGEND - yytext = malloc(BUFSIZ); - buff = malloc(BUFSIZ); + yytext = malloc(BUFSIZ); + buffcap = BUFSIZ; + buff = malloc(buffcap); if (!yytext || !buff) eprintf("out of memory\n"); flowid = 128; @@ -910,9 +1093,17 @@ main(int argc, char *argv[]) if (lflag) bc(PREFIX "/share/misc/bc.library"); - while (*argv) - bc(*argv++); - bc(NULL); + // stdin is only the script source when no file was given at all: + // a real file argument alongside piped stdin data (the kernel's + // own "echo $HZ | bc -q file.bc" being the standing example) means + // that data is meant for read(), not for bc itself to parse as + // more of the program + if (!*argv) { + bc(NULL); + } else { + while (*argv) + bc(*argv++); + } quit(); } diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <stdint.h> @@ -25,7 +25,7 @@ isleap(size_t year, enum caltype cal) if (year % 100 == 0) return 0; return (year % 4 == 0); - } else { /* cal == Julian */ + } else { /* cal == julian */ return (year % 4 == 0); } } @@ -38,7 +38,7 @@ monthlength(size_t year, int month, enum caltype cal) return (month == FEB && isleap(year, cal)) ? 29 : mdays[month]; } -/* From http://www.tondering.dk/claus/cal/chrweek.php#calcdow */ +/* From http:// www.tondering.dk/claus/cal/chrweek.php#calcdow */ static int dayofweek(size_t year, int month, int dom, enum caltype cal) { @@ -51,7 +51,7 @@ dayofweek(size_t year, int month, int dom, enum caltype cal) if (cal == GREGORIAN) return (dom + y + y / 4 - y / 100 + y / 400 + (31 * m) / 12) % 7; - else /* cal == Julian */ + else /* cal == julian */ return (5 + dom + y + y / 4 + (31 * m) / 12) % 7; } @@ -59,7 +59,7 @@ static void printgrid(size_t year, int month, int fday, int line) { enum caltype cal; - int offset, dom, d = 0, trans; /* are we in the transition from Julian to Gregorian? */ + int offset, dom, d = 0, trans; /* are we in the transition from julian to gregorian? */ int today = 0; cal = (year < TRANS_YEAR || (year == TRANS_YEAR && month <= TRANS_MONTH)) ? JULIAN : GREGORIAN; @@ -187,7 +187,7 @@ main(int argc, char *argv[]) fday = 0; if (!isatty(STDOUT_FILENO)) - ltime = NULL; /* don't highlight today's date */ + ltime = NULL; /* dont highlight today's date */ #ifdef FEATURE_CAL_EXT ncols = 3; @@ -223,7 +223,7 @@ main(int argc, char *argv[]) fday = estrtonum(EARGF(usage()), 0, 6); break; // ?man -m: specify mode or limit - case 'm': /* Monday */ + case 'm': /* monday */ fday = 1; break; // ?man -n:num: print line numbers or counts @@ -233,7 +233,7 @@ main(int argc, char *argv[]) ); break; // ?man -s: silent mode or print summary - case 's': /* Sunday */ + case 's': /* sunday */ fday = 0; break; #endif diff --git a/cmd/posix/cat.c b/cmd/posix/cat.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <string.h> @@ -62,7 +62,7 @@ main(int argc, char *argv[]) // ?man ## Exit status // ?man // ?man cat exits 0 on success, and >0 if an error occurs reading any - // file ?man or writing to standard output ?man ?man ## See also ?man + // file ?man or writing to standard output ?man ?man ## see also ?man // ?man cp(1), dd(1) // ?man diff --git a/cmd/posix/chgrp.c b/cmd/posix/chgrp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/chmod.c b/cmd/posix/chmod.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <sys/stat.h> @@ -57,12 +57,12 @@ main(int argc, char *argv[]) case 'X': case 's': case 't': - /* -[rwxXst] are valid modes, so we're done */ + /* -[rwxxst] are valid modes, so we're done */ if (i == 1) goto done; /* fallthrough */ case '-': - /* -- terminator */ + /* "--" option terminator */ if (i == 1 && !(*argv)[i + 1]) { argv++; argc--; diff --git a/cmd/posix/chown.c b/cmd/posix/chown.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <fcntl.h> diff --git a/cmd/posix/cksum.c b/cmd/posix/cksum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <inttypes.h> diff --git a/cmd/posix/cmp.c b/cmd/posix/cmp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/comm.c b/cmd/posix/comm.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/cp.c b/cmd/posix/cp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/cut.c b/cmd/posix/cut.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> @@ -8,22 +8,22 @@ #include "utf.h" #include "util.h" -typedef struct Range { +struct Range { size_t min, max; struct Range *next; -} Range; +}; -static Range *list = NULL; -static char mode = 0; -static char *delim = "\t"; -static size_t delimlen = 1; -static int nflag = 0; -static int sflag = 0; +static struct Range *list = NULL; +static char mode = 0; +static char *delim = "\t"; +static size_t delimlen = 1; +static int nflag = 0; +static int sflag = 0; static void -insert(Range *r) +insert(struct Range *r) { - Range *l, *p, *t; + struct Range *l, *p, *t; for (p = NULL, l = list; l; p = l, l = l->next) { if (r->max && r->max + 1 < l->min) { @@ -48,9 +48,9 @@ insert(Range *r) static void parselist(char *str) { - char *s; - size_t n = 1; - Range *r; + char *s; + size_t n = 1; + struct Range *r; if (!*str) eprintf("empty list\n"); @@ -109,7 +109,8 @@ seek(struct line *s, size_t pos, size_t *prev, size_t count) static void cut(FILE *fp, const char *fname) { - Range *r; + struct Range *r; + struct line s; static struct line line; static size_t size; diff --git a/cmd/posix/date.c b/cmd/posix/date.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdio.h> diff --git a/cmd/posix/dd.c b/cmd/posix/dd.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <fcntl.h> @@ -71,9 +71,17 @@ ucase(unsigned char *buf, size_t len) buf[0] = toupper(buf[0]); } +enum Status { + STATUS_DEFAULT, + STATUS_NOXFER, + STATUS_NONE, +}; + static void -summary(void) +summary(enum Status status) { + if (status == STATUS_NONE) + return; fprintf(stderr, "%" PRIdMAX "+%" PRIdMAX " records in\n", (intmax_t)ifull, (intmax_t)ipart); fprintf(stderr, "%" PRIdMAX "+%" PRIdMAX " records out\n", (intmax_t)ofull, (intmax_t)opart); } @@ -92,6 +100,7 @@ main(int argc, char *argv[]) NOTRUNC = 1 << 4, SYNC = 1 << 5, } conv = 0; + enum Status status = STATUS_DEFAULT; char *arg, *val, *end; const char *iname = "-", *oname = "-"; int ifd = 0, ofd = 1, eof = 0; @@ -123,6 +132,13 @@ main(int argc, char *argv[]) seek = estrtonum(val, 0, LLONG_MAX); } else if (strcmp(arg, "count") == 0) { count = estrtonum(val, 0, LLONG_MAX); + } else if (strcmp(arg, "status") == 0) { + if (strcmp(val, "none") == 0) + status = STATUS_NONE; + else if (strcmp(val, "noxfer") == 0) + status = STATUS_NOXFER; + else + eprintf("unknown status level '%s'\n", val); } else if (strcmp(arg, "conv") == 0) { do { end = strchr(val, ','); @@ -198,7 +214,7 @@ main(int argc, char *argv[]) weprintf("read:"); if (!(conv & NOERROR)) return 1; - summary(); + summary(status); if (!(conv & SYNC)) continue; ret = 0; @@ -241,7 +257,7 @@ main(int argc, char *argv[]) ipos -= opos; opos = 0; } - summary(); + summary(status); return 0; } diff --git a/cmd/posix/df.c b/cmd/posix/df.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/statvfs.h> diff --git a/cmd/posix/diff.c b/cmd/posix/diff.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "paths.h" #include "util.h" #include "wexec.h" @@ -2079,7 +2079,7 @@ proceed: 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); + printf("%ds/.// \n", a + edoffset - 1); b = a + edoffset - 1; a = b + 1; c += edoffset; diff --git a/cmd/posix/dirname.c b/cmd/posix/dirname.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <libgen.h> #include <stdio.h> diff --git a/cmd/posix/du.c b/cmd/posix/du.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/posix/echo.c b/cmd/posix/echo.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "util.h" #include <stdio.h> diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <regex.h> @@ -24,11 +24,11 @@ #define AFTER 0 #define BEFORE 1 -typedef struct { +struct String { char *str; size_t cap; size_t siz; -} String; +}; struct hline { off_t seek; @@ -48,7 +48,7 @@ struct undo { static char *prompt = "*"; static regex_t *pattern; static regmatch_t matchs[10]; -static String lastre; +static struct String lastre; static int optverbose, optprompt, exstatus, optdiag = 1; static int marks['z' - 'a' + 1]; @@ -58,13 +58,13 @@ static jmp_buf savesp; static char *lasterr; static size_t idxsize, lastidx; static struct hline *zero; -static String text; +static struct String text; static char savfname[FILENAME_MAX]; static char tmpname[FILENAME_MAX]; static int scratch; static int pflag, modflag, uflag, gflag; static size_t csize; -static String cmdline; +static struct String cmdline; static char *ocmdline; static int inputidx; static char *rhs; @@ -106,8 +106,8 @@ prevln(int line) return (line < 0) ? lastln : line; } -static String * -copystring(String *s, char *from) +static struct String * +copystring(struct String *s, char *from) { size_t len; char *t; @@ -124,8 +124,8 @@ copystring(String *s, char *from) return s; } -static String * -string(String *s) +static struct String * +string(struct String *s) { free(s->str); s->str = NULL; @@ -136,7 +136,7 @@ string(String *s) } static char * -addchar(char c, String *s) +addchar(char c, struct String *s) { size_t cap = s->cap, siz = s->siz; char *t = s->str; @@ -303,8 +303,8 @@ newundo(int from1, int from2) } /* - * relink: to1 <- from1 - * from2 -> to2 + * relink: to1 <- from1 + * from2 -> to2 */ static void relink(int to1, int from1, int from2, int to2) @@ -464,13 +464,13 @@ rematch(int num) return 1; } - /* Zero width match was found at the end of the input, done */ + /* zero width match was found at the end of the input, done */ if (lastmatch[off] == '\n') { lastmatch += off; return 0; } - /* Zero width match at the current posiion, find the next one */ + /* zero width match at the current posiion, find the next one */ text.str[text.siz - 2] = '\0'; r = !regexec(pattern, lastmatch + off + 1, 10, matchs, REG_NOTBOL); text.str[text.siz - 2] = '\n'; @@ -478,7 +478,7 @@ rematch(int num) if (!r) return 0; - /* Re-adjust matches to account for +1 in regexec */ + /* re-adjust matches to account for +1 in regexec */ for (m = matchs; m < &matchs[10]; m++) { m->rm_so += 1; m->rm_eo += 1; @@ -778,7 +778,7 @@ chksignals(void) static const char * expandcmd(void) { - static String cmd; + static struct String cmd; char *p; int c, repl = 0; @@ -1027,7 +1027,7 @@ static void append(int num) { int ch; - static String line; + static struct String line; curln = num; while (moreinput()) { @@ -1089,7 +1089,7 @@ join(void) { int i; char *t, c; - static String s; + static struct String s; string(&s); for (i = line1;; i = nextln(i)) { @@ -1156,7 +1156,7 @@ static void getrhs(int delim) { int c; - static String s; + static struct String s; string(&s); while ((c = input()) != '\0' && c != delim) @@ -1196,7 +1196,7 @@ getnth(void) } static void -addpre(String *s) +addpre(struct String *s) { char *p; @@ -1205,7 +1205,7 @@ addpre(String *s) } static void -addpost(String *s) +addpost(struct String *s) { char c, *p; @@ -1215,7 +1215,7 @@ addpost(String *s) } static int -addsub(String *s, int nth, int nmatch) +addsub(struct String *s, int nth, int nmatch) { char *end, *q, *p, c; int sub; @@ -1258,7 +1258,7 @@ static void subline(int num, int nth) { int i, m, changed; - static String s; + static struct String s; string(&s); i = changed = 0; @@ -1288,10 +1288,10 @@ subst(int nth) subline(line, nth); /* - * The substitution command can add lines, so - * we have to skip lines until we find the - * index that we saved before the substitution - */ + * the substitution command can add lines, so + * we have to skip lines until we find the + * index that we saved before the substitution + */ do line = nextln(line); while (getindex(line) != next); diff --git a/cmd/posix/env.c b/cmd/posix/env.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> diff --git a/cmd/posix/expand.c b/cmd/posix/expand.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdlib.h> diff --git a/cmd/posix/expr.c b/cmd/posix/expr.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <stdio.h> @@ -238,7 +238,7 @@ parse(char *expr[], int numexpr) switch ((type = lex(*expr, &v))) { case VAL: /* treatment of *expr is not known until - * doop(); treat as a string for now */ + * doop(); treat as a string for now */ valp->str = *expr; valp++; break; diff --git a/cmd/posix/false.c b/cmd/posix/false.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ // ?man false: return unsuccessful exit status // ?man exit with status 1 representing failure diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "config.h" #include "util.h" @@ -26,32 +26,32 @@ union extra { intmax_t i; }; -/* Argument passed into a primary's function */ +/* argument passed into a primary's function */ struct arg { char *path; struct stat *st; union extra extra; }; -/* Information about each primary, for lookup table */ +/* information about each primary, for lookup table */ struct pri_info { char *name; int (*func)(struct arg *arg); char **(*getarg)(char **argv, union extra *extra); void (*freearg)(union extra extra); - char narg; /* -xdev, -depth, -print don't take args but have getarg() */ + char narg; /* -xdev, -depth, -print dont take args but have getarg() */ }; -/* Information about operators, for lookup table */ +/* information about operators, for lookup table */ struct op_info { - char *name; /* string representation of op */ - char type; /* from tok.type */ - char prec; /* precedence */ + char *name; /* string representation of op */ + char type; /* from tok.type */ + char prec; /* precedence */ char nargs; /* number of arguments (unary or binary) */ - char lassoc; /* left associative */ + char lassoc; /* left associative */ }; -/* Token when lexing/parsing +/* token when lexing/parsing * (although also used for the expression tree) */ struct tok { struct tok *left, *right; /* if (type == NOT) left = NULL */ @@ -90,21 +90,21 @@ struct execarg { union { struct { char ***braces; /* NULL terminated list of pointers into - argv where {} were */ + * argv where {} were */ } s; /* semicolon */ struct { size_t arglen; /* number of bytes in argv before files - are added */ + * are added */ size_t filelen; /* numer of bytes in file names added to - argv */ + * argv */ size_t first; /* index one past last arg, where first - file goes */ - size_t next; /* index where next file goes */ - size_t cap; /* capacity of argv */ + * file goes */ + size_t next; /* index where next file goes */ + size_t cap; /* capacity of argv */ } p; /* plus */ } u; char **argv; /* NULL terminated list of arguments (allocated if isplus) - */ + */ char isplus; /* -exec + instead of -exec ; */ }; @@ -116,11 +116,11 @@ struct findhist { ino_t ino; }; -/* Utility */ +/* utility */ static int spawn(char *argv[]); static int do_stat(char *path, struct stat *sb, struct findhist *hist); -/* Primaries */ +/* primaries */ static int pri_name(struct arg *arg); #if FEATURE_FIND_INAME static int pri_iname(struct arg *arg); @@ -192,7 +192,7 @@ static int pri_print0(struct arg *arg); static int pri_newer(struct arg *arg); static int pri_depth(struct arg *arg); -/* Getargs */ +/* getargs */ static char **get_name_arg(char *argv[], union extra *extra); static char **get_path_arg(char *argv[], union extra *extra); static char **get_xdev_arg(char *argv[], union extra *extra); @@ -208,12 +208,12 @@ static char **get_print_arg(char *argv[], union extra *extra); static char **get_newer_arg(char *argv[], union extra *extra); static char **get_depth_arg(char *argv[], union extra *extra); -/* Freeargs */ +/* freeargs */ static void free_extra(union extra extra); static void free_exec_arg(union extra extra); static void free_ok_arg(union extra extra); -/* Parsing/Building/Running */ +/* parsing/building/running */ static void fill_narg(char *s, struct narg *n); static struct pri_info *find_primary(char *name); static struct op_info *find_op(char *name); @@ -325,24 +325,24 @@ static struct tok *root; /* points to root of expression tree, inside toks array static struct timespec start; /* time find was started, used for -[acm]time */ static size_t envlen; /* number of bytes in environ, used to calculate against - ARG_MAX */ + * ARG_MAX */ static size_t argmax; /* value of ARG_MAX retrieved using sysconf(3p) */ static struct { - char ret; /* return value from main */ + char ret; /* return value from main */ char depth; /* -depth, directory contents before directory itself */ - char h; /* -H, follow symlinks on command line */ - char l; /* -L, follow all symlinks (command line and search) */ - char prune; /* hit -prune */ - char xdev; /* -xdev, prune directories on different devices */ - char print; /* whether we will need -print when parsing */ - char quit; /* quit execution immediately */ - long maxdepth; /* max depth of recursion */ - long mindepth; /* min depth of recursion */ + char h; /* -H, follow symlinks on command line */ + char l; /* -L, follow all symlinks (command line and search) */ + char prune; /* hit -prune */ + char xdev; /* -xdev, prune directories on different devices */ + char print; /* whether we will need -print when parsing */ + char quit; /* quit execution immediately */ + long maxdepth; /* max depth of recursion */ + long mindepth; /* min depth of recursion */ } gflags; /* - * Utility + * utility */ static int spawn(char *argv[]) @@ -351,8 +351,8 @@ spawn(char *argv[]) int status; /* flush stdout so that -print output always appears before - * any output from the command and does not get cut-off in - * the middle of a line. */ + * any output from the command and does not get cut-off in + * the middle of a line */ fflush(stdout); switch ((pid = fork())) { @@ -389,7 +389,7 @@ do_stat(char *path, struct stat *sb, struct findhist *hist) } /* - * Primaries + * primaries */ static int pri_name(struct arg *arg) @@ -534,7 +534,7 @@ pri_exec(struct arg *arg) len = strlen(arg->path) + 1; /* if we reached ARG_MAX, fork, exec, wait, free file names, - * reset list */ + * reset list */ if (len + e->u.p.arglen + e->u.p.filelen + envlen > argmax) { e->argv[e->u.p.next] = NULL; @@ -549,7 +549,7 @@ pri_exec(struct arg *arg) } /* if we have too many files, realloc (with space for NULL - * termination) */ + * termination) */ if (e->u.p.next + 1 == e->u.p.cap) e->argv = ereallocarray(e->argv, e->u.p.cap *= 2, sizeof(*e->argv)); @@ -580,7 +580,7 @@ pri_ok(struct arg *arg) /* throw away rest of line */ while ((c = fgetc(stdin)) != '\n' && c != EOF) /* FIXME: what if the first character of the rest of the line is - * a null byte? */ + * a null byte? */ ; if (feof(stdin) || ferror(stdin)) @@ -630,7 +630,7 @@ pri_depth(struct arg *arg) } /* - * Getargs + * getargs * consume any arguments for given primary and fill extra * return pointer to last argument, the pointer will be incremented in parse() */ @@ -760,7 +760,7 @@ get_exec_arg(char *argv[], union extra *extra) *arg = NULL; if (e->isplus) { - *(arg - 1) = NULL; /* don't need the {} in there now */ + *(arg - 1) = NULL; /* dont need the {} in there now */ e->u.p.arglen = e->u.p.filelen = 0; e->u.p.first = e->u.p.next = arg - argv - 1; e->u.p.cap = (arg - argv) * 2; @@ -843,7 +843,7 @@ get_depth_arg(char *argv[], union extra *extra) } /* - * Freeargs + * freeargs */ static void free_extra(union extra extra) @@ -885,7 +885,7 @@ free_ok_arg(union extra extra) } /* - * Parsing/Building/Running + * parsing/building/running */ static void fill_narg(char *s, struct narg *n) @@ -934,12 +934,12 @@ find_op(char *name) /* given the expression from the command line * 1) convert arguments from strings to tok and place in an array duplicating - * the infix expression given, inserting "-a" where it was omitted + * the infix expression given, inserting "-a" where it was omitted * 2) allocate an array to hold the correct number of tok, and convert from - * infix to rpn (using shunting-yard), add -a and -print if necessary + * infix to rpn (using shunting-yard), add -a and -print if necessary * 3) evaluate the rpn filling in left and right pointers to create an - * expression tree (tok are still all contained in the rpn array, just - * pointing at eachother) + * expression tree (tok are still all contained in the rpn array, just + * pointing at eachother) */ static void parse(int argc, char **argv) @@ -960,7 +960,7 @@ parse(int argc, char **argv) pri = find_primary(*arg); if (pri) { /* token is a primary, fill out tok and get arguments - */ + */ if (lasttype == PRIM || lasttype == RPAR) { *tok++ = and; ntok++; @@ -990,7 +990,7 @@ parse(int argc, char **argv) eprintf("paths must precede expression: %s\n", *arg); } if (tok->type != LPAR && tok->type != RPAR) - ntok++; /* won't have parens in rpn */ + ntok++; /* wont have parens in rpn */ lasttype = tok->type; } tok->type = END; @@ -1000,9 +1000,9 @@ parse(int argc, char **argv) gflags.print++; /* use shunting-yard to convert from infix to rpn - * https://en.wikipedia.org/wiki/Shunting-yard_algorithm - * read from infix, resulting rpn ends up in rpn, next position in rpn - * is out push operators onto stack, next position in stack is top */ + * https:// en.wikipedia.org/wiki/shunting-yard_algorithm + * read from infix, resulting rpn ends up in rpn, next position in rpn + * is out push operators onto stack, next position in stack is top */ rpn = ereallocarray(NULL, ntok + gflags.print, sizeof(*rpn)); stack = ereallocarray(NULL, argc + gflags.print, sizeof(*stack)); for (tok = infix, out = rpn, top = stack; tok->type != END; tok++) { @@ -1020,18 +1020,18 @@ parse(int argc, char **argv) eprintf("extra )\n"); break; default: - /* this expression can be simplified, but I decided copy - * the verbage from the wikipedia page in order to more - * clearly explain what's going on */ + /* this expression can be simplified, but i decided copy + * the verbage from the wikipedia page in order to more + * clearly explain what's going on */ while (top-- > stack && ((tok->u.oinfo->lassoc && tok->u.oinfo->prec <= (*top)->u.oinfo->prec) || (!tok->u.oinfo->lassoc && tok->u.oinfo->prec < (*top)->u.oinfo->prec))) *out++ = **top; /* top now points to either an operator we didn't pop, - * or stack[-1] either way we need to increment it - * before using it, then increment again so the stack - * works */ + * or stack[-1] either way we need to increment it + * before using it, then increment again so the stack + * works */ top++; *top++ = tok; break; @@ -1044,8 +1044,8 @@ parse(int argc, char **argv) } /* if there was no expression, use -print - * if there was an expression but no -print, -exec, or -ok, add -a - * -print in rpn, not infix */ + * if there was an expression but no -print, -exec, or -ok, add -a + * -print in rpn, not infix */ if (gflags.print) *out++ = (struct tok){.u.pinfo = find_primary("-print"), .type = PRIM}; if (gflags.print == 2) @@ -1054,10 +1054,10 @@ parse(int argc, char **argv) out->type = END; /* rpn now holds all operators and arguments in reverse polish notation - * values are pushed onto stack, operators pop values off stack into - * left and right pointers, pushing operator node back onto stack could - * probably just do this during shunting-yard, but this is simpler code - * IMO */ + * values are pushed onto stack, operators pop values off stack into + * left and right pointers, pushing operator node back onto stack could + * probably just do this during shunting-yard, but this is simpler code + * IMO */ for (tok = rpn, top = stack; tok->type != END; tok++) { if (tok->type == PRIM) { *top++ = tok; @@ -1109,7 +1109,7 @@ eval(struct tok *tok, struct arg *arg) return ret ^ (tok->type == NOT); } -/* evaluate path, if it's a directory iterate through directory entries and +/* evaluate path, if its a directory iterate through directory entries and * recurse */ #if FEATURE_FIND_INAME @@ -1385,11 +1385,11 @@ find(char *path, struct findhist *hist) return; if (gflags.mindepth < 0 || depth >= gflags.mindepth) { - /* don't eval now iff we will hit the eval at the bottom which - * means - * 1. we are a directory 2. we have -depth 3. we don't have - * -xdev or we are on same device (so most of the time we eval - * here) */ + /* dont eval now iff we will hit the eval at the bottom which + * means + * 1. we are a directory 2. we have -depth 3. we dont have + * -xdev or we are on same device (so most of the time we eval + * here) */ if (!S_ISDIR(st.st_mode) || !gflags.depth || (gflags.xdev && hist && st.st_dev != hist->dev)) eval(root, &arg); } @@ -1502,8 +1502,8 @@ main(int argc, char **argv) parse(argc - npaths, argv); /* calculate number of bytes in environ for -exec {} + ARG_MAX avoidance - * libc implementation defined whether null bytes, pointers, and - * alignment are counted, so count them */ + * libc implementation defined whether null bytes, pointers, and + * alignment are counted, so count them */ for (argv = environ; *argv; argv++) envlen += strlen(*argv) + 1 + sizeof(*argv); diff --git a/cmd/posix/fold.c b/cmd/posix/fold.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdint.h> diff --git a/cmd/posix/getconf.c b/cmd/posix/getconf.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <limits.h> diff --git a/cmd/posix/head.c b/cmd/posix/head.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/posix/id.c b/cmd/posix/id.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/types.h> @@ -172,7 +172,7 @@ main(int argc, char *argv[]) userid(getuid()); break; case 1: - /* user names can't begin [0-9] */ + /* user names cant begin [0-9] */ if (isdigit(argv[0][0])) userid(estrtol(argv[0], 0)); else diff --git a/cmd/posix/join.c b/cmd/posix/join.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdint.h> @@ -378,8 +378,8 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) if (unpairsa) prline(spa.lines[0]); if (!addtospan(&spa, fa, RESET)) { - if (unpairsb) { /* a is EOF'd; print the rest of - b */ + if (unpairsb) { /* a is eof'd; print the rest of + * b */ do prline(spb.lines[0]); while (addtospan(&spb, fb, RESET)); @@ -392,8 +392,8 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) if (unpairsb) prline(spb.lines[0]); if (!addtospan(&spb, fb, RESET)) { - if (unpairsa) { /* b is EOF'd; print the rest of - a */ + if (unpairsa) { /* b is eof'd; print the rest of + * a */ do prline(spa.lines[0]); while (addtospan(&spa, fa, RESET)); diff --git a/cmd/posix/kill.c b/cmd/posix/kill.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "sig.h" #include "util.h" @@ -97,7 +97,7 @@ main(int argc, char *argv[]) break; default: longopt: - /* XSI-extensions -argnum and -argname*/ + /* xsi-extensions -argnum and -argname */ if (isdigit((*argv)[1])) { sig = estrtonum((*argv) + 1, 0, INT_MAX); sig2name(sig); diff --git a/cmd/posix/link.c b/cmd/posix/link.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c @@ -1,24 +1,114 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <libgen.h> +#include <limits.h> +#include <stdlib.h> #include <string.h> #include <unistd.h> #include "util.h" +#if FEATURE_LN_RELATIVE +#define MAXPATHPARTS (PATH_MAX / 2) + +/* splits an absolute, realpath()-canonicalized path in place on '/', + * returning pointers to each component; safe only against realpath() + * output, which has no trailing or doubled slashes to worry about */ +static int +split_path(char *path, char **parts, int max) +{ + char *p = path; + int n = 0; + + if (*p == '/') + p++; + while (*p && n < max) { + parts[n++] = p; + p = strchr(p, '/'); + if (!p) + break; + *p++ = '\0'; + } + return n; +} + +/* the text a relative symlink at from_dir/name needs to store to reach + * to_path: the common prefix of both canonicalized paths, a ".." per + * remaining from_dir component, then whatever is left of to_path */ +static void +relpath(const char *from_dir, const char *to_path, char *out, size_t outsz) +{ + char from_real[PATH_MAX], to_real[PATH_MAX], to_dir_buf[PATH_MAX], to_base_buf[PATH_MAX]; + char *from_parts[MAXPATHPARTS], *to_parts[MAXPATHPARTS]; + int nfrom, nto, ncommon, i; + + if (!realpath(from_dir, from_real)) + eprintf("realpath %s:", from_dir); + + strlcpy(to_dir_buf, to_path, sizeof(to_dir_buf)); + strlcpy(to_base_buf, to_path, sizeof(to_base_buf)); + if (!realpath(dirname(to_dir_buf), to_real)) + eprintf("realpath %s:", to_path); + + nfrom = split_path(from_real, from_parts, MAXPATHPARTS); + nto = split_path(to_real, to_parts, MAXPATHPARTS); + + ncommon = 0; + while (ncommon < nfrom && ncommon < nto && + strcmp(from_parts[ncommon], to_parts[ncommon]) == 0) + ncommon++; + + out[0] = '\0'; + for (i = ncommon; i < nfrom; i++) + strlcat(out, "../", outsz); + for (i = ncommon; i < nto; i++) { + strlcat(out, to_parts[i], outsz); + strlcat(out, "/", outsz); + } + strlcat(out, basename(to_base_buf), outsz); +} +#endif + static void usage(void) { +#if FEATURE_LN_RELATIVE +#if FEATURE_LN_NO_TARGET_DIR + eprintf( + "usage: %s [-f] [-L | -P | -r | -s] [-T] target [name]\n" + " %s [-f] [-L | -P | -r | -s] target ... dir\n", + argv0, + argv0 + ); +#else + eprintf( + "usage: %s [-f] [-L | -P | -r | -s] target [name]\n" + " %s [-f] [-L | -P | -r | -s] target ... dir\n", + argv0, + argv0 + ); +#endif +#else +#if FEATURE_LN_NO_TARGET_DIR + eprintf( + "usage: %s [-f] [-L | -P | -s] [-T] target [name]\n" + " %s [-f] [-L | -P | -s] target ... dir\n", + argv0, + argv0 + ); +#else eprintf( "usage: %s [-f] [-L | -P | -s] target [name]\n" " %s [-f] [-L | -P | -s] target ... dir\n", argv0, argv0 ); +#endif +#endif } // ?man ln: make links between files @@ -30,6 +120,13 @@ main(int argc, char *argv[]) char *targetdir = ".", *target = NULL; int ret = 0, sflag = 0, fflag = 0, dirfd = AT_FDCWD, hastarget = 0, flags = AT_SYMLINK_FOLLOW; struct stat st, tst; +#if FEATURE_LN_RELATIVE + int rflag = 0; + char relbuf[PATH_MAX]; +#endif +#if FEATURE_LN_NO_TARGET_DIR + int Tflag = 0; +#endif ARGBEGIN { @@ -46,10 +143,26 @@ main(int argc, char *argv[]) case 'P': flags &= ~AT_SYMLINK_FOLLOW; break; +#if FEATURE_LN_RELATIVE + // ?man -r: with -s, store the target as a path relative to name's + // own directory instead of copying it as given + case 'r': + rflag = 1; + sflag = 1; + break; +#endif // ?man -s: make symbolic links instead of hard links case 's': sflag = 1; break; +#if FEATURE_LN_NO_TARGET_DIR + // ?man -T: treat name as a regular file, never as a directory to + // place the link into, even if a file of that name is currently + // a directory + case 'T': + Tflag = 1; + break; +#endif default: usage(); } @@ -59,7 +172,13 @@ main(int argc, char *argv[]) usage(); if (argc > 1) { +#if FEATURE_LN_NO_TARGET_DIR + if (Tflag && argc != 2) + eprintf("%s: extra operand\n", argv[2]); + if (!Tflag && !stat(argv[argc - 1], &st) && S_ISDIR(st.st_mode)) { +#else if (!stat(argv[argc - 1], &st) && S_ISDIR(st.st_mode)) { +#endif if ((dirfd = open(argv[argc - 1], O_RDONLY)) < 0) eprintf("open %s:", argv[argc - 1]); targetdir = argv[argc - 1]; @@ -110,7 +229,31 @@ main(int argc, char *argv[]) ret = 1; continue; } - if ((sflag ? symlinkat(*argv, dirfd, target) : linkat(AT_FDCWD, *argv, dirfd, target, flags)) + +#if FEATURE_LN_RELATIVE + if (rflag) { + /* targetdir only names the real destination directory when name + * was defaulted from target's own basename (the dir-argument + * form); an explicit name may itself carry a directory prefix + * (ln -r target dir/name), which then names it instead */ + char dirbuf[PATH_MAX]; + const char *fromdir = targetdir; + + if (hastarget) { + strlcpy(dirbuf, target, sizeof(dirbuf)); + fromdir = dirname(dirbuf); + } + relpath(fromdir, *argv, relbuf, sizeof(relbuf)); + } +#endif + + if ((sflag ? +#if FEATURE_LN_RELATIVE + symlinkat(rflag ? relbuf : *argv, dirfd, target) +#else + symlinkat(*argv, dirfd, target) +#endif + : linkat(AT_FDCWD, *argv, dirfd, target, flags)) < 0) { weprintf("%s %s <- %s/%s:", sflag ? "symlinkat" : "linkat", *argv, targetdir, target); ret = 1; diff --git a/cmd/posix/logger.c b/cmd/posix/logger.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/logname.c b/cmd/posix/logname.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <unistd.h> diff --git a/cmd/posix/make/main.c b/cmd/posix/make/main.c @@ -125,14 +125,14 @@ parseflag(int flag, char **args, char ***argv) switch (flag) { case 'j': /* ?man -j:jobs: number of parallel jobs (accepted, runs - * serially) */ + * serially) */ case 'f': /* ?man -f:file: read rules from file instead of makefile or - * Makefile */ + * makefile */ break; case 'e': /* ?man -e: environment variables override makefile assignments - */ + */ eflag = 1; appendmakeflags("-e"); break; @@ -157,7 +157,7 @@ parseflag(int flag, char **args, char ***argv) break; case 'q': /* ?man -q: question mode, return zero if up to date, one - * otherwise */ + * otherwise */ qflag = 1; appendmakeflags("-q"); break; @@ -302,9 +302,9 @@ parsemakefiles(char **argv) } /* - * We want to enable debug as earlier as possible, - * if we wait until we read the Makefiles then - * we are going to lose to much debug information. + * we want to enable debug as earlier as possible, + * if we wait until we read the makefiles then + * we are going to lose to much debug information */ static void enadebug(char *argv[]) @@ -325,9 +325,9 @@ enadebug(char *argv[]) // ?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. +// ?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[]) { diff --git a/cmd/posix/make/parser.c b/cmd/posix/make/parser.c @@ -136,12 +136,12 @@ setmacro(char *name, char *val, int where, int export) 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. - */ + * 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: @@ -683,10 +683,10 @@ nextc(void) } /* - * This function only can be called after a call to nextc - * that didn't return EOF. It can return '\0', but as + * this function only can be called after a call to nextc + * that didn't return EOF. it can return '\0', but as * it is used only to check against '$' then it is not - * a problem. + * a problem */ static int ahead(void) @@ -993,11 +993,11 @@ no_replace: } /* - * Horrible hack to do string expansion. - * We cannot use normal push and nextc because that - * would consume characters of the current file too. - * For that reason it cleans the input and it recovers - * it later. + * horrible hack to do string expansion + * we cannot use normal push and nextc because that + * would consume characters of the current file too + * for that reason it cleans the input and it recovers + * it later */ char * expandstring(char *line, Target *tp, struct loc *loc) @@ -1071,10 +1071,10 @@ next(void) 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. - */ + * 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; diff --git a/cmd/posix/mesg.c b/cmd/posix/mesg.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/posix/mkdir.c b/cmd/posix/mkdir.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/mkfifo.c b/cmd/posix/mkfifo.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/mv.c b/cmd/posix/mv.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/nice.c b/cmd/posix/nice.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/resource.h> diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <stdint.h> diff --git a/cmd/posix/nohup.c b/cmd/posix/nohup.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/od.c b/cmd/posix/od.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "queue.h" #include "util.h" @@ -93,9 +93,21 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) basefac <<= 8; } } - fmt[2] = big_endian ? '-' : ' '; + /* x/o print a fixed-width, zero-padded field: 2 hex digits per + * byte, or ceil(8*len/3) octal digits, the exact digit count + * needed for len bytes' worth of bits, not the old 4*len-1 + * estimate (right for octal/decimal at len==1 only by + * coincidence, and short for hex at every len). d/u stay right- + * justified with spaces at that same estimate, same as every + * other od: an oversized width there is just extra leading + * whitespace, harmless under a space fill */ + fmt[2] = (format == 'x' || format == 'o') ? '0' : ' '; fmt[6] = format; - printf(fmt, (int)(3 * len + len - 1), res); + switch (format) { + case 'x': printf(fmt, (int)(2 * len), res); break; + case 'o': printf(fmt, (int)((8 * len + 2) / 3), res); break; + default: printf(fmt, (int)(3 * len + len - 1), res); break; + } } } @@ -174,7 +186,11 @@ od(int fd, char *fname, int last) } if (lineoff && last) printline(line, lineoff, addr - lineoff); - if (last) + /* the trailing all-data-consumed line exists to show the final + * address (the file's total size); with -an there is no address to + * show, so it degrades to a content-free, address-column-only blank + * line nothing after it can use, unlike every other od */ + if (last && addr_format != 'n') printline((unsigned char *)"", 0, addr); return 0; } diff --git a/cmd/posix/paste.c b/cmd/posix/paste.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdlib.h> #include <string.h> diff --git a/cmd/posix/patch.c b/cmd/posix/patch.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "paths.h" #include "util.h" #include "wexec.h" @@ -2769,8 +2769,9 @@ strtolinenum(char *nptr, char **endptr) 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; + if (endptr) + *endptr = p; return rv; } diff --git a/cmd/posix/pathchk.c b/cmd/posix/pathchk.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> @@ -12,8 +12,8 @@ #include "util.h" #define PORTABLE_CHARACTER_SET "0123456789._-qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" -/* If your system supports more other characters, but not all non-NUL - * characters, define SYSTEM_CHARACTER_SET. */ +/* if your system supports more other characters, but not all non-nul + * characters, define SYSTEM_CHARACTER_SET */ static int most = 0; static int extra = 0; @@ -26,15 +26,15 @@ pathchk(char *filename) size_t len, maxlen; struct stat st; - /* Empty? */ + /* empty? */ if (extra && !*filename) eprintf("empty filename\n"); - /* Leading hyphen? */ + /* leading hyphen? */ if (extra && ((*filename == '-') || strstr(filename, "/-"))) eprintf("%s: leading '-' in component of filename\n", filename); - /* Nonportable character? */ + /* nonportable character? */ #ifdef SYSTEM_CHARACTER_SET character_set = "/" SYSTEM_CHARACTER_SET; #else @@ -50,19 +50,19 @@ pathchk(char *filename) eprintf("%s: nonportable character '%s'\n", p, invalid); } - /* Symlink error? Non-searchable directory? */ + /* symlink error? non-searchable directory? */ if (lstat(filename, &st) && errno != ENOENT) { /* lstat rather than stat, so that if filename is a bad symlink, - * but all parents are OK, no error will be detected. */ + * but all parents are OK, no error will be detected */ eprintf("%s:", filename); } - /* Too long pathname? */ + /* too long pathname? */ maxlen = most ? _POSIX_PATH_MAX : PATH_MAX; if (strlen(filename) >= maxlen) eprintf("%s: is longer than %zu bytes\n", filename, maxlen); - /* Too long component? */ + /* too long component? */ maxlen = most ? _POSIX_NAME_MAX : NAME_MAX; for (p = filename; p; p = q) { q = strchr(p, '/'); diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c @@ -1,6 +1,6 @@ -/* taken from: https://github.com/michaelforney/pax */ +/* taken from: https:// github.com/michaelforney/pax */ #ifndef _GNU_SOURCE #define _GNU_SOURCE /* needed for major/minor (non-posix) */ #endif @@ -2079,7 +2079,7 @@ writefile(FILE *unused, struct header *h) exitstatus = 1; } else { /* add back setuid/setgid bits if we preserved the - * uid/gid */ + * uid/gid */ mode = h->mode; } } diff --git a/cmd/posix/printf.c b/cmd/posix/printf.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <errno.h> diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/sysinfo.h> @@ -39,7 +39,7 @@ psout(struct procstat *ps) struct passwd *pw; struct winsize w; - /* Ignore session leaders */ + /* ignore session leaders */ if (flags & PS_dflag) if (ps->pid == ps->sid) return; @@ -47,8 +47,8 @@ psout(struct procstat *ps) devtotty(ps->tty_nr, &tty_maj, &tty_min); ttytostr(tty_maj, tty_min, ttystr, sizeof(ttystr)); - /* Only print processes that are associated with - * a terminal and they are not session leaders */ + /* only print processes that are associated with + * a terminal and they are not session leaders */ if (flags & PS_aflag) if (ps->pid == ps->sid || ttystr[0] == '?') return; @@ -56,17 +56,17 @@ psout(struct procstat *ps) if (parsestatus(ps->pid, &pstatus) < 0) return; - /* This is the default case, only print processes that have - * the same controlling terminal as the invoker and the same - * euid as the current user */ + /* this is the default case, only print processes that have + * the same controlling terminal as the invoker and the same + * euid as the current user */ if (!(flags & (PS_aflag | PS_Aflag | PS_dflag))) { myttystr = ttyname(0); if (myttystr) { if (strcmp(myttystr + strlen("/dev/"), ttystr)) return; } else { - /* The invoker has no controlling terminal - just - * go ahead and print the processes anyway */ + /* the invoker has no controlling terminal - just + * go ahead and print the processes anyway */ ttystr[0] = '?'; ttystr[1] = '\0'; } @@ -107,8 +107,8 @@ psout(struct procstat *ps) start += (ps->starttime / sysconf(_SC_CLK_TCK)); strftime(stimestr, sizeof(stimestr), "%H:%M", localtime(&start)); - /* For kthreads/zombies /proc/<pid>/cmdline will be - * empty so use ps->comm in that case */ + /* for kthreads/zombies /proc/<pid>/cmdline will be + * empty so use ps->comm in that case */ if (parsecmdline(ps->pid, cmdline, sizeof(cmdline)) < 0) cmd = ps->comm; else diff --git a/cmd/posix/pwd.c b/cmd/posix/pwd.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/readlink.c b/cmd/posix/readlink.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <stdio.h> diff --git a/cmd/posix/renice.c b/cmd/posix/renice.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/resource.h> diff --git a/cmd/posix/rm.c b/cmd/posix/rm.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <string.h> diff --git a/cmd/posix/rmdir.c b/cmd/posix/rmdir.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <libgen.h> #include <string.h> diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c @@ -1,12 +1,12 @@ /* FIXME: summary - * decide whether we enforce valid UTF-8, right now it's enforced in certain - * parts of the script, but not the input... + * decide whether we enforce valid UTF-8, right now its enforced in certain + * parts of the script, but not the input... * nul bytes cause explosions due to use of libc string functions. thoughts? * lack of newline at end of file, currently we add one. what should we do? * allow "\\t" for "\t" etc. in regex? in replacement text? - * POSIX says don't flush on N when out of input, but GNU and busybox do. + * POSIX says dont flush on n when out of input, but GNU and busybox do */ #include "config.h" @@ -22,7 +22,7 @@ #include <sys/stat.h> #include <unistd.h> -/* Types */ +/* types */ /* used as queue for writes and stack for {,:,b,t */ typedef struct { @@ -31,9 +31,9 @@ typedef struct { size_t cap; } Vec; -/* used for arbitrary growth, str is a C string +/* used for arbitrary growth, str is a c string * FIXME: does it make sense to keep track of length? or just rely on libc - * string functions? If we want to support nul bytes everything changes + * string functions? if we want to support nul bytes everything changes */ typedef struct { char *str; @@ -54,17 +54,17 @@ typedef struct { regex_t *re; } u; enum { - IGNORE, /* empty address, ignore */ - EVERY, /* every line */ - LINE, /* line number */ - LAST, /* last line ($) */ - REGEX, /* use included regex */ + IGNORE, /* empty address, ignore */ + EVERY, /* every line */ + LINE, /* line number */ + LAST, /* last line ($) */ + REGEX, /* use included regex */ LASTRE, /* use most recently used regex */ } type; } Addr; /* DISCUSS: naddr is not strictly necessary, but very helpful - * naddr == 0 iff beg.type == EVERY && end.type == IGNORE + * naddr == 0 iff beg.type == EVERY && end.type == IGNORE * naddr == 1 iff beg.type != IGNORE && end.type == IGNORE * naddr == 2 iff beg.type != IGNORE && end.type != IGNORE */ @@ -91,39 +91,39 @@ typedef struct { typedef struct { String str; /* a,c,i text. r file path */ void (*print)(char *, FILE *); /* check_puts for a, write_file for r, - unused for c,i */ + * unused for c,i */ } ACIRarg; struct Cmd { Range range; Fninfo *fninfo; union { - Cmd *jump; /* used for b,t when running */ + Cmd *jump; /* used for b,t when running */ char *label; /* used for :,b,t when building */ ptrdiff_t offset; /* used for { (pointers break during realloc) */ FILE *file; /* used for w */ - /* FIXME: Should the following be in the union? or pointers and - * malloc? */ + /* FIXME: should the following be in the union? or pointers and + * malloc? */ Sarg s; Yarg y; ACIRarg acir; - } u; /* I find your lack of anonymous unions disturbing */ + } u; /* i find your lack of anonymous unions disturbing */ unsigned int in_match : 1; unsigned int negate : 1; }; -/* Files for w command (and s' w flag) */ +/* files for w command (and s' w flag) */ typedef struct { char *path; FILE *file; } Wfile; /* - * Function Declarations + * function declarations */ -/* Dynamically allocated arrays and strings */ +/* dynamically allocated arrays and strings */ static void resize(void **ptr, size_t *nmemb, size_t size, size_t new_nmemb, void **next); static void *pop(Vec *v); static void push(Vec *v, void *p); @@ -131,10 +131,10 @@ static void stracat(String *dst, char *src); static void strnacat(String *dst, char *src, size_t n); static void stracpy(String *dst, char *src); -/* Cleanup and errors */ +/* cleanup and errors */ static void usage(void); -/* Parsing functions and related utilities */ +/* parsing functions and related utilities */ static void compile(char *s, int isfile); static int read_line(FILE *f, String *s); static char *make_range(Range *range, char *s); @@ -148,7 +148,7 @@ static size_t escapes(char *beg, char *end, Rune delim, int n_newline); static size_t echarntorune(Rune *r, char *s, size_t n); static void insert_labels(void); -/* Get and Free arg and related utilities */ +/* get and free arg and related utilities */ static char *get_aci_arg(Cmd *c, char *s); static void aci_append(Cmd *c, char *s); static void free_acir_arg(Cmd *c); @@ -164,7 +164,7 @@ static char *get_lbrace_arg(Cmd *c, char *s); static char *get_rbrace_arg(Cmd *c, char *s); static char *semicolon_arg(char *s); -/* Running */ +/* running */ static void run(void); static int in_range(Cmd *c); static int match_addr(Addr *a); @@ -176,7 +176,7 @@ static void check_puts(char *s, FILE *f); static void write_patt(char *s, FILE *f); static void update_ranges(Cmd *beg, Cmd *end); -/* Sed functions */ +/* sed functions */ static void cmd_y(Cmd *c); static void cmd_x(Cmd *c); static void cmd_w(Cmd *c); @@ -205,20 +205,20 @@ static void cmd_lbrace(Cmd *c); static void cmd_rbrace(Cmd *c); static void cmd_last(Cmd *c); -/* Actions */ +/* actions */ static void new_line(void); static void app_line(void); static void new_next(void); static void old_next(void); /* - * Globals + * globals */ static Vec braces, labels, branches; /* holds ptrdiff_t. addrs of {, :, bt */ static Vec writes; /* holds cmd*. writes scheduled by a and r commands */ -static Vec wfiles; /* holds Wfile*. files for w and s///w commands */ +static Vec wfiles; /* holds Wfile*. files for w and s// /w commands */ -static Cmd *prog, *pc; /* Program, program counter */ +static Cmd *prog, *pc; /* program, program counter */ static size_t pcap; static size_t lineno; #if FEATURE_SED_PRESERVE_NEWLINE @@ -235,23 +235,23 @@ static String patt, hold, genbuf; static struct { unsigned int n : 1; /* -n (no print) */ unsigned int E : 1; /* -E (extended re) */ - unsigned int s : 1; /* s/// replacement happened */ + unsigned int s : 1; /* s// / replacement happened */ unsigned int aci_cont : 1; /* a,c,i text continuation */ - unsigned int s_cont : 1; /* s/// replacement text continuation */ + unsigned int s_cont : 1; /* s// / replacement text continuation */ unsigned int halt : 1; /* halt execution */ } gflags; -/* FIXME: move character inside Fninfo and only use 26*sizeof(Fninfo) instead of - * 127*sizeof(Fninfo) bytes */ +/* FIXME: move character inside fninfo and only use 26*sizeof(fninfo) instead of + * 127*sizeof(fninfo) bytes */ static Fninfo fns[] = { ['a'] = {cmd_a, get_aci_arg, free_acir_arg, 1}, /* schedule write of text for later */ - ['b'] = {cmd_b, get_bt_arg, NULL, 2}, /* branch to label char *label when building, Cmd *jump - when running */ + ['b'] = {cmd_b, get_bt_arg, NULL, 2}, /* branch to label char *label when building, cmd *jump + * when running */ ['c'] = {cmd_c, get_aci_arg, free_acir_arg, 2}, /* delete pattern space. at 0 or 1 addr or end - of 2 addr, write text */ + * of 2 addr, write text */ ['d'] = {cmd_d, NULL, NULL, 2}, /* delete pattern space */ ['D'] = {cmd_D, NULL, NULL, 2}, /* delete to first newline and start new cycle without - reading (if no newline, d) */ + * reading (if no newline, d) */ ['g'] = {cmd_g, NULL, NULL, 2}, /* replace pattern space with hold space */ ['G'] = {cmd_G, NULL, NULL, 2}, /* append newline and hold space to pattern space */ ['h'] = {cmd_h, NULL, NULL, 2}, /* replace hold space with pattern space */ @@ -259,16 +259,16 @@ static Fninfo fns[] = { ['i'] = {cmd_i, get_aci_arg, free_acir_arg, 1}, /* write text */ ['l'] = {cmd_l, NULL, NULL, 2}, /* write pattern space in 'visually unambiguous form' */ ['n'] = {cmd_n, NULL, NULL, 2}, /* write pattern space (unless -n) read to replace pattern - space (if no input, quit) */ + * space (if no input, quit) */ ['N'] = {cmd_N, NULL, NULL, 2}, /* append to pattern space separated by newline, line - number changes (if no input, quit) */ + * number changes (if no input, quit) */ ['p'] = {cmd_p, NULL, NULL, 2}, /* write pattern space */ ['P'] = {cmd_P, NULL, NULL, 2}, /* write pattern space up to first newline */ ['q'] = {cmd_q, NULL, NULL, 1}, /* quit */ ['r'] = {cmd_r, get_r_arg, free_acir_arg, 1}, /* write contents of file (unable to open/read - treated as empty file) */ + * treated as empty file) */ ['s'] = {cmd_s, get_s_arg, free_s_arg, 2}, /* find/replace/all that crazy s stuff */ - ['t'] = {cmd_t, get_bt_arg, NULL, 2}, /* if s/// succeeded (since input or last t) branch to + ['t'] = {cmd_t, get_bt_arg, NULL, 2}, /* if s// / succeeded (since input or last t) branch to label (branch to end if no label) */ ['w'] = {cmd_w, get_w_arg, NULL, 2}, /* append pattern space to file */ ['x'] = {cmd_x, NULL, NULL, 2}, /* exchange pattern and hold spaces */ @@ -276,16 +276,16 @@ static Fninfo fns[] = { [':'] = {cmd_colon, get_colon_arg, NULL, 0}, /* defines label for later b and t commands */ ['='] = {cmd_equal, NULL, NULL, 1}, /* printf("%d\n", line_number); */ ['{'] = {cmd_lbrace, get_lbrace_arg, NULL, 2}, /* if we match, run commands, otherwise jump to - close */ + * close */ ['}'] = {cmd_rbrace, get_rbrace_arg, NULL, 0}, /* noop, hold onto open for ease of building - scripts */ + * scripts */ - [0x7f] = {NULL, NULL, NULL, 0}, /* index is checked with isascii(3p). - fill out rest of array */ + [0x7f] = {NULL, NULL, NULL, 0}, /* index is checked with isascii(3p) + * fill out rest of array */ }; /* - * Function Definitions + * function definitions */ /* given memory pointed to by *ptr that currently holds *nmemb members of size @@ -414,7 +414,7 @@ usage(void) ); } -/* Differences from POSIX +/* differences from POSIX * we allows semicolons and trailing blanks inside {} * we allow spaces after ! (and in between !s) * we allow extended regular expressions (-E) @@ -436,12 +436,12 @@ compile(char *s, int isfile) eprintf("fmemopen:"); } - /* NOTE: get arg functions can't use genbuf */ + /* NOTE: get arg functions cant use genbuf */ while (read_line(f, &genbuf) != EOF) { s = genbuf.str; /* if the first two characters of the script are "#n" default - * output shall be suppressed */ + * output shall be suppressed */ if (++lineno == 1 && *s == '#' && s[1] == 'n') { gflags.n = 1; continue; @@ -594,17 +594,17 @@ find_delim(char *s, Rune delim, int do_brackets) enum { OUTSIDE, /* not in brackets */ BRACKETS_OPENING, /* last char was first [ or last two were - first [^ */ + * first [^ */ BRACKETS_INSIDE, /* inside [] */ INSIDE_OPENING, /* inside [] and last char was [ */ CLASS_INSIDE, /* inside class [::], or colating element [..] or - [==], inside [] */ + * [==], inside [] */ CLASS_CLOSING, /* inside class [::], or colating element [..] or - [==], and last character was the respective : - . or = */ + * [==], and last character was the respective : + * . or = */ } state = OUTSIDE; - Rune r, c = 0; /* no c won't be used uninitialized, shutup -Wall */ + Rune r, c = 0; /* no c wont be used uninitialized, shutup -wall */ size_t rlen; int escape = 0; char *end = s + strlen(s); @@ -670,7 +670,7 @@ chompr(char *s, Rune rune) return s; } -/* convert first nrunes Runes from UTF-8 string s in allocated Rune* +/* convert first nrunes runes from UTF-8 string s in allocated rune* * NOTE: sequence must be valid UTF-8, check first */ static Rune * strtorunes(char *s, size_t nrunes) @@ -717,8 +717,8 @@ escapes(char *beg, char *end, Rune delim, int n_newline) char *src = beg, *dst = beg; while (src < end) { - /* handle escaped backslash specially so we don't think the - * second backslash is escaping something */ + /* handle escaped backslash specially so we dont think the + * second backslash is escaping something */ if (*src == '\\' && src[1] == '\\') { *dst++ = *src++; if (delim) @@ -736,7 +736,7 @@ escapes(char *beg, char *end, Rune delim, int n_newline) if (r == 'n' && delim == 'n') { *src = n_newline ? '\n' : 'n'; /* src so we can still - memmove() */ + * memmove() */ } else if (r == 'n') { *src = '\n'; } else if (r != delim) { @@ -790,8 +790,8 @@ insert_labels(void) } /* - * Getargs / Freeargs - * Read argument from s, return pointer to one past last character of argument + * getargs / freeargs + * read argument from s, return pointer to one past last character of argument */ /* POSIX compliant @@ -799,16 +799,16 @@ insert_labels(void) * foobar * * also allow the following non POSIX compliant - * i # empty line + * i # empty line * ifoobar * ifoobar\ * baz * * FIXME: GNU and busybox discard leading spaces - * i foobar + * i foobar * i foobar * ifoobar - * are equivalent in GNU and busybox. We don't. Should we? + * are equivalent in GNU and busybox. we dont. should we? */ static char * get_aci_arg(Cmd *c, char *s) @@ -850,12 +850,12 @@ free_acir_arg(Cmd *c) /* POSIX dictates that label is rest of line, including semicolons, trailing * whitespace, closing braces, etc. and can be limited to 8 bytes * - * I allow a semicolon or closing brace to terminate a label name, it's not - * POSIX compliant, but it's useful and every sed version I've tried to date - * does the same. + * i allow a semicolon or closing brace to terminate a label name, its not + * POSIX compliant, but its useful and every sed version i've tried to date + * does the same * * FIXME: POSIX dictates that leading whitespace is ignored but trailing - * whitespace is not. This is annoying and we should probably get rid of it. + * whitespace is not. this is annoying and we should probably get rid of it */ static char * get_bt_arg(Cmd *c, char *s) @@ -876,8 +876,8 @@ get_bt_arg(Cmd *c, char *s) /* POSIX dictates file name is rest of line including semicolons, trailing * whitespace, closing braces, etc. and file name must be preceded by a space * - * I allow a semicolon or closing brace to terminate a file name and don't - * enforce leading space. + * i allow a semicolon or closing brace to terminate a file name and dont + * enforce leading space * * FIXME: decide whether trailing whitespace should be included and fix * accordingly @@ -908,11 +908,11 @@ get_s_arg(Cmd *c, char *s) char *p; int esc, lastre; - /* s/Find/Replace/Flags */ + /* s/find/replace/flags */ - /* Find */ + /* find */ if (!gflags.s_cont) { /* NOT continuing from literal newline in - replacement text */ + * replacement text */ lastre = 0; c->u.s.repl = (String){NULL, 0}; c->u.s.occurrence = 1; @@ -946,7 +946,7 @@ get_s_arg(Cmd *c, char *s) s = p + runelen(delim); } - /* Replace */ + /* replace */ delim = c->u.s.delim; p = find_delim(s, delim, 0); @@ -985,11 +985,11 @@ get_s_arg(Cmd *c, char *s) s = p + runelen(delim); - /* Flags */ + /* flags */ p = semicolon_arg(s = chomp(s)); /* FIXME: currently for simplicity take last of g or occurrence flags - * and ignore multiple p flags. need to fix that */ + * and ignore multiple p flags. need to fix that */ for (; s < p; s++) { if (isdigit(*s)) { c->u.s.occurrence = stol(s, &s); @@ -1004,7 +1004,7 @@ get_s_arg(Cmd *c, char *s) break; case 'w': /* must be last flag, take everything up to - * newline/semicolon s == p after this */ + * newline/semicolon s == p after this */ s = get_w_arg(&buf, chomp(s + 1)); c->u.s.file = buf.u.file; break; @@ -1126,10 +1126,10 @@ get_rbrace_arg(Cmd *c, char *s) * return pointer to semicolon or nul byte after string * or closing brace as to not force ; before } * FIXME: decide whether or not to eat trailing whitespace for arguments that - * we allow semicolon/brace termination that POSIX doesn't - * b, r, t, w, : - * POSIX says trailing whitespace is part of label name, file name, etc. - * we should probably eat it + * we allow semicolon/brace termination that POSIX doesnt + * b, r, t, w, : + * POSIX says trailing whitespace is part of label name, file name, etc + * we should probably eat it */ static char * semicolon_arg(char *s) @@ -1148,7 +1148,7 @@ run(void) leprintf("extra {"); /* genbuf has already been initialized, patt will be in new_line - * (or we'll halt) */ + * (or we'll halt) */ stracpy(&hold, ""); insert_labels(); @@ -1311,7 +1311,7 @@ write_patt(char *s, FILE *f) #endif } -/* iterate from beg to end updating ranges so we don't miss any commands +/* iterate from beg to end updating ranges so we dont miss any commands * e.g. sed -n '1d;1,3p' should still print lines 2 and 3 */ static void @@ -1322,7 +1322,7 @@ update_ranges(Cmd *beg, Cmd *end) } /* - * Sed functions + * sed functions */ static void cmd_a(Cmd *c) @@ -1338,7 +1338,7 @@ cmd_b(Cmd *c) return; /* if we jump backwards update to end, otherwise update to destination - */ + */ update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap); pc = c->u.jump; } @@ -1353,7 +1353,7 @@ cmd_c(Cmd *c) if (!c->in_match) check_puts(c->u.acir.str.str, stdout); /* otherwise start the next cycle without printing pattern space - * effectively deleting the text */ + * effectively deleting the text */ new_next(); } @@ -1424,7 +1424,7 @@ cmd_i(Cmd *c) check_puts(c->u.acir.str.str, stdout); } -/* I think it makes sense to print invalid UTF-8 sequences in octal to satisfy +/* i think it makes sense to print invalid UTF-8 sequences in octal to satisfy * the "visually unambiguous form" sed(1p) */ static void @@ -1450,16 +1450,16 @@ cmd_l(Cmd *c) return; /* FIXME: line wrapping. sed(1p) says "length at which folding occurs is - * unspecified, but should be appropraite for the output device" - * just wrap at 80 Runes? - */ + * unspecified, but should be appropraite for the output device" + * just wrap at 80 runes? + */ for (p = patt.str, end = p + strlen(p); p < end; p += rlen) { if (isascii(*p) && escapes[(unsigned int)*p]) { fputs(escapes[(unsigned int)*p], stdout); rlen = 1; } else if (!(rlen = charntorune(&r, p, end - p))) { /* ran out of chars, print the bytes of the short - * sequence */ + * sequence */ for (; p < end; p++) printf("\\%03hho", (unsigned char)*p); break; @@ -1568,21 +1568,21 @@ cmd_s(Cmd *c) while (!qflag && !regexec(re, s, plen, pmatch, cflags)) { cflags = REG_NOTBOL; /* match against beginning of line first - time, but not again */ + * time, but not again */ if (!*s) /* match against empty string first time, but not again - */ + */ qflag = 1; - /* don't substitute if last match was not empty but this one is. - * s_a*_._g - * foobar -> .f.o.o.b.r. - */ + /* dont substitute if last match was not empty but this one is + * s_a*_._g + * foobar -> .f.o.o.b.r + */ if ((last_empty || pmatch[0].rm_eo) && (++matches == c->u.s.occurrence || !c->u.s.occurrence)) { /* copy over everything before the match */ strnacat(&genbuf, s, pmatch[0].rm_so); /* copy over replacement text, taking into account &, - * backreferences, and \ escapes */ + * backreferences, and \ escapes */ for (p = c->u.s.repl.str, len = strcspn(p, "\\&"); *p; len = strcspn(++p, "\\&")) { strnacat(&genbuf, p, len); p += len; @@ -1592,8 +1592,8 @@ cmd_s(Cmd *c) break; case '\0': /* we're at the end, back up one so the - * ++p will put us on the null byte to - * break out of the loop */ + * ++p will put us on the null byte to + * break out of the loop */ --p; break; case '&': @@ -1602,8 +1602,8 @@ cmd_s(Cmd *c) case '\\': if (isdigit(*++p)) { /* backreference */ /* only need to check here if - * using lastre, otherwise we - * checked when building */ + * using lastre, otherwise we + * checked when building */ if (!c->u.s.re && (size_t)(*p - '0') > re->re_nsub) leprintf( "back " @@ -1616,8 +1616,8 @@ cmd_s(Cmd *c) rm = &pmatch[*p - '0']; strnacat(&genbuf, s + rm->rm_so, rm->rm_eo - rm->rm_so); } else { /* character after backslash - taken literally (well one - byte, but it works) */ + * taken literally (well one + * byte, but it works) */ strnacat(&genbuf, p, 1); } break; @@ -1625,19 +1625,19 @@ cmd_s(Cmd *c) } } else { /* not replacing, copy over everything up to and - * including the match */ + * including the match */ strnacat(&genbuf, s, pmatch[0].rm_eo); } if (!pmatch[0].rm_eo) { /* empty match, advance one rune and add - it to output */ + * it to output */ end = s + strlen(s); rlen = charntorune(&r, s, end - s); if (!rlen) { /* ran out of bytes, copy short sequence */ stracat(&genbuf, s); s = end; - } else { /* copy whether or not it's a good rune */ + } else { /* copy whether or not its a good rune */ strnacat(&genbuf, s, rlen); s += rlen; } @@ -1671,7 +1671,7 @@ cmd_t(Cmd *c) return; /* if we jump backwards update to end, otherwise update to destination - */ + */ update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap); pc = c->u.jump; gflags.s = 0; @@ -1719,8 +1719,8 @@ cmd_y(Cmd *c) for (rp = c->u.y.set1; *rp; rp++) if (*rp == r) break; - if (*rp) { /* found r in set1, replace with Rune from - set2 */ + if (*rp) { /* found r in set1, replace with rune from + * set2 */ n = runetochar(buf, c->u.y.set2 + (rp - c->u.y.set1)); strnacat(&genbuf, buf, n); } else { @@ -1778,7 +1778,7 @@ cmd_last(Cmd *c) } /* - * Actions + * actions */ /* read new line, continue current cycle */ @@ -1796,9 +1796,9 @@ new_line(void) } /* append new line, continue current cycle - * FIXME: used for N, POSIX specifies do not print pattern space when out of - * input, but GNU does so busybox does as well. Currently we don't. - * Should we? + * FIXME: used for n, POSIX specifies do not print pattern space when out of + * input, but GNU does so busybox does as well. currently we dont + * should we? */ static void app_line(void) diff --git a/cmd/posix/sh/alias.c b/cmd/posix/sh/alias.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "alias.h" @@ -87,12 +87,12 @@ unalias(const char *name) for (ap = *app; ap; app = &(ap->next), ap = ap->next) { if (equal(name, ap->name)) { /* - * if the alias is currently in use (i.e. its - * buffer is being used by the input routine) we - * just null out the name instead of freeing it. - * We could clear it out later, but this situation - * is so rare that it hardly seems worth it. - */ + * if the alias is currently in use (i.e. its + * buffer is being used by the input routine) we + * just null out the name instead of freeing it + * we could clear it out later, but this situation + * is so rare that it hardly seems worth it + */ if (ap->flag & ALIASINUSE) *ap->name = '\0'; else { diff --git a/cmd/posix/sh/alias.h b/cmd/posix/sh/alias.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #define ALIASINUSE 1 diff --git a/cmd/posix/sh/arith.h b/cmd/posix/sh/arith.h @@ -1,32 +1,32 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1995 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1995 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "shell.h" diff --git a/cmd/posix/sh/arith_yacc.c b/cmd/posix/sh/arith_yacc.c @@ -1,37 +1,37 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. - * Copyright (c) 2007 - * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved + * copyright (c) 2007 + * herbert xu <herbert@gondor.apana.org.au>. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #if defined(__has_include) @@ -357,7 +357,7 @@ arith(const char *s) } /* - * The exp(1) builtin. + * the exp(1) builtin */ int letcmd(int argc, char **argv) @@ -371,8 +371,8 @@ letcmd(int argc, char **argv) p = argv[1]; if (argc > 2) { /* - * Concatenate arguments. - */ + * concatenate arguments + */ STARTSTACKSTR(concat); ap = argv + 2; for (;;) { diff --git a/cmd/posix/sh/arith_yacc.h b/cmd/posix/sh/arith_yacc.h @@ -1,37 +1,37 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. - * Copyright (c) 2007 - * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved + * copyright (c) 2007 + * herbert xu <herbert@gondor.apana.org.au>. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "shell.h" diff --git a/cmd/posix/sh/arith_yylex.c b/cmd/posix/sh/arith_yylex.c @@ -1,37 +1,37 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 2002 - * Herbert Xu. - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 2002 + * herbert xu + * copyright (c) 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #if defined(__has_include) diff --git a/cmd/posix/sh/bltin.h b/cmd/posix/sh/bltin.h @@ -1,41 +1,41 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * This file is included by programs which are optionally built into the - * shell. If SHELL is defined, we try to map the standard UNIX library - * routines to ash routines using defines. + * this file is included by programs which are optionally built into the + * shell. if SHELL is defined, we try to map the standard UNIX library + * routines to ash routines using defines */ #include "mystring.h" diff --git a/cmd/posix/sh/cd.c b/cmd/posix/sh/cd.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -41,7 +41,7 @@ #include <unistd.h> /* - * The cd and pwd commands. + * the cd and pwd commands */ #include "builtins.h" @@ -120,8 +120,8 @@ cdcmd(int argc __unused, char **argv __unused) else { if (!print) { /* - * XXX - rethink - */ + * XXX - rethink + */ if (p[0] == '.' && p[1] == '/' && p[2] != '\0') print = strcmp(p + 2, dest); else @@ -135,13 +135,13 @@ cdcmd(int argc __unused, char **argv __unused) } } error("%s: %s", dest, strerror(errno1)); - /*NOTREACHED*/ + /* NOTREACHED */ return 0; } /* - * Actually change the directory. In an interactive shell, print the - * directory name if "print" is nonzero. + * actually change the directory. in an interactive shell, print the + * directory name if "print" is nonzero */ static int docd(char *dest, int print, int phys) @@ -150,18 +150,18 @@ docd(char *dest, int print, int phys) TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys)); - /* If logical cd fails, fall back to physical. */ + /* if logical cd fails, fall back to physical */ if ((phys || (rc = cdlogical(dest)) < 0) && (rc = cdphysical(dest)) < 0) return (-1); if (print && iflag && curdir) { out1fmt("%s\n", curdir); /* - * Ignore write errors to preserve the invariant that the - * current directory is changed iff the exit status is 0 - * (or 1 if -e was given and the full pathname could not be - * determined). - */ + * ignore write errors to preserve the invariant that the + * current directory is changed iff the exit status is 0 + * (or 1 if -e was given and the full pathname could not be + * determined) + */ flushout(out1); outclearerror(out1); } @@ -181,10 +181,10 @@ cdlogical(char *dest) int badstat; /* - * Check each component of the path. If we find a symlink or - * something we can't stat, clear curdir to force a getcwd() - * next time we get the value of the current directory. - */ + * check each component of the path. if we find a symlink or + * something we cant stat, clear curdir to force a getcwd() + * next time we get the value of the current directory + */ badstat = 0; path = stsavestr(dest); STARTSTACKSTR(p); @@ -242,8 +242,8 @@ cdphysical(char *dest) } /* - * Get the next component of the path name pointed to by *path. - * This routine overwrites *path and the string pointed to by it. + * get the next component of the path name pointed to by *path + * this routine overwrites *path and the string pointed to by it */ static char * getcomponent(char **path) @@ -273,10 +273,10 @@ findcwd(char *dir) char *path; /* - * If our argument is NULL, we don't know the current directory - * any more because we traversed a symbolic link or something - * we couldn't stat(). - */ + * if our argument is NULL, we dont know the current directory + * any more because we traversed a symbolic link or something + * we couldnt stat() + */ if (dir == NULL || curdir == NULL) return getpwd2(); path = stsavestr(dir); @@ -302,9 +302,9 @@ findcwd(char *dir) } /* - * Update curdir (the name of the current directory) in response to a - * cd command. We also call hashcd to let the routines in exec.c know - * that the current directory has changed. + * update curdir (the name of the current directory) in response to a + * cd command. we also call hashcd to let the routines in exec.c know + * that the current directory has changed */ static void updatepwd(char *dir) @@ -353,7 +353,7 @@ pwdcmd(int argc __unused, char **argv __unused) } /* - * Get the current directory and cache the result in curdir. + * get the current directory and cache the result in curdir */ static char * getpwd(void) @@ -376,7 +376,7 @@ getpwd(void) #define MAXPWD 256 /* - * Return the current directory. + * return the current directory */ static char * getpwd2(void) @@ -397,8 +397,8 @@ getpwd2(void) } /* - * Initialize PWD in a new shell. - * If the shell is interactive, we need to warn if this fails. + * initialize PWD in a new shell + * if the shell is interactive, we need to warn if this fails */ void pwd_init(int warn) diff --git a/cmd/posix/sh/cd.h b/cmd/posix/sh/cd.h @@ -1,32 +1,32 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1995 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1995 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ void pwd_init(int); diff --git a/cmd/posix/sh/easter.c b/cmd/posix/sh/easter.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "bltin.h" #include "fs.h" #include "util.h" @@ -15,8 +15,8 @@ enum { COMMENT_HASH, /* line # only */ COMMENT_PERCENT, /* line % only */ COMMENT_SEMI, /* line ; only */ - COMMENT_DASH, /* line -- only */ - COMMENT_HASKELL, /* line -- and block {- -} */ + COMMENT_DASH, /* line, only */ + COMMENT_HASKELL, /* line, and block {- -} */ COMMENT_PAREN, /* block (* *) only, no line comment */ }; @@ -60,7 +60,7 @@ struct CommentSpec { }; static const struct CommentSpec comment_specs[] = { - [COMMENT_C] = {"//", "/*", "*/"}, + [COMMENT_C] = {"// ", "/*", "*/"}, [COMMENT_HASH] = {"#", NULL, NULL}, [COMMENT_PERCENT] = {"%", NULL, NULL}, [COMMENT_SEMI] = {";", NULL, NULL}, @@ -261,9 +261,9 @@ detect_lang(const char *name) } /* - * anchored to the end of the name, so arch.txt (which contains "rc" - * but does not end in it) is never mistaken for a shell rc file - */ + * anchored to the end of the name, so arch.txt (which contains "rc" + * but does not end in it) is never mistaken for a shell rc file + */ nlen = strlen(name); if (nlen >= 2 && !strcmp(name + nlen - 2, "rc")) return LANG_SH; diff --git a/cmd/posix/sh/echo.c b/cmd/posix/sh/echo.c @@ -1,41 +1,41 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "bltin.h" /* - * Echo command. + * echo command */ #define main echocmd diff --git a/cmd/posix/sh/error.c b/cmd/posix/sh/error.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Errors and exceptions. + * errors and exceptions */ #include "error.h" @@ -51,7 +51,7 @@ #include <unistd.h> /* - * Code to handle exceptions in C. + * code to handle exceptions in c */ struct jmploc *handler; @@ -62,12 +62,12 @@ volatile sig_atomic_t intpending; static void verrorwithstatus(int, const char *, va_list) __printf0like(2, 0) __dead2; /* - * Called to raise an exception. Since C doesn't include exceptions, we - * just do a longjmp to the exception handler. The type of exception is - * stored in the global variable "exception". + * called to raise an exception. since c doesnt include exceptions, we + * just do a longjmp to the exception handler. the type of exception is + * stored in the global variable "exception" * - * Interrupts are disabled; they should be re-enabled when the exception is - * caught. + * interrupts are disabled; they should be re-enabled when the exception is + * caught */ void @@ -81,14 +81,14 @@ exraise(int e) } /* - * Called from trap.c when a SIGINT is received and not suppressed, or when - * an interrupt is pending and interrupts are re-enabled using INTON. - * (If the user specifies that SIGINT is to be trapped or ignored using the - * trap builtin, then this routine is not called.) Suppressint is nonzero - * when interrupts are held using the INTOFF macro. If SIGINTs are not + * called from trap.c when a SIGINT is received and not suppressed, or when + * an interrupt is pending and interrupts are re-enabled using INTON + * (if the user specifies that SIGINT is to be trapped or ignored using the + * trap builtin, then this routine is not called.) suppressint is nonzero + * when interrupts are held using the INTOFF macro. if sigints are not * suppressed and the shell is not a root shell, then we want to be - * terminated if we get here, as if we were terminated directly by a SIGINT. - * Arrange for this here. + * terminated if we get here, as if we were terminated directly by a SIGINT + * arrange for this here */ void @@ -101,8 +101,8 @@ onint(void) sigprocmask(SIG_SETMASK, &sigs, NULL); /* - * This doesn't seem to be needed, since main() emits a newline. - */ + * this doesnt seem to be needed, since main() emits a newline + */ #if 0 if (tcgetpgrp(0) == getpid()) write(STDERR_FILENO, "\n", 1); @@ -137,21 +137,21 @@ warning(const char *msg, ...) } /* - * Exverror is called to raise the error exception. If the first argument + * exverror is called to raise the error exception. if the first argument * is not NULL then error prints an error message using printf style - * formatting. It then raises the error exception. + * formatting. it then raises the error exception */ static void verrorwithstatus(int status, const char *msg, va_list ap) { /* - * An interrupt trumps an error. Certain places catch error - * exceptions or transform them to a plain nonzero exit code - * in child processes, and if an error exception can be handled, - * an interrupt can be handled as well. - * - * exraise() will disable interrupts for the exception handler. - */ + * an interrupt trumps an error. certain places catch error + * exceptions or transform them to a plain nonzero exit code + * in child processes, and if an error exception can be handled, + * an interrupt can be handled as well + * + * exraise() will disable interrupts for the exception handler + */ FORCEINTON; #ifdef DEBUG diff --git a/cmd/posix/sh/error.h b/cmd/posix/sh/error.h @@ -1,47 +1,47 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" /* - * We enclose jmp_buf in a structure so that we can declare pointers to - * jump locations. The global variable handler contains the location to + * we enclose jmp_buf in a structure so that we can declare pointers to + * jump locations. the global variable handler contains the location to * jump to when an exception occurs, and the global variable exception - * contains a code identifying the exception. To implement nested + * contains a code identifying the exception. to implement nested * exception handlers, the user should save the value of handler on entry * to an inner scope, set handler to point to a jmploc structure for the - * inner scope, and restore handler on exit from the scope. + * inner scope, and restore handler on exit from the scope */ #include <setjmp.h> @@ -60,9 +60,9 @@ extern volatile sig_atomic_t exception; #define EXEXIT 2 /* call exitshell(exitstatus) */ /* - * These macros allow the user to suspend the handling of interrupt signals - * over a period of time. This is similar to SIGHOLD to or sigblock, but - * much more efficient and portable. (But hacking the kernel is so much + * these macros allow the user to suspend the handling of interrupt signals + * over a period of time. this is similar to SIGHOLD to or sigblock, but + * much more efficient and portable. (but hacking the kernel is so much * more fun than worrying about efficiency and portability. :-)) */ @@ -99,8 +99,8 @@ void error(const char *, ...) __printf0like(1, 2) __dead2; void errorwithstatus(int, const char *, ...) __printf0like(2, 3) __dead2; /* - * BSD setjmp saves the signal mask, which violates ANSI C and takes time, - * so we use _setjmp instead. + * BSD setjmp saves the signal mask, which violates ANSI c and takes time, + * so we use _setjmp instead */ #undef setjmp diff --git a/cmd/posix/sh/eval.c b/cmd/posix/sh/eval.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -39,7 +39,7 @@ #include <unistd.h> /* - * Evaluate a command. + * evaluate a command */ #include "../../../shared/paths.h" @@ -91,7 +91,7 @@ static void evalcommand(union node *, int, struct backcmd *); static void prehash(union node *); /* - * Called to reset things after an exception. + * called to reset things after an exception */ void @@ -102,7 +102,7 @@ reseteval(void) } /* - * The eval command. + * the eval command */ int @@ -133,7 +133,7 @@ evalcmd(int argc, char **argv) } /* - * Execute a command or commands contained in a string. + * execute a command or commands contained in a string */ void @@ -171,8 +171,8 @@ evalstring(const char *s, int flags) } /* - * Evaluate a parse tree. The value is left in the global variable - * exitstatus. + * evaluate a parse tree. the value is left in the global variable + * exitstatus */ void @@ -366,9 +366,9 @@ evalfor(union node *n, int flags) } /* - * Evaluate a case statement, returning the selected tree. + * evaluate a case statement, returning the selected tree * - * The exit status needs care to get right. + * the exit status needs care to get right */ static union node * @@ -399,7 +399,7 @@ evalcase(union node *n) } /* - * Kick off a subshell to evaluate a tree. + * kick off a subshell to evaluate a tree */ static void @@ -425,7 +425,7 @@ evalsubshell(union node *n, int flags) } /* - * Evaluate a redirected compound command. + * evaluate a redirected compound command */ static void @@ -497,7 +497,7 @@ exphere(union node *redir, struct arglist *fn) } /* - * Compute the names of the files in a redirection list. + * compute the names of the files in a redirection list */ static void @@ -532,8 +532,8 @@ expredir(union node *n) } /* - * Evaluate a pipeline. All the processes in the pipeline are children - * of the process creating the pipeline. (This differs from some versions + * evaluate a pipeline. all the processes in the pipeline are children + * of the process creating the pipeline. (this differs from some versions * of the shell, which make the last process in a pipeline the parent * of all the rest.) */ @@ -603,10 +603,10 @@ is_valid_fast_cmdsubst(union node *n) } /* - * Execute a command inside back quotes. If it's a builtin command, we - * want to save its output in a block obtained from malloc. Otherwise - * we fork off a subprocess and get the output of the command via a pipe. - * Should be called with interrupts off. + * execute a command inside back quotes. if its a builtin command, we + * want to save its output in a block obtained from malloc. otherwise + * we fork off a subprocess and get the output of the command via a pipe + * should be called with interrupts off */ void @@ -717,11 +717,11 @@ isdeclarationcmd(struct narg *arg) if (arg == NULL) return (0); /* - * To also allow "command -p" and "command --" as part of - * a declaration command, add code here. - * We do not do this, as ksh does not do it either and it - * is not required by POSIX. - */ + * to also allow "command -p" and "command --" as part of + * a declaration command, add code here + * we do not do this, as ksh does not do it either and it + * is not required by POSIX + */ } return ( mustexpandto(arg->text, "export") || mustexpandto(arg->text, "readonly") @@ -763,16 +763,16 @@ xtracecommand(struct arglist *varlist, int argc, char **argv) } /* - * Check if a builtin can safely be executed in the same process, - * even though it should be in a subshell (command substitution). - * Note that jobid, jobs, times and trap can show information not - * available in a child process; this is deliberate. - * The arguments should already have been expanded. + * check if a builtin can safely be executed in the same process, + * even though it should be in a subshell (command substitution) + * note that jobid, jobs, times and trap can show information not + * available in a child process; this is deliberate + * the arguments should already have been expanded */ static int safe_builtin(int idx, int argc, char **argv) { - /* Generated from builtins.def. */ + /* generated from builtins.def */ if (safe_builtin_always(idx)) return (1); if (idx == EXPORTCMD || idx == TRAPCMD || idx == ULIMITCMD || idx == UMASKCMD) @@ -787,13 +787,13 @@ safe_builtin(int idx, int argc, char **argv) } /* - * Perform redirections, then execute a simple command with vfork. - * This cannot be used for command substitutions for two reasons: - * - Redirections might cause the error message for later redirections or for - * an unknown command to be sent to the pipe (to be substituted), and this - * might cause a deadlock if the message is too long. - * - The assignment of the pipe needs to come before instead of after the - * redirections. + * perform redirections, then execute a simple command with vfork + * this cannot be used for command substitutions for two reasons: + * - redirections might cause the error message for later redirections or for + * an unknown command to be sent to the pipe (to be substituted), and this + * might cause a deadlock if the message is too long + * - the assignment of the pipe needs to come before instead of after the + * redirections */ static int redirected_vforkexecshell( @@ -832,8 +832,8 @@ redirected_vforkexecshell( } /* - * Execute a simple command. - * Note: This may or may not return if (flags & EV_EXIT). + * execute a simple command + * note: this may or may not return if (flags & EV_EXIT) */ static void @@ -863,7 +863,7 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) const char *path = pathval(); int i; - /* First expand the arguments. */ + /* first expand the arguments */ TRACE(("evalcommand(%p, %d) called\n", (void *)cmd, flags)); emptyarglist(&arglist); emptyarglist(&varlist); @@ -872,7 +872,7 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) do_clearcmdentry = 0; oexitstatus = exitstatus; exitstatus = 0; - /* Add one slot at the beginning for tryexec(). */ + /* add one slot at the beginning for tryexec() */ appendarglist(&arglist, nullstr); for (argp = cmd->ncmd.args; argp; argp = argp->narg.next) { if (varflag && isassignment(argp->narg.text)) { @@ -892,13 +892,13 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) if (iflag && funcnest == 0 && argc > 0) lastarg = argv[argc - 1]; - /* Print the command if xflag is set. */ + /* print the command if xflag is set */ if (xflag) xtracecommand(&varlist, argc, argv); - /* Now locate the command. */ + /* now locate the command */ if (argc == 0) { - /* Variable assignment(s) without command */ + /* variable assignment(s) without command */ cmdentry.cmdtype = CMDBUILTIN; cmdentry.u.index = BLTINCMD; cmdentry.special = 0; @@ -907,30 +907,30 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) int cmd_flags = 0, bltinonly = 0; /* - * Modify the command lookup path, if a PATH= assignment - * is present - */ + * modify the command lookup path, if a PATH= assignment + * is present + */ for (i = 0; i < varlist.count; i++) if (strncmp(varlist.args[i], PATH, sizeof(PATH) - 1) == 0) { path = varlist.args[i] + sizeof(PATH) - 1; /* - * On `PATH=... command`, we need to make - * sure that the command isn't using the - * non-updated hash table of the outer PATH - * setting and we need to make sure that - * the hash table isn't filled with items - * from the temporary setting. - * - * It would be better to forbid using and - * updating the table while this command - * runs, by the command finding mechanism - * is heavily integrated with hash handling, - * so we just delete the hash before and after - * the command runs. Partly deleting like - * changepatch() does doesn't seem worth the - * booking effort, since most such runs add - * directories in front of the new PATH. - */ + * on `PATH=... command`, we need to make + * sure that the command isnt using the + * non-updated hash table of the outer PATH + * setting and we need to make sure that + * the hash table isnt filled with items + * from the temporary setting + * + * it would be better to forbid using and + * updating the table while this command + * runs, by the command finding mechanism + * is heavily integrated with hash handling, + * so we just delete the hash before and after + * the command runs. partly deleting like + * changepatch() does doesnt seem worth the + * booking effort, since most such runs add + * directories in front of the new PATH + */ clearcmdentry(); do_clearcmdentry = 1; } @@ -992,14 +992,14 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) break; } /* - * Special builtins lose their special properties when - * called via 'command'. - */ + * special builtins lose their special properties when + * called via 'command' + */ if (cmd_flags & DO_NOFUNC) cmdentry.special = 0; } - /* Fork off a child process if necessary. */ + /* fork off a child process if necessary */ if (((cmdentry.cmdtype == CMDNORMAL || cmdentry.cmdtype == CMDUNKNOWN || (cmdentry.cmdtype == CMDWEXEC && !(wexec_get_nofork() && wexec_is_nofork(argv[0])))) && ((flags & EV_EXIT) == 0 || have_traps())) @@ -1042,8 +1042,8 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) flags |= EV_EXIT; } - /* This is the child process if a fork occurred. */ - /* Execute the command. */ + /* this is the child process if a fork occurred */ + /* execute the command */ if (cmdentry.cmdtype == CMDFUNCTION) { #ifdef DEBUG trputs("Shell function: "); @@ -1167,9 +1167,9 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) redirect(cmd->ncmd.redirect, mode); outclearerror(out1); /* - * If there is no command word, redirection errors should - * not be fatal but assignment errors should. - */ + * if there is no command word, redirection errors should + * not be fatal but assignment errors should + */ if (argc == 0) cmdentry.special = 1; listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); @@ -1224,7 +1224,7 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) setvareq(varlist.args[i], VEXPORT | VSTACK); envp = environment(); shellexec(argv, envp, path, cmdentry.u.index); - /*NOTREACHED*/ + /* NOTREACHED */ } goto out; @@ -1251,10 +1251,10 @@ out: } /* - * Search for a command. This is called before we fork so that the + * search for a command. this is called before we fork so that the * location of the command will be available in the parent as well as - * the child. The check for "goodname" is an overly conservative - * check that the name will not be subject to expansion. + * the child. the check for "goodname" is an overly conservative + * check that the name will not be subject to expansion */ static void @@ -1268,13 +1268,13 @@ prehash(union node *n) } /* - * Builtin commands. Builtin commands whose functions are closely - * tied to evaluation are implemented here. + * builtin commands. builtin commands whose functions are closely + * tied to evaluation are implemented here */ /* - * No command given, a bltin command with no arguments, or a bltin command - * with an invalid name. + * no command given, a bltin command with no arguments, or a bltin command + * with an invalid name */ int @@ -1285,21 +1285,21 @@ bltincmd(int argc, char **argv) return 127; } /* - * Preserve exitstatus of a previous possible command substitution - * as POSIX mandates - */ + * preserve exitstatus of a previous possible command substitution + * as POSIX mandates + */ return exitstatus; } /* - * Handle break and continue commands. Break, continue, and return are - * all handled by setting the evalskip flag. The evaluation routines + * handle break and continue commands. break, continue, and return are + * all handled by setting the evalskip flag. the evaluation routines * above all check this flag, and if it is set they start skipping - * commands rather than executing them. The variable skipcount is + * commands rather than executing them. the variable skipcount is * the number of loops to break/continue, or the number of function - * levels to return. (The latter is always 1.) It should probably - * be an error to break out of more loops than exist, but it isn't - * in the standard shell so we don't make it one here. + * levels to return. (the latter is always 1.) it should probably + * be an error to break out of more loops than exist, but it isnt + * in the standard shell so we dont make it one here */ int @@ -1309,7 +1309,7 @@ breakcmd(int argc, char **argv) char *end; if (argc > 1) { - /* Allow arbitrarily large numbers. */ + /* allow arbitrarily large numbers */ n = strtol(argv[1], &end, 10); if (!is_digit(argv[1][0]) || *end != '\0') error("Illegal number: %s", argv[1]); @@ -1325,7 +1325,7 @@ breakcmd(int argc, char **argv) } /* - * The `command' command. + * the `command' command */ int commandcmd(int argc __unused, char **argv __unused) @@ -1359,14 +1359,14 @@ commandcmd(int argc __unused, char **argv __unused) error("commandcmd bad call"); /* - * Do nothing successfully if no command was specified; - * ksh also does this. - */ + * do nothing successfully if no command was specified; + * ksh also does this + */ return 0; } /* - * The return command. + * the return command */ int @@ -1397,9 +1397,9 @@ execcmd(int argc, char **argv) int i; /* - * Because we have historically not supported any options, - * only treat "--" specially. - */ + * because we have historically not supported any options, + * only treat "--" specially + */ if (argc > 1 && strcmp(argv[1], "--") == 0) argc--, argv++; if (argc > 1) { diff --git a/cmd/posix/sh/eval.h b/cmd/posix/sh/eval.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ extern char *commandname; /* currently executing command */ @@ -52,7 +52,7 @@ void reseteval(void); #define EV_BACKCMD 04 /* command executing within back quotes */ void evalstring(const char *, int); -union node; /* BLETCH for ansi C */ +union node; /* BLETCH for ansi c */ void evaltree(union node *, int); void evalbackcmd(union node *, struct backcmd *); diff --git a/cmd/posix/sh/exec.c b/cmd/posix/sh/exec.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -41,12 +41,12 @@ #include <unistd.h> /* - * When commands are first encountered, they are entered in a hash table. - * This ensures that a full path search will not have to be done for them - * on each invocation. + * when commands are first encountered, they are entered in a hash table + * this ensures that a full path search will not have to be done for them + * on each invocation * - * We should investigate converting to a linear search, even though that - * would make the command name "hash" a misnomer. + * we should investigate converting to a linear search, even though that + * would make the command name "hash" a misnomer */ #include "../../../shared/paths.h" @@ -91,10 +91,10 @@ static void delete_cmd_entry(void); static void addcmdentry(const char *, struct cmdentry *); /* - * Exec a program. Never returns. If you change this routine, you may - * have to change the find_command routine as well. + * exec a program. never returns. if you change this routine, you may + * have to change the find_command routine as well * - * The argv array may be changed and element argv[-1] should be writable. + * the argv array may be changed and element argv[-1] should be writable */ void @@ -156,7 +156,7 @@ shellexec(char **argv, char **envp, const char *path, int idx) } } - /* Map to POSIX errors */ + /* map to POSIX errors */ if (e == ENOENT || e == ENOTDIR) errorwithstatus(127, "%s: not found", argv[0]); else @@ -173,16 +173,16 @@ isbinary(const char *data, size_t len) if (nul == NULL) return 0; /* - * POSIX says we shall allow execution if the initial part intended - * to be parsed by the shell consists of characters and does not - * contain the NUL character. This allows concatenating a shell - * script (ending with exec or exit) and a binary payload. - * - * In order to reject common binary files such as PNG images, check - * that there is a lowercase letter or expansion before the last - * newline before the NUL character, in addition to the check for - * the newline character suggested by POSIX. - */ + * POSIX says we shall allow execution if the initial part intended + * to be parsed by the shell consists of characters and does not + * contain the NUL character. this allows concatenating a shell + * script (ending with exec or exit) and a binary payload + * + * in order to reject common binary files such as PNG images, check + * that there is a lowercase letter or expansion before the last + * newline before the NUL character, in addition to the check for + * the newline character suggested by POSIX + */ hasletter = 0; for (p = data; *p != '\0'; p++) { if ((*p >= 'a' && *p <= 'z') || *p == '$' || *p == '`') @@ -221,13 +221,13 @@ tryexec(char *cmd, char **argv, char **envp) } /* - * Do a path search. The variable path (passed by reference) should be + * do a path search. the variable path (passed by reference) should be * set to the start of the path before the first call; padvance will update - * this value as it proceeds. Successive calls to padvance will return - * the possible path expansions in sequence. If popt is not NULL, options + * this value as it proceeds. successive calls to padvance will return + * the possible path expansions in sequence. if popt is not NULL, options * are processed: if an option (indicated by a percent sign) appears in * the path entry then *popt will be set to point to it; else *popt will be - * set to NULL. If popt is NULL, percent signs are not special. + * set to NULL. if popt is NULL, percent signs are not special */ char * @@ -271,7 +271,7 @@ padvance(const char **path, const char **popt, const char *name) return stalloc(len); } -/*** Command hashing code ***/ +/* ** command hashing code ** */ int hashcmd(int argc __unused, char **argv __unused) @@ -363,8 +363,8 @@ printentry(struct tblentry *cmdp, int verbose) } /* - * Resolve a command name. If you change this routine, you may have to - * change the shellexec routine as well. + * resolve a command name. if you change this routine, you may have to + * change the shellexec routine as well */ void @@ -380,7 +380,7 @@ find_command(const char *name, struct cmdentry *entry, int act, const char *path int spec; int cd; - /* If name contains a slash, don't use the hash table */ + /* if name contains a slash, dont use the hash table */ if (strchr(name, '/') != NULL) { entry->cmdtype = CMDNORMAL; entry->u.index = 0; @@ -390,7 +390,7 @@ find_command(const char *name, struct cmdentry *entry, int act, const char *path cd = 0; - /* If name is in the table, we're done */ + /* if name is in the table, we're done */ if ((cmdp = cmdlookup(name, 0)) != NULL) { if (cmdp->cmdtype == CMDFUNCTION && act & DO_NOFUNC) cmdp = NULL; @@ -413,7 +413,7 @@ find_command(const char *name, struct cmdentry *entry, int act, const char *path #if FEATURE_NOEXEC || FEATURE_NOFORK /* when builtin dispatch is active, registered wexec builtins are available - * even if they are not present on the filesystem */ + * even if they are not present on the filesystem */ if ((wexec_get_noexec() || wexec_get_nofork()) && wexec_is_builtin(name)) { INTOFF; cmdp = cmdlookup(name, 1); @@ -427,7 +427,7 @@ find_command(const char *name, struct cmdentry *entry, int act, const char *path } #endif - /* We have to search path. */ + /* we have to search path */ e = ENOENT; idx = -1; @@ -502,7 +502,7 @@ success: } /* - * Search the table of builtin commands. + * search the table of builtin commands */ int @@ -522,8 +522,8 @@ find_builtin(const char *name, int *special) } /* - * Called when a cd is done. If any entry in cmdtable depends on the current - * directory, simply clear cmdtable completely. + * called when a cd is done. if any entry in cmdtable depends on the current + * directory, simply clear cmdtable completely */ void @@ -534,9 +534,9 @@ hashcd(void) } /* - * Called before PATH is changed. The argument is the new value of PATH; - * pathval() still returns the old value at this point. Called with - * interrupts off. + * called before PATH is changed. the argument is the new value of PATH; + * pathval() still returns the old value at this point. called with + * interrupts off */ void @@ -546,7 +546,7 @@ changepath(const char *newval __unused) } /* - * Clear out cached utility locations. + * clear out cached utility locations */ void @@ -585,11 +585,11 @@ hashname(const char *p) } /* - * Locate a command in the command hash table. If "add" is nonzero, - * add the command to the table if it is not already present. The + * locate a command in the command hash table. if "add" is nonzero, + * add the command to the table if it is not already present. the * variable "lastcmdentry" is set to point to the address of the link * pointing to the entry, so that delete_cmd_entry can delete the - * entry. + * entry */ static struct tblentry **lastcmdentry; @@ -646,7 +646,7 @@ success: } /* - * Delete the command entry returned on the last lookup. + * delete the command entry returned on the last lookup */ static void @@ -662,8 +662,8 @@ delete_cmd_entry(void) } /* - * Add a new command entry, replacing any existing command entry for - * the same name. + * add a new command entry, replacing any existing command entry for + * the same name */ static void @@ -683,7 +683,7 @@ addcmdentry(const char *name, struct cmdentry *entry) } /* - * Define a shell function. + * define a shell function */ void @@ -700,8 +700,8 @@ defun(const char *name, union node *func) } /* - * Delete a function if it exists. - * Called with interrupts off. + * delete a function if it exists + * called with interrupts off */ int @@ -718,7 +718,7 @@ unsetfunc(const char *name) } /* - * Check if a function by a certain name exists. + * check if a function by a certain name exists */ int isfunc(const char *name) @@ -743,8 +743,8 @@ print_absolute_path(const char *name) } /* - * Shared code for the following builtin commands: - * type, command -v, command -V + * shared code for the following builtin commands: + * type, command -v, command -V */ int @@ -761,7 +761,7 @@ typecmd_impl(int argc, char **argv, int cmd, const char *path) clearcmdentry(); for (i = 1; i < argc; i++) { - /* First look at the keywords */ + /* first look at the keywords */ for (pp = parsekwd; *pp; pp++) if (**pp == *argv[i] && equal(*pp, argv[i])) break; @@ -774,7 +774,7 @@ typecmd_impl(int argc, char **argv, int cmd, const char *path) continue; } - /* Then look at the aliases */ + /* then look at the aliases */ if ((ap = lookupalias(argv[i], 1)) != NULL) { if (cmd == TYPECMD_SMALLV) { out1fmt("alias %s=", argv[i]); @@ -785,13 +785,13 @@ typecmd_impl(int argc, char **argv, int cmd, const char *path) continue; } - /* Then check if it is a tracked alias */ + /* then check if it is a tracked alias */ if ((cmdp = cmdlookup(argv[i], 0)) != NULL) { entry.cmdtype = cmdp->cmdtype; entry.u = cmdp->param; entry.special = cmdp->special; } else { - /* Finally use brute force */ + /* finally use brute force */ find_command(argv[i], &entry, 0, path); } @@ -875,7 +875,7 @@ typecmd_impl(int argc, char **argv, int cmd, const char *path) } /* - * Locate and print what a word is... + * locate and print what a word is... */ int diff --git a/cmd/posix/sh/exec.h b/cmd/posix/sh/exec.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" @@ -61,7 +61,7 @@ struct cmdentry { /* action to find_command() */ #define DO_ERR 0x01 /* prints errors */ -#define DO_NOFUNC 0x02 /* don't return shell functions, for command */ +#define DO_NOFUNC 0x02 /* dont return shell functions, for command */ void shellexec(char **, char **, const char *, int) __dead2; char *padvance(const char **, const char **, const char *); diff --git a/cmd/posix/sh/expand.c b/cmd/posix/sh/expand.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. - * Copyright (c) 1997-2005 - * Herbert Xu <herbert@gondor.apana.org.au>. All rights reserved. - * Copyright (c) 2010-2015 - * Jilles Tjoelker <jilles@stack.nl>. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved + * copyright (c) 1997-2005 + * herbert xu <herbert@gondor.apana.org.au>. all rights reserved + * copyright (c) 2010-2015 + * jilles tjoelker <jilles@stack.nl>. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <dirent.h> @@ -52,8 +52,8 @@ #include <wctype.h> /* - * Routines to expand arguments to commands. We have to deal with - * backquotes, shell variables, and file metacharacters. + * routines to expand arguments to commands. we have to deal with + * backquotes, shell variables, and file metacharacters */ #include "arith.h" @@ -172,7 +172,7 @@ nextword(char c, int flag, char *p, struct worddest *dst) dst->state = is_ws ? WORD_WS_DELIMITED : WORD_IDLE; } else if (!is_ws && dst->state == WORD_WS_DELIMITED) dst->state = WORD_IDLE; - /* Reserve space while the stack string is empty. */ + /* reserve space while the stack string is empty */ appendarglist(dst->list, NULL); dst->list->count--; STARTSTACKSTR(p); @@ -203,16 +203,16 @@ stputs_split(const char *data, const char *syntax, int flag, char *p, struct wor #define STPUTS_SPLIT(data, syntax, flag, p, dst) p = stputs_split((data), syntax, flag, p, dst) /* - * Perform expansions on an argument, placing the resulting list of arguments - * in arglist. Parameter expansion, command substitution and arithmetic + * perform expansions on an argument, placing the resulting list of arguments + * in arglist. parameter expansion, command substitution and arithmetic * expansion are always performed; additional expansions can be requested - * via flag (EXP_*). - * The result is left in the stack string. - * When arglist is NULL, perform here document expansion. + * via flag (EXP_*) + * the result is left in the stack string + * when arglist is NULL, perform here document expansion * - * When doing something that may cause this to be re-entered, make sure + * when doing something that may cause this to be re-entered, make sure * the stack string is empty via grabstackstr() and do not assume expdest - * remains valid. + * remains valid */ void expandarg(union node *arg, struct arglist *arglist, int flag) @@ -245,14 +245,14 @@ expandarg(union node *arg, struct arglist *arglist, int flag) } /* - * Perform parameter expansion, command substitution and arithmetic - * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE. - * Processing ends at a CTLENDVAR or CTLENDARI character as well as '\0'. - * This is used to expand word in ${var+word} etc. - * If EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC - * characters to allow for further processing. + * perform parameter expansion, command substitution and arithmetic + * expansion, and tilde expansion if requested via EXP_TILDE/EXP_VARTILDE + * processing ends at a CTLENDVAR or CTLENDARI character as well as '\0' + * this is used to expand word in ${var+word} etc + * if EXP_GLOB or EXP_CASE are set, keep and/or generate CTLESC + * characters to allow for further processing * - * If EXP_SPLIT is set, dst receives any complete words produced. + * if EXP_SPLIT is set, dst receives any complete words produced */ static const char * argstr(const char *p, struct nodelist **restrict argbackq, int flag, struct worddest *dst) @@ -311,9 +311,9 @@ argstr(const char *p, struct nodelist **restrict argbackq, int flag, struct word case ':': case '=': /* - * sort of a hack - expand tildes in variable - * assignments (after the first '=' and after ':'s). - */ + * sort of a hack - expand tildes in variable + * assignments (after the first '=' and after ':'s) + */ if (split_lit && !lit_quoted && strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) { NEXTWORD(c, flag, expdest, dst); break; @@ -336,8 +336,8 @@ argstr(const char *p, struct nodelist **restrict argbackq, int flag, struct word } /* - * Perform tilde expansion, placing the result in the stack string and - * returning the next position in the input string to process. + * perform tilde expansion, placing the result in the stack string and + * returning the next position in the input string to process */ static const char * exptilde(const char *p, int flag) @@ -352,7 +352,7 @@ exptilde(const char *p, int flag) for (;;) { c = *p; switch (c) { - case CTLESC: /* This means CTL* are always considered quoted. */ + case CTLESC: /* this means CTL* are always considered quoted */ case CTLVAR: case CTLBACKQ: case CTLBACKQ | CTLQUOTE: @@ -388,7 +388,7 @@ exptilde(const char *p, int flag) } /* - * Expand arithmetic expression. + * expand arithmetic expression */ static const char * expari(const char *p, struct nodelist **restrict argbackq, int flag, struct worddest *dst) @@ -418,16 +418,16 @@ expari(const char *p, struct nodelist **restrict argbackq, int flag, struct word adj = strlen(expdest); STADJUST(adj, expdest); /* - * If this is quoted, a '-' must not indicate a range in [...]. - * If this is not quoted, splitting may occur. - */ + * if this is quoted, a '-' must not indicate a range in [...] + * if this is not quoted, splitting may occur + */ if (quoted ? result < 0 && begoff > 1 && flag & (EXP_GLOB | EXP_CASE) : flag & EXP_SPLIT) reprocess(expdest - adj - stackblock(), flag, VSNORMAL, quoted, dst); return p; } /* - * Perform command substitution. + * perform command substitution */ static void expbackq(union node *cmd, int quoted, int flag, struct worddest *dst) @@ -456,7 +456,7 @@ expbackq(union node *cmd, int quoted, int flag, struct worddest *dst) ifs = ifsset() ? ifsval() : " \t\n"; else ifs = ""; - /* Remove trailing newlines */ + /* remove trailing newlines */ for (;;) { if (--in.nleft < 0) { if (in.fd < 0) @@ -629,8 +629,8 @@ subevalvar_misc( } /* - * Expand a variable, and return a pointer to the next character in the - * input string. + * expand a variable, and return a pointer to the next character in the + * input string */ static const char * @@ -748,9 +748,9 @@ evalvar(const char *p, struct nodelist **restrict argbackq, int flag, struct wor if (!set) break; /* - * Terminate the string and start recording the pattern - * right after it - */ + * terminate the string and start recording the pattern + * right after it + */ STPUTC('\0', expdest); patloc = expdest - stackblock(); p = subevalvar_trim(p, argbackq, patloc, subtype, startloc); @@ -798,7 +798,7 @@ evalvar(const char *p, struct nodelist **restrict argbackq, int flag, struct wor } /* - * Test whether a special or positional parameter is set. + * test whether a special or positional parameter is set */ static int @@ -891,7 +891,7 @@ reprocess(int startloc, int flag, int subtype, int quoted, struct worddest *dst) } /* - * Add the value of a special or positional parameter to the stack string. + * add the value of a special or positional parameter to the stack string */ static void @@ -989,9 +989,9 @@ static char expdir[PATH_MAX]; #define expdir_end (expdir + sizeof(expdir)) /* - * Perform pathname generation and remove control characters. - * At this point, the only control characters should be CTLESC. - * The results are stored in the list dstlist. + * perform pathname generation and remove control characters + * at this point, the only control characters should be CTLESC + * the results are stored in the list dstlist */ static void expandmeta(char *pattern, struct arglist *dstlist) @@ -1013,8 +1013,8 @@ expandmeta(char *pattern, struct arglist *dstlist) } if (dstlist->count == firstmatch) { /* - * no matches - */ + * no matches + */ rmescapes(pattern); appendarglist(dstlist, pattern); } else { @@ -1028,7 +1028,7 @@ expandmeta(char *pattern, struct arglist *dstlist) } /* - * Do metacharacter (i.e. *, ?, [...]) expansion. + * do metacharacter (i.e. *, ?, [...]) expansion */ static void @@ -1182,11 +1182,11 @@ get_wc(const char **p) } /* - * See if a character matches a character class, starting at the first colon - * of "[:class:]". - * If a valid character class is recognized, a pointer to the next character + * see if a character matches a character class, starting at the first colon + * of "[:class:]" + * if a valid character class is recognized, a pointer to the next character * after the final closing bracket is stored into *end, otherwise a null - * pointer is stored into *end. + * pointer is stored into *end */ static int match_charclass(const char *p, wchar_t chr, const char **end) @@ -1204,14 +1204,14 @@ match_charclass(const char *p, wchar_t chr, const char **end) name[nameend - p] = '\0'; *end = nameend + 2; cclass = wctype(name); - /* An unknown class matches nothing but is valid nevertheless. */ + /* an unknown class matches nothing but is valid nevertheless */ if (cclass == 0) return 0; return iswctype(chr, cclass); } /* - * Returns true if the pattern matches the string. + * returns true if the pattern matches the string */ static int @@ -1242,9 +1242,9 @@ patmatch(const char *pattern, const char *string) if (localeisutf8) { wc = get_wc(&q); /* - * A '?' does not match invalid UTF-8 but a - * '*' does, so backtrack. - */ + * a '?' does not match invalid UTF-8 but a + * '*' does, so backtrack + */ if (wc == 0) goto backtrack; } else @@ -1255,17 +1255,17 @@ patmatch(const char *pattern, const char *string) while (c == '*') c = *++p; /* - * If the pattern ends here, we know the string - * matches without needing to look at the rest of it. - */ + * if the pattern ends here, we know the string + * matches without needing to look at the rest of it + */ if (c == '\0') return 1; /* - * First try the shortest match for the '*' that - * could work. We can forget any earlier '*' since - * there is no way having it match more characters - * can help us, given that we are already here. - */ + * first try the shortest match for the '*' that + * could work. we can forget any earlier '*' since + * there is no way having it match more characters + * can help us, given that we are already here + */ bt_p = p; bt_q = q; break; @@ -1341,10 +1341,10 @@ patmatch(const char *pattern, const char *string) break; backtrack: /* - * If we have a mismatch (other than hitting the end - * of the string), go back to the last '*' seen and - * have it match one additional character. - */ + * if we have a mismatch (other than hitting the end + * of the string), go back to the last '*' seen and + * have it match one additional character + */ if (bt_p == NULL) return 0; if (*bt_q == '\0') @@ -1358,7 +1358,7 @@ patmatch(const char *pattern, const char *string) } /* - * Remove any CTLESC and CTLQUOTEMARK characters from a string. + * remove any CTLESC and CTLQUOTEMARK characters from a string */ void @@ -1385,7 +1385,7 @@ rmescapes(char *str) } /* - * See if a pattern matches in a case statement. + * see if a pattern matches in a case statement */ int @@ -1408,7 +1408,7 @@ casematch(union node *pattern, const char *val) } /* - * Our own itoa(). + * our own itoa() */ static void @@ -1431,7 +1431,7 @@ cvtnum(int num, char *buf) } /* - * Do most of the work for wordexp(3). + * do most of the work for wordexp(3) */ int @@ -1450,7 +1450,7 @@ wordexpcmd(int argc, char **argv) } /* - * Do most of the work for wordexp(3), new version. + * do most of the work for wordexp(3), new version */ int diff --git a/cmd/posix/sh/expand.h b/cmd/posix/sh/expand.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ struct arglist { diff --git a/cmd/posix/sh/input.c b/cmd/posix/sh/input.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -40,7 +40,7 @@ #include <unistd.h> /* - * This file implements the input routines used by the parser. + * this file implements the input routines used by the parser */ #include "alias.h" @@ -69,8 +69,8 @@ struct strpush { }; /* - * The parsefile structure pointed to by the global variable parsefile - * contains information about the current file being read. + * the parsefile structure pointed to by the global variable parsefile + * contains information about the current file being read */ struct parsefile { @@ -112,8 +112,8 @@ resetinput(void) } /* - * Read a character from the script, returning PEOF on end of file. - * Nul characters in the input are silently discarded. + * read a character from the script, returning PEOF on end of file + * nul characters in the input are silently discarded */ int @@ -189,13 +189,13 @@ retry: } /* - * Refill the input buffer and return the next input character: + * refill the input buffer and return the next input character: * - * 1) If a string was pushed back on the input, pop it; - * 2) If an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading - * from a string so we can't refill the buffer, return EOF. - * 3) If there is more in this buffer, use it else call read to fill it. - * 4) Process input up to the next newline, deleting nul characters. + * 1) if a string was pushed back on the input, pop it; + * 2) if an EOF was pushed back (parsenleft == EOF_NLEFT) or we are reading + * from a string so we cant refill the buffer, return EOF + * 3) if there is more in this buffer, use it else call read to fill it + * 4) process input up to the next newline, deleting nul characters */ int @@ -207,10 +207,10 @@ preadbuffer(void) while (parsefile->strpush) { /* - * Add a space to the end of an alias to ensure that the - * alias remains in use while parsing its last word. - * This avoids alias recursions. - */ + * add a space to the end of an alias to ensure that the + * alias remains in use while parsing its last word + * this avoids alias recursions + */ if (parsenleft == -1 && parsefile->strpush->ap != NULL) return ' '; popstring(); @@ -275,8 +275,8 @@ again: } /* - * Returns if we are certain we are at EOF. Does not cause any more input - * to be read from the outside world. + * returns if we are certain we are at EOF. does not cause any more input + * to be read from the outside world */ int @@ -292,8 +292,8 @@ preadateof(void) } /* - * Undo the last call to pgetc. Only one character may be pushed back. - * PEOF may be pushed back. + * undo the last call to pgetc. only one character may be pushed back + * PEOF may be pushed back */ void @@ -304,8 +304,8 @@ pungetc(void) } /* - * Push a string back onto the input at this current parsefile level. - * We handle aliases this way. + * push a string back onto the input at this current parsefile level + * we handle aliases this way */ void pushstring(const char *s, int len, struct alias *ap) @@ -313,7 +313,7 @@ pushstring(const char *s, int len, struct alias *ap) struct strpush *sp; INTOFF; - /*out2fmt_flush("*** calling pushstring: %s, %d\n", s, len);*/ + /* out2fmt_flush("*** calling pushstring: %s, %d\n", s, len); */ if (parsefile->strpush) { sp = ckmalloc(sizeof(struct strpush)); sp->prev = parsefile->strpush; @@ -345,8 +345,8 @@ popstring(void) parsenextc = sp->prevstring; parsenleft = sp->prevnleft; parselleft = sp->prevlleft; - /*out2fmt_flush("*** calling popstring: restoring to '%s'\n", - * parsenextc);*/ + /* out2fmt_flush("*** calling popstring: restoring to '%s'\n", + * parsenextc); */ parsefile->strpush = sp->prev; if (sp != &(parsefile->basestrpush)) ckfree(sp); @@ -354,12 +354,12 @@ popstring(void) } /* - * Set the input to take input from a file. If push is set, push the - * old input onto the stack first. - * About verify: - * -1: Obey verifyflag - * 0: Do not verify - * 1: Do verify + * set the input to take input from a file. if push is set, push the + * old input onto the stack first + * about verify: + * -1: obey verifyflag + * 0: do not verify + * 1: do verify */ void @@ -392,8 +392,8 @@ setinputfile(const char *fname, int push, int verify) } /* - * Like setinputfile, but takes an open file descriptor (which should have - * its FD_CLOEXEC flag already set). Call this with interrupts off. + * like setinputfile, but takes an open file descriptor (which should have + * its FD_CLOEXEC flag already set). call this with interrupts off */ void @@ -413,7 +413,7 @@ setinputfd(int fd, int push) } /* - * Like setinputfile, but takes input from a string. + * like setinputfile, but takes input from a string */ void @@ -428,8 +428,8 @@ setinputstring(const char *string) } /* - * To handle the "." command, a stack of input files is used. Pushfile - * adds a new entry to the stack and popfile restores the previous level. + * to handle the "." command, a stack of input files is used. pushfile + * adds a new entry to the stack and popfile restores the previous level */ static void @@ -468,7 +468,7 @@ popfile(void) } /* - * Return current file (to go back to it later using popfilesupto()). + * return current file (to go back to it later using popfilesupto()) */ struct parsefile * @@ -478,9 +478,9 @@ getcurrentfile(void) } /* - * Pop files until the given file is on top again. Useful for regular - * builtins that read shell commands from files or strings. - * If the given file is not an active file, an error is raised. + * pop files until the given file is on top again. useful for regular + * builtins that read shell commands from files or strings + * if the given file is not an active file, an error is raised */ void @@ -493,7 +493,7 @@ popfilesupto(struct parsefile *file) } /* - * Return to top level. + * return to top level */ void @@ -504,8 +504,8 @@ popallfiles(void) } /* - * Close the file(s) that the shell is reading commands from. Called - * after a fork is done. + * close the file(s) that the shell is reading commands from. called + * after a fork is done */ void diff --git a/cmd/posix/sh/input.h b/cmd/posix/sh/input.h @@ -1,43 +1,43 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* PEOF (the end of file marker) is defined in syntax.h */ /* - * The input line number. Input.c just defines this variable, and saves - * and restores it when files are pushed and popped. The user of this - * package must set its value. + * the input line number. input.c just defines this variable, and saves + * and restores it when files are pushed and popped. the user of this + * package must set its value */ extern int plinno; extern int parsenleft; /* number of characters left in input buffer */ diff --git a/cmd/posix/sh/jobs.c b/cmd/posix/sh/jobs.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -70,10 +70,10 @@ #include "var.h" /* - * A job structure contains information about a job. A job is either a - * single process or a set of processes contained in a pipeline. In the - * latter case, pidlist will be non-NULL, and will point to a -1 terminated - * array of pids. + * a job structure contains information about a job. a job is either a + * single process or a set of processes contained in a pipeline. in the + * latter case, pidlist will be non-null, and will point to a -1 terminated + * array of pids */ struct procstat { @@ -140,7 +140,7 @@ static void printjobcmd(struct job *); static void showjob(struct job *, int); /* - * Turn job control on and off. + * turn job control on and off */ static int jobctl; @@ -185,9 +185,9 @@ setjobctl(int on) } if (ttyfd < 10) { /* - * Keep our TTY file descriptor out of the way of - * the user's redirections. - */ + * keep our TTY file descriptor out of the way of + * the user's redirections + */ if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) { jobctl_notty(); return; @@ -452,12 +452,12 @@ showjob(struct job *jp, int mode) } /* - * Print a list of jobs. If "change" is nonzero, only print jobs whose - * statuses have changed since the last call to showjobs. + * print a list of jobs. if "change" is nonzero, only print jobs whose + * statuses have changed since the last call to showjobs * - * If the shell is interrupted in the process of creating a job, the - * result may be a job structure containing zero processes. Such structures - * will be freed here. + * if the shell is interrupted in the process of creating a job, the + * result may be a job structure containing zero processes. such structures + * will be freed here */ void @@ -480,9 +480,9 @@ showjobs(int change, int mode) showjob(jp, mode); if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) { jp->changed = 0; - /* Hack: discard jobs for which $! has not been - * referenced in interactive mode when they terminate. - */ + /* hack: discard jobs for which $! has not been + * referenced in interactive mode when they terminate + */ if (jp->state == JOBDONE && !jp->remembered && (iflag || jp != bgjob)) { freejob(jp); } @@ -491,7 +491,7 @@ showjobs(int change, int mode) } /* - * Mark a job structure as unused. + * mark a job structure as unused */ static void @@ -545,9 +545,9 @@ waitcmdloop(struct job *job) struct job *jp; /* - * Loop until a process is terminated or stopped, or a SIGINT is - * received. - */ + * loop until a process is terminated or stopped, or a SIGINT is + * received + */ do { if (job != NULL) { @@ -611,7 +611,7 @@ jobidcmd(int argc __unused, char **argv __unused) } /* - * Convert a job name to a job structure. + * convert a job name to a job structure */ static struct job * @@ -713,7 +713,7 @@ killjob(const char *name, int sig) } /* - * Return a new job structure, + * return a new job structure, */ struct job * @@ -734,7 +734,7 @@ makejob(union node *node __unused, int nprocs) jp = ckmalloc((njobs + 4) * sizeof jobtab[0]); memcpy(jp, jobtab, njobs * sizeof jp[0]); #if JOBS - /* Relocate `next' pointers and list head */ + /* relocate `next' pointers and list head */ if (jobmru != NULL) jobmru = &jp[jobmru - jobtab]; for (i = 0; i < njobs; i++) @@ -743,7 +743,7 @@ makejob(union node *node __unused, int nprocs) #endif if (bgjob != NULL) bgjob = &jp[bgjob - jobtab]; - /* Relocate `ps' pointers */ + /* relocate `ps' pointers */ for (i = 0; i < njobs; i++) if (jp[i].ps == &jobtab[i].ps0) jp[i].ps = &jp[i].ps0; @@ -819,19 +819,19 @@ deljob(struct job *j) } /* - * Return the most recently used job that isn't `nj', and preferably one - * that is stopped. + * return the most recently used job that isnt `nj', and preferably one + * that is stopped */ static struct job * getcurjob(struct job *nj) { struct job *jp; - /* Try to find a stopped one.. */ + /* try to find a stopped one.. */ for (jp = jobmru; jp != NULL; jp = jp->next) if (jp->used && jp != nj && jp->state == JOBSTOPPED) return (jp); - /* Otherwise the most recently used job that isn't `nj' */ + /* otherwise the most recently used job that isnt `nj' */ for (jp = jobmru; jp != NULL; jp = jp->next) if (jp->used && jp != nj) return (jp); @@ -842,18 +842,18 @@ getcurjob(struct job *nj) #endif /* - * Fork of a subshell. If we are doing job control, give the subshell its - * own process group. Jp is a job structure that the job is to be added to. - * N is the command that will be evaluated by the child. Both jp and n may - * be NULL. The mode parameter can be one of the following: - * FORK_FG - Fork off a foreground process. - * FORK_BG - Fork off a background process. - * FORK_NOJOB - Like FORK_FG, but don't give the process its own - * process group even if job control is on. + * fork of a subshell. if we are doing job control, give the subshell its + * own process group. jp is a job structure that the job is to be added to + * n is the command that will be evaluated by the child. both jp and n may + * be NULL. the mode parameter can be one of the following: + * FORK_FG - fork off a foreground process + * FORK_BG - fork off a background process + * FORK_NOJOB - like FORK_FG, but dont give the process its own + * process group even if job control is on * - * When job control is turned off, background processes have their standard + * when job control is turned off, background processes have their standard * input redirected to /dev/null (except for the second and later processes - * in a pipeline). + * in a pipeline) */ pid_t @@ -895,11 +895,11 @@ forkshell(struct job *jp, union node *n, int mode) pgrp = jp->ps[0].pid; if (setpgid(0, pgrp) == 0 && mode == FORK_FG && ttyfd >= 0) { /* - * Each process in a pipeline must have the tty - * pgrp set before running its code. - * Only for pipelines of three or more processes - * could this be reduced to two calls. - */ + * each process in a pipeline must have the tty + * pgrp set before running its code + * only for pipelines of three or more processes + * could this be reduced to two calls + */ if (tcsetpgrp(ttyfd, pgrp) < 0) error("tcsetpgrp failed, errno=%d", errno); } @@ -1017,22 +1017,22 @@ vforkexecshell(struct job *jp, char **argv, char **envp, const char *path, int i } /* - * Wait for job to finish. + * wait for job to finish * - * Under job control we have the problem that while a child process is + * under job control we have the problem that while a child process is * running interrupts generated by the user are sent to the child but not - * to the shell. This means that an infinite loop started by an inter- - * active user may be hard to kill. With job control turned off, an - * interactive user may place an interactive program inside a loop. If - * the interactive program catches interrupts, the user doesn't want - * these interrupts to also abort the loop. The approach we take here + * to the shell. this means that an infinite loop started by an inter- + * active user may be hard to kill. with job control turned off, an + * interactive user may place an interactive program inside a loop. if + * the interactive program catches interrupts, the user doesnt want + * these interrupts to also abort the loop. the approach we take here * is to have the shell ignore interrupt signals while waiting for a * foreground process to terminate, and then send itself an interrupt - * signal if the child process was terminated by an interrupt signal. - * Unfortunately, some programs want to do a bit of cleanup and then + * signal if the child process was terminated by an interrupt signal + * unfortunately, some programs want to do a bit of cleanup and then * exit on interrupt; unless these processes terminate themselves by * sending a signal to themselves (instead of calling exit) they will - * confuse this approach. + * confuse this approach */ int @@ -1093,7 +1093,7 @@ dummy_handler(int sig __unused) } /* - * Wait for a process to terminate. + * wait for a process to terminate */ static pid_t @@ -1291,8 +1291,8 @@ backgndpidval(void) } /* - * Return a string identifying a command (to be printed by the - * jobs command. + * return a string identifying a command (to be printed by the + * jobs command */ static char *cmdnextc; diff --git a/cmd/posix/sh/jobs.h b/cmd/posix/sh/jobs.h @@ -1,38 +1,38 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ -/* Mode argument to forkshell. Don't change FORK_FG or FORK_BG. */ +/* mode argument to forkshell. dont change FORK_FG or FORK_BG */ #define FORK_FG 0 #define FORK_BG 1 #define FORK_NOJOB 2 diff --git a/cmd/posix/sh/kill.c b/cmd/posix/sh/kill.c @@ -1,36 +1,36 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1988, 1993, 1994 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1988, 1993, 1994 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Important: This file is used both as a standalone program /bin/kill and - * as a builtin for /bin/sh (#define SHELL). + * important: this file is used both as a standalone program /bin/kill and + * as a builtin for /bin/sh (#define SHELL) */ #include "sig.h" @@ -128,7 +128,7 @@ main(int argc, char *argv[]) #endif { pidl = strtol(*argv, &ep, 10); - /* Check for overflow of pid_t. */ + /* check for overflow of pid_t */ pid = (pid_t)pidl; if (!**argv || *ep || pid != pidl) errx(2, "illegal process id: %s", *argv); diff --git a/cmd/posix/sh/lineedit.c b/cmd/posix/sh/lineedit.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #if !FEATURE_SH_HISTEDIT @@ -262,7 +262,7 @@ find_completions_recurse( snprintf(next_user, sizeof(next_user), "%s", user_prefix); if (S_ISDIR(st.st_mode)) { /* if it is a directory and doesnt end with - * slash, add slash */ + * slash, add slash */ len = strlen(next_user); if (len > 0 && next_user[len - 1] != '/') { strlcat(next_user, "/", sizeof(next_user)); @@ -384,7 +384,7 @@ complete_files(const char *word, int is_cmd, struct redlineCompletions *lc) path_to_split = (unescaped_word[1] == '\0') ? "" : (char *)(unescaped_word + 2); } else { /* ~username is not supported for abbreviation, fallback - * to home */ + * to home */ fs_dir = home ? home : "/"; user_prefix = "~/"; path_to_split = (char *)(unescaped_word + 1); @@ -420,7 +420,7 @@ complete_files(const char *word, int is_cmd, struct redlineCompletions *lc) } } else { /* empty path_to_split (e.g. exactly ~ or exactly / or empty - * word) */ + * word) */ comps[comp_count++] = p; } diff --git a/cmd/posix/sh/mail.c b/cmd/posix/sh/mail.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Routines to check for mail. (Perhaps make part of main.c?) + * routines to check for mail. (perhaps make part of main.c?) */ #include "mail.h" @@ -52,9 +52,9 @@ static int nmboxes; /* number of mailboxes */ static time_t mailtime[MAXMBOXES]; /* times of mailboxes */ /* - * Print appropriate message(s) if mail has arrived. If the argument is + * print appropriate message(s) if mail has arrived. if the argument is * non-zero, then the value of MAIL has changed, so we just update the - * values. + * values */ void @@ -86,7 +86,7 @@ chkmail(int silent) msg = strchr(p, '%'); if (msg != NULL) *msg++ = '\0'; -#ifdef notdef /* this is what the System V shell claims to do (it lies) */ +#ifdef notdef /* this is what the system v shell claims to do (it lies) */ if (stat(p, &statb) < 0) statb.st_mtime = 0; if (statb.st_mtime > mailtime[i] && !silent) { diff --git a/cmd/posix/sh/mail.h b/cmd/posix/sh/mail.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ void chkmail(int); diff --git a/cmd/posix/sh/main.c b/cmd/posix/sh/main.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -79,22 +79,22 @@ static void read_profile(const char *); static char *find_dot_file(char *); /* - * Main routine. We initialize things, parse the arguments, execute + * main routine. we initialize things, parse the arguments, execute * profiles if we're a login shell, and then call cmdloop to execute - * commands. The setjmp call sets up the location to jump to when an - * exception occurs. When an exception occurs the variable "state" - * is used to figure out how far we had gotten. + * commands. the setjmp call sets up the location to jump to when an + * exception occurs. when an exception occurs the variable "state" + * is used to figure out how far we had gotten */ int main(int argc, char *argv[]) { /* - * As smark is accessed after a longjmp, it cannot be a local in main(). - * The C standard specifies that the values of non-volatile local - * variables are unspecified after a jump if modified between the - * setjmp and longjmp. - */ + * as smark is accessed after a longjmp, it cannot be a local in main() + * the c standard specifies that the values of non-volatile local + * variables are unspecified after a jump if modified between the + * setjmp and longjmp + */ static struct stackmark smark, smark2; volatile int state; char *shinit; @@ -130,10 +130,10 @@ main(int argc, char *argv[]) rootpid = getpid(); if (rootpid == 1) { /* - * Make sh usable for invocation as interactive init - * substitute with init_path=/bin/sh, by opening - * file descriptors 0, 1, and 2 on /dev/console. - */ + * make sh usable for invocation as interactive init + * substitute with init_path=/bin/sh, by opening + * file descriptors 0, 1, and 2 on /dev/console + */ if (fcntl(STDIN_FILENO, F_GETFL, NULL) == -1 && errno == EBADF) { (void)open(ARUU_PATH_DEVCONSOLE, O_RDWR); (void)setsid(); @@ -188,7 +188,7 @@ state4: cmdloop(1); } exitshell(exitstatus); - /*NOTREACHED*/ + /* NOTREACHED */ return 0; } @@ -200,8 +200,8 @@ reset(void) } /* - * Read and execute commands. "Top" is nonzero for the top level command - * loop; it turns on prompting if the shell is interactive. + * read and execute commands. "top" is nonzero for the top level command + * loop; it turns on prompting if the shell is interactive */ static void @@ -256,7 +256,7 @@ cmdloop(int top) } /* - * Read /etc/profile or .profile. Return on error. + * read /etc/profile or .profile. return on error */ static void @@ -283,7 +283,7 @@ read_profile(const char *name) } /* - * Read a file containing shell functions. + * read a file containing shell functions */ void @@ -295,8 +295,8 @@ readcmdfile(const char *name, int verify) } /* - * Take commands from a file. To be compatible we should do a path - * search for the file, which is necessary to find sub-commands. + * take commands from a file. to be compatible we should do a path + * search for the file, which is necessary to find sub-commands */ static char * @@ -307,16 +307,16 @@ find_dot_file(char *basename) const char *path = pathval(); struct stat statb; - /* don't try this for absolute or relative paths */ + /* dont try this for absolute or relative paths */ if (strchr(basename, '/')) return basename; while ((fullname = padvance(&path, &opt, basename)) != NULL) { if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) { /* - * Don't bother freeing here, since it will - * be freed by the caller. - */ + * dont bother freeing here, since it will + * be freed by the caller + */ return fullname; } stunalloc(fullname); @@ -335,9 +335,9 @@ dotcmd(int argc, char **argv) exitstatus = 0; /* - * Because we have historically not supported any options, - * only treat "--" specially. - */ + * because we have historically not supported any options, + * only treat "--" specially + */ filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1]; fullname = find_dot_file(filename); diff --git a/cmd/posix/sh/main.h b/cmd/posix/sh/main.h @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ extern int rootpid; /* pid of main shell */ -extern int rootshell; /* true if we aren't a child of the main shell */ +extern int rootshell; /* true if we arent a child of the main shell */ extern struct jmploc main_handler; /* top level exception handler */ void readcmdfile(const char *, int); diff --git a/cmd/posix/sh/memalloc.c b/cmd/posix/sh/memalloc.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "memalloc.h" @@ -50,7 +50,7 @@ badalloc(const char *message) } /* - * Like malloc, but returns an error when out of space. + * like malloc, but returns an error when out of space */ pointer @@ -67,7 +67,7 @@ ckmalloc(size_t nbytes) } /* - * Same for realloc. + * same for realloc */ pointer @@ -90,7 +90,7 @@ ckfree(pointer p) } /* - * Make a copy of a string in safe storage. + * make a copy of a string in safe storage */ char * @@ -106,19 +106,19 @@ savestr(const char *s) } /* - * Parse trees for commands are allocated in lifo order, so we use a stack + * parse trees for commands are allocated in lifo order, so we use a stack * to make this more efficient, and also to avoid all sorts of exception - * handling code to handle interrupts in the middle of a parse. + * handling code to handle interrupts in the middle of a parse * - * The size 496 was chosen because with 16-byte alignment the total size - * for the allocated block is 512. + * the size 496 was chosen because with 16-byte alignment the total size + * for the allocated block is 512 */ -#define MINSIZE 496 /* minimum size of a block. */ +#define MINSIZE 496 /* minimum size of a block */ struct stack_block { struct stack_block *prev; - /* Data follows */ + /* data follows */ }; #define SPACE(sp) ((char *)(sp) + ALIGN(sizeof(struct stack_block))) @@ -165,7 +165,7 @@ stalloc(int nbytes) void stunalloc(pointer p) { - if (p == NULL) { /*DEBUG */ + if (p == NULL) { /* DEBUG */ write(STDERR_FILENO, "stunalloc\n", 10); abort(); } @@ -191,7 +191,7 @@ setstackmark(struct stackmark *mark) mark->stackp = stackp; mark->stacknxt = stacknxt; mark->stacknleft = stacknleft; - /* Ensure this block stays in place. */ + /* ensure this block stays in place */ if (stackp != NULL && stacknxt == SPACE(stackp)) stalloc(1); } @@ -217,13 +217,13 @@ popstackmark(struct stackmark *mark) } /* - * When the parser reads in a string, it wants to stick the string on the + * when the parser reads in a string, it wants to stick the string on the * stack and only adjust the stack pointer when it knows how big the - * string is. Stackblock (defined in stack.h) returns a pointer to a block + * string is. stackblock (defined in stack.h) returns a pointer to a block * of space on top of the stack and stackblocklen returns the length of - * this block. Growstackblock will grow this space by at least one byte, - * possibly moving it (like realloc). Grabstackblock actually allocates the - * part of the block that has been used. + * this block. growstackblock will grow this space by at least one byte, + * possibly moving it (like realloc). grabstackblock actually allocates the + * part of the block that has been used */ static void @@ -269,21 +269,21 @@ growstackblock(int min) } /* - * The following routines are somewhat easier to use than the above. - * The user declares a variable of type STACKSTR, which may be declared - * to be a register. The macro STARTSTACKSTR initializes things. Then - * the user uses the macro STPUTC to add characters to the string. In - * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is - * grown as necessary. When the user is done, she can just leave the - * string there and refer to it using stackblock(). Or she can allocate - * the space for it using grabstackstr(). If it is necessary to allow + * the following routines are somewhat easier to use than the above + * the user declares a variable of type STACKSTR, which may be declared + * to be a register. the macro STARTSTACKSTR initializes things. then + * the user uses the macro STPUTC to add characters to the string. in + * effect, stputc(c, p) is the same as *p++ = c except that the stack is + * grown as necessary. when the user is done, she can just leave the + * string there and refer to it using stackblock(). or she can allocate + * the space for it using grabstackstr(). if it is necessary to allow * someone else to use the stack temporarily and then continue to grow * the string, the user should use grabstack to allocate the space, and - * then call ungrabstr(p) to return to the previous mode of operation. + * then call ungrabstr(p) to return to the previous mode of operation * - * USTPUTC is like STPUTC except that it doesn't check for overflow. + * USTPUTC is like STPUTC except that it doesnt check for overflow * CHECKSTACKSPACE can be called before USTPUTC to ensure that there - * is space for at least one character. + * is space for at least one character */ static char * @@ -303,7 +303,7 @@ growstackstr(void) } /* - * Called from CHECKSTRSPACE. + * called from CHECKSTRSPACE */ char * diff --git a/cmd/posix/sh/memalloc.h b/cmd/posix/sh/memalloc.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" @@ -77,11 +77,11 @@ char *stputs(const char *data, char *p); } #define USTPUTC(c, p) (*p++ = (c)) /* - * STACKSTRNUL's use is where we want to be able to turn a stack - * (non-sentinel, character counting string) into a C string, - * and later pretend the NUL is not there. - * Note: Because of STACKSTRNUL's semantics, STACKSTRNUL cannot be used - * on a stack that will grabstackstr()ed. + * stackstrnul's use is where we want to be able to turn a stack + * (non-sentinel, character counting string) into a c string, + * and later pretend the NUL is not there + * note: because of stackstrnul's semantics, STACKSTRNUL cannot be used + * on a stack that will grabstackstr()ed */ #define STACKSTRNUL(p) (p == sstrend ? (p = growstackstr(), *p = '\0') : (*p = '\0')) #define STUNPUTC(p) (--p) diff --git a/cmd/posix/sh/miscbltin.c b/cmd/posix/sh/miscbltin.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Miscellaneous builtins. + * miscellaneous builtins */ #include <sys/resource.h> @@ -92,12 +92,12 @@ fdctx_init(int fd, struct fdctx *fdc) { off_t cur; - /* Check if fd is seekable. */ + /* check if fd is seekable */ cur = lseek(fd, 0, SEEK_CUR); *fdc = (struct fdctx){ .fd = fd, .buflen = (cur != -1) ? READ_BUFLEN : 1, - .ep = &fdc->buf[0], /* No data */ + .ep = &fdc->buf[0], /* no data */ }; } @@ -126,18 +126,18 @@ fdctx_destroy(struct fdctx *fdc) if (fdc->buflen > 1) { /* - * Reposition the file offset. Here is the layout of buf: - * - * | off - * v - * |*****************|-------| - * buf ep buf+buflen - * |<- residue ->| - * - * off: current character - * ep: offset just after read(2) - * residue: length for reposition - */ + * reposition the file offset. here is the layout of buf: + * + * | off + * v + * |*****************|-------| + * buf ep buf+buflen + * |<- residue ->| + * + * off: current character + * ep: offset just after read(2) + * residue: length for reposition + */ residue = (fdc->ep - fdc->buf) - fdc->off; if (residue > 0) (void)lseek(fdc->fd, -residue, SEEK_CUR); @@ -145,18 +145,18 @@ fdctx_destroy(struct fdctx *fdc) } /* - * The read builtin. The -r option causes backslashes to be treated like - * ordinary characters. + * the read builtin. the -r option causes backslashes to be treated like + * ordinary characters * - * Note that if IFS=' :' then read x y should work so that: - * 'a b' x='a', y='b' - * ' a b ' x='a', y='b' - * ':b' x='', y='b' - * ':' x='', y='' - * '::' x='', y='' - * ': :' x='', y='' - * ':::' x='', y='::' - * ':b c:' x='', y='b c:' + * note that if IFS=' :' then read x y should work so that: + * 'a b' x='a', y='b' + * ' a b ' x='a', y='b' + * ':b' x='', y='b' + * ':' x='', y='' + * '::' x='', y='' + * ': :' x='', y='' + * ':::' x='', y='::' + * ':b c:' x='', y='b c:' */ int @@ -263,8 +263,8 @@ readcmd(int argc __unused, char **argv __unused) if (timeout >= 0) { /* - * Wait for something to become available. - */ + * wait for something to become available + */ pfd.fd = STDIN_FILENO; pfd.events = POLLIN; status = sig = 0; @@ -289,8 +289,8 @@ readcmd(int argc __unused, char **argv __unused) } sigprocmask(SIG_SETMASK, &oset, NULL); /* - * If there's nothing ready, return an error. - */ + * if there's nothing ready, return an error + */ if (status <= 0) { while (*ap != NULL) setvar(*ap++, "", 0); @@ -363,13 +363,13 @@ readcmd(int argc __unused, char **argv __unused) if (startword != 0) { if (is_ifs == 1) { - /* Ignore leading IFS whitespace */ + /* ignore leading IFS whitespace */ if (saveall) USTPUTC(c, p); continue; } if (is_ifs == 2 && startword == 1) { - /* Only one non-whitespace IFS per word */ + /* only one non-whitespace IFS per word */ startword = 2; if (saveall) { lastnonifsws = p - stackblock(); @@ -383,7 +383,7 @@ readcmd(int argc __unused, char **argv __unused) /* append this character to the current variable */ startword = 0; if (saveall) - /* Not just a spare terminator */ + /* not just a spare terminator */ saveall++; lastnonifs = lastnonifsws = p - stackblock(); USTPUTC(c, p); @@ -394,7 +394,7 @@ readcmd(int argc __unused, char **argv __unused) startword = is_ifs; if (ap[1] == NULL) { - /* Last variable needs all IFS chars */ + /* last variable needs all IFS chars */ saveall++; if (is_ifs == 2) lastnonifsws = p - stackblock(); @@ -412,15 +412,15 @@ readcmd(int argc __unused, char **argv __unused) STACKSTRNUL(p); /* - * Remove trailing IFS chars: always remove whitespace, don't remove - * non-whitespace unless it was naked - */ + * remove trailing IFS chars: always remove whitespace, dont remove + * non-whitespace unless it was naked + */ if (saveall <= 1) lastnonifsws = lastnonifs; stackblock()[lastnonifsws + 1] = '\0'; setvar(*ap, stackblock(), 0); - /* Set any remaining args to "" */ + /* set any remaining args to "" */ while (*++ap != NULL) setvar(*ap, "", 0); #if FEATURE_SH_HISTEDIT @@ -504,11 +504,11 @@ umaskcmd(int argc __unused, char **argv __unused) /* * ulimit builtin * - * This code, originally by Doug Gwyn, Doug Kingston, Eric Gisin, and - * Michael Rendell was ripped from pdksh 5.0.8 and hacked for use with - * ash by J.T. Conklin. + * this code, originally by doug gwyn, doug kingston, eric gisin, and + * michael rendell was ripped from pdksh 5.0.8 and hacked for use with + * ash by J.T. conklin * - * Public domain. + * public domain */ struct limits { diff --git a/cmd/posix/sh/mknodes.c b/cmd/posix/sh/mknodes.c @@ -1,40 +1,40 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * This program reads the nodetypes file and nodes.c.pat file. It generates - * the files nodes.h and nodes.c. + * this program reads the nodetypes file and nodes.c.pat file. it generates + * the files nodes.h and nodes.c */ #include <errno.h> @@ -60,7 +60,7 @@ #define T_STRING 3 #define T_INT 4 /* int field */ #define T_OTHER 5 /* other */ -#define T_TEMP 6 /* don't copy this field */ +#define T_TEMP 6 /* dont copy this field */ struct field { /* a structure field */ char *name; /* name of field */ @@ -193,8 +193,8 @@ parsefield(void) } static const char writer[] = "\ -/*\n\ - * This file was generated by the mknodes program.\n\ +/* \n\ + * this file was generated by the mknodes program.\n\ */\n\ \n"; diff --git a/cmd/posix/sh/mksyntax.c b/cmd/posix/sh/mksyntax.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * This program creates syntax.h and syntax.c. + * this program creates syntax.h and syntax.c */ #include "parser.h" @@ -50,7 +50,7 @@ struct synclass { const char *comment; }; -/* Syntax classes */ +/* syntax classes */ static const struct synclass synclass[] = { {"CWORD", "character is nothing special"}, {"CNL", "newline character"}, @@ -73,8 +73,8 @@ static const struct synclass synclass[] = { }; /* - * Syntax classes for is_ functions. Warning: if you add new classes - * you may have to change the definition of the is_in_name macro. + * syntax classes for is_ functions. warning: if you add new classes + * you may have to change the definition of the is_in_name macro */ static const struct synclass is_entry[] = { {"ISDIGIT", "a digit"}, @@ -86,8 +86,8 @@ static const struct synclass is_entry[] = { }; static const char writer[] = "\ -/*\n\ - * This file was generated by the mksyntax program.\n\ +/* \n\ + * this file was generated by the mksyntax program.\n\ */\n\ \n"; @@ -107,7 +107,7 @@ main(int argc __unused, char **argv __unused) char buf[80]; int pos; - /* Create output files */ + /* create output files */ if ((cfile = fopen("syntax.c", "w")) == NULL) { perror("syntax.c"); exit(2); @@ -121,8 +121,8 @@ main(int argc __unused, char **argv __unused) fputs("#include <limits.h>\n\n", hfile); - /* Generate the #define statements in the header file */ - fputs("/* Syntax classes */\n", hfile); + /* generate the #define statements in the header file */ + fputs("/* syntax classes */\n", hfile); for (i = 0; synclass[i].name; i++) { if (strcmp(synclass[i].name, "CEOF") == 0) { fputs("#ifdef CEOF\n#undef CEOF\n#endif\n", hfile); @@ -134,7 +134,7 @@ main(int argc __unused, char **argv __unused) fprintf(hfile, "/* %s */\n", synclass[i].comment); } putc('\n', hfile); - fputs("/* Syntax classes for is_ functions */\n", hfile); + fputs("/* syntax classes for is_ functions */\n", hfile); for (i = 0; is_entry[i].name; i++) { sprintf(buf, "#define %s %#o", is_entry[i].name, 1 << i); fputs(buf, hfile); @@ -151,10 +151,10 @@ main(int argc __unused, char **argv __unused) fputs("#define SQSYNTAX (sqsyntax + SYNBASE)\n", hfile); fputs("#define ARISYNTAX (arisyntax + SYNBASE)\n", hfile); putc('\n', hfile); - output_type_macros(); /* is_digit, etc. */ + output_type_macros(); /* is_digit, etc */ putc('\n', hfile); - /* Generate the syntax tables. */ + /* generate the syntax tables */ fputs("#include \"parser.h\"\n", cfile); fputs("#include \"shell.h\"\n", cfile); fputs("#include \"syntax.h\"\n\n", cfile); @@ -221,7 +221,7 @@ main(int argc __unused, char **argv __unused) } /* - * Output the header and declaration of a syntax table. + * output the header and declaration of a syntax table */ static void @@ -238,7 +238,7 @@ add_one(const char *key, const char *type) } /* - * Add default values to the syntax table. + * add default values to the syntax table */ static void @@ -257,7 +257,7 @@ add_default(void) } /* - * Output the footer of a syntax table. + * output the footer of a syntax table */ static void @@ -267,7 +267,7 @@ finish(void) } /* - * Add entries to the syntax table. + * add entries to the syntax table */ static void @@ -298,8 +298,8 @@ add(const char *p, const char *type) } /* - * Output character classification macros (e.g. is_digit). If digits are - * contiguous, we can test for them quickly. + * output character classification macros (e.g. is_digit). if digits are + * contiguous, we can test for them quickly */ static const char *macro[] = { diff --git a/cmd/posix/sh/mystring.c b/cmd/posix/sh/mystring.c @@ -1,43 +1,43 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * String functions. + * string functions * - * equal(s1, s2) Return true if strings are equal. - * number(s) Convert a string of digits to an integer. - * is_number(s) Return true if s is a string of digits. + * equal(s1, s2) return true if strings are equal + * number(s) convert a string of digits to an integer + * is_number(s) return true if s is a string of digits */ #include "mystring.h" @@ -53,8 +53,8 @@ char nullstr[1]; /* zero length string */ */ /* - * Convert a string of digits to an integer, printing an error message on - * failure. + * convert a string of digits to an integer, printing an error message on + * failure */ int @@ -66,7 +66,7 @@ number(const char *s) } /* - * Check for a valid number. This should be elsewhere. + * check for a valid number. this should be elsewhere */ int diff --git a/cmd/posix/sh/mystring.h b/cmd/posix/sh/mystring.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <string.h> diff --git a/cmd/posix/sh/options.c b/cmd/posix/sh/options.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <signal.h> @@ -71,7 +71,7 @@ static void setparam(int, char **); static int getopts(char *, char *, char **, char ***, char **); /* - * Process the shell command line arguments. + * process the shell command line arguments */ int @@ -133,10 +133,10 @@ optschanged(void) } /* - * Process shell options. The global variable argptr contains a pointer - * to the argument list; we advance it past the options. - * If cmdline is true, process the shell's argv; otherwise, process arguments - * to the set special builtin. + * process shell options. the global variable argptr contains a pointer + * to the argument list; we advance it past the options + * if cmdline is true, process the shell's argv; otherwise, process arguments + * to the set special builtin */ static int @@ -153,23 +153,23 @@ options(int cmdline) argptr++; if ((c = *p++) == '-') { val = 1; - /* A "-" or "--" terminates options */ + /* a "-" or "--" terminates options */ if (p[0] == '\0') goto end_options1; if (p[0] == '-' && p[1] == '\0') goto end_options2; - /** - * For the benefit of `#!' lines in shell scripts, - * treat a string of '-- *#.*' the same as '--'. - * This is needed so that a script starting with: - * #!/bin/sh -- # -*- perl -*- - * will continue to work after a change is made to - * kern/imgact_shell.c to NOT token-ize the options - * specified on a '#!' line. A bit of a kludge, - * but that trick is recommended in documentation - * for some scripting languages, and we might as - * well continue to support it. - */ + /* * + * for the benefit of `#!' lines in shell scripts, + * treat a string of '-- *#.*' the same as '--' + * this is needed so that a script starting with: + * #!/bin/sh, # -*- perl -*- + * will continue to work after a change is made to + * kern/imgact_shell.c to NOT token-ize the options + * specified on a '#!' line. a bit of a kludge, + * but that trick is recommended in documentation + * for some scripting languages, and we might as + * well continue to support it + */ if (p[0] == '-') { kp = p + 1; while (*kp == ' ' || *kp == '\t') @@ -203,7 +203,7 @@ options(int cmdline) } return (login); - /* When processing `set', a single "-" means turn off -x and -v */ + /* when processing `set', a single "-" means turn off -x and -v */ end_options1: if (!cmdline) { xflag = vflag = 0; @@ -211,11 +211,11 @@ end_options1: } /* - * When processing `set', a "--" means the remaining arguments - * replace the positional parameters in the active shell. If - * there are no remaining options, then all the positional - * parameters are cleared (equivalent to doing ``shift $#''). - */ + * when processing `set', a "--" means the remaining arguments + * replace the positional parameters in the active shell. if + * there are no remaining options, then all the positional + * parameters are cleared (equivalent to doing ``shift $#'') + */ end_options2: if (!cmdline) { if (*argptr == NULL) @@ -224,19 +224,19 @@ end_options2: } /* - * At this point we are processing options given to 'sh' on a command - * line. If an end-of-options marker ("-" or "--") is followed by an - * arg of "#", then skip over all remaining arguments. Some scripting - * languages (e.g.: perl) document that /bin/sh will implement this - * behavior, and they recommend that users take advantage of it to - * solve certain issues that can come up when writing a perl script. - * Yes, this feature is in /bin/sh to help users write perl scripts. - */ + * at this point we are processing options given to 'sh' on a command + * line. if an end-of-options marker ("-" or "--") is followed by an + * arg of "#", then skip over all remaining arguments. some scripting + * languages (e.g.: perl) document that /bin/sh will implement this + * behavior, and they recommend that users take advantage of it to + * solve certain issues that can come up when writing a perl script + * yes, this feature is in /bin/sh to help users write perl scripts + */ p = *argptr; if (p != NULL && p[0] == '#' && p[1] == '\0') { while (*argptr != NULL) argptr++; - /* We need to keep the final argument */ + /* we need to keep the final argument */ argptr--; } @@ -252,12 +252,12 @@ minus_o(char *name, int val) if (name == NULL) { if (val) { - /* "Pretty" output. */ + /* "pretty" output */ out1str("Current option settings\n"); for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1) out1fmt("%-16.*s%s\n", *on, on + 1, optval[i] ? "on" : "off"); } else { - /* Output suitable for re-input to shell. */ + /* output suitable for re-input to shell */ for (i = 0, on = optname; i < NOPTS; i++, on += *on + 1) out1fmt( "%s %co %.*s%s", @@ -312,7 +312,7 @@ setoption(int flag, int val) } /* - * Set the shell parameters. + * set the shell parameters */ static void @@ -336,7 +336,7 @@ setparam(int argc, char **argv) } /* - * Free the list of positional parameters. + * free the list of positional parameters */ void @@ -357,7 +357,7 @@ freeparam(struct shparam *param) } /* - * The shift builtin command. + * the shift builtin command */ int @@ -382,7 +382,7 @@ shiftcmd(int argc, char **argv) } /* - * The set builtin command. + * the set builtin command */ int @@ -410,10 +410,10 @@ getoptsreset(const char *value) } /* - * The getopts builtin. Shellparam.optnext points to the next argument - * to be processed. Shellparam.optptr points to the next character to - * be processed in the current argument. If shellparam.optnext is NULL, - * then it's the first time getopts has been called. + * the getopts builtin. shellparam.optnext points to the next argument + * to be processed. shellparam.optptr points to the next character to + * be processed in the current argument. if shellparam.optnext is NULL, + * then its the first time getopts has been called */ int @@ -462,7 +462,7 @@ getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **opt const char *newoptarg = NULL; if ((p = *optptr) == NULL || *p == '\0') { - /* Current word is done, advance */ + /* current word is done, advance */ if (*optnext == NULL) return 1; p = **optnext; @@ -541,10 +541,10 @@ out: } /* - * Standard option processing (a la getopt) for builtin routines. The + * standard option processing (a la getopt) for builtin routines. the * only argument that is passed to nextopt is the option string; the - * other arguments are unnecessary. It returns the option, or '\0' on - * end of input. + * other arguments are unnecessary. it returns the option, or '\0' on + * end of input */ int diff --git a/cmd/posix/sh/options.h b/cmd/posix/sh/options.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ struct shparam { diff --git a/cmd/posix/sh/output.c b/cmd/posix/sh/output.c @@ -1,45 +1,45 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Shell output routines. We use our own output routines because: - * When a builtin command is interrupted we have to discard - * any pending output. - * When a builtin command appears in back quotes, we want to - * save the output of the command in a region obtained - * via malloc, rather than doing a fork and reading the - * output of the command via a pipe. + * shell output routines. we use our own output routines because: + * when a builtin command is interrupted we have to discard + * any pending output + * when a builtin command appears in back quotes, we want to + * save the output of the command in a region obtained + * via malloc, rather than doing a fork and reading the + * output of the command via a pipe */ #include <errno.h> @@ -203,7 +203,7 @@ outdqstr(const char *p, struct output *file) outcslow('\'', file); } -/* Like outstr(), but quote for re-input into the shell. */ +/* like outstr(), but quote for re-input into the shell */ void outqstr(const char *p, struct output *file) { @@ -372,7 +372,7 @@ out1fp(void) } /* - * Version of write which resumes after a signal is caught. + * version of write which resumes after a signal is caught */ int diff --git a/cmd/posix/sh/output.h b/cmd/posix/sh/output.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" @@ -54,7 +54,7 @@ extern struct output errout; /* to fd 2 */ extern struct output memout; extern struct output *out1; /* &memout if backquote, otherwise &output */ extern struct output *out2; /* &memout if backquote with 2>&1, otherwise - &errout */ + * &errout */ void outcslow(int, struct output *); void out1str(const char *); diff --git a/cmd/posix/sh/parser.c b/cmd/posix/sh/parser.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <pwd.h> @@ -67,7 +67,7 @@ size_t xstrlcpy(char *, const char *, size_t); #endif /* - * Shell command parser. + * shell command parser */ #define PROMPTLEN 192 @@ -194,7 +194,7 @@ parser_temp_free_all(void) } /* - * Read and parse a command. Returns NEOF on end of file. (NULL is a + * read and parse a command. returns NEOF on end of file. (NULL is a * valid parse tree indicating a blank line.) */ @@ -203,9 +203,9 @@ parsecmd(int interact) { int t; - /* This assumes the parser is not re-entered, - * which could happen if we add command substitution on PS1/PS2. - */ + /* this assumes the parser is not re-entered, + * which could happen if we add command substitution on PS1/PS2 + */ parser_temp_free_all(); heredoclist = NULL; @@ -227,8 +227,8 @@ parsecmd(int interact) } /* - * Read and parse words for wordexp. - * Returns a list of NARG nodes; NULL if there are no words. + * read and parse words for wordexp + * returns a list of NARG nodes; NULL if there are no words */ union node * parsewordexp(void) @@ -236,9 +236,9 @@ parsewordexp(void) union node *n, *first = NULL, **pnext; int t; - /* This assumes the parser is not re-entered, - * which could happen if we add command substitution on PS1/PS2. - */ + /* this assumes the parser is not re-entered, + * which could happen if we add command substitution on PS1/PS2 + */ parser_temp_free_all(); heredoclist = NULL; @@ -411,7 +411,7 @@ command(void) n1 = NULL; rpp = &redir; - /* Check for redirection which may precede command */ + /* check for redirection which may precede command */ while (readtoken() == TREDIR) { *rpp = n2 = redirnode; rpp = &n2->nfile.next; @@ -485,9 +485,9 @@ command(void) n2->narg.next = NULL; n1->nfor.args = n2; /* - * Newline or semicolon here is optional (but note - * that the original Bourne shell only allowed NL). - */ + * newline or semicolon here is optional (but note + * that the original bourne shell only allowed NL) + */ if (lasttoken != TSEMI) tokpushback++; } @@ -560,7 +560,7 @@ command(void) consumetoken(TEND); checkkwd = CHKKWD | CHKALIAS; break; - /* A simple command must have at least one redirection or word. */ + /* a simple command must have at least one redirection or word */ case TBACKGND: case TSEMI: case TAND: @@ -582,7 +582,7 @@ command(void) synexpect(-1); } - /* Now check for redirection which may follow command */ + /* now check for redirection which may follow command */ while (readtoken() == TREDIR) { *rpp = n2 = redirnode; rpp = &n2->nfile.next; @@ -612,18 +612,18 @@ simplecmd(union node **rpp, union node *redir) int special; int savecheckkwd; - /* If we don't have any redirections already, then we must reset */ - /* rpp to be the address of the local redir variable. */ + /* if we dont have any redirections already, then we must reset */ + /* rpp to be the address of the local redir variable */ if (redir == NULL) rpp = &redir; args = NULL; app = &args; /* - * We save the incoming value, because we need this for shell - * functions. There can not be a redirect or an argument between - * the function name and the open parenthesis. - */ + * we save the incoming value, because we need this for shell + * functions. there can not be a redirect or an argument between + * the function name and the open parenthesis + */ orig_rpp = rpp; savecheckkwd = CHKALIAS; @@ -641,15 +641,15 @@ simplecmd(union node **rpp, union node *redir) rpp = &n->nfile.next; parsefname(); /* read name of redirection file */ } else if (lasttoken == TLP && app == &args->narg.next && rpp == orig_rpp) { - /* We have a function */ + /* we have a function */ consumetoken(TRP); funclinno = plinno; /* - * - Require plain text. - * - Functions with '/' cannot be called. - * - Reject name=(). - * - Reject ksh extended glob patterns. - */ + * - require plain text + * - functions with '/' cannot be called + * - reject name=() + * - reject ksh extended glob patterns + */ if (!noexpand(n->narg.text) || quoteflag || strchr(n->narg.text, '/') || strchr("!%*+-=?@}~", n->narg.text[strlen(n->narg.text) - 1])) synerror("Bad function name"); @@ -764,7 +764,7 @@ parsefname(void) } /* - * Input any here documents. + * input any here documents */ static void @@ -811,8 +811,8 @@ top: t = xxreadtoken(); /* - * eat newlines - */ + * eat newlines + */ if (checkkwd & CHKNL) { while (t == TNL) { parseheredoc(); @@ -821,8 +821,8 @@ top: } /* - * check for keywords and aliases - */ + * check for keywords and aliases + */ if (t == TWORD && !quoteflag) { const char *const *pp; @@ -853,21 +853,21 @@ out: } /* - * Read the next input token. - * If the token is a word, we set backquotelist to the list of cmds in - * backquotes. We set quoteflag to true if any part of the word was - * quoted. - * If the token is TREDIR, then we set redirnode to a structure containing - * the redirection. - * In all cases, the variable startlinno is set to the number of the line - * on which the token starts. + * read the next input token + * if the token is a word, we set backquotelist to the list of cmds in + * backquotes. we set quoteflag to true if any part of the word was + * quoted + * if the token is TREDIR, then we set redirnode to a structure containing + * the redirection + * in all cases, the variable startlinno is set to the number of the line + * on which the token starts * - * [Change comment: here documents and internal procedures] - * [Readtoken shouldn't have any arguments. Perhaps we should make the - * word parsing code into a separate routine. In this case, readtoken - * doesn't need to have any internal procedures, but parseword does. - * We could also make parseoperator in essence the main routine, and - * have parseword (readtoken1?) handle both words and redirection.] + * [change comment: here documents and internal procedures] + * [readtoken shouldnt have any arguments. perhaps we should make the + * word parsing code into a separate routine. in this case, readtoken + * doesnt need to have any internal procedures, but parseword does + * we could also make parseoperator in essence the main routine, and + * have parseword (readtoken1?) handle both words and redirection.] */ #define RETURN(token) return lasttoken = token @@ -956,10 +956,10 @@ struct tokenstate { }; /* - * Check to see whether we are at the end of the here document. When this - * is called, c is set to the first character of the next input line. If - * we are at the end of the here document, this routine sets the c to PEOF. - * The new value of c is returned. + * check to see whether we are at the end of the here document. when this + * is called, c is set to the first character of the next input line. if + * we are at the end of the here document, this routine sets the c to PEOF + * the new value of c is returned */ static int @@ -994,9 +994,9 @@ checkend(int c, const char *eofmark, int striptabs) } /* - * Parse a redirection operator. The variable "out" points to a string - * specifying the fd to be redirected. The variable "c" contains the - * first character of the redirection operator. + * parse a redirection operator. the variable "out" points to a string + * specifying the fd to be redirected. the variable "c" contains the + * first character of the redirection operator */ static void @@ -1051,7 +1051,7 @@ parseredir(char *out, int c) } /* - * Called to parse command substitutions. + * called to parse command substitutions */ static char * @@ -1095,9 +1095,9 @@ parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int heredoclist = NULL; INTON; if (oldstyle) { - /* We must read until the closing backquote, giving special - treatment to some slashes, and then push the string and - reread it as input, interpreting it normally. */ + /* we must read until the closing backquote, giving special + * treatment to some slashes, and then push the string and + * reread it as input, interpreting it normally */ char *oout; int c; int olen; @@ -1165,9 +1165,9 @@ parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int (*nlpp)->n = n; if (oldstyle) { /* - * Start reading from old file again, ignoring any pushed back - * tokens left from the backquote parsing - */ + * start reading from old file again, ignoring any pushed back + * tokens left from the backquote parsing + */ popfile(); tokpushback = 0; } @@ -1201,8 +1201,8 @@ parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int } /* - * Called to parse a backslash escape sequence inside $'...'. - * The backslash has already been read. + * called to parse a backslash escape sequence inside $'...' + * the backslash has already been read */ static char * readcstyleesc(char *out) @@ -1315,13 +1315,13 @@ readcstyleesc(char *out) } if (v == 0 || (v >= 0xd800 && v <= 0xdfff)) synerror("Bad escape sequence"); - /* We really need iconv here. */ + /* we really need iconv here */ if (initial_localeisutf8 && v > 127) { CHECKSTRSPACE(4, out); /* - * We cannot use wctomb() as the locale may have - * changed. - */ + * we cannot use wctomb() as the locale may have + * changed + */ if (v <= 0x7ff) { USTPUTC(0xc0 | v >> 6, out); USTPUTC(0x80 | (v & 0x3f), out); @@ -1347,9 +1347,9 @@ readcstyleesc(char *out) } vc = (char)v; /* - * We can't handle NUL bytes. - * POSIX says we should skip till the closing quote. - */ + * we cant handle NUL bytes + * POSIX says we should skip till the closing quote + */ if (vc == '\0') { while ((c = pgetc()) != '\'') { if (c == '\\') @@ -1374,15 +1374,15 @@ readcstyleesc(char *out) } /* - * If eofmark is NULL, read a word or a redirection symbol. If eofmark - * is not NULL, read a here document. In the latter case, eofmark is the + * if eofmark is NULL, read a word or a redirection symbol. if eofmark + * is not NULL, read a here document. in the latter case, eofmark is the * word which marks the end of the document and striptabs is true if - * leading tabs should be stripped from the document. The argument firstc - * is the first character of the input token or document. + * leading tabs should be stripped from the document. the argument firstc + * is the first character of the input token or document * - * Because C does not have internal subroutines, I have simulated them - * using goto's to implement the subroutine linkage. The following macros - * will run code that appears at the end of readtoken1. + * because c does not have internal subroutines, i have simulated them + * using goto's to implement the subroutine linkage. the following macros + * will run code that appears at the end of readtoken1 */ #define PARSESUB() \ @@ -1539,9 +1539,9 @@ loop: { /* for each line, until end of word */ USTPUTC(')', out); } else { /* - * unbalanced parens - * (don't 2nd guess - no error) - */ + * unbalanced parens + * (dont 2nd guess - no error) + */ pungetc(); USTPUTC(')', out); } @@ -1598,9 +1598,9 @@ endword: /* end of readtoken routine */ /* - * Parse a substitution. At this point, we have read the dollar sign - * and nothing else. - */ + * parse a substitution. at this point, we have read the dollar sign + * and nothing else + */ parsesub: { int subtype; @@ -1645,8 +1645,8 @@ parsesub: { length++; } while (!is_eof(c) && is_in_name(c)); if (length == 6 && strncmp(out - length, "LINENO", length) == 0) { - /* Replace the variable name with the - * current line number. */ + /* replace the variable name with the + * current line number */ STADJUST(-6, out); CHECKSTRSPACE(11, out); linno = plinno; @@ -1705,7 +1705,7 @@ parsesub: { case ':': flags |= VSNUL; c = pgetc_linecont(); - /*FALLTHROUGH*/ + /* FALLTHROUGH */ default: p = strchr(types, c); if (p == NULL) { @@ -1756,18 +1756,18 @@ parsesub: { state[level].parenlevel = 0; if (subtype == VSMINUS || subtype == VSPLUS || subtype == VSQUESTION || subtype == VSASSIGN) { /* - * For operators that were in the Bourne shell, - * inherit the double-quote state. - */ + * for operators that were in the bourne shell, + * inherit the double-quote state + */ state[level].syntax = state[level - 1].syntax; state[level].category = TSTATE_VAR_OLD; } else { /* - * The other operators take a pattern, - * so go to BASESYNTAX. - * Also, ' and " are now special, even - * in here documents. - */ + * the other operators take a pattern, + * so go to BASESYNTAX + * also, ' and " are now special, even + * in here documents + */ state[level].syntax = BASESYNTAX; state[level].category = TSTATE_VAR_NEW; newvarnest++; @@ -1786,7 +1786,7 @@ parsesub: { } /* - * Parse an arithmetic expansion (indicate start of one and set state) + * parse an arithmetic expansion (indicate start of one and set state) */ parsearith: { if (level + 1 >= maxnest) { @@ -1812,8 +1812,8 @@ parsearith: { } /* end of readtoken */ /* - * Returns true if the text contains nothing to expand (no dollar signs - * or backquotes). + * returns true if the text contains nothing to expand (no dollar signs + * or backquotes) */ static int @@ -1835,8 +1835,8 @@ noexpand(char *text) } /* - * Return true if the argument is a legal variable name (a letter or - * underscore followed by zero or more letters, underscores, and digits). + * return true if the argument is a legal variable name (a letter or + * underscore followed by zero or more letters, underscores, and digits) */ int @@ -1877,9 +1877,9 @@ consumetoken(int token) } /* - * Called when an unexpected token is read during the parse. The argument + * called when an unexpected token is read during the parse. the argument * is the token that is expected, or -1 if more than one type of token can - * occur at this point. + * occur at this point */ static void @@ -1937,7 +1937,7 @@ pgetc_linecont(void) setprompt(0); } else { pungetc(); - /* Allow the backslash to be pushed back. */ + /* allow the backslash to be pushed back */ pushstring("\\", 1, NULL); return (pgetc()); } @@ -1968,11 +1968,11 @@ getusername(char *name, size_t namelen) euid = geteuid(); /* - * Handle the case when there is more than one - * login with the same UID, or when the login - * returned by getlogin(2) does no longer match - * the current UID. - */ + * handle the case when there is more than one + * login with the same UID, or when the login + * returned by getlogin(2) does no longer match + * the current UID + */ pw = getpwlogin(); if (pw == NULL || pw->pw_uid != euid) pw = getpwuid(euid); @@ -1988,8 +1988,8 @@ getusername(char *name, size_t namelen) } /* - * called by editline -- any expansions to the prompt - * should be added here. + * called by editline, any expansions to the prompt + * should be added here */ char * getprompt(void *unused __unused) @@ -2003,8 +2003,8 @@ getprompt(void *unused __unused) static char internal_error[] = "??"; /* - * Select prompt format. - */ + * select prompt format + */ switch (whichprompt) { case 0: fmt = ""; @@ -2022,17 +2022,17 @@ getprompt(void *unused __unused) } /* - * Format prompt string. - */ + * format prompt string + */ for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++) { if (*fmt == '$') { const char *varname_start, *varname_end, *value; char varname[256]; int namelen, braced = 0; - fmt++; /* Skip the '$' */ + fmt++; /* skip the '$' */ - /* Check for ${VAR} syntax */ + /* check for ${VAR} syntax */ if (*fmt == '{') { braced = 1; fmt++; @@ -2040,26 +2040,26 @@ getprompt(void *unused __unused) varname_start = fmt; - /* Extract variable name */ + /* extract variable name */ if (is_digit(*fmt)) { - /* Positional parameter: $0, $1, etc. */ + /* positional parameter: $0, $1, etc */ fmt++; varname_end = fmt; } else if (is_special(*fmt)) { - /* Special parameter: $?, $!, $$, etc. */ + /* special parameter: $?, $!, $$, etc */ fmt++; varname_end = fmt; } else if (is_name(*fmt)) { - /* Regular variable name */ + /* regular variable name */ do fmt++; while (is_in_name(*fmt)); varname_end = fmt; } else { /* - * Not a valid variable reference. - * Output literal '$'. - */ + * not a valid variable reference + * output literal '$' + */ ps[i] = '$'; if (braced && i < PROMPTLEN - 2) ps[++i] = '{'; @@ -2069,23 +2069,23 @@ getprompt(void *unused __unused) namelen = varname_end - varname_start; if (namelen == 0 || namelen >= (int)sizeof(varname)) { - /* Invalid or too long, output literal */ + /* invalid or too long, output literal */ ps[i] = '$'; fmt = varname_start - 1; continue; } - /* Copy variable name */ + /* copy variable name */ memcpy(varname, varname_start, namelen); varname[namelen] = '\0'; - /* Handle closing brace for ${VAR} */ + /* handle closing brace for ${VAR} */ if (braced) { if (*fmt == '}') { fmt++; } else { - /* Missing closing brace, treat as - * literal */ + /* missing closing brace, treat as + * literal */ ps[i] = '$'; if (i < PROMPTLEN - 2) ps[++i] = '{'; @@ -2094,9 +2094,9 @@ getprompt(void *unused __unused) } } - /* Look up the variable */ + /* look up the variable */ if (namelen == 1 && is_digit(*varname)) { - /* Positional parameters - check digits FIRST */ + /* positional parameters - check digits FIRST */ int num = *varname - '0'; if (num == 0) value = arg0 ? arg0 : ""; @@ -2105,7 +2105,7 @@ getprompt(void *unused __unused) else value = ""; } else if (namelen == 1 && is_special(*varname)) { - /* Special parameters */ + /* special parameters */ char valbuf[20]; int num; @@ -2129,22 +2129,22 @@ getprompt(void *unused __unused) snprintf(valbuf, sizeof(valbuf), "%d", num); value = valbuf; } else { - /* Regular variables */ + /* regular variables */ value = lookupvar(varname); if (value == NULL) value = ""; } - /* Copy value to output, respecting buffer size */ + /* copy value to output, respecting buffer size */ while (*value != '\0' && i < PROMPTLEN - 1) { ps[i++] = *value++; } /* - * Adjust fmt and i for the loop increment. - * fmt will be incremented by the for loop, - * so position it one before where we want. - */ + * adjust fmt and i for the loop increment + * fmt will be incremented by the for loop, + * so position it one before where we want + */ fmt--; i--; continue; @@ -2155,19 +2155,19 @@ getprompt(void *unused __unused) switch (*++fmt) { /* - * Non-printing sequence begin and end. - */ + * non-printing sequence begin and end + */ case '[': case ']': ps[i] = '\001'; break; /* - * Literal \ and some ASCII characters: - * \a BEL - * \e ESC - * \r CR - */ + * literal \ and some ASCII characters: + * \a bel + * \e esc + * \r cr + */ case '\\': case 'a': case 'e': @@ -2183,8 +2183,8 @@ getprompt(void *unused __unused) break; /* - * CRLF sequence - */ + * CRLF sequence + */ case 'n': if (i < PROMPTLEN - 3) { ps[i++] = '\r'; @@ -2193,60 +2193,60 @@ getprompt(void *unused __unused) break; /* - * Print the current time as per provided strftime format. - */ + * print the current time as per provided strftime format + */ case 'D': { - char tfmt[128] = "%X"; /* \D{} means %X. */ + char tfmt[128] = "%X"; /* \d{} means %x */ struct tm *now; if (fmt[1] != '{') { /* - * "\D" but not "\D{", so treat the '\' - * literally and rewind fmt to treat 'D' - * literally next iteration. - */ + * "\d" but not "\d{", so treat the '\' + * literally and rewind fmt to treat 'd' + * literally next iteration + */ ps[i] = '\\'; fmt--; break; } - fmt += 2; /* Consume "D{". */ + fmt += 2; /* consume "d{" */ if (fmt[0] != '}') { char *end; end = memccpy(tfmt, fmt, '}', sizeof(tfmt)); if (end == NULL) { /* - * Format too long or no '}', so - * ignore "\D{" altogether. - * The loop will do i++, but nothing - * was written to ps, so do i-- here. - * Rewind fmt for similar reason. - */ + * format too long or no '}', so + * ignore "\d{" altogether + * the loop will do i++, but nothing + * was written to ps, so do i-- here + * rewind fmt for similar reason + */ i--; fmt--; break; } - *--end = '\0'; /* Ignore the copy of '}'. */ + *--end = '\0'; /* ignore the copy of '}' */ fmt += end - tfmt; } now = localtime(&(time_t){time(NULL)}); i += strftime(&ps[i], PROMPTLEN - i - 1, tfmt, now); - i--; /* The loop will do i++. */ + i--; /* the loop will do i++ */ break; } /* - * Hostname. - * - * \h specifies just the local hostname, - * \H specifies fully-qualified hostname. - */ + * hostname + * + * \h specifies just the local hostname, + * \h specifies fully-qualified hostname + */ case 'h': case 'H': ps[i] = '\0'; gethostname(&ps[i], PROMPTLEN - i - 1); ps[PROMPTLEN - 1] = '\0'; - /* Skip to end of hostname. */ + /* skip to end of hostname */ trim = (*fmt == 'h') ? '.' : '\0'; while ((ps[i] != '\0') && (ps[i] != trim)) i++; @@ -2254,22 +2254,22 @@ getprompt(void *unused __unused) break; /* - * User name. - */ + * user name + */ case 'u': ps[i] = '\0'; getusername(&ps[i], PROMPTLEN - i); - /* Skip to end of username. */ + /* skip to end of username */ while (ps[i + 1] != '\0') i++; break; /* - * Working directory. - * - * \W specifies just the final component, - * \w specifies the entire path. - */ + * working directory + * + * \w specifies just the final component, + * \w specifies the entire path + */ case 'W': case 'w': pwd = lookupvar("PWD"); @@ -2289,23 +2289,23 @@ getprompt(void *unused __unused) strlcpy(&ps[i], pwd, PROMPTLEN - i); } } - /* Skip to end of path. */ + /* skip to end of path */ while (ps[i + 1] != '\0') i++; break; /* - * Superuser status. - * - * '$' for normal users, '#' for root. - */ + * superuser status + * + * '$' for normal users, '#' for root + */ case '$': ps[i] = (geteuid() != 0) ? '$' : '#'; break; /* - * Emit unrecognized formats verbatim. - */ + * emit unrecognized formats verbatim + */ default: ps[i] = '\\'; if (i < PROMPTLEN - 2) diff --git a/cmd/posix/sh/parser.h b/cmd/posix/sh/parser.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* control characters in argument strings */ @@ -38,7 +38,7 @@ #define CTLENDVAR '\371' #define CTLBACKQ '\372' #define CTLQUOTE 01 /* ored with CTLBACKQ code if in quotes */ -/* CTLBACKQ | CTLQUOTE == '\373' */ +/* CTLBACKQ | CTLQUOTE == '\373' */ #define CTLARI '\374' #define CTLENDARI '\375' #define CTLQUOTEMARK '\376' @@ -46,14 +46,14 @@ /* variable substitution byte (follows CTLVAR) */ #define VSTYPE 0x0f /* type of variable substitution */ -#define VSNUL 0x10 /* colon--treat the empty string as unset */ +#define VSNUL 0x10 /* colon, treat the empty string as unset */ #define VSLINENO \ - 0x20 /* expansion of $LINENO, the line number \ - follows immediately */ -#define VSQUOTE 0x80 /* inside double quotes--suppress splitting */ + 0x20 /* expansion of $LINENO, the line number \ + * follows immediately */ +#define VSQUOTE 0x80 /* inside double quotes, suppress splitting */ /* values of VSTYPE field */ -#define VSNORMAL 0x1 /* normal variable: $var or ${var} */ +#define VSNORMAL 0x1 /* normal variable: $var or ${var} */ #define VSMINUS 0x2 /* ${var-text} */ #define VSPLUS 0x3 /* ${var+text} */ #define VSQUESTION 0x4 /* ${var?message} */ @@ -63,11 +63,11 @@ #define VSTRIMRIGHT 0x8 /* ${var%pattern} */ #define VSTRIMRIGHTMAX 0x9 /* ${var%%pattern} */ #define VSLENGTH 0xa /* ${#var} */ -#define VSERROR 0xb /* Syntax error, issue when expanded */ +#define VSERROR 0xb /* syntax error, issue when expanded */ /* - * NEOF is returned by parsecmd when it encounters an end of file. It - * must be distinct from NULL. + * NEOF is returned by parsecmd when it encounters an end of file. it + * must be distinct from NULL */ #define NEOF ((union node *)-1) extern int whichprompt; /* 1 == PS1, 2 == PS2 */ diff --git a/cmd/posix/sh/printf.c b/cmd/posix/sh/printf.c @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright 2018 Staysail Systems, Inc. <info@staysail.tech> - * Copyright 2014 Garrett D'Amore <garrett@damore.org> - * Copyright 2010 Nexenta Systems, Inc. All rights reserved. - * Copyright (c) 1989, 1993 - * The Regents of the University of California. All rights reserved. + * copyright 2018 staysail systems, inc. <info@staysail.tech> + * copyright 2014 garrett d'amore <garrett@damore.org> + * copyright 2010 nexenta systems, inc. all rights reserved + * copyright (c) 1989, 1993 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Important: This file is used both as a standalone program /usr/bin/printf - * and as a builtin for /bin/sh (#define SHELL). + * important: this file is used both as a standalone program /usr/bin/printf + * and as a builtin for /bin/sh (#define SHELL) */ #include <sys/types.h> @@ -126,13 +126,13 @@ main(int argc, char *argv[]) INTOFF; #endif /* - * Basic algorithm is to scan the format string for conversion - * specifications -- once one is found, find out if the field - * width or precision is a '*'; if it is, gather up value. Note, - * format strings are reused as necessary to use up the provided - * arguments, arguments of zero/null string are provided to use - * up the format string. - */ + * basic algorithm is to scan the format string for conversion + * specifications, once one is found, find out if the field + * width or precision is a '*'; if it is, gather up value. note, + * format strings are reused as necessary to use up the provided + * arguments, arguments of zero/null string are provided to use + * up the format string + */ fmt = format = *argv; escape(fmt, 1, &len); /* backslash interpretation */ rval = end = 0; @@ -184,7 +184,7 @@ main(int argc, char *argv[]) #endif return (rval); } - /* Restart at the beginning of the format string. */ + /* restart at the beginning of the format string */ fmt = format; end = 1; } @@ -322,15 +322,15 @@ printf_doformat(char *fmt, int *rval) *dptr = 0; /* - * Look for a length modifier. POSIX doesn't have these, so - * we only support them for floating-point conversions, which - * are extensions. This is useful because the L modifier can - * be used to gain extra range and precision, while omitting - * it is more likely to produce consistent results on different - * architectures. This is not so important for integers - * because overflow is the only bad thing that can happen to - * them, but consider the command printf %a 1.1 - */ + * look for a length modifier. POSIX doesnt have these, so + * we only support them for floating-point conversions, which + * are extensions. this is useful because the l modifier can + * be used to gain extra range and precision, while omitting + * it is more likely to produce consistent results on different + * architectures. this is not so important for integers + * because overflow is the only bad thing that can happen to + * them, but consider the command printf %a 1.1 + */ if (*fmt == 'L') { mod_ldbl = 1; fmt++; @@ -357,7 +357,7 @@ printf_doformat(char *fmt, int *rval) char *p; int getout; - /* Convert "b" to "s" for output. */ + /* convert "b" to "s" for output */ start[strlen(start) - 1] = 's'; if ((p = strdup(getstr())) == NULL) { warnx("%s", strerror(ENOMEM)); @@ -365,7 +365,7 @@ printf_doformat(char *fmt, int *rval) } getout = escape(p, 0, &len); PF(start, p); - /* Restore format for next loop. */ + /* restore format for next loop */ free(p); if (getout) diff --git a/cmd/posix/sh/redir.c b/cmd/posix/sh/redir.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -42,7 +42,7 @@ #include <unistd.h> /* - * Code for dealing with input/output redirection. + * code for dealing with input/output redirection */ #include "error.h" @@ -68,31 +68,31 @@ struct redirtab { static struct redirtab *redirlist; /* - * We keep track of whether or not fd0 has been redirected. This is for + * we keep track of whether or not fd0 has been redirected. this is for * background commands, where we want to redirect fd0 to /dev/null only - * if it hasn't already been redirected. + * if it hasnt already been redirected */ static int fd0_redirected = 0; -/* Number of redirtabs that have not been allocated. */ +/* number of redirtabs that have not been allocated */ static unsigned int empty_redirs = 0; static void openredirect(union node *, char[10]); static int openhere(union node *); /* - * Process a list of redirection commands. If the REDIR_PUSH flag is set, + * process a list of redirection commands. if the REDIR_PUSH flag is set, * old file descriptors are stashed away so that the redirection can be - * undone by calling popredir. If the REDIR_BACKQ flag is set, then the + * undone by calling popredir. if the REDIR_BACKQ flag is set, then the * standard output, and the standard error if it becomes a duplicate of - * stdout, is saved in memory. + * stdout, is saved in memory * - * We suppress interrupts so that we won't leave open file - * descriptors around. Because the signal handler remains + * we suppress interrupts so that we wont leave open file + * descriptors around. because the signal handler remains * installed and we do not use system call restart, interrupts * will still abort blocking opens such as fifos (they will fail - * with EINTR). There is, however, a race condition if an interrupt - * arrives after INTOFF and before open blocks. + * with EINTR). there is, however, a race condition if an interrupt + * arrives after INTOFF and before open blocks */ void @@ -235,9 +235,9 @@ openredirect(union node *redir, char memory[10]) } /* - * Handle here documents. Normally we fork off a process to write the - * data to a pipe. If the document is short, we can stuff the data in - * the pipe without forking. + * handle here documents. normally we fork off a process to write the + * data to a pipe. if the document is short, we can stuff the data in + * the pipe without forking */ static int @@ -285,7 +285,7 @@ out: } /* - * Undo the effects of the last redirection. + * undo the effects of the last redirection */ void @@ -317,7 +317,7 @@ popredir(void) INTON; } -/* Return true if fd 0 has already been redirected at least once. */ +/* return true if fd 0 has already been redirected at least once */ int fd0_redirected_p(void) { @@ -325,7 +325,7 @@ fd0_redirected_p(void) } /* - * Discard all saved file descriptors. + * discard all saved file descriptors */ void diff --git a/cmd/posix/sh/redir.h b/cmd/posix/sh/redir.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* flags passed to redirect */ diff --git a/cmd/posix/sh/sh_cdefs.h b/cmd/posix/sh/sh_cdefs.h @@ -1,13 +1,13 @@ -/*- - * Compat defs for non-BSDs +/* - + * compat defs for non-bsds * - * __unused and __nonstring are intentionally NOT defined here - * They collide with struct field names in some libc's <bits/stat.h> + * __unused and __nonstring are intentionally NOT defined here + * they collide with struct field names in some libc's <bits/stat.h> * (`long __unused[3]`) and similar system headers when defined as - * macros before those headers are included. They remain defined in + * macros before those headers are included. they remain defined in * shell.h, which includes <sys/stat.h> before defining them * - * All definitions are guarded with #ifndef so they do not conflict + * all definitions are guarded with #ifndef so they do not conflict * with each other or with system-provided definitions */ @@ -29,9 +29,9 @@ #ifndef _SH_POINTER_TYPEDEF #define _SH_POINTER_TYPEDEF typedef void *pointer; /* used in our memalloc.h and bltin.h - canonical home is shell.h, but we - want memalloc to be self-contained - and not pull all of shell.h */ + * canonical home is shell.h, but we + * want memalloc to be self-contained + * and not pull all of shell.h */ #endif #endif /* SH_CDEFS_H */ diff --git a/cmd/posix/sh/shell.h b/cmd/posix/sh/shell.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #ifndef SHELL_H_ @@ -128,20 +128,20 @@ #endif /* - * The follow should be set to reflect the type of system you have: - * JOBS -> 1 if you have Berkeley job control, 0 otherwise. - * define DEBUG=1 to compile in debugging (set global "debug" to turn on) - * define DEBUG=2 to compile in and turn on debugging. + * the follow should be set to reflect the type of system you have: + * JOBS -> 1 if you have berkeley job control, 0 otherwise + * define DEBUG=1 to compile in debugging (set global "debug" to turn on) + * define DEBUG=2 to compile in and turn on debugging * - * When debugging is on, debugging info will be written to ./trace and - * a quit signal will generate a core dump. + * when debugging is on, debugging info will be written to ./trace and + * a quit signal will generate a core dump */ #define JOBS 1 /* #define DEBUG 1 */ /* - * Type of used arithmetic. SUSv3 requires us to have at least signed long. + * type of used arithmetic. susv3 requires us to have at least signed long */ typedef intmax_t arith_t; #define ARITH_FORMAT_STR "%" PRIdMAX diff --git a/cmd/posix/sh/show.c b/cmd/posix/sh/show.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <errno.h> @@ -79,7 +79,7 @@ shtree(union node *n, int ind, char *pfx, FILE *fp) s = " || "; binop: shtree(n->nbinary.ch1, ind, NULL, fp); - /* if (ind < 0) */ + /* if (ind < 0) */ fputs(s, fp); shtree(n->nbinary.ch2, ind, NULL, fp); break; @@ -283,7 +283,7 @@ indent(int amount, char *pfx, FILE *fp) } /* - * Debugging stuff. + * debugging stuff */ static FILE *tracefile; diff --git a/cmd/posix/sh/show.h b/cmd/posix/sh/show.h @@ -1,32 +1,32 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1995 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1995 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" diff --git a/cmd/posix/sh/test.c b/cmd/posix/sh/test.c @@ -1,17 +1,17 @@ -/* $NetBSD: test.c,v 1.21 1999/04/05 09:48:38 kleink Exp $ */ - -/*- - * test(1); version 7-like -- author Erik Baalbergen - * modified by Eric Gisin to be used as built-in. - * modified by Arnold Robbins to add SVR3 compatibility - * (-x -c -b -p -u -g -k) plus Korn's -L -nt -ot -ef and new -S (socket). - * modified by J.T. Conklin for NetBSD. +/* $netbsd: test.c,v 1.21 1999/04/05 09:48:38 kleink exp $ */ + +/* - + * test(1); version 7-like, author erik baalbergen + * modified by eric gisin to be used as built-in + * modified by arnold robbins to add SVR3 compatibility + * (-x -c -b -p -u -g -k) plus korn's -L -nt -ot -ef and new -S (socket) + * modified by J.T. conklin for netbsd * - * This program is in the Public Domain. + * this program is in the public domain */ /* - * Important: This file is used both as a standalone program /bin/test and - * as a builtin for /bin/sh (#define SHELL). + * important: this file is used both as a standalone program /bin/test and + * as a builtin for /bin/sh (#define SHELL) */ #ifndef SHELL @@ -68,27 +68,27 @@ error(const char *msg, ...) va_list ap; va_start(ap, msg); verrx(2, msg, ap); - /*NOTREACHED*/ + /* NOTREACHED */ va_end(ap); } #endif /* test(1) accepts the following grammar: - oexpr ::= aexpr | aexpr "-o" oexpr ; - aexpr ::= nexpr | nexpr "-a" aexpr ; - nexpr ::= primary | "!" primary - primary ::= unary-operator operand - | operand binary-operator operand - | operand - | "(" oexpr ")" - ; - unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"| - "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-O"|"-G"|"-L"|"-S"; - - binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"| - "-nt"|"-ot"|"-ef"; - operand ::= <any legal UNIX file name> -*/ + * oexpr ::= aexpr | aexpr "-o" oexpr ; + * aexpr ::= nexpr | nexpr "-a" aexpr ; + * nexpr ::= primary | "!" primary + * primary ::= unary-operator operand + * | operand binary-operator operand + * | operand + * | "(" oexpr ")" + * ; + * unary-operator ::= "-r"|"-w"|"-x"|"-f"|"-d"|"-c"|"-b"|"-p"| + * "-u"|"-g"|"-k"|"-s"|"-t"|"-z"|"-n"|"-o"|"-o"|"-g"|"-l"|"-s"; + * + * binary-operator ::= "="|"!="|"-eq"|"-ne"|"-ge"|"-gt"|"-le"|"-lt"| + * "-nt"|"-ot"|"-ef"; + * operand ::= <any legal UNIX file name> + */ enum token_types { UNOP = 0x100, BINOP = 0x200, BUNOP = 0x300, BBINOP = 0x400, PAREN = 0x500 }; @@ -224,7 +224,7 @@ main(int argc, char **argv) t_wp = &argv[1]; parenlevel = 0; if (nargc == 4 && strcmp(*t_wp, "!") == 0) { - /* Things like ! "" -o x do not fit in the normal grammar. */ + /* things like ! "" -o x do not fit in the normal grammar */ --nargc; ++t_wp; res = oexpr(t_lex(*t_wp)); diff --git a/cmd/posix/sh/trap.c b/cmd/posix/sh/trap.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "trap.h" @@ -55,8 +55,8 @@ #include <unistd.h> /* - * Sigmode records the current value of the signal handlers for the various - * modes. A value of zero means that the current handler is not known. + * sigmode records the current value of the signal handlers for the various + * modes. a value of zero means that the current handler is not known * S_HARD_IGN indicates that the signal was ignored on entry to the shell, */ @@ -73,7 +73,7 @@ static int in_dotrap; /* do we execute in a trap handler? */ static char *volatile trap[NSIG]; /* trap handler commands */ static volatile sig_atomic_t gotsig[NSIG]; /* indicates specified signal received */ -static int ignore_sigchld; /* Used while handling SIGCHLD traps. */ +static int ignore_sigchld; /* used while handling SIGCHLD traps */ static int last_trapsig; static int exiting; /* exitshell() has been called */ @@ -82,9 +82,9 @@ static int exiting_exitstatus; /* value passed to exitshell() */ static int getsigaction(int, sig_t *); /* - * Map a string to a signal number. + * map a string to a signal number * - * Note: the signal number may exceed NSIG. + * note: the signal number may exceed NSIG */ static int sigstring_to_signum(char *sig) @@ -109,7 +109,7 @@ sigstring_to_signum(char *sig) } /* - * Print a list of valid signal names. + * print a list of valid signal names */ static void printsignals(void) @@ -136,7 +136,7 @@ printsignals(void) } /* - * The trap builtin. + * the trap builtin */ int trapcmd(int argc __unused, char **argv) @@ -200,7 +200,7 @@ trapcmd(int argc __unused, char **argv) } /* - * Clear traps on a fork. + * clear traps on a fork */ void clear_traps(void) @@ -220,7 +220,7 @@ clear_traps(void) } /* - * Check if we have any traps enabled. + * check if we have any traps enabled */ int have_traps(void) @@ -235,8 +235,8 @@ have_traps(void) } /* - * Set the signal handler for the specified signal. The routine figures - * out what it should be set to. + * set the signal handler for the specified signal. the routine figures + * out what it should be set to */ void setsignal(int signo) @@ -281,19 +281,19 @@ setsignal(int signo) t = &sigmode[signo]; if (*t == 0) { /* - * current setting unknown - */ + * current setting unknown + */ if (!getsigaction(signo, &sigact)) { /* - * Pretend it worked; maybe we should give a warning - * here, but other shells don't. We don't alter - * sigmode, so that we retry every time. - */ + * pretend it worked; maybe we should give a warning + * here, but other shells dont. we dont alter + * sigmode, so that we retry every time + */ return; } if (sigact == SIG_IGN) { if (mflag && (signo == SIGTSTP || signo == SIGTTIN || signo == SIGTTOU)) { - *t = S_IGN; /* don't hard ignore these */ + *t = S_IGN; /* dont hard ignore these */ } else *t = S_HARD_IGN; } else { @@ -321,7 +321,7 @@ setsignal(int signo) } /* - * Return the current setting for sig w/o changing it. + * return the current setting for sig w/o changing it */ static int getsigaction(int signo, sig_t *sigact) @@ -335,7 +335,7 @@ getsigaction(int signo, sig_t *sigact) } /* - * Ignore a signal. + * ignore a signal */ void ignoresig(int signo) @@ -355,7 +355,7 @@ issigchldtrapped(void) } /* - * Signal handler. + * signal handler */ void onsig(int signo) @@ -368,7 +368,7 @@ onsig(int signo) return; } - /* If we are currently in a wait builtin, prepare to break it */ + /* if we are currently in a wait builtin, prepare to break it */ if (signo == SIGINT || signo == SIGQUIT) pendingsig_waitcmd = signo; @@ -380,8 +380,8 @@ onsig(int signo) } /* - * Called to execute a trap. Perhaps we should avoid entering new trap - * handlers while we are executing a trap handler. + * called to execute a trap. perhaps we should avoid entering new trap + * handlers while we are executing a trap handler */ void dotrap(void) @@ -399,21 +399,21 @@ dotrap(void) gotsig[i] = 0; if (trap[i]) { /* - * Ignore SIGCHLD to avoid infinite - * recursion if the trap action does - * a fork. - */ + * ignore SIGCHLD to avoid infinite + * recursion if the trap action does + * a fork + */ if (i == SIGCHLD) ignore_sigchld++; /* - * Backup current evalskip - * state and reset it before - * executing a trap, so that the - * trap is not disturbed by an - * ongoing break/continue/return - * statement. - */ + * backup current evalskip + * state and reset it before + * executing a trap, so that the + * trap is not disturbed by an + * ongoing break/continue/return + * statement + */ prev_evalskip = evalskip; prev_skipcount = skipcount; evalskip = 0; @@ -425,12 +425,12 @@ dotrap(void) popstackmark(&smark); /* - * If such a command was not - * already in progress, allow a - * break/continue/return in the - * trap action to have an effect - * outside of it. - */ + * if such a command was not + * already in progress, allow a + * break/continue/return in the + * trap action to have an effect + * outside of it + */ if (evalskip == 0 || prev_evalskip != 0) { evalskip = prev_evalskip; skipcount = prev_skipcount; @@ -457,7 +457,7 @@ trap_init(void) } /* - * Controls whether the shell is interactive or not based on iflag. + * controls whether the shell is interactive or not based on iflag */ void setinteractive(void) @@ -466,7 +466,7 @@ setinteractive(void) } /* - * Called to exit the shell. + * called to exit the shell */ void exitshell(int status) @@ -497,9 +497,9 @@ exitshell_savedstatus(void) handler = &loc1; if ((p = trap[0]) != NULL && *p != '\0') { /* - * Reset evalskip, or the trap on EXIT could be - * interrupted if the last command was a "return". - */ + * reset evalskip, or the trap on EXIT could be + * interrupted if the last command was a "return" + */ evalskip = 0; trap[0] = NULL; FORCEINTON; @@ -523,7 +523,7 @@ exitshell_savedstatus(void) sigaddset(&sigs, sig); sigprocmask(SIG_UNBLOCK, &sigs, NULL); kill(getpid(), sig); - /* If the default action is to ignore, fall back to _exit(). */ + /* if the default action is to ignore, fall back to _exit() */ } _exit(exiting_exitstatus); } diff --git a/cmd/posix/sh/trap.h b/cmd/posix/sh/trap.h @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "sh_cdefs.h" diff --git a/cmd/posix/sh/var.c b/cmd/posix/sh/var.c @@ -1,35 +1,35 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include "var.h" @@ -58,7 +58,7 @@ #include <unistd.h> /* - * Shell variables. + * shell variables */ #ifndef VTABSIZE @@ -98,8 +98,8 @@ static const struct varinit varinit[] = { {&vmpath, VUNSET, "MAILPATH=", NULL}, {&vpath, 0, "PATH=" ARUU_PATH_DEFPATH, changepath}, /* - * vps1 depends on uid - */ + * vps1 depends on uid + */ {&vps2, 0, "PS2=> ", NULL}, {&vps4, 0, "PS4=+ ", NULL}, #ifndef NO_HISTORY @@ -127,8 +127,8 @@ static void setvareq_const(const char *s, int flags); extern char **environ; /* - * This routine initializes the builtin variables and imports the environment. - * It is called when the shell is initialized. + * this routine initializes the builtin variables and imports the environment + * it is called when the shell is initialized */ void @@ -150,8 +150,8 @@ initvar(void) vp->func = ip->func; } /* - * PS1 depends on uid - */ + * PS1 depends on uid + */ if (find_var("PS1", &vpp, &vps1.name_len) == NULL) { vps1.next = *vpp; *vpp = &vps1; @@ -170,7 +170,7 @@ initvar(void) } /* - * Safe version of setvar, returns 1 on success 0 on failure. + * safe version of setvar, returns 1 on success 0 on failure */ int @@ -194,8 +194,8 @@ setvarsafe(const char *name, const char *val, int flags) } /* - * Set the value of a variable. The flags argument is stored with the - * flags of the variable. If val is NULL, the variable is unset. + * set the value of a variable. the flags argument is stored with the + * flags of the variable. if val is NULL, the variable is unset */ void @@ -264,8 +264,8 @@ localevar(const char *s) } /* - * Sets/unsets an environment variable from a pointer that may actually be a - * pointer into environ where the string should not be manipulated. + * sets/unsets an environment variable from a pointer that may actually be a + * pointer into environ where the string should not be manipulated */ static void change_env(const char *s, int set) @@ -288,10 +288,10 @@ change_env(const char *s, int set) } /* - * Same as setvar except that the variable and value are passed in - * the first argument as name=value. Since the first argument will + * same as setvar except that the variable and value are passed in + * the first argument as name=value. since the first argument will * be actually stored in the table, it should not be a string that - * will go away. + * will go away */ void @@ -329,13 +329,13 @@ setvareq(char *s, int flags) vp->text = s; /* - * We could roll this to a function, to handle it as - * a regular variable function callback, but why bother? - * - * Note: this assumes iflag is not set to 1 initially. - * As part of initvar(), this is called before arguments - * are looked at. - */ + * we could roll this to a function, to handle it as + * a regular variable function callback, but why bother? + * + * note: this assumes iflag is not set to 1 initially + * as part of initvar(), this is called before arguments + * are looked at + */ if ((vp == &vmpath || (vp == &vmail && !mpathset())) && iflag == 1) chkmail(1); if ((vp->flags & VEXPORT) && localevar(s)) { @@ -375,7 +375,7 @@ setvareq_const(const char *s, int flags) } /* - * Process a linked list of variable assignments. + * process a linked list of variable assignments */ void @@ -390,7 +390,7 @@ listsetvar(struct arglist *list, int flags) } /* - * Find the value of a variable. Returns NULL if not set. + * find the value of a variable. returns NULL if not set */ char * @@ -405,9 +405,9 @@ lookupvar(const char *name) } /* - * Search the environment of a builtin command. If the second argument - * is nonzero, return the value of a variable even if it hasn't been - * exported. + * search the environment of a builtin command. if the second argument + * is nonzero, return the value of a variable even if it hasnt been + * exported */ char * @@ -433,7 +433,7 @@ bltinlookup(const char *name, int doall) } /* - * Set up locale for a builtin (LANG/LC_* assignments). + * set up locale for a builtin (LANG/LC_* assignments) */ void bltinsetlocale(void) @@ -472,7 +472,7 @@ bltinsetlocale(void) } /* - * Undo the effect of bltinlocaleset(). + * undo the effect of bltinlocaleset() */ void bltinunsetlocale(void) @@ -492,7 +492,7 @@ bltinunsetlocale(void) } /* - * Update the localeisutf8 flag. + * update the localeisutf8 flag */ void updatecharset(void) @@ -511,8 +511,8 @@ initcharset(void) } /* - * Generate a list of exported variables. This routine is used to construct - * the third argument to execve when executing a program. + * generate a list of exported variables. this routine is used to construct + * the third argument to execve when executing a program */ char ** @@ -547,16 +547,16 @@ var_compare(const void *a, const void *b) sa = a; sb = b; /* - * This compares two var=value strings which creates a different - * order from what you would probably expect. POSIX is somewhat - * ambiguous on what should be sorted exactly. - */ + * this compares two var=value strings which creates a different + * order from what you would probably expect. POSIX is somewhat + * ambiguous on what should be sorted exactly + */ return strcoll(*sa, *sb); } /* - * Command to list all variables which are set. This is invoked from the - * set command when it is called without any options or operands. + * command to list all variables which are set. this is invoked from the + * set command when it is called without any options or operands */ int @@ -569,8 +569,8 @@ showvarscmd(int argc __unused, char **argv __unused) int i, n; /* - * POSIX requires us to sort the variables. - */ + * POSIX requires us to sort the variables + */ n = 0; for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) { for (vp = *vpp; vp; vp = vp->next) { @@ -592,9 +592,9 @@ showvarscmd(int argc __unused, char **argv __unused) qsort(vars, n, sizeof(*vars), var_compare); for (i = 0; i < n; i++) { /* - * Skip improper variable names so the output remains usable as - * shell input. - */ + * skip improper variable names so the output remains usable as + * shell input + */ if (!isassignment(vars[i])) continue; s = strchr(vars[i], '='); @@ -610,7 +610,7 @@ showvarscmd(int argc __unused, char **argv __unused) } /* - * The export and readonly commands. + * the export and readonly commands */ int @@ -661,10 +661,10 @@ exportcmd(int argc __unused, char **argv) if (vp->flags & flag) { if (values) { /* - * Skip improper variable names - * so the output remains usable - * as shell input. - */ + * skip improper variable names + * so the output remains usable + * as shell input + */ if (!isassignment(vp->text)) continue; out1str(cmdname); @@ -684,7 +684,7 @@ exportcmd(int argc __unused, char **argv) } /* - * The "local" command. + * the "local" command */ int @@ -702,10 +702,10 @@ localcmd(int argc __unused, char **argv __unused) } /* - * Make a variable a local variable. When a variable is made local, it's - * value and flags are saved in a localvar structure. The saved values - * will be restored when the shell function returns. We handle the name - * "-" as a special case. + * make a variable a local variable. when a variable is made local, its + * value and flags are saved in a localvar structure. the saved values + * will be restored when the shell function returns. we handle the name + * "-" as a special case */ void @@ -746,7 +746,7 @@ mklocal(char *name) } /* - * Called after a function returns. + * called after a function returns */ void @@ -799,7 +799,7 @@ setvarcmd(int argc, char **argv) } /* - * The unset builtin command. + * the unset builtin command */ int @@ -832,8 +832,8 @@ unsetcmd(int argc __unused, char **argv __unused) } /* - * Unset the specified variable. - * Called with interrupts off. + * unset the specified variable + * called with interrupts off */ int @@ -866,9 +866,9 @@ unsetvar(const char *s) } /* - * Returns true if the two strings specify the same variable. The first + * returns true if the two strings specify the same variable. the first * variable name is terminated by '='; the second may be terminated by - * either '=' or '\0'. + * either '=' or '\0' */ static int @@ -884,9 +884,9 @@ varequal(const char *p, const char *q) } /* - * Search for a variable. - * 'name' may be terminated by '=' or a NUL. - * vppp is set to the pointer to vp, or the list head if vp isn't found + * search for a variable + * 'name' may be terminated by '=' or a NUL + * vppp is set to the pointer to vp, or the list head if vp isnt found * lenp is set to the number of characters in 'name' */ diff --git a/cmd/posix/sh/var.h b/cmd/posix/sh/var.h @@ -1,39 +1,39 @@ -/*- - * SPDX-License-Identifier: BSD-3-Clause +/* - + * spdx-license-identifier: bsd-3-clause * - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * This code is derived from software contributed to Berkeley by - * Kenneth Almquist. + * this code is derived from software contributed to berkeley by + * kenneth almquist * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ /* - * Shell variables. + * shell variables */ /* flags */ @@ -43,7 +43,7 @@ #define VTEXTFIXED 0x08 /* text is statically allocated */ #define VSTACK 0x10 /* text is allocated on the stack */ #define VUNSET 0x20 /* the variable is not set */ -#define VNOFUNC 0x40 /* don't call the callback function */ +#define VNOFUNC 0x40 /* dont call the callback function */ #define VNOSET 0x80 /* do not set variable - just readonly test */ #define VNOLOCAL 0x100 /* ignore forcelocal */ @@ -53,7 +53,7 @@ struct var { int name_len; /* length of name */ char *text; /* name=value */ void (*func)(const char *); - /* function to be called when */ + /* function to be called when */ /* the variable gets set/unset */ }; @@ -81,13 +81,13 @@ extern struct var vterm; #endif extern int localeisutf8; -/* The parser uses the locale that was in effect at startup. */ +/* the parser uses the locale that was in effect at startup */ extern int initial_localeisutf8; /* - * The following macros access the values of the above variables. - * They have to skip over the name. They return the null string - * for unset variables. + * the following macros access the values of the above variables + * they have to skip over the name. they return the null string + * for unset variables */ #define ifsval() (vifs.text + 4) diff --git a/cmd/posix/sleep.c b/cmd/posix/sleep.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "queue.h" #include "text.h" @@ -212,8 +212,8 @@ slinecmp(struct line *a, struct line *b) columns(a, kd, &col1); columns(b, kd, &col2); - /* if -u is given, don't use default key definition - * unless it is the only one */ + /* if -u is given, dont use default key definition + * unless it is the only one */ if (uflag && kd == TAILQ_LAST(&kdhead, kdhead) && TAILQ_LAST(&kdhead, kdhead) != TAILQ_FIRST(&kdhead)) { res = 0; @@ -338,8 +338,8 @@ addkeydef(char *kdstr, int flags) kd = enmalloc(2, sizeof(*kd)); /* parse key definition kdstr with format - * start_column[.start_char][flags][,end_column[.end_char][flags]] - */ + * start_column[.start_char][flags][,end_column[.end_char][flags]] + */ kd->start_column = 1; kd->start_char = 1; kd->end_column = 0; /* 0 means end of line */ @@ -443,10 +443,10 @@ main(int argc, char *argv[]) // ?man -m: specify mode or limit case 'm': /* more or less for free, but for performance-reasons, - * we should keep this flag in mind and maybe some later - * day implement it properly so we don't run out of memory - * while merging large sorted files. - */ + * we should keep this flag in mind and maybe some later + * day implement it properly so we dont run out of memory + * while merging large sorted files + */ break; // ?man -n: print line numbers or counts case 'n': diff --git a/cmd/posix/split.c b/cmd/posix/split.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdint.h> diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> @@ -49,9 +49,9 @@ dropinit(int fd, const char *fname, size_t count) for (p = buf; count && n > 0; p += nr, n -= nr, count--) { nr = charntorune(&r, p, n); if (!nr) { - /* we don't have a full rune, move - * remaining data to beginning and read - * again */ + /* we dont have a full rune, move + * remaining data to beginning and read + * again */ memmove(buf, p, n); break; } @@ -109,7 +109,7 @@ taketail(int fd, const char *fname, size_t count) // ?man -n: print line numbers or counts case 'n': /* lines */ /* ignore the last character; if it is a newline, it - * ends the last line */ + * ends the last line */ for (p = buf + len - 2, left = count; p >= buf; p--) { if (*p != '\n') continue; diff --git a/cmd/posix/tee.c b/cmd/posix/tee.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <signal.h> diff --git a/cmd/posix/test.c b/cmd/posix/test.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/time.c b/cmd/posix/time.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/times.h> #include <sys/wait.h> diff --git a/cmd/posix/touch.c b/cmd/posix/touch.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> @@ -77,7 +77,7 @@ parsetime(char *str) format = "%Y-%m-%dT%H:%M:%S"; break; case 20: - /* only Zulu-timezone supported */ + /* only zulu-timezone supported */ if (str[19] != 'Z') eprintf("Invalid time zone\n"); str[19] = 0; diff --git a/cmd/posix/tr.c b/cmd/posix/tr.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdlib.h> @@ -137,7 +137,7 @@ makeset(char *str, struct range **set, unsigned *checks) eprintf("Invalid character class.\n"); } - /* REPEAT [_*n] (only allowed in set2) */ + /* REPEAT [_*n] (only allowed in set2) */ if (j - i > 2 && rstr[i + 2] == '*') { /* check if right side of '*' is a number */ q = 0; diff --git a/cmd/posix/true.c b/cmd/posix/true.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ // ?man true: return successful exit status // ?man exit with status 0 representing success diff --git a/cmd/posix/tsort.c b/cmd/posix/tsort.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdio.h> diff --git a/cmd/posix/tty.c b/cmd/posix/tty.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <unistd.h> diff --git a/cmd/posix/uname.c b/cmd/posix/uname.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/utsname.h> diff --git a/cmd/posix/unexpand.c b/cmd/posix/unexpand.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdlib.h> diff --git a/cmd/posix/uniq.c b/cmd/posix/uniq.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdio.h> diff --git a/cmd/posix/unlink.c b/cmd/posix/unlink.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> diff --git a/cmd/posix/uudecode.c b/cmd/posix/uudecode.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> @@ -109,7 +109,7 @@ uudecodeb64(FILE *fp, FILE *outfp) switch (b) { case 0: /* expected '=' remaining - * including footer */ + * including footer */ if (--t) { fwrite(out, 1, (po - out), outfp); return; diff --git a/cmd/posix/uuencode.c b/cmd/posix/uuencode.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/posix/wc.c b/cmd/posix/wc.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <string.h> diff --git a/cmd/posix/who.c b/cmd/posix/who.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/wait.h> @@ -276,7 +276,7 @@ main(int argc, char *argv[]) if ((argmaxsz = sysconf(_SC_ARG_MAX)) == (size_t)-1) argmaxsz = _POSIX_ARG_MAX; - /* Leave some room for environment variables */ + /* leave some room for environment variables */ argmaxsz -= 4096; cmd = emalloc(NARGS * sizeof(*cmd)); diff --git a/cmd/pseudo/base64.c b/cmd/pseudo/base64.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdlib.h> diff --git a/cmd/pseudo/clear.c b/cmd/pseudo/clear.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> diff --git a/cmd/pseudo/cols.c b/cmd/pseudo/cols.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> diff --git a/cmd/pseudo/cron.c b/cmd/pseudo/cron.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/types.h> #include <sys/wait.h> @@ -97,7 +97,7 @@ runjob(char *cmd) t = time(NULL); - /* If command is already running, skip it */ + /* if command is already running, skip it */ TAILQ_FOREACH(je, &jobhead, entry) { if (strcmp(je->cmd, cmd) == 0) { @@ -552,7 +552,7 @@ main(int argc, char *argv[]) if (nflag == 0) unlink(pidfile); unloadentries(); - /* Don't wait or kill forked processes, just exit */ + /* dont wait or kill forked processes, just exit */ break; } diff --git a/cmd/pseudo/diff3.c b/cmd/pseudo/diff3.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "config.h" #include "diffutil.h" #include "util.h" diff --git a/cmd/pseudo/dmesg.c b/cmd/pseudo/dmesg.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/fallocate.c b/cmd/pseudo/fallocate.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/file.h> #include <sys/wait.h> diff --git a/cmd/pseudo/free.c b/cmd/pseudo/free.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/ioctl.h> #include <sys/stat.h> @@ -96,7 +96,7 @@ main(int argc, char *argv[]) sigemptyset(&sa.sa_mask); sigaction(SIGHUP, &sa, NULL); - /* Clear all utmp entries for this tty */ + /* clear all utmp entries for this tty */ fp = fopen(UTMP_PATH, "r+"); if (fp) { do { @@ -129,7 +129,7 @@ main(int argc, char *argv[]) printf("login: "); fflush(stdout); - /* Flush pending input */ + /* flush pending input */ ioctl(0, TCFLSH, (void *)0); memset(logname, 0, sizeof(logname)); while (1) { diff --git a/cmd/pseudo/gzip.c b/cmd/pseudo/gzip.c @@ -0,0 +1,715 @@ +/* see LICENSE file for copyright and license details */ + +/* deflate decoder adapted from puff.c, mark adlers rfc 1951 reference + * decoder. zlib license: copyright (c) 2002-2013 mark adler, provided + * as-is, free to use/alter/redistribute, origin not misrepresented, + * this notice kept. see zlib.net */ + +#include <setjmp.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#include "util.h" + +#define MAXBITS 15 +#define MAXLCODES 286 +#define MAXDCODES 30 +#define MAXCODES (MAXLCODES + MAXDCODES) +#define FIXLCODES 288 + +struct InflateState { + unsigned char *out; + unsigned long outlen; + unsigned long outcnt; + + const unsigned char *in; + unsigned long inlen; + unsigned long incnt; + int bitbuf; + int bitcnt; + + jmp_buf env; +}; + +struct Huffman { + short *count; + short *symbol; +}; + +static int +inflate_bits(struct InflateState *s, int need) +{ + long val; + + val = s->bitbuf; + while (s->bitcnt < need) { + if (s->incnt == s->inlen) + longjmp(s->env, 1); + val |= (long)(s->in[s->incnt++]) << s->bitcnt; + s->bitcnt += 8; + } + + s->bitbuf = (int)(val >> need); + s->bitcnt -= need; + + return (int)(val & ((1L << need) - 1)); +} + +static int +inflate_stored(struct InflateState *s) +{ + unsigned len; + + s->bitbuf = 0; + s->bitcnt = 0; + + if (s->incnt + 4 > s->inlen) + return 2; + len = s->in[s->incnt++]; + len |= s->in[s->incnt++] << 8; + if (s->in[s->incnt++] != (~len & 0xff) || s->in[s->incnt++] != ((~len >> 8) & 0xff)) + return -2; + + if (s->incnt + len > s->inlen) + return 2; + if (s->out != NULL) { + if (s->outcnt + len > s->outlen) + return 1; + while (len--) + s->out[s->outcnt++] = s->in[s->incnt++]; + } else { + s->outcnt += len; + s->incnt += len; + } + + return 0; +} + +/* codes are bit-reversed on the wire, rebuilt one bit at a time here */ +static int +inflate_decode(struct InflateState *s, const struct Huffman *h) +{ + int len, code, first, count, index; + int bitbuf, left; + short *next; + + bitbuf = s->bitbuf; + left = s->bitcnt; + code = first = index = 0; + len = 1; + next = h->count + 1; + for (;;) { + while (left--) { + code |= bitbuf & 1; + bitbuf >>= 1; + count = *next++; + if (code - count < first) { + s->bitbuf = bitbuf; + s->bitcnt = (s->bitcnt - len) & 7; + return h->symbol[index + (code - first)]; + } + index += count; + first += count; + first <<= 1; + code <<= 1; + len++; + } + left = (MAXBITS + 1) - len; + if (left == 0) + break; + if (s->incnt == s->inlen) + longjmp(s->env, 1); + bitbuf = s->in[s->incnt++]; + if (left > 8) + left = 8; + } + return -10; +} + +/* 0: complete code, > 0: incomplete but usable, < 0: over-subscribed */ +static int +huffman_construct(struct Huffman *h, const short *length, int n) +{ + int symbol, len, left; + short offs[MAXBITS + 1]; + + for (len = 0; len <= MAXBITS; len++) + h->count[len] = 0; + for (symbol = 0; symbol < n; symbol++) + (h->count[length[symbol]])++; + if (h->count[0] == n) + return 0; + + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= h->count[len]; + if (left < 0) + return left; + } + + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + h->count[len]; + + for (symbol = 0; symbol < n; symbol++) + if (length[symbol] != 0) + h->symbol[offs[length[symbol]]++] = symbol; + + return left; +} + +static int +inflate_codes(struct InflateState *s, const struct Huffman *lencode, const struct Huffman *distcode) +{ + int symbol, len; + unsigned dist; + static const short lens[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, + 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, + 163, 195, 227, 258}; + static const short lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, + 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; + static const short dists[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, + 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + static const short dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; + + do { + symbol = inflate_decode(s, lencode); + if (symbol < 0) + return symbol; + if (symbol < 256) { + if (s->out != NULL) { + if (s->outcnt == s->outlen) + return 1; + s->out[s->outcnt] = symbol; + } + s->outcnt++; + } else if (symbol > 256) { + symbol -= 257; + if (symbol >= 29) + return -10; + len = lens[symbol] + inflate_bits(s, lext[symbol]); + + symbol = inflate_decode(s, distcode); + if (symbol < 0) + return symbol; + dist = dists[symbol] + inflate_bits(s, dext[symbol]); + if (dist > s->outcnt) + return -11; + + if (s->out != NULL) { + if (s->outcnt + len > s->outlen) + return 1; + while (len--) { + s->out[s->outcnt] = s->out[s->outcnt - dist]; + s->outcnt++; + } + } else { + s->outcnt += len; + } + } + } while (symbol != 256); + + return 0; +} + +static int +inflate_fixed(struct InflateState *s) +{ + static int built; + static short lencnt[MAXBITS + 1], lensym[FIXLCODES]; + static short distcnt[MAXBITS + 1], distsym[MAXDCODES]; + static struct Huffman lencode, distcode; + + if (!built) { + int symbol; + short lengths[FIXLCODES]; + + lencode.count = lencnt; + lencode.symbol = lensym; + distcode.count = distcnt; + distcode.symbol = distsym; + + for (symbol = 0; symbol < 144; symbol++) + lengths[symbol] = 8; + for (; symbol < 256; symbol++) + lengths[symbol] = 9; + for (; symbol < 280; symbol++) + lengths[symbol] = 7; + for (; symbol < FIXLCODES; symbol++) + lengths[symbol] = 8; + huffman_construct(&lencode, lengths, FIXLCODES); + + for (symbol = 0; symbol < MAXDCODES; symbol++) + lengths[symbol] = 5; + huffman_construct(&distcode, lengths, MAXDCODES); + + built = 1; + } + + return inflate_codes(s, &lencode, &distcode); +} + +static int +inflate_dynamic(struct InflateState *s) +{ + int nlen, ndist, ncode, index, err; + short lengths[MAXCODES]; + short lencnt[MAXBITS + 1], lensym[MAXLCODES]; + short distcnt[MAXBITS + 1], distsym[MAXDCODES]; + struct Huffman lencode, distcode; + static const short order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, + 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + lencode.count = lencnt; + lencode.symbol = lensym; + distcode.count = distcnt; + distcode.symbol = distsym; + + nlen = inflate_bits(s, 5) + 257; + ndist = inflate_bits(s, 5) + 1; + ncode = inflate_bits(s, 4) + 4; + if (nlen > MAXLCODES || ndist > MAXDCODES) + return -3; + + for (index = 0; index < ncode; index++) + lengths[order[index]] = inflate_bits(s, 3); + for (; index < 19; index++) + lengths[order[index]] = 0; + + err = huffman_construct(&lencode, lengths, 19); + if (err != 0) + return -4; + + index = 0; + while (index < nlen + ndist) { + int symbol, len; + + symbol = inflate_decode(s, &lencode); + if (symbol < 0) + return symbol; + if (symbol < 16) { + lengths[index++] = symbol; + } else { + len = 0; + if (symbol == 16) { + if (index == 0) + return -5; + len = lengths[index - 1]; + symbol = 3 + inflate_bits(s, 2); + } else if (symbol == 17) { + symbol = 3 + inflate_bits(s, 3); + } else { + symbol = 11 + inflate_bits(s, 7); + } + if (index + symbol > nlen + ndist) + return -6; + while (symbol--) + lengths[index++] = len; + } + } + + if (lengths[256] == 0) + return -9; + + err = huffman_construct(&lencode, lengths, nlen); + if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1])) + return -7; + + err = huffman_construct(&distcode, lengths + nlen, ndist); + if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1])) + return -8; + + return inflate_codes(s, &lencode, &distcode); +} + +/* raw deflate (rfc 1951) decoder; dest null just computes destlen */ +static int +inflate_raw(unsigned char *dest, unsigned long *destlen, const unsigned char *source, + unsigned long *sourcelen) +{ + struct InflateState s; + int last, type, err; + + s.out = dest; + s.outlen = *destlen; + s.outcnt = 0; + + s.in = source; + s.inlen = *sourcelen; + s.incnt = 0; + s.bitbuf = 0; + s.bitcnt = 0; + + if (setjmp(s.env) != 0) { + err = 2; + } else { + do { + last = inflate_bits(&s, 1); + type = inflate_bits(&s, 2); + err = type == 0 ? inflate_stored(&s) + : type == 1 ? inflate_fixed(&s) + : type == 2 ? inflate_dynamic(&s) + : -1; + if (err != 0) + break; + } while (!last); + } + + if (err <= 0) { + *destlen = s.outcnt; + *sourcelen = s.incnt; + } + return err; +} + +static uint32_t crc32_table[256]; + +static void +crc32_init(void) +{ + uint32_t c; + int n, k; + + for (n = 0; n < 256; n++) { + c = (uint32_t)n; + for (k = 0; k < 8; k++) + c = (c & 1) ? (0xedb88320u ^ (c >> 1)) : (c >> 1); + crc32_table[n] = c; + } +} + +static uint32_t +crc32_update(uint32_t crc, const unsigned char *buf, size_t len) +{ + crc = ~crc; + while (len--) + crc = crc32_table[(crc ^ *buf++) & 0xff] ^ (crc >> 8); + return ~crc; +} + +static uint32_t +get_le32(const unsigned char *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +static void +put_le32(unsigned char *p, uint32_t v) +{ + p[0] = v & 0xff; + p[1] = (v >> 8) & 0xff; + p[2] = (v >> 16) & 0xff; + p[3] = (v >> 24) & 0xff; +} + +/* FLG bits in the gzip header (rfc 1952) */ +enum GzipFlag { + GZ_FTEXT = 1 << 0, + GZ_FHCRC = 1 << 1, + GZ_FEXTRA = 1 << 2, + GZ_FNAME = 1 << 3, + GZ_FCOMMENT = 1 << 4, +}; + +static unsigned char * +read_all(FILE *fp, size_t *len) +{ + unsigned char *buf; + size_t cap, n; + ssize_t r; + + cap = 1 << 16; + buf = emalloc(cap); + n = 0; + for (;;) { + if (n == cap) { + cap *= 2; + buf = erealloc(buf, cap); + } + r = fread(buf + n, 1, cap - n, fp); + if (r <= 0) + break; + n += (size_t)r; + } + if (ferror(fp)) + eprintf("read:"); + *len = n; + return buf; +} + +/* decodes one gzip member; multi-member streams are not supported */ +static void +gunzip(const unsigned char *in, size_t inlen, FILE *out) +{ + size_t pos, hdr; + unsigned flg; + unsigned char *dest; + unsigned long destlen, srclen; + uint32_t want_crc, want_isize, got_crc; + int err; + + if (inlen < 18 || in[0] != 0x1f || in[1] != 0x8b) + eprintf("gzip: not in gzip format\n"); + if (in[2] != 8) + eprintf("gzip: unsupported compression method\n"); + + flg = in[3]; + pos = 10; + + if (flg & GZ_FEXTRA) { + unsigned xlen; + if (pos + 2 > inlen) + eprintf("gzip: truncated header\n"); + xlen = in[pos] | (in[pos + 1] << 8); + pos += 2 + xlen; + } + if (flg & GZ_FNAME) { + while (pos < inlen && in[pos] != '\0') + pos++; + pos++; + } + if (flg & GZ_FCOMMENT) { + while (pos < inlen && in[pos] != '\0') + pos++; + pos++; + } + if (flg & GZ_FHCRC) + pos += 2; + if (pos + 8 > inlen) + eprintf("gzip: truncated header\n"); + + hdr = pos; + + /* first pass just measures destlen, second pass does the real decode */ + destlen = 0; + srclen = (unsigned long)(inlen - hdr - 8); + err = inflate_raw(NULL, &destlen, in + hdr, &srclen); + if (err != 0) + eprintf("gzip: corrupt compressed data\n"); + + dest = emalloc(destlen ? destlen : 1); + srclen = (unsigned long)(inlen - hdr - 8); + destlen = destlen ? destlen : 1; + err = inflate_raw(dest, &destlen, in + hdr, &srclen); + if (err != 0) + eprintf("gzip: corrupt compressed data\n"); + + want_crc = get_le32(in + hdr + srclen); + want_isize = get_le32(in + hdr + srclen + 4); + got_crc = crc32_update(0, dest, destlen); + if (got_crc != want_crc) + eprintf("gzip: crc mismatch\n"); + if ((uint32_t)destlen != want_isize) + eprintf("gzip: size mismatch\n"); + + if (fwrite(dest, 1, destlen, out) != destlen) + eprintf("write:"); + free(dest); +} + +/* stored (uncompressed) deflate blocks: no compression, always valid */ +static void +gzip_write_stored(const unsigned char *in, size_t len, FILE *out) +{ + unsigned char hdr[5]; + size_t chunk; + int last; + + if (len == 0) { + hdr[0] = 1; + hdr[1] = hdr[2] = hdr[3] = hdr[4] = 0; + if (fwrite(hdr, 1, 5, out) != 5) + eprintf("write:"); + return; + } + + while (len > 0) { + chunk = len > 65535 ? 65535 : len; + last = chunk == len; + + hdr[0] = last ? 1 : 0; + hdr[1] = chunk & 0xff; + hdr[2] = (chunk >> 8) & 0xff; + hdr[3] = (~chunk) & 0xff; + hdr[4] = ((~chunk) >> 8) & 0xff; + + if (fwrite(hdr, 1, 5, out) != 5 || fwrite(in, 1, chunk, out) != chunk) + eprintf("write:"); + + in += chunk; + len -= chunk; + } +} + +static void +gzip_compress(const unsigned char *in, size_t len, const char *name, FILE *out) +{ + unsigned char hdr[10]; + unsigned char trl[8]; + uint32_t crc; + + hdr[0] = 0x1f; + hdr[1] = 0x8b; + hdr[2] = 8; + hdr[3] = name ? GZ_FNAME : 0; + put_le32(hdr + 4, 0); + hdr[8] = 0; + hdr[9] = 255; + if (fwrite(hdr, 1, 10, out) != 10) + eprintf("write:"); + if (name && (fwrite(name, 1, strlen(name) + 1, out) != strlen(name) + 1)) + eprintf("write:"); + + gzip_write_stored(in, len, out); + + crc = crc32_update(0, in, len); + put_le32(trl, crc); + put_le32(trl + 4, (uint32_t)len); + if (fwrite(trl, 1, 8, out) != 8) + eprintf("write:"); +} + +static char * +strip_gz_suffix(const char *name) +{ + size_t n = strlen(name); + if (n > 3 && strcmp(name + n - 3, ".gz") == 0) + return estrndup(name, n - 3); + return NULL; +} + +static void +usage(void) +{ + eprintf("usage: %s [-cdfkn] [-1..-9] [file ...]\n", argv0); +} + +// ?man gzip: compress or decompress files +// ?man arguments: [file ...] +// ?man with no files, reads standard input and writes standard output +// ?man compressing replaces each file with file.gz; decompressing +// ?man reverses that. only single-member gzip streams are read back +int +main(int argc, char *argv[]) +{ + int dflag = 0, cflag = 0, fflag = 0, kflag = 0, nflag = 0; + int i; + char outname[4096]; + + ARGBEGIN + { + // ?man -c: write to standard output, keep the input file + case 'c': + cflag = 1; + break; + // ?man -d: decompress instead of compress + case 'd': + dflag = 1; + break; + // ?man -f: accepted for compatibility, no effect + case 'f': + fflag = 1; + break; + // ?man -k: keep the input file instead of removing it + case 'k': + kflag = 1; + break; + // ?man -n: omit the original file name from the header + case 'n': + nflag = 1; + break; + // ?man -1: accepted for compatibility, no effect (stored blocks only) + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + break; + default: + usage(); + } + ARGEND + + (void)fflag; + crc32_init(); + + if (argc == 0) { + unsigned char *buf; + size_t len; + + buf = read_all(stdin, &len); + if (dflag) + gunzip(buf, len, stdout); + else + gzip_compress(buf, len, NULL, stdout); + free(buf); + return 0; + } + + for (i = 0; i < argc; i++) { + FILE *fp; + unsigned char *buf; + size_t len; + char *stripped; + + fp = fopen(argv[i], "rb"); + if (!fp) { + weprintf("open %s:", argv[i]); + continue; + } + buf = read_all(fp, &len); + fclose(fp); + + if (dflag) { + if (cflag) { + gunzip(buf, len, stdout); + } else { + stripped = strip_gz_suffix(argv[i]); + if (!stripped) + eprintf("gzip: %s: unknown suffix, ignored\n", argv[i]); + strlcpy(outname, stripped, sizeof(outname)); + free(stripped); + + fp = fopen(outname, "wb"); + if (!fp) + eprintf("open %s:", outname); + gunzip(buf, len, fp); + if (fclose(fp)) + eprintf("close %s:", outname); + if (!kflag && unlink(argv[i]) < 0) + weprintf("unlink %s:", argv[i]); + } + } else { + if (cflag) { + gzip_compress(buf, len, NULL, stdout); + } else { + strlcpy(outname, argv[i], sizeof(outname)); + strlcat(outname, ".gz", sizeof(outname)); + + fp = fopen(outname, "wb"); + if (!fp) + eprintf("open %s:", outname); + gzip_compress(buf, len, nflag ? NULL : argv[i], fp); + if (fclose(fp)) + eprintf("close %s:", outname); + if (!kflag && unlink(argv[i]) < 0) + weprintf("unlink %s:", argv[i]); + } + } + + free(buf); + } + + return 0; +} diff --git a/cmd/pseudo/halt.c b/cmd/pseudo/halt.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/syscall.h> diff --git a/cmd/pseudo/hostname.c b/cmd/pseudo/hostname.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <string.h> diff --git a/cmd/pseudo/install.c b/cmd/pseudo/install.c @@ -0,0 +1,214 @@ +/* see LICENSE file for copyright and license details */ + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <grp.h> +#include <pwd.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <unistd.h> + +#include "util.h" + +static int Dflag = 0; +static gid_t group; +static uid_t owner; +static mode_t mode = 0755; + +static void +make_dir(char *dir, int was_missing) +{ + if (!mkdir(dir, was_missing ? 0755 : mode)) { + if (!was_missing && (lchown(dir, owner, group) < 0)) + eprintf("lchmod %s:", dir); + } else if (errno != EEXIST) { + eprintf("mkdir %s:", dir); + } +} + +static void +make_dirs(char *dir, int was_missing) +{ + char *p; + for (p = strchr(dir + (dir[0] == '/'), '/'); p; p = strchr(p + 1, '/')) { + *p = '\0'; + make_dir(dir, was_missing); + *p = '/'; + } + make_dir(dir, was_missing); +} + +static int +install(const char *s1, const char *s2, int depth) +{ + int f1, f2; + + (void)depth; + + if ((f1 = open(s1, O_RDONLY)) < 0) + eprintf("open %s:", s1); + if ((f2 = creat(s2, 0600)) < 0) { + if (unlink(s2) < 0 && errno != ENOENT) + eprintf("unlink %s:", s2); + if ((f2 = creat(s2, 0600)) < 0) + eprintf("creat %s:", s2); + } + if (concat(f1, s1, f2, s2) < 0) + goto fail; + if (fchmod(f2, mode) < 0) { + weprintf("fchmod %s:", s2); + goto fail; + } + if (fchown(f2, owner, group) < 0) { + weprintf("fchown %s:", s2); + goto fail; + } + + close(f1); + close(f2); + + return 0; + +fail: + unlink(s2); + exit(1); +} + +static void +usage(void) +{ + eprintf( + "usage: %s [-g group] [-o owner] [-m mode] (-d dir ... | [-D] " + "(-t dest source ... | source ... dest))\n", + argv0 + ); +} + +// ?man install: copy files and set attributes +// ?man arguments: (-d dir ... | (-t dest source ... | source ... dest)) +// ?man copy files and set their permissions and ownership +int +main(int argc, char *argv[]) +{ + int dflag = 0; + char *gflag = 0; + char *oflag = 0; + char *mflag = 0; + char *tflag = 0; + struct group *gr; + struct passwd *pw; + struct stat st; + char *p; + + ARGBEGIN + { + // ?man -c: print count or perform stdout action + case 'c': + /* no-op for compatibility */ + break; + // ?man -d: specify directory + case 'd': + dflag = 1; + break; + // ?man -D: specify option flag + case 'D': + Dflag = 1; + break; + // ?man -s: silent mode or print summary + case 's': + /* no-op for compatibility */ + break; + // ?man -g:str: specify option flag + case 'g': + gflag = EARGF(usage()); + break; + // ?man -o:str: specify output file + case 'o': + oflag = EARGF(usage()); + break; + // ?man -m:str: specify mode or limit + case 'm': + mflag = EARGF(usage()); + break; + // ?man -t:str: sort or specify timestamp + case 't': + tflag = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + + if (argc < 1 + (!tflag & !dflag) || dflag & (Dflag | !!tflag)) + usage(); + + if (gflag) { + errno = 0; + gr = getgrnam(gflag); + if (gr) { + group = gr->gr_gid; + } else { + if (errno) + eprintf("getgrnam %s:", gflag); + group = estrtonum(gflag, 0, UINT_MAX); + } + } else { + group = getgid(); + } + + if (oflag) { + errno = 0; + pw = getpwnam(oflag); + if (pw) { + owner = pw->pw_uid; + } else { + if (errno) + eprintf("getpwnam %s:", oflag); + owner = estrtonum(oflag, 0, UINT_MAX); + } + } else { + owner = getuid(); + } + + if (mflag) + mode = parsemode(mflag, mode, 0); + + if (dflag) { + for (; *argv; argc--, argv++) + make_dirs(*argv, 0); + return 0; + } + + if (tflag) { + argv = memmove(argv - 1, argv, argc * sizeof(*argv)); + argv[argc++] = tflag; + } + if (tflag || argc > 2) { + if (stat(argv[argc - 1], &st) < 0) { + if ((errno == ENOENT) && Dflag) { + make_dirs(argv[argc - 1], 1); + } else { + eprintf("stat %s:", argv[argc - 1]); + } + } else if (!S_ISDIR(st.st_mode)) { + eprintf("%s: not a directory\n", argv[argc - 1]); + } + } + if (stat(argv[argc - 1], &st) < 0) { + if (errno != ENOENT) + eprintf("stat %s:", argv[argc - 1]); + if (tflag || Dflag || argc > 2) { + if ((p = strrchr(argv[argc - 1], '/')) != NULL) { + *p = '\0'; + make_dirs(argv[argc - 1], 1); + *p = '/'; + } + } + } + enmasse(argc, argv, install); + + return 0; +} diff --git a/cmd/pseudo/killall5.c b/cmd/pseudo/killall5.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <dirent.h> #include <limits.h> diff --git a/cmd/pseudo/last.c b/cmd/pseudo/last.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <libgen.h> diff --git a/cmd/pseudo/lastlog.c b/cmd/pseudo/lastlog.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <pwd.h> @@ -39,7 +39,7 @@ lastlog(char *user) eprintf("%s: read error:", ARUU_PATH_LASTLOG); /* on glibc `ll_time' can be an int32_t with compat32 - * avoid compiler warning when calling ctime() */ + * avoid compiler warning when calling ctime() */ lltime = ll.ll_time; printf("%-8.8s %-8.8s %-16.16s %s", user, ll.ll_line, ll.ll_host, ctime(&lltime)); } diff --git a/cmd/pseudo/login.c b/cmd/pseudo/login.c @@ -1,138 +0,0 @@ -/* See LICENSE file for copyright and license details. */ - -#include <sys/ioctl.h> -#include <sys/types.h> - -#include <errno.h> -#include <grp.h> -#include <pwd.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <time.h> -#include <unistd.h> -#include <utmp.h> - -#include "config.h" -#include "passwd.h" -#include "util.h" -#include "wexec.h" - -/* Write utmp entry */ -static void -writeutmp(const char *user, const char *tty) -{ - struct utmp usr; - FILE *fp; - - memset(&usr, 0, sizeof(usr)); - - usr.ut_type = USER_PROCESS; - usr.ut_pid = getpid(); - strlcpy(usr.ut_user, user, sizeof(usr.ut_user)); - strlcpy(usr.ut_line, tty, sizeof(usr.ut_line)); - usr.ut_tv.tv_sec = time(NULL); - - fp = fopen(UTMP_PATH, "a"); - if (fp) { - if (fwrite(&usr, sizeof(usr), 1, fp) != 1) - if (ferror(fp)) - weprintf("%s: write error:", UTMP_PATH); - fclose(fp); - } else { - weprintf("fopen %s:", UTMP_PATH); - } -} - -static int -dologin(struct passwd *pw, int preserve) -{ - char *shell = pw->pw_shell[0] == '\0' ? "/bin/sh" : pw->pw_shell; - - if (preserve == 0) - clearenv(); - setenv("HOME", pw->pw_dir, 1); - setenv("SHELL", shell, 1); - setenv("USER", pw->pw_name, 1); - setenv("LOGNAME", pw->pw_name, 1); - setenv("PATH", ENV_PATH, 1); - if (chdir(pw->pw_dir) < 0) - eprintf("chdir %s:", pw->pw_dir); - wexecvp_self(shell, (char *const[]){shell, "-l", NULL}); - weprintf("wexecvp %s:", shell); - return (errno == ENOENT) ? 127 : 126; -} - -static void -usage(void) -{ - eprintf("usage: %s [-p] username\n", argv0); -} - -// ?man login: begin terminal session -// ?man arguments: username -// ?man authenticate and start a session on the system -int -main(int argc, char *argv[]) -{ - struct passwd *pw; - char *pass, *user; - char *tty; - uid_t uid; - gid_t gid; - int pflag = 0; - - ARGBEGIN - { - // ?man -p: preserve file attributes - case 'p': - pflag = 1; - break; - default: - usage(); - } - ARGEND; - - if (argc < 1) - usage(); - - if (isatty(0) == 0 || isatty(1) == 0 || isatty(2) == 0) - eprintf("no tty"); - - user = argv[0]; - errno = 0; - pw = getpwnam(user); - if (!pw) { - if (errno) - eprintf("getpwnam %s:", user); - else - eprintf("who are you?\n"); - } - - uid = pw->pw_uid; - gid = pw->pw_gid; - - /* Flush pending input */ - ioctl(0, TCFLSH, (void *)0); - - pass = getpass("Password: "); - if (!pass) - eprintf("getpass:"); - if (pw_check(pw, pass) <= 0) - exit(1); - - tty = ttyname(0); - if (!tty) - eprintf("ttyname:"); - - writeutmp(user, tty); - - if (initgroups(user, gid) < 0) - eprintf("initgroups:"); - if (setgid(gid) < 0) - eprintf("setgid:"); - if (setuid(uid) < 0) - eprintf("setuid:"); - - return dologin(pw, pflag); -} diff --git a/cmd/pseudo/md5sum.c b/cmd/pseudo/md5sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/mkpasswd.c b/cmd/pseudo/mkpasswd.c @@ -1,138 +0,0 @@ -/* See LICENSE file for copyright and license details. */ -#include "passwd.h" -#include "paths.h" -#include "util.h" - -#include <ctype.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> - -static void -usage(void) -{ - eprintf("usage: %s [-P fd] [-m type] [-S salt] [password] [salt]\n", argv0); -} - -// ?man mkpasswd: encrypt the given password using salt -// ?man arguments: [password] [salt] -// ?man encrypt password using crypt(3) with random or provided salt -int -main(int argc, char *argv[]) -{ - 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/mktemp.c b/cmd/pseudo/mktemp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <libgen.h> #include <stdio.h> diff --git a/cmd/pseudo/nologin.c b/cmd/pseudo/nologin.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <stdio.h> diff --git a/cmd/pseudo/nproc.c b/cmd/pseudo/nproc.c @@ -0,0 +1,41 @@ +/* see LICENSE file for copyright and license details */ + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#include "util.h" + +static void +usage(void) +{ + eprintf("usage: %s [-a]\n", argv0); +} + +// ?man nproc: print the number of available processors +// ?man arguments: [-a] +// ?man with no options, prints the number of processors currently +// ?man online. -a prints the number installed, including any offline +int +main(int argc, char *argv[]) +{ + int aflag = 0; + long n; + + ARGBEGIN + { + // ?man -a: count installed processors, not just online ones + case 'a': + aflag = 1; + break; + default: + usage(); + } + ARGEND; + + n = sysconf(aflag ? _SC_NPROCESSORS_CONF : _SC_NPROCESSORS_ONLN); + if (n <= 0) + n = 1; + printf("%ld\n", n); + return 0; +} diff --git a/cmd/pseudo/pagesize.c b/cmd/pseudo/pagesize.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/pidof.c b/cmd/pseudo/pidof.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/types.h> @@ -99,7 +99,7 @@ main(int argc, char *argv[]) cmd = cmdline; cmdbase = basename(cmdline); } - /* Workaround for login shells */ + /* workaround for login shells */ if (cmd[0] == '-') cmd++; for (i = 0; i < argc; i++) { diff --git a/cmd/pseudo/printenv.c b/cmd/pseudo/printenv.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/pwdx.c b/cmd/pseudo/pwdx.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <limits.h> diff --git a/cmd/pseudo/respawn.c b/cmd/pseudo/respawn.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/time.h> diff --git a/cmd/pseudo/rev.c b/cmd/pseudo/rev.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <string.h> diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/setsid.c b/cmd/pseudo/setsid.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <unistd.h> diff --git a/cmd/pseudo/sha1sum.c b/cmd/pseudo/sha1sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha224sum.c b/cmd/pseudo/sha224sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha256sum.c b/cmd/pseudo/sha256sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha384sum.c b/cmd/pseudo/sha384sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha512-224sum.c b/cmd/pseudo/sha512-224sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha512-256sum.c b/cmd/pseudo/sha512-256sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sha512sum.c b/cmd/pseudo/sha512sum.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> diff --git a/cmd/pseudo/sponge.c b/cmd/pseudo/sponge.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <stdlib.h> diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -630,9 +630,9 @@ sanitize(struct header *h) {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. */ + /* 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++) @@ -706,17 +706,17 @@ xt(int argc, char *argv[], int mode) 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*/ + /* 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 */ + /* 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 - */ + /* 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 != ' ') @@ -734,15 +734,15 @@ xt(int argc, char *argv[], int mode) } fname[size] = '\0'; - /* Non L-like header (eg. pax 'g') is skipped by setting - * q=null */ + /* 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) */ + /* 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]; @@ -750,8 +750,8 @@ xt(int argc, char *argv[], int mode) } q = NULL; - /* If argc > 0 or files_from_cnt > 0 then only extract the - * matching files/dirs */ + /* 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++) { diff --git a/cmd/pseudo/truncate.c b/cmd/pseudo/truncate.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> diff --git a/cmd/pseudo/uptime.c b/cmd/pseudo/uptime.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> diff --git a/cmd/pseudo/watch.c b/cmd/pseudo/watch.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> diff --git a/cmd/pseudo/which.c b/cmd/pseudo/which.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "arg.h" #include "util.h" #include "wexec.h" diff --git a/cmd/pseudo/whoami.c b/cmd/pseudo/whoami.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <pwd.h> diff --git a/cmd/pseudo/xinstall.c b/cmd/pseudo/xinstall.c @@ -1,214 +0,0 @@ -/* See LICENSE file for copyright and license details. */ - -#include <dirent.h> -#include <errno.h> -#include <fcntl.h> -#include <grp.h> -#include <pwd.h> -#include <stdlib.h> -#include <string.h> -#include <sys/stat.h> -#include <sys/wait.h> -#include <unistd.h> - -#include "util.h" - -static int Dflag = 0; -static gid_t group; -static uid_t owner; -static mode_t mode = 0755; - -static void -make_dir(char *dir, int was_missing) -{ - if (!mkdir(dir, was_missing ? 0755 : mode)) { - if (!was_missing && (lchown(dir, owner, group) < 0)) - eprintf("lchmod %s:", dir); - } else if (errno != EEXIST) { - eprintf("mkdir %s:", dir); - } -} - -static void -make_dirs(char *dir, int was_missing) -{ - char *p; - for (p = strchr(dir + (dir[0] == '/'), '/'); p; p = strchr(p + 1, '/')) { - *p = '\0'; - make_dir(dir, was_missing); - *p = '/'; - } - make_dir(dir, was_missing); -} - -static int -install(const char *s1, const char *s2, int depth) -{ - int f1, f2; - - (void)depth; - - if ((f1 = open(s1, O_RDONLY)) < 0) - eprintf("open %s:", s1); - if ((f2 = creat(s2, 0600)) < 0) { - if (unlink(s2) < 0 && errno != ENOENT) - eprintf("unlink %s:", s2); - if ((f2 = creat(s2, 0600)) < 0) - eprintf("creat %s:", s2); - } - if (concat(f1, s1, f2, s2) < 0) - goto fail; - if (fchmod(f2, mode) < 0) { - weprintf("fchmod %s:", s2); - goto fail; - } - if (fchown(f2, owner, group) < 0) { - weprintf("fchown %s:", s2); - goto fail; - } - - close(f1); - close(f2); - - return 0; - -fail: - unlink(s2); - exit(1); -} - -static void -usage(void) -{ - eprintf( - "usage: %s [-g group] [-o owner] [-m mode] (-d dir ... | [-D] " - "(-t dest source ... | source ... dest))\n", - argv0 - ); -} - -// ?man xinstall: copy files and set attributes -// ?man arguments: (-d dir ... | (-t dest source ... | source ... dest)) -// ?man copy files and set their permissions and ownership -int -main(int argc, char *argv[]) -{ - int dflag = 0; - char *gflag = 0; - char *oflag = 0; - char *mflag = 0; - char *tflag = 0; - struct group *gr; - struct passwd *pw; - struct stat st; - char *p; - - ARGBEGIN - { - // ?man -c: print count or perform stdout action - case 'c': - /* no-op for compatibility */ - break; - // ?man -d: specify directory - case 'd': - dflag = 1; - break; - // ?man -D: specify option flag - case 'D': - Dflag = 1; - break; - // ?man -s: silent mode or print summary - case 's': - /* no-op for compatibility */ - break; - // ?man -g:str: specify option flag - case 'g': - gflag = EARGF(usage()); - break; - // ?man -o:str: specify output file - case 'o': - oflag = EARGF(usage()); - break; - // ?man -m:str: specify mode or limit - case 'm': - mflag = EARGF(usage()); - break; - // ?man -t:str: sort or specify timestamp - case 't': - tflag = EARGF(usage()); - break; - default: - usage(); - } - ARGEND - - if (argc < 1 + (!tflag & !dflag) || dflag & (Dflag | !!tflag)) - usage(); - - if (gflag) { - errno = 0; - gr = getgrnam(gflag); - if (gr) { - group = gr->gr_gid; - } else { - if (errno) - eprintf("getgrnam %s:", gflag); - group = estrtonum(gflag, 0, UINT_MAX); - } - } else { - group = getgid(); - } - - if (oflag) { - errno = 0; - pw = getpwnam(oflag); - if (pw) { - owner = pw->pw_uid; - } else { - if (errno) - eprintf("getpwnam %s:", oflag); - owner = estrtonum(oflag, 0, UINT_MAX); - } - } else { - owner = getuid(); - } - - if (mflag) - mode = parsemode(mflag, mode, 0); - - if (dflag) { - for (; *argv; argc--, argv++) - make_dirs(*argv, 0); - return 0; - } - - if (tflag) { - argv = memmove(argv - 1, argv, argc * sizeof(*argv)); - argv[argc++] = tflag; - } - if (tflag || argc > 2) { - if (stat(argv[argc - 1], &st) < 0) { - if ((errno == ENOENT) && Dflag) { - make_dirs(argv[argc - 1], 1); - } else { - eprintf("stat %s:", argv[argc - 1]); - } - } else if (!S_ISDIR(st.st_mode)) { - eprintf("%s: not a directory\n", argv[argc - 1]); - } - } - if (stat(argv[argc - 1], &st) < 0) { - if (errno != ENOENT) - eprintf("stat %s:", argv[argc - 1]); - if (tflag || Dflag || argc > 2) { - if ((p = strrchr(argv[argc - 1], '/')) != NULL) { - *p = '\0'; - make_dirs(argv[argc - 1], 1); - *p = '/'; - } - } - } - enmasse(argc, argv, install); - - return 0; -} diff --git a/cmd/pseudo/yes.c b/cmd/pseudo/yes.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> diff --git a/cmd/xsi/login.c b/cmd/xsi/login.c @@ -0,0 +1,202 @@ +/* see LICENSE file for copyright and license details */ + +#include "config.h" +#include "passwd.h" +#include "util.h" +#include "wexec.h" + +#include <grp.h> +#include <limits.h> +#include <pwd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <termios.h> +#include <time.h> +#include <unistd.h> +#include <utmp.h> + +static void +usage(void) +{ + eprintf("usage: %s [-p name] [-f name]\n", argv0); +} + +/* reads one line of input, echoing it or not, into a reusable static + * buffer. returns null on eof so a hung-up line doesnt loop forever */ +static char * +readline(const char *prompt, int echo) +{ + static char buf[LOGIN_NAME_MAX + 1]; + struct termios old, raw; + int have_old = 0; + size_t n; + + fputs(prompt, stdout); + fflush(stdout); + + if (!echo && tcgetattr(STDIN_FILENO, &old) == 0) { + have_old = 1; + raw = old; + raw.c_lflag &= ~ECHO; + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); + } + + if (!fgets(buf, sizeof(buf), stdin)) { + if (have_old) + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + return NULL; + } + + if (have_old) { + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + fputc('\n', stdout); + } + + n = strlen(buf); + if (n && buf[n - 1] == '\n') + buf[--n] = '\0'; + + return buf; +} + +/* best effort utmp record for the controlling tty: getty already + * cleared any stale entry for this line before exec-ing us. only + * ut_line, ut_name (musl aliases this to ut_user), and ut_time + * (aliased to ut_tv.tv_sec) exist on both linux and bsd utmp + * layouts; ut_type/ut_pid do not exist at all on bsd, so those two + * fields are the one genuinely platform-specific part of this record */ +static void +write_utmp(const char *user) +{ + struct utmp usr; + char *line; + FILE *fp; + + memset(&usr, 0, sizeof(usr)); +#if defined(__linux__) + usr.ut_type = USER_PROCESS; + usr.ut_pid = getpid(); +#endif + line = ttyname(STDIN_FILENO); + if (line) { + if (!strncmp(line, "/dev/", 5)) + line += 5; + strlcpy(usr.ut_line, line, sizeof(usr.ut_line)); + } + strlcpy(usr.ut_name, user, sizeof(usr.ut_name)); + usr.ut_time = time(NULL); + + /* utmp: a live table, so this overwrites/appends the one entry for + * this session */ + fp = fopen(UTMP_PATH, "r+"); + if (fp) { + fseek(fp, 0, SEEK_END); + fwrite(&usr, sizeof(usr), 1, fp); + fclose(fp); + } + + /* wtmp: an ever-growing append-only log of the same record, same + * portable field subset, just opened differently */ + fp = fopen(WTMP_PATH, "a"); + if (fp) { + fwrite(&usr, sizeof(usr), 1, fp); + fclose(fp); + } +} + +// ?man login: authenticate a user and start a session +// ?man arguments: [-p name] [-f name] +// ?man prompt for a username (unless given) and password, verify against +// ?man the system password database, then exec the user's login shell +// ?man invoked by getty with -p name once a username has already been +// ?man typed at the "login:" prompt +int +main(int argc, char *argv[]) +{ + struct passwd *pw; + char namebuf[LOGIN_NAME_MAX + 1]; + char shellbuf[PATH_MAX]; + char *preset = NULL, *trusted = NULL; + char *name, *pass, *line, *base; + char *shargv[2]; + int tries; + + ARGBEGIN + { + // ?man -p:name preset the username; still prompts for a password + case 'p': + preset = EARGF(usage()); + break; + // ?man -f:name log in as name without a password prompt: the + // ?man caller has already authenticated this user out-of-band + case 'f': + trusted = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + + pw_init(); + + if (trusted) { + pw = getpwnam(trusted); + if (!pw) + eprintf("login: unknown user: %s\n", trusted); + } else { + pw = NULL; + for (tries = 0; tries < 3 && !pw; tries++) { + if (preset && tries == 0) { + strlcpy(namebuf, preset, sizeof(namebuf)); + } else { + line = readline("login: ", 1); + if (!line) + exit(1); + strlcpy(namebuf, line, sizeof(namebuf)); + } + name = namebuf; + + pass = readline("Password: ", 0); + if (!pass) + pass = ""; + + pw = getpwnam(name); + if (!pw || pw_check(pw, pass) != 1) { + fputs("Login incorrect\n", stdout); + pw = NULL; + } + } + if (!pw) + exit(1); + } + + if (initgroups(pw->pw_name, pw->pw_gid) < 0) + weprintf("initgroups:"); + if (setgid(pw->pw_gid) < 0) + eprintf("setgid:"); + if (setuid(pw->pw_uid) < 0) + eprintf("setuid:"); + + write_utmp(pw->pw_name); + + if (chdir(pw->pw_dir) < 0) + weprintf("chdir %s:", pw->pw_dir); + + setenv("HOME", pw->pw_dir, 1); + setenv("USER", pw->pw_name, 1); + setenv("LOGNAME", pw->pw_name, 1); + strlcpy(shellbuf, pw->pw_shell[0] ? pw->pw_shell : "/bin/sh", sizeof(shellbuf)); + setenv("SHELL", shellbuf, 1); + + base = strrchr(shellbuf, '/'); + base = base ? base + 1 : shellbuf; + + shargv[0] = emalloc(strlen(base) + 2); + shargv[0][0] = '-'; + strcpy(shargv[0] + 1, base); + shargv[1] = NULL; + + wexecv_self(shellbuf, shargv); + return 1; +} diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/xsi/mkpasswd.c b/cmd/xsi/mkpasswd.c @@ -0,0 +1,79 @@ +/* see LICENSE file for copyright and license details */ +#include "passwd.h" +#include "util.h" + +#include <crypt.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <termios.h> +#include <unistd.h> + +static void +usage(void) +{ + eprintf("usage: %s [password]\n", argv0); +} + +// ?man mkpasswd: generate a crypt(3) password hash +// ?man arguments: [password] +// ?man hash a password for use in /etc/passwd or /etc/shadow. reads +// ?man the password from the command line, or prompts for it if not given +int +main(int argc, char *argv[]) +{ + static char buf[128]; + struct termios old, raw; + char salt[PW_SALT_MAX]; + char *pass, *hash; + int have_old; + size_t n; + + ARGBEGIN + { + default: + usage(); + } + ARGEND + + if (argc > 0) { + pass = argv[0]; + } else { + fputs("Password: ", stdout); + fflush(stdout); + + have_old = tcgetattr(STDIN_FILENO, &old) == 0; + if (have_old) { + raw = old; + raw.c_lflag &= ~ECHO; + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); + } + + if (!fgets(buf, sizeof(buf), stdin)) { + if (have_old) + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + exit(1); + } + + if (have_old) { + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + fputc('\n', stdout); + } + + n = strlen(buf); + if (n && buf[n - 1] == '\n') + buf[--n] = '\0'; + pass = buf; + } + + pw_init(); + if (pw_gensalt(salt, sizeof(salt)) < 0) + eprintf("mkpasswd: cannot generate salt\n"); + + hash = crypt(pass, salt); + if (!hash) + eprintf("mkpasswd: crypt:"); + + printf("%s\n", hash); + return 0; +} diff --git a/cmd/xsi/passwd.c b/cmd/xsi/passwd.c @@ -1,118 +1,168 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "passwd.h" -#include "config.h" -#include "text.h" #include "util.h" -#include <errno.h> +#include <crypt.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <sys/stat.h> +#include <termios.h> #include <unistd.h> static void usage(void) { - eprintf("usage: %s [username]\n", argv0); + eprintf("usage: %s [-l | -u | -d] [name]\n", argv0); } -// ?man passwd: change a user password -// ?man arguments: [username] -// ?man change the password associated with the calling user or with username +/* reads one line with echo off into a reusable static buffer */ +static char * +readpass(const char *prompt) +{ + static char buf[128]; + struct termios old, raw; + int have_old; + size_t n; + + fputs(prompt, stdout); + fflush(stdout); + + have_old = tcgetattr(STDIN_FILENO, &old) == 0; + if (have_old) { + raw = old; + raw.c_lflag &= ~ECHO; + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); + } + + if (!fgets(buf, sizeof(buf), stdin)) { + if (have_old) + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + return NULL; + } + + if (have_old) { + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + fputc('\n', stdout); + } + + n = strlen(buf); + if (n && buf[n - 1] == '\n') + buf[--n] = '\0'; + + return buf; +} + +// ?man passwd: change a user's password +// ?man arguments: [-l | -u | -d] [name] +// ?man change name's password (default: the caller's own), or with -l/-u/-d +// ?man lock, unlock, or clear it instead. only root may target another +// ?man user, or use -l/-u/-d at all int main(int argc, char *argv[]) { - struct pwdb_entry ent; - struct passwd *pw; - char *inpass, *prevhash = NULL, *newhash = NULL, salt[PW_SALT_MAX]; - char *c1, *c2; - int status = 1; + struct pwdb_entry ent; + struct passwd *self, *target; + char *name, *cur, *new1, *new2, *hash; + char salt[PW_SALT_MAX]; + int lflag = 0, uflag = 0, dflag = 0; + uid_t uid; ARGBEGIN { + // ?man -l: lock the account by prefixing its hash with '!' + case 'l': + lflag = 1; + break; + // ?man -u: unlock an account previously locked with -l + case 'u': + uflag = 1; + break; + // ?man -d: clear the password, allowing a blank password login + case 'd': + dflag = 1; + break; default: usage(); } ARGEND + if (lflag + uflag + dflag > 1) + usage(); + + uid = getuid(); + self = getpwuid(uid); + if (!self) + eprintf("passwd: who are you?\n"); + + name = argc > 0 ? argv[0] : self->pw_name; + if (uid != 0 && (strcmp(name, self->pw_name) != 0 || lflag || uflag || dflag)) + eprintf("passwd: permission denied\n"); + + target = getpwnam(name); + if (!target) + eprintf("passwd: unknown user: %s\n", name); + pw_init(); - umask(077); - - if (argc == 0) - pw = getpwuid(getuid()); - else - pw = getpwnam(argv[0]); - if (!pw) { - if (errno) - eprintf("getpwnam: %s:", argv[0]); - else - eprintf("who are you?\n"); - } - if (pwdb_lookup(&ent, pw->pw_name) < 0) - return 1; - prevhash = ent.hash; + if (lflag || uflag || dflag) { + if (pwdb_lookup(&ent, name) < 0) + eprintf("passwd: cannot look up %s\n", name); - if (getuid() != 0) { - if (prevhash[0] == '!' || prevhash[0] == '*') - eprintf("denied\n"); - if (prevhash[0] == '\0') { - /* no password set */ + if (lflag) { + if (ent.hash[0] == '!') { + hash = ent.hash; + } else { + hash = emalloc(strlen(ent.hash) + 2); + hash[0] = '!'; + strcpy(hash + 1, ent.hash); + } + if (pwdb_update(name, hash) < 0) + eprintf("passwd: update failed\n"); + printf("passwd: password for %s locked\n", name); + } else if (uflag) { + hash = ent.hash[0] == '!' ? ent.hash + 1 : ent.hash; + if (pwdb_update(name, hash) < 0) + eprintf("passwd: update failed\n"); + printf("passwd: password for %s unlocked\n", name); } 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 (pwdb_update(name, "") < 0) + eprintf("passwd: update failed\n"); + printf("passwd: password for %s cleared\n", name); } + return 0; } - inpass = getpass("Enter new password: "); - if (!inpass) - eprintf("getpass:"); - if (inpass[0] == '\0') - eprintf("no password supplied\n"); + if (uid != 0) { + cur = readpass("Current password: "); + if (!cur || pw_check(self, cur) != 1) + eprintf("passwd: authentication failed\n"); + } + + new1 = readpass("New password: "); + if (!new1) + exit(1); + new1 = estrdup(new1); - if (prevhash && prevhash[0] != '\0') { - c1 = crypt(inpass, prevhash); - if (c1 && strcmp(c1, prevhash) == 0) - eprintf("password left unchanged\n"); + new2 = readpass("Retype new password: "); + if (!new2 || strcmp(new1, new2) != 0) { + free(new1); + eprintf("passwd: passwords do not match\n"); } + if (new1[0] == '\0') + weprintf("passwd: warning: empty password\n"); 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"); - c2 = crypt(inpass, salt); - if (!c2) - eprintf("crypt:"); - if (strcmp(c2, newhash) != 0) - eprintf("passwords don't match\n"); - explicit_bzero(inpass, strlen(inpass)); - - if (pwdb_update(pw->pw_name, newhash) == 0) - status = 0; - - free(newhash); - free(ent.name); - free(ent.hash); - return status; + eprintf("passwd: cannot generate salt\n"); + + hash = crypt(new1, salt); + free(new1); + if (!hash) + eprintf("passwd: crypt:"); + + if (pwdb_update(name, hash) < 0) + eprintf("passwd: update failed\n"); + + printf("passwd: password for %s updated\n", name); + return 0; } diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c @@ -1,121 +1,128 @@ -/* See LICENSE file for copyright and license details. */ -#include "config.h" +/* see LICENSE file for copyright and license details */ #include "passwd.h" #include "util.h" +#include "wexec.h" -#include <errno.h> #include <grp.h> +#include <limits.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <sys/types.h> +#include <termios.h> #include <unistd.h> -extern char **environ; - -#ifndef ENV_PATH_SHELL -#define ENV_PATH_SHELL "/bin/sh" -#endif - -static int lflag = 0; -static int pflag = 0; - static void usage(void) { - eprintf("usage: %s [-lp] [username]\n", argv0); + eprintf("usage: %s [-l] [name]\n", argv0); } -// ?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 +/* reads one line with echo off into a reusable static buffer */ +static char * +readpass(const char *prompt) +{ + static char buf[128]; + struct termios old, raw; + int have_old; + size_t n; + + fputs(prompt, stdout); + fflush(stdout); + + have_old = tcgetattr(STDIN_FILENO, &old) == 0; + if (have_old) { + raw = old; + raw.c_lflag &= ~ECHO; + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); + } + + if (!fgets(buf, sizeof(buf), stdin)) { + if (have_old) + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + return NULL; + } + + if (have_old) { + tcsetattr(STDIN_FILENO, TCSAFLUSH, &old); + fputc('\n', stdout); + } + + n = strlen(buf); + if (n && buf[n - 1] == '\n') + buf[--n] = '\0'; + + return buf; +} + +// ?man su: become another user +// ?man arguments: [-l] [name] +// ?man authenticate as name (default: root) and start a shell as them +// ?man with -l, also chdir to their home directory and run a login shell, +// ?man same as login would int main(int argc, char *argv[]) { - char *usr, *pass; - char *shell, *envshell, *term; struct passwd *pw; - char *newargv[3]; + char shellbuf[PATH_MAX]; + char *name, *pass, *base; + char *shargv[2]; + int lflag = 0; uid_t uid; ARGBEGIN { + // ?man -l: start a login shell, chdir home like login does case 'l': - // ?man -l: make the shell a login shell lflag = 1; break; - case 'p': - // ?man -p: preserve the current environment - pflag = 1; - break; default: usage(); } ARGEND - if (argc > 1) - usage(); - usr = argc > 0 ? argv[0] : "root"; - - errno = 0; - pw = getpwnam(usr); - if (!pw) { - if (errno) - eprintf("getpwnam: %s:", usr); - else - eprintf("who are you?\n"); - } + name = argc > 0 ? argv[0] : "root"; + pw = getpwnam(name); + if (!pw) + eprintf("su: unknown user: %s\n", name); uid = getuid(); - if (uid) { - pass = getpass("Password: "); - if (!pass) - eprintf("getpass:"); - if (pw_check(pw, pass) <= 0) - exit(1); - explicit_bzero(pass, strlen(pass)); + if (uid != 0) { + pass = readpass("Password: "); + if (!pass || pw_check(pw, pass) != 1) + eprintf("su: incorrect password\n"); } - if (initgroups(usr, pw->pw_gid) < 0) - eprintf("initgroups:"); + if (initgroups(pw->pw_name, pw->pw_gid) < 0) + weprintf("initgroups:"); if (setgid(pw->pw_gid) < 0) eprintf("setgid:"); if (setuid(pw->pw_uid) < 0) eprintf("setuid:"); - shell = pw->pw_shell[0] == '\0' ? ENV_PATH_SHELL : pw->pw_shell; + strlcpy(shellbuf, pw->pw_shell[0] ? pw->pw_shell : "/bin/sh", sizeof(shellbuf)); + if (lflag) { - term = getenv("TERM"); - clearenv(); - setenv("HOME", pw->pw_dir, 1); - setenv("SHELL", shell, 1); - setenv("USER", pw->pw_name, 1); - setenv("LOGNAME", pw->pw_name, 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; - newargv[1] = "-l"; - newargv[2] = NULL; + weprintf("chdir %s:", pw->pw_dir); + setenv("HOME", pw->pw_dir, 1); + } + setenv("USER", pw->pw_name, 1); + setenv("LOGNAME", pw->pw_name, 1); + setenv("SHELL", shellbuf, 1); + + base = strrchr(shellbuf, '/'); + base = base ? base + 1 : shellbuf; + + if (lflag) { + shargv[0] = emalloc(strlen(base) + 2); + shargv[0][0] = '-'; + strcpy(shargv[0] + 1, base); } else { - if (pflag) { - envshell = getenv("SHELL"); - if (envshell && envshell[0] != '\0') - shell = envshell; - } else { - setenv("HOME", pw->pw_dir, 1); - setenv("SHELL", shell, 1); - if (strcmp(pw->pw_name, "root") != 0) { - setenv("USER", pw->pw_name, 1); - setenv("LOGNAME", pw->pw_name, 1); - } - } - newargv[0] = shell; - newargv[1] = NULL; + shargv[0] = estrdup(base); } - execve(shell, newargv, environ); - weprintf("execve %s:", shell); - return (errno == ENOENT) ? 127 : 126; + shargv[1] = NULL; + + wexecv_self(shellbuf, shargv); + return 1; } diff --git a/ninqu.rules b/ninqu.rules @@ -1,8 +1,12 @@ -; genconfig.sh config produces four files from build.cfg: -; config.set (read by ninqu), config.kv (read by mkman), +; genconfig.sh config produces four files from build.cfg in one +; invocation: config.set (read by ninqu), config.kv (read by mkman), ; nofork_list.h (included by wexec.c), and features.h (-included -; into every compile). each gets its own rule so ninqu can find a -; producer for any of them +; into every compile). only CONFIG_SET actually runs the script; +; NOFORK_LIST_H and FEATURES_H depend on its output instead of +; re-running genconfig.sh themselves, so ninja never schedules two +; invocations of the same script concurrently. running it twice in +; parallel raced both invocations' truncate-then-append writes to +; the same files, byte-interleaving their output into invalid C ; (rule CONFIG_SET (out "scripts/mk/config.set") @@ -11,13 +15,13 @@ (rule NOFORK_LIST_H (out "shared/libutil/nofork_list.h") - (dep "build.cfg" "scripts/genconfig.sh") - (exec sh scripts/genconfig.sh config)) + (dep "scripts/mk/config.set") + (exec true)) (rule FEATURES_H (out "scripts/mk/features.h") - (dep "build.cfg" "scripts/genconfig.sh") - (exec sh scripts/genconfig.sh config)) + (dep "scripts/mk/config.set") + (exec true)) (set-file "scripts/mk/config.set") @@ -29,125 +33,159 @@ (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libutf $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule LIBUTF + (rule LIBUTF (dep LIBUTF_OBJ) (out "shared/libutf/libutf.a") (description "utf-8 and rune handling, linked into every aruu tool") (feature core-lib) (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) -(rule LIBUTIL_OBJ + (rule LIBUTIL_OBJ (glob "shared/libutil/*.c") (dep $(MATCH)) (after NOFORK_LIST_H FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS_LIBUTIL) -Ishared/libutil $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule LIBUTIL + (rule LIBUTIL (dep LIBUTIL_OBJ) (out "shared/libutil/libutil.a") (description "allocation, error reporting, and string helpers shared by every tool") (feature core-lib) (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) -(rule LIBREDLINE_OBJ + (rule LIBREDLINE_OBJ (glob "shared/libredline/*.c") (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libredline $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule LIBREDLINE + (rule LIBREDLINE (dep LIBREDLINE_OBJ) (out "shared/libredline/libredline.a") (description "line editing used by sh and any other interactive tool") (feature core-lib) (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) -(group lib LIBUTF LIBUTIL LIBREDLINE) + (rule LIBBLAKE3_OBJ + (glob "shared/libblake3/*.c") + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Ishared/libblake3 $(CFLAGS) -c -o $(OUT) $(MATCH))) -; perfile: every *.c directly inside one of these dirs becomes its -; own binary of the same name, individually gated by -; build_<category>_<ident> (lowercase, hyphens and dots turned to -; underscores, see the $(IDENT) comment above BOX_OBJ below for why) -; (skip) excludes files that belong to a multi-file tool below instead -; -(map EXTRA_LIBS - (diff "-lm") - (wget $(LDLIBS_TLS))) + (rule LIBBLAKE3 + (dep LIBBLAKE3_OBJ) + (out "shared/libblake3/libblake3.a") + (description "the BLAKE3 hash algorithm, linked into b3sum, not embedded in it") + (feature core-lib) + (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) -; Every .c file in a category builds into its own binary. (PERFILE) -; Only EXTRA_AFTER differs cuz POSIX waits for GETCONF_H, the rest pass "". -; cmd/posix/bc.c overrides this with its own yacc-based rule, so no need for -; PERFILE to have that as a special case -; -(template PERFILE (NAME CATEGORY DESC EXTRA_AFTER) + (group lib LIBUTF LIBUTIL LIBREDLINE LIBBLAKE3) + + ; perfile: every *.c directly inside one of these dirs becomes its + ; own binary of the same name, individually gated by + ; build_<category>_<ident> (lowercase, hyphens and dots turned to + ; underscores, see the $(IDENT) comment above BOX_OBJ below for why) + ; (skip) excludes files that belong to a multi-file tool below instead + ; + ; -lcrypt and -lresolv used to be blanket LDLIBS entries, linked into + ; every single utility whether it called crypt(3)/resolver functions + ; or not. tracing real callers of shared/libutil/passwd.c's pw_check/ + ; pw_gensalt (not just direct crypt() calls) turns up exactly four: + ; passwd, mkpasswd, login, su need -lcrypt; host needs -lresolv + ; narrowing this here, not just for tidiness, is what makes aruu + ; buildable on a host whose libc ships a static libresolv/libm but no + ; static libcrypt. b3sum is the one EXTRA_BIN file with its own extra + ; library dependency for a different reason: BLAKE3 used to be + ; implemented inline in b3sum.c itself, which meant anything else + ; that wanted the same algorithm (ports/pkgtools/libpkg, for hashing + ; package archives) had no real library to link against and carried + ; its own separate copy instead, with no way to notice the two had + ; drifted until one of them turned out to have a bug the other one + ; didn't. shared/libblake3 exists so there is exactly one copy + (map EXTRA_LIBS + (diff "-lm") + (wget $(LDLIBS_TLS)) + (passwd "-lcrypt") + (mkpasswd "-lcrypt") + (login "-lcrypt") + (su "-lcrypt") + (host "-lresolv") + (b3sum "-Lshared/libblake3 -lblake3")) + + ; every .c file in a category builds into its own binary. (PERFILE) + ; only EXTRA_AFTER differs cuz POSIX waits for GETCONF_H, the rest pass "" + ; cmd/posix/bc.c overrides this with its own yacc-based rule, so no need for + ; PERFILE to have that as a special case + ; + (template PERFILE (NAME CATEGORY DESC EXTRA_AFTER) (rule $(NAME) (glob "cmd/$(CATEGORY)/*.c") - (gate build_$(CATEGORY)_$(IDENT)) - (dep $(MATCH) LIBUTIL LIBUTF) - (after $(EXTRA_AFTER)) - (out $(STEM)) - (description $(DESC)) - (feature perfile) - (exec $(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) $(EXTRA_LIBS:$(BASESTEM))))) - -(use PERFILE POSIX_BIN posix "one POSIX2024 utility per source file under cmd/posix" GETCONF_H) -(use PERFILE LINUX_BIN linux "Linux-only utility, one source file per binary under cmd/linux" "") -(use PERFILE NET_BIN net "networking utility, one source file per binary under cmd/net" "") -(use PERFILE XSI_BIN xsi "XSI-specified utility, one source file per binary under cmd/xsi" "") -(use PERFILE PSEUDO_BIN pseudo "common but undefined utility, one source file per binary under cmd/pseudo" "") -(use PERFILE EXTRA_BIN extra "extra utility outside POSIX/XSI scope, one source file per binary under cmd/extra" "") - -(group posix lib POSIX_BIN POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE) -(group linux lib LINUX_BIN) -(group net lib NET_BIN) -(group xsi lib XSI_BIN) -(group pseudo lib PSEUDO_BIN) -(group extra lib EXTRA_BIN EXTRA_YAP) - -; codegen: generate sources consumed by the build rules below. Ungated -; ones always run. conditional ones use (req) so they only run when -; their inputs exists in this checkout -; -(rule GETCONF_H + (gate build_$(CATEGORY)_$(IDENT)) + (dep $(MATCH) LIBUTIL LIBUTF LIBBLAKE3) + (after $(EXTRA_AFTER)) + (out $(STEM)) + (description $(DESC)) + (feature perfile) + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) $(EXTRA_LIBS:$(BASESTEM))))) + + (use PERFILE POSIX_BIN posix "one POSIX2024 utility per source file under cmd/posix" GETCONF_H) + (use PERFILE LINUX_BIN linux "linux-only utility, one source file per binary under cmd/linux" "") + (use PERFILE NET_BIN net "networking utility, one source file per binary under cmd/net" "") + (use PERFILE XSI_BIN xsi "xsi-specified utility, one source file per binary under cmd/xsi" "") + (use PERFILE PSEUDO_BIN pseudo "common but undefined utility, one source file per binary under cmd/pseudo" "") + (use PERFILE EXTRA_BIN extra "extra utility outside POSIX/XSI scope, one source file per binary under cmd/extra" "") + + (group posix lib POSIX_BIN POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE) + (group linux lib LINUX_BIN) + (group net lib NET_BIN) + (group xsi lib XSI_BIN) + (group pseudo lib PSEUDO_BIN) + (group extra lib EXTRA_BIN EXTRA_YAP) + + ; codegen: generate sources consumed by the build rules below. ungated + ; ones always run. conditional ones use (req) so they only run when + ; their inputs exists in this checkout + ; + (rule GETCONF_H (gate build_posix_getconf) (out "cmd/posix/getconf.h") (dep "scripts/getconf.sh") (exec sh scripts/genconfig.sh getconf)) -(rule POSIX_BC_C + (rule POSIX_BC_C (gate build_posix_bc) (req "cmd/posix/bc.y") (out "cmd/posix/bc.c") (dep "cmd/posix/bc.y") (exec sh scripts/genconfig.sh bc)) -(rule POSIX_AWK_C + (rule POSIX_AWK_C (gate build_posix_awk) (out "cmd/posix/awk/awkgram.tab.c") (dep "cmd/posix/awk/awkgram.y") (exec sh scripts/genconfig.sh awk)) -(rule POSIX_SH_C + (rule POSIX_SH_C (gate build_posix_sh) (out "cmd/posix/sh/syntax.c") (dep "cmd/posix/sh/mksyntax.c" "cmd/posix/sh/mknodes.c" "cmd/posix/sh/mkbuiltins" "cmd/posix/sh/mktokens") (exec sh scripts/genconfig.sh sh)) -(rule DEVCONF + (rule DEVCONF (req "cmd/dev/configure") (out "cmd/dev/config.h") (dep "cmd/dev/configure") (phony) (exec sh cmd/dev/configure)) -(group codegen GETCONF_H POSIX_BC_C POSIX_AWK_C POSIX_SH_C DEVCONF) + (group codegen GETCONF_H POSIX_BC_C POSIX_AWK_C POSIX_SH_C DEVCONF) -; multi: one binary from all .c files in one or more dirs (minus skip). -; codegen must run first so generated sources are present before these -; globs collect them -; -(rule POSIX_BC_OBJ + ; multi: one binary from all .c files in one or more dirs (minus skip) + ; codegen must run first so generated sources are present before these + ; globs collect them + ; + (rule POSIX_BC_OBJ (glob "cmd/posix/bc.c") (gate build_posix_bc) (dep $(MATCH)) @@ -155,14 +193,14 @@ (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_BC + (rule POSIX_BC (gate build_posix_bc) (member posix bc) (dep POSIX_BC_OBJ LIBUTIL LIBUTF) (out "cmd/posix/bc") (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) -lm)) -(rule POSIX_AWK_OBJ + (rule POSIX_AWK_OBJ (glob "cmd/posix/awk/*.c") (gate build_posix_awk) (skip "maketab.c") @@ -171,14 +209,14 @@ (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_AWK + (rule POSIX_AWK (gate build_posix_awk) (member posix awk) (dep POSIX_AWK_OBJ LIBUTIL LIBUTF) (out "cmd/posix/awk/awk") (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) -lm)) -(rule POSIX_SH_OBJ + (rule POSIX_SH_OBJ (glob "cmd/posix/sh/*.c") (gate build_posix_sh) (skip "mknodes.c" "mksyntax.c") @@ -187,50 +225,50 @@ (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_SH + (rule POSIX_SH (gate build_posix_sh) (member posix sh) (dep POSIX_SH_OBJ LIBUTIL LIBUTF LIBREDLINE) (out "cmd/posix/sh/sh") (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) -(rule POSIX_MAKE_OBJ + (rule POSIX_MAKE_OBJ (glob "cmd/posix/make/*.c") (gate build_posix_make) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_MAKE + (rule POSIX_MAKE (gate build_posix_make) (member posix make) (dep POSIX_MAKE_OBJ LIBUTIL LIBUTF) (out "cmd/posix/make/make") (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) -(rule EXTRA_YAP_OBJ + (rule EXTRA_YAP_OBJ (glob "cmd/extra/yap/*.c") (gate build_extra_yap) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule EXTRA_YAP + (rule EXTRA_YAP (gate build_extra_yap) (member extra yap) (dep EXTRA_YAP_OBJ LIBUTIL LIBUTF) (out "cmd/extra/yap/yap") (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) -ltinfo)) -; (member GROUP ALIAS) gives a rule a qualified user-facing name -; (e.g. posix/bc) while keeping its internal name (POSIX_BC) for deps, -; gates, and other references -; + ; (member GROUP ALIAS) gives a rule a qualified user-facing name + ; (e.g. posix/bc) while keeping its internal name (POSIX_BC) for deps, + ; gates, and other references + ; -; dev: the aruu toolchain. ar/as/ld are standalone and cc -; shares one object pool linked into three frontends -; -(rule AR_OBJ + ; dev: the aruu toolchain. ar/as/ld are standalone and cc + ; shares one object pool linked into three frontends + ; + (rule AR_OBJ (glob "cmd/dev/ar/*.c") (gate build_dev_ar) (skip "tinyar.c") @@ -238,100 +276,113 @@ (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/ar $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule AR + (rule AR (gate build_dev_ar) (dep AR_OBJ LIBUTIL LIBUTF) + ; static: these tools run inside whatever rootfs they target via + ; nac, not just the host that built them, and never need the + ; project-wide LDLIBS default (openssl, unused by any of them) (out "cmd/dev/ar/ar") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -(rule XCUTIL_OBJ - (glob "cmd/dev/xcutil/*.c") + (rule TCUTIL_OBJ + (glob "shared/libtcutil/*.c" "shared/libtcutil/elf/*.c" "shared/libtcutil/ar/*.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") - (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil $(CFLAGS) -c -o $(OUT) $(MATCH))) + (exec $(CC) $(CPPFLAGS) -Ishared/libtcutil -Ishared/libtcutil/elf -Ishared/libtcutil/ar -Icmd/dev $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule AS_OBJ + (rule AS_OBJ (glob "cmd/dev/as/*.c" "cmd/dev/as/arch/x64/*.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") - (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil -Icmd/dev/as -Icmd/dev/as/arch/x64 -Ishared $(CFLAGS) -c -o $(OUT) $(MATCH))) + (exec $(CC) $(CPPFLAGS) -Ishared/libtcutil -Ishared/libtcutil/elf -Ishared/libtcutil/ar -Icmd/dev -Icmd/dev/as -Icmd/dev/as/arch/x64 -Ishared $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule AS + (rule AS (gate build_dev_cc) - (dep AS_OBJ LIBUTIL LIBUTF) - (after XCUTIL_OBJ) + (dep AS_OBJ TCUTIL_OBJ LIBUTIL LIBUTF) (out "cmd/dev/as/as") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -(rule LD_OBJ - (glob "cmd/dev/ld/*.c") + (rule LD_OBJ + (glob "cmd/dev/ld/*.c" "cmd/dev/ld/arch/*/*.c") (gate build_dev_ld) (dep $(MATCH)) (out "$(STEM).o") - (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil -Icmd/dev/ld $(CFLAGS) -c -o $(OUT) $(MATCH))) + (exec $(CC) $(CPPFLAGS) -Icmd/dev/ld $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule LD + (rule LD (gate build_dev_ld) (dep LD_OBJ LIBUTIL LIBUTF) - (after XCUTIL_OBJ) (out "cmd/dev/ld/ld") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -; CCPOOL_OBJ globs the whole directory. The entry points below use -; literal globs, so the override excludes them automatically -(rule CCPOOL_OBJ + ; CCPOOL_OBJ globs the whole directory. the entry points below use + ; literal globs, so the override excludes them automatically + (rule CCPOOL_OBJ (glob "cmd/dev/cc/*.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule CC1_OBJ + (rule CC1_OBJ (glob "cmd/dev/cc/cc1.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule CC1 + ; util.c is its own rule, not folded into CCPOOL_OBJ's wildcard or + ; CCDRV_OBJ's own glob: cc1, cpp, and cc (the driver) all call its + ; helpers (fatal, xmalloc, arrayadd, ...), but only cc has its own + ; main(), so driver.c cannot be a shared link input the other two + ; binaries pull in too + (rule UTIL_OBJ + (glob "cmd/dev/cc/util.c") (gate build_dev_cc) - (dep CC1_OBJ CCPOOL_OBJ LIBUTIL LIBUTF) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + + (rule CC1 + (gate build_dev_cc) + (dep CC1_OBJ CCPOOL_OBJ UTIL_OBJ LIBUTIL LIBUTF) (out "cmd/dev/cc/cc1") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -(rule CPP_OBJ + (rule CPP_OBJ (glob "cmd/dev/cc/cpp.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule CPP + (rule CPP (gate build_dev_cc) - (dep CPP_OBJ CCPOOL_OBJ LIBUTIL LIBUTF) + (dep CPP_OBJ CCPOOL_OBJ UTIL_OBJ LIBUTIL LIBUTF) (out "cmd/dev/cc/cpp") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -(rule CCDRV_OBJ - (glob "cmd/dev/cc/driver.c" "cmd/dev/cc/util.c") + (rule CCDRV_OBJ + (glob "cmd/dev/cc/driver.c") (gate build_dev_cc) (dep $(MATCH)) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule CCDRV + (rule CCDRV (gate build_dev_cc) - (dep CCDRV_OBJ LIBUTIL LIBUTF) + (dep CCDRV_OBJ UTIL_OBJ LIBUTIL LIBUTF) (out "cmd/dev/cc/cc") - (exec $(CC) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS))) + (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) -; Like BOX_OBJ: rename main and hide other globals so ninqu can link -; into aruu-box. It is still not reentrant, so it stays out of -; NOFORK_LIST -; -(rule NINQU_BOX_OBJ + ; like BOX_OBJ: rename main and hide other globals so ninqu can link + ; into aruu-box. it is still not reentrant, so it stays out of + ; NOFORK_LIST + ; + (rule NINQU_BOX_OBJ (glob "cmd/dev/ninqu/*.c") (gate build_dev_ninqu) (dep $(MATCH)) @@ -341,17 +392,17 @@ (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH) && sym=`echo $(BASESTEM) | tr '.-' '__'`_main && $(OBJCOPY) --redefine-sym main=$sym $(OUT) && $(OBJCOPY) --keep-global-symbol=$sym $(OUT)") (group box)) -(group dev lib DEVCONF AR AS LD CC1 CPP CCDRV) + (group dev lib DEVCONF AR AS LD CC1 CPP CCDRV) -; man pages: build mdoc and text pages from ?man-marked sources -; -(rule MKMAN + ; man pages: build mdoc and text pages from ?man-marked sources + ; + (rule MKMAN (dir "scripts/mkman") (dep "glob:scripts/mkman/*.go") (out "scripts/mkman/mkman") (exec go build -o mkman .)) -(rule MAN_MDOC + (rule MAN_MDOC (glob "cmd/**/*.c") (mark "?man") (dep (after MKMAN)) @@ -359,7 +410,7 @@ (exec scripts/mkman/mkman -fmt mdoc -config scripts/mk/config.kv $(MATCH)) (redirect)) -(rule MAN_TXT + (rule MAN_TXT (glob "cmd/**/*.c") (mark "?man") (dep (after MKMAN)) @@ -367,7 +418,7 @@ (exec scripts/mkman/mkman -fmt txt -config scripts/mk/config.kv $(MATCH)) (redirect)) -(map SEC_OF + (map SEC_OF (cmd/posix 1) (cmd/linux 8) (cmd/net 8) @@ -376,64 +427,116 @@ (cmd/extra 1) (cmd/dev 1)) -(group man MAN_MDOC MAN_TXT) + (group man MAN_MDOC MAN_TXT) -(rule CLEAN + (rule CLEAN (phony) (shell " - printf ' CLEAN object files\n' - find shared cmd -name '*.o' -exec rm -f {} + + 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 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 compiled binaries\n' + find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} + - sh scripts/genconfig.sh clean - rm -f scripts/mk/config.mk scripts/mk/config.kv scripts/mk/rules.mk shared/libutil/nofork_list.h + sh scripts/genconfig.sh clean + rm -f scripts/mk/config.mk scripts/mk/config.kv scripts/mk/rules.mk shared/libutil/nofork_list.h - printf ' CLEAN build tools\n' - rm -f scripts/mkman/mkman + printf ' CLEAN build tools\n' + 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 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 - rm -rf .ninja_log .ninja_deps + printf ' CLEAN misc\n' + rm -rf man/man1 man/man8 + rm -rf aruu-box .box + rm -rf .ninja_log .ninja_deps - printf ' CLEAN done\n' + printf ' CLEAN done\n' ")) -(group clean CLEAN) + (group clean CLEAN) -; install every built executable and generated man page -(rule INSTALL + ; install every built executable and generated man page, plus + ; shared/libutil itself as a real linkable library: other MICE + ; components (ports/pkgtools, nac) should link against this, not carry + ; their own copy of ealloc/eprintf/wexec/etc alongside it + (rule INSTALL (phony) - (after ALL_BINS MAN_MDOC MAN_TXT) + (after ALL_BINS LIBUTIL MAN_MDOC MAN_TXT) (shell " - mkdir -p \"$(PREFIX)/bin\" \"$(MANPREFIX)/man1\" \"$(MANPREFIX)/man8\" + d=\"${DESTDIR:-}$(PREFIX)\" + m=\"${DESTDIR:-}$(MANPREFIX)\" + mkdir -p \"$d/bin\" \"$m/man1\" \"$m/man8\" \"$d/lib\" \"$d/include/aruu\" - find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do - name=${bin##*/} + find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do + name=${bin##*/} printf ' INSTALL %s/bin/%s\n' '$(PREFIX)' \"$name\" - cp \"$bin\" \"$(PREFIX)/bin/$name\" - chmod 755 \"$(PREFIX)/bin/$name\" + cp \"$bin\" \"$d/bin/$name\" + chmod 755 \"$d/bin/$name\" done find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do sec=${f%/*}; sec=${sec##*/} name=${f##*/} - cp \"$f\" \"$(MANPREFIX)/$sec/$name\" + cp \"$f\" \"$m/$sec/$name\" + done + + printf ' INSTALL %s/lib/libaruu.a\n' '$(PREFIX)' + cp shared/libutil/libutil.a \"$d/lib/libaruu.a\" + chmod 644 \"$d/lib/libaruu.a\" + for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h; do + printf ' INSTALL %s/include/aruu/%s\n' '$(PREFIX)' \"${h##*/}\" + cp \"$h\" \"$d/include/aruu/${h##*/}\" + chmod 644 \"$d/include/aruu/${h##*/}\" done ")) (group install INSTALL) +; same body as INSTALL, minus the dev (compiler toolchain) category: +; what a MICE port needs to put a shell and coreutils on a rootfs, +; not a hard dependency on the separate, not-yet-portable dev build +(rule INSTALL_BASE + (phony) + (after POSIX_BIN LINUX_BIN NET_BIN XSI_BIN PSEUDO_BIN EXTRA_BIN + POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE EXTRA_YAP + LIBUTIL MAN_MDOC MAN_TXT) + (shell " + d=\"${DESTDIR:-}$(PREFIX)\" + m=\"${DESTDIR:-}$(MANPREFIX)\" + mkdir -p \"$d/bin\" \"$m/man1\" \"$m/man8\" \"$d/lib\" \"$d/include/aruu\" + + find cmd -type f ! -name '*.*' -perm -100 ! -path 'cmd/dev/*' | while read -r bin; do + name=${bin##*/} + printf ' INSTALL %s/bin/%s\n' '$(PREFIX)' \"$name\" + cp \"$bin\" \"$d/bin/$name\" + chmod 755 \"$d/bin/$name\" + done + + find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do + sec=${f%/*}; sec=${sec##*/} + name=${f##*/} + cp \"$f\" \"$m/$sec/$name\" + done + + printf ' INSTALL %s/lib/libaruu.a\n' '$(PREFIX)' + cp shared/libutil/libutil.a \"$d/lib/libaruu.a\" + chmod 644 \"$d/lib/libaruu.a\" + for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h; do + printf ' INSTALL %s/include/aruu/%s\n' '$(PREFIX)' \"${h##*/}\" + cp \"$h\" \"$d/include/aruu/${h##*/}\" + chmod 644 \"$d/include/aruu/${h##*/}\" + done + ")) + +(group install-base INSTALL_BASE) + ; remove exactly what install would have copied (rule REMOVE (phony) @@ -450,6 +553,14 @@ printf ' REMOVE %s/%s/%s\n' '$(MANPREFIX)' \"$sec\" \"$name\" rm -f \"$(MANPREFIX)/$sec/$name\" done + + printf ' REMOVE %s/lib/libaruu.a\n' '$(PREFIX)' + rm -f \"$(PREFIX)/lib/libaruu.a\" + for h in util.h wexec.h arg.h compat.h; do + printf ' REMOVE %s/include/aruu/%s\n' '$(PREFIX)' \"$h\" + rm -f \"$(PREFIX)/include/aruu/$h\" + done + rmdir \"$(PREFIX)/include/aruu\" 2>/dev/null || : ")) (group remove REMOVE) @@ -464,62 +575,62 @@ ! -path 'cmd/posix/sh/*' \ ! -path 'cmd/posix/make/*' \ ! -path 'cmd/extra/yap/*' \ - ! -path 'cmd/posix/bc.c' \ - -print | xargs -r clang-format -i + ! -path 'cmd/posix/bc.c' \ + -print | xargs -r clang-format -i ")) -(rule FMT_ALL + (rule FMT_ALL (phony) (shell " - printf ' FMT cmd and shared (including dir tools)\n' - find cmd shared -type f \( -name '*.c' -o -name '*.h' \) -print \ - | xargs -r clang-format -i + printf ' FMT cmd and shared (including dir tools)\n' + find cmd shared -type f \( -name '*.c' -o -name '*.h' \) -print \ + | xargs -r clang-format -i ")) -(group fmt FMT) -(group fmt-all FMT_ALL) - -; box: one executable containing every enabled tool, dispatched through -; a table. a single-file tool just gets its main renamed by BOX_OBJ. -; multi-file tools (POSIX_BC, POSIX_AWK, POSIX_SH, POSIX_MAKE, EXTRA_YAP) -; go through a partial link (ld -r) first, merging their objects into -; one before main gets renamed and helper symbols hidden. replaces -; scripts/mkbox -; -; object files live under .box/, mirroring the cmd/ layout -; -; Ninqu determines which tools enter the box using the gate on BOX_OBJ. -; BOX_DISPATCH reads the object paths passed on argv rather than consulting -; build.cfg or config.set directly -; - -; CATEGORY_OF maps a directory path to its category name, matching the toggles -; in build.cfg. Since BOX_OBJ globs multiple directories, its gate evaluates the -; category dynamically based on the match directory -; -; Gates evaluate $(IDENT) instead of $(BASESTEM) because toggle names must be -; valid shell variables. Genconfig.sh replaces hyphens and periods with -; underscores, and $(IDENT) applies the same normalization so they match -; -(map CATEGORY_OF - (cmd/posix posix) - (cmd/linux linux) - (cmd/net net) + (group fmt FMT) + (group fmt-all FMT_ALL) + + ; box: one executable containing every enabled tool, dispatched through + ; a table. a single-file tool just gets its main renamed by BOX_OBJ + ; multi-file tools (POSIX_BC, POSIX_AWK, POSIX_SH, POSIX_MAKE, EXTRA_YAP) + ; go through a partial link (ld -r) first, merging their objects into + ; one before main gets renamed and helper symbols hidden. replaces + ; scripts/mkbox + ; + ; object files live under .box/, mirroring the cmd/ layout + ; + ; ninqu determines which tools enter the box using the gate on BOX_OBJ + ; BOX_DISPATCH reads the object paths passed on argv rather than consulting + ; build.cfg or config.set directly + ; + + ; CATEGORY_OF maps a directory path to its category name, matching the toggles + ; in build.cfg. since BOX_OBJ globs multiple directories, its gate evaluates the + ; category dynamically based on the match directory + ; + ; gates evaluate $(IDENT) instead of $(BASESTEM) because toggle names must be + ; valid shell variables. genconfig.sh replaces hyphens and periods with + ; underscores, and $(IDENT) applies the same normalization so they match + ; + (map CATEGORY_OF + (cmd/posix posix) + (cmd/linux linux) + (cmd/net net) (cmd/pseudo pseudo) - (cmd/xsi xsi) - (cmd/extra extra)) - -; Tool basestems match their C symbols using a shell transform (tr '.-' '__' -; and appending _main) in both the objcopy step and in genbox.sh. A static map -; is unnecessary because no current tools require custom overrides, and -; genbox.sh only receives paths via argv -; - -; the match directory picks the gate and output path, so one rule covers -; all six categories. bc.c inside cmd/posix is excluded automatically by -; the literal-glob override mechanism -; -(rule BOX_OBJ + (cmd/xsi xsi) + (cmd/extra extra)) + + ; tool basestems match their c symbols using a shell transform (tr '.-' '__' + ; and appending _main) in both the objcopy step and in genbox.sh. a static map + ; is unnecessary because no current tools require custom overrides, and + ; genbox.sh only receives paths via argv + ; + + ; the match directory picks the gate and output path, so one rule covers + ; all six categories. bc.c inside cmd/posix is excluded automatically by + ; the literal-glob override mechanism + ; + (rule BOX_OBJ (glob "cmd/posix/*.c" "cmd/linux/*.c" "cmd/net/*.c" "cmd/pseudo/*.c" "cmd/xsi/*.c" "cmd/extra/*.c") (gate build_$(CATEGORY_OF:$(DIR))_$(IDENT)) @@ -530,15 +641,15 @@ (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH) && sym=`echo $(BASESTEM) | tr '.-' '__'`_main && $(OBJCOPY) --redefine-sym main=$sym $(OUT) && $(OBJCOPY) --keep-global-symbol=$sym $(OUT)") (group box)) -; POSIX_BC, POSIX_AWK, POSIX_SH, POSIX_MAKE, and EXTRA_YAP cant go through -; the single-file objcopy step, their global helper symbols would collide -; once linked into one binary. a partial link (ld -r) resolves those -; internal references first, then main gets renamed and the rest hidden -; -; Combined objects use the layout .box/cmd/<category>/<tool>.o so genbox.sh -; can parse them without structural modifications -; -(rule POSIX_BC_BOX_OBJ + ; POSIX_BC, POSIX_AWK, POSIX_SH, POSIX_MAKE, and EXTRA_YAP cant go through + ; the single-file objcopy step, their global helper symbols would collide + ; once linked into one binary. a partial link (ld -r) resolves those + ; internal references first, then main gets renamed and the rest hidden + ; + ; combined objects use the layout .box/cmd/<category>/<tool>.o so genbox.sh + ; can parse them without structural modifications + ; + (rule POSIX_BC_BOX_OBJ (glob "cmd/posix/bc.c") (gate build_posix_bc) (dep $(MATCH)) @@ -546,7 +657,7 @@ (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_BC_BOX + (rule POSIX_BC_BOX (gate build_posix_bc) (dep POSIX_BC_BOX_OBJ) (out ".box/cmd/posix/bc.o") @@ -554,7 +665,7 @@ (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=bc_main $(OUT) && $(OBJCOPY) --keep-global-symbol=bc_main $(OUT)") (group box)) -(rule POSIX_AWK_BOX_OBJ + (rule POSIX_AWK_BOX_OBJ (glob "cmd/posix/awk/*.c") (gate build_posix_awk) (skip "maketab.c") @@ -563,7 +674,7 @@ (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_AWK_BOX + (rule POSIX_AWK_BOX (gate build_posix_awk) (dep POSIX_AWK_BOX_OBJ) (out ".box/cmd/posix/awk.o") @@ -571,7 +682,7 @@ (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=awk_main $(OUT) && $(OBJCOPY) --keep-global-symbol=awk_main $(OUT)") (group box)) -(rule POSIX_SH_BOX_OBJ + (rule POSIX_SH_BOX_OBJ (glob "cmd/posix/sh/*.c") (gate build_posix_sh) (skip "mknodes.c" "mksyntax.c") @@ -580,7 +691,7 @@ (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_SH_BOX + (rule POSIX_SH_BOX (gate build_posix_sh) (dep POSIX_SH_BOX_OBJ) (out ".box/cmd/posix/sh.o") @@ -588,14 +699,14 @@ (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=sh_main $(OUT) && $(OBJCOPY) --keep-global-symbol=sh_main $(OUT)") (group box)) -(rule POSIX_MAKE_BOX_OBJ + (rule POSIX_MAKE_BOX_OBJ (glob "cmd/posix/make/*.c") (gate build_posix_make) (dep $(MATCH)) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule POSIX_MAKE_BOX + (rule POSIX_MAKE_BOX (gate build_posix_make) (dep POSIX_MAKE_BOX_OBJ) (out ".box/cmd/posix/make.o") @@ -603,14 +714,14 @@ (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=make_main $(OUT) && $(OBJCOPY) --keep-global-symbol=make_main $(OUT)") (group box)) -(rule EXTRA_YAP_BOX_OBJ + (rule EXTRA_YAP_BOX_OBJ (glob "cmd/extra/yap/*.c") (gate build_extra_yap) (dep $(MATCH)) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) -(rule EXTRA_YAP_BOX + (rule EXTRA_YAP_BOX (gate build_extra_yap) (dep EXTRA_YAP_BOX_OBJ) (out ".box/cmd/extra/yap.o") @@ -618,11 +729,11 @@ (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=yap_main $(OUT) && $(OBJCOPY) --keep-global-symbol=yap_main $(OUT)") (group box)) -; Genbox.sh relies on arguments passed by ninqu, where each argument matches -; an output from BOX_OBJ or a custom box rule. The script derives categories -; and tool names directly from these paths and outputs the dispatch code -; -(rule BOX_DISPATCH + ; genbox.sh relies on arguments passed by ninqu, where each argument matches + ; an output from BOX_OBJ or a custom box rule. the script derives categories + ; and tool names directly from these paths and outputs the dispatch code + ; + (rule BOX_DISPATCH (dep BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX_OBJ) (out ".box/aruu-box.c") (description "dispatch table and main() for aruu-box, generated from the enabled tool list") @@ -630,49 +741,49 @@ (redirect) (group box)) -; Libm is linked unconditionally because bc requires it, and unused library -; references are safe. Modern toolchains omit unreferenced archive components. -; Yap requires terminfo, which is an optional system dependency. Linking it -; unconditionally breaks builds on systems without ncurses-dev when yap is -; disabled. Genconfig.sh exports BOX_EXTRA_LIBS as "-ltinfo" or an empty string -; based on whether yap is enabled -; -(rule BOX + ; libm is linked unconditionally because bc requires it, and unused library + ; references are safe. modern toolchains omit unreferenced archive components + ; yap requires terminfo, which is an optional system dependency. linking it + ; unconditionally breaks builds on systems without ncurses-dev when yap is + ; disabled. genconfig.sh exports BOX_EXTRA_LIBS as "-ltinfo" or an empty string + ; based on whether yap is enabled + ; + (rule BOX (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX_OBJ LIBUTIL LIBUTF LIBREDLINE) (out "aruu-box") (description "single multi-call binary, one dispatch table for every enabled tool") (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) $(BOX_EXTRA_LIBS)") (group box)) -(group box BOX) + (group box BOX) -; ------------------------------------------------------------------- -; top level. (group all) contains every build target except clean -; and box. box is separate because it produces a different binary -; with different .o files, and mixing it with standalone builds -; would cause confusion. clean is never in all because it removes -; what all builds -; ------------------------------------------------------------------- + ; ------------------------------------------------------------------- + ; top level. (group all) contains every build target except clean + ; and box. box is separate because it produces a different binary + ; with different .o files, and mixing it with standalone builds + ; would cause confusion. clean is never in all because it removes + ; what all builds + ; ------------------------------------------------------------------- -(rule ALL_BINS + (rule ALL_BINS (phony) (after LIBUTIL LIBUTF LIBREDLINE - POSIX_BIN LINUX_BIN NET_BIN XSI_BIN - PSEUDO_BIN EXTRA_BIN - POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE EXTRA_YAP - AR AS LD CC1 CPP CCDRV) + POSIX_BIN LINUX_BIN NET_BIN XSI_BIN + PSEUDO_BIN EXTRA_BIN + POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE EXTRA_YAP + AR AS LD CC1 CPP CCDRV) (exec true)) -(group all ALL_BINS) + (group all ALL_BINS) -(group default all) + (group default all) -; meta-targets: apply an override, then build a normal target under -; it. invoke as `ninqu META.TARGET` (`ninqu debug.posix`) or bare -; `ninqu META` to apply the override and build (group default) -; -(meta debug + ; meta-targets: apply an override, then build a normal target under + ; it. invoke as `ninqu META.TARGET` (`ninqu debug.posix`) or bare + ; `ninqu META` to apply the override and build (group default) + ; + (meta debug (set CFLAGS "$(CFLAGS) -g -O0")) -(meta release + (meta release (set CFLAGS "$(CFLAGS) -O2 -DNDEBUG")) diff --git a/scripts/genbox.sh b/scripts/genbox.sh @@ -2,7 +2,7 @@ # genbox.sh - generate the aruu-box dispatch table # # does one thing: given a list of object file paths on argv, each one -# of BOX_OBJ's own outputs (".box/cmd/<category>/<tool>.o"), emit the C +# of BOX_OBJ's own outputs (".box/cmd/<category>/<tool>.o"), emit the c # source for aruu-box's dispatch table and main() on stdout # set -e @@ -12,7 +12,7 @@ set -e exit 1 } -# derive category, tool basestem, and C symbol from one BOX_OBJ output +# derive category, tool basestem, and c symbol from one BOX_OBJ output # path. the symbol transform (tr '.-' '__', append _main) must match # BOX_OBJ's own objcopy step exactly, see the CATEGORY_OF/symbol # comment in ninqu.rules for why this is a shell transform and not a @@ -35,13 +35,13 @@ path_symbol() { cat << 'HEAD' /* this file is autogenerated by genbox.sh. do not edit */ -#include "wexec.h" -#include "util.h" +# include "wexec.h" +# include "util.h" -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> +# include <stdio.h> +# include <stdlib.h> +# include <string.h> +# include <unistd.h> HEAD @@ -78,9 +78,6 @@ for category in $categories; do if [ "$tool" = "test" ]; then printf '\t{ "[", %s, "%s" },\n' "$sym" "$category" fi - if [ "$tool" = "xinstall" ]; then - printf '\t{ "install", %s, "%s" },\n' "$sym" "$category" - fi done done diff --git a/scripts/genconfig.sh b/scripts/genconfig.sh @@ -3,24 +3,24 @@ # # outputs four files: # -# scripts/mk/config.set ninqu reads this via (set-file). flat -# KEY=VAL, unquoted. per-tool BUILD_CATEGORY_TOOL -# toggles get a lowercase alias here, since -# (gate ...) in ninqu.rules only ever checks -# the lowercase form +# scripts/mk/config.set ninqu reads this via (set-file). flat +# KEY=VAL, unquoted. per-tool BUILD_CATEGORY_TOOL +# toggles get a lowercase alias here, since +# (gate ...) in ninqu.rules only ever checks +# the lowercase form # -# scripts/mk/config.kv shell-quoted KEY="VAL" format. sourced by -# read via the -config flag by scripts/mkman. -# nothing in the ninqu build itself sources -# this file: genbox.sh takes its input on argv -# only, see the BOX section of ninqu.rules +# scripts/mk/config.kv shell-quoted KEY="VAL" format. sourced by +# read via the -config flag by scripts/mkman +# nothing in the ninqu build itself sources +# this file: genbox.sh takes its input on argv +# only, see the BOX section of ninqu.rules # -# shared/libutil/nofork_list.h -# wexec.c includes this at compile time. -# generated from NOFORK_LIST in build.cfg +# shared/libutil/nofork_list.h +# wexec.c includes this at compile time +# generated from NOFORK_LIST in build.cfg # -# scripts/mk/features.h every resolved FEATURE_* as a #define -# CPPFLAGS pulls this in with -include +# scripts/mk/features.h every resolved FEATURE_* as a #define +# CPPFLAGS pulls this in with -include # # the codegen subcommands (getconf, bc, awk, sh) are also here so # ninqu.rules can call (exec sh scripts/genconfig.sh <step>) for @@ -201,11 +201,11 @@ config() { emit LDFLAGS_TLS "${LDFLAGS_TLS:-}" emit LDLIBS_TLS "${LDLIBS_TLS:-}" - # For when ninqu builds itself, otherwise it won't have this value + # for when ninqu builds itself, otherwise it wont have this value emit NINJA_TRY "${NINJA_TRY:-samu,ninja}" - # these seven are only consulted per-tool below (build_CATEGORY_TOOL, - # build_CATEGORY_$(BASESTEM)). + # these seven are only consulted per-tool below (build_category_tool, + # build_category_$(basestem)) for g in BUILD_POSIX BUILD_XSI BUILD_NET BUILD_PSEUDO BUILD_EXTRA BUILD_LINUX BUILD_DEV; do eval "val=\${$g:-0}" echo "${g}=\"${val}\"" >> "${kv_file}" @@ -240,9 +240,9 @@ config() { u_tool=$(echo "$b" | tr 'a-z-' 'A-Z_') var_name="BUILD_${u_category}_${u_tool}" - #if [ "$category" = "dev" ] && [ "$u_tool" = "AS" ]; then - # var_name="BUILD_DEV_CC" - #fi + # if [ "$category" = "dev" ] && [ "$u_tool" = "AS" ]; then + # var_name="build_dev_cc" + # fi eval "has_override=\${$var_name+yes}" if [ "$has_override" = "yes" ]; then @@ -280,13 +280,13 @@ config() { # header. config.h's own #ifndef guards still apply to anything # not here (there is nothing not here), and any file gets the # real values just by being compiled with -include, whether or - # not it bothers to #include "config.h" itself. + # not it bothers to #include "config.h" itself features_h="scripts/mk/features.h" { echo "/* autogenerated by genconfig.sh, do not edit */" for f in $features; do eval "fval=\$$f" - echo "#define ${f} ${fval}" + echo "# define ${f} ${fval}" done } > "${features_h}" @@ -296,7 +296,7 @@ config() { echo "CPPFLAGS=${cppflags_set}" >> "${set_file}" # shared/tls.h would conflict with the system's tls.h - # if we passed -Ishared to build libutil + # if we passed -ishared to build libutil echo "CPPFLAGS_LIBUTIL=\"${cppflags_common}\"" >> "${kv_file}" echo "CPPFLAGS_LIBUTIL=${cppflags_common}" >> "${set_file}" diff --git a/scripts/getconf.sh b/scripts/getconf.sh @@ -2,7 +2,7 @@ ifdef() { printf 'static const struct var %s[] = {\n' "$1" - awk '{printf("#ifdef %s\n\t{\"%s\",\t%s},\n#endif\n", $2, $1, $2)}' + awk '{printf("# ifdef %s\n\t{\"%s\",\t%s},\n#endif\n", $2, $1, $2)}' echo '};' } diff --git a/scripts/mkman/main.go b/scripts/mkman/main.go @@ -142,7 +142,7 @@ func inferSection(path string) int { } } -// a Renderer turns a parsed Page into one output format on os.Stdout +// a renderer turns a parsed page into one output format on os.stdout type Renderer interface { Render() error } diff --git a/scripts/mkman/parse.go b/scripts/mkman/parse.go @@ -70,7 +70,7 @@ func extractManLines(path string, cfg Config) ([]string, error) { if strings.HasPrefix(trimmed, "#") { directive := trimmed[1:] - if ci := strings.Index(directive, "//"); ci >= 0 { + if ci := strings.Index(directive, "// "); ci >= 0 { directive = directive[:ci] } directive = strings.TrimSpace(directive) @@ -120,7 +120,7 @@ func extractManLines(path string, cfg Config) ([]string, error) { if strings.Contains(trimmed, "/* ?man") { startIdx := strings.Index(trimmed, "/* ?man") rest := strings.TrimSpace(trimmed[startIdx+7:]) - if strings.HasSuffix(rest, "*/") { + if strings.HasSuffix(rest, " */") { lines = append(lines, strings.TrimSpace(rest[:len(rest)-2])) } else { lines = append(lines, rest) @@ -318,7 +318,7 @@ func parseOption(line string) (Option, bool) { }, true } -// splitOptionSpec peels the required marker (!) and the mutual exclusion +// splitoptionspec peels the required marker (!) and the mutual exclusion // group marker ({name}) off a raw option spec, leaving the bare flag and // its optional colon-delimited type suffix func splitOptionSpec(raw string) (flag, typ, group string, required bool) { @@ -947,8 +947,8 @@ func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) } func splitGroupedFlags(tok string) ([]SynopsisItem, bool) { - // we expand compacted synopsis tokens like some -abcDef into separate - // semantic flags so the renderer can emit a separate Fl for each one + // we expand compacted synopsis tokens like some -abcdef into separate + // semantic flags so the renderer can emit a separate fl for each one if len(tok) < 3 || tok[0] != '-' { return nil, false } diff --git a/scripts/mkman/txt.go b/scripts/mkman/txt.go @@ -7,7 +7,7 @@ import ( ) // fixed-width ascii layout, matching the column widths a classic -// nroff -Tascii rendering of an mdoc page would produce +// nroff -tascii rendering of an mdoc page would produce const ( txtWidth = 78 txtIndent = 7 @@ -132,7 +132,7 @@ func (r *TxtRenderer) renderBlock(block Block, indent int) { } } -// writeIndented word-wraps text to the page width minus indent, then +// writeindented word-wraps text to the page width minus indent, then // writes each line prefixed by indent spaces func (r *TxtRenderer) writeIndented(text string, indent int) { width := txtWidth - indent @@ -166,7 +166,7 @@ func wrapWords(text string, width int) []string { return lines } -// renderSynopsisItemsTxt mirrors renderSynopsisPhrase from mdoc.go but +// rendersynopsisitemstxt mirrors rendersynopsisphrase from mdoc.go but // writes literal brackets and braces instead of mdoc macros func renderSynopsisItemsTxt(items []SynopsisItem) string { var parts []string diff --git a/shared/arg.h b/shared/arg.h @@ -1,5 +1,5 @@ /* - * Copy me if you can. + * copy me if you can * by 20h */ @@ -26,7 +26,7 @@ extern char *argv0; argc_ = argv[0][0]; \ switch (argc_) -/* Handles obsolete -NUM syntax */ +/* handles obsolete -NUM syntax */ #define ARGNUM \ case '0': \ case '1': \ diff --git a/shared/compat.h b/shared/compat.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #ifndef HOST_NAME_MAX diff --git a/shared/config.h b/shared/config.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "paths.h" #define ENV_PATH ARUU_PATH_BIN diff --git a/shared/crypt.h b/shared/crypt.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> struct crypt_ops { void (*init)(void *); diff --git a/shared/diffutil.h b/shared/diffutil.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #ifndef ARUU_DIFFUTIL_H #define ARUU_DIFFUTIL_H diff --git a/shared/diskutil.h b/shared/diskutil.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #ifndef ARUU_DISKUTIL_H #define ARUU_DISKUTIL_H diff --git a/shared/fs.h b/shared/fs.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <limits.h> #include <sys/stat.h> #include <sys/types.h> diff --git a/shared/libatomic/atomic_x64.s b/shared/libatomic/atomic_x64.s @@ -0,0 +1,177 @@ +/* x86-64 out-of-line atomic helpers, called by cc1-emitted code for + * __atomic_* builtins (see cmd/dev/cc/qbe.c's mkatomicfn). every + * memory order argument is treated as seq_cst: a conservative choice + * that is always standards-conformant, only ever slower than what a + * weaker order would allow. matches the real gcc/clang libatomic + * fallback abi (out-of-line calls for sizes the compiler does not + * inline directly), size-suffixed per operation, so any future + * inlining work can drop straight in without changing callers + */ + +.text + +.globl __atomic_load_4 +__atomic_load_4: + movl (%rdi), %eax + ret + +.globl __atomic_load_8 +__atomic_load_8: + movq (%rdi), %rax + ret + +/* plain store already has release ordering on x86-64; mfence upgrades + * it to full seq_cst, ordering it against a later seq_cst load + */ +.globl __atomic_store_4 +__atomic_store_4: + movl %esi, (%rdi) + mfence + ret + +.globl __atomic_store_8 +__atomic_store_8: + movq %rsi, (%rdi) + mfence + ret + +/* xchg with a memory operand is implicitly locked, no explicit lock + * prefix needed + */ +.globl __atomic_exchange_4 +__atomic_exchange_4: + movl %esi, %eax + xchg %eax, (%rdi) + ret + +.globl __atomic_exchange_8 +__atomic_exchange_8: + movq %rsi, %rax + xchg %rax, (%rdi) + ret + +.globl __atomic_fetch_add_4 +__atomic_fetch_add_4: + movl %esi, %eax + lock xadd %eax, (%rdi) + ret + +.globl __atomic_fetch_add_8 +__atomic_fetch_add_8: + movq %rsi, %rax + lock xadd %rax, (%rdi) + ret + +.globl __atomic_fetch_sub_4 +__atomic_fetch_sub_4: + neg %esi + movl %esi, %eax + lock xadd %eax, (%rdi) + ret + +.globl __atomic_fetch_sub_8 +__atomic_fetch_sub_8: + neg %rsi + movq %rsi, %rax + lock xadd %rax, (%rdi) + ret + +/* no single locked fetch-and-op instruction exists for and/or/xor: + * load, compute the new value, lock cmpxchg it in, retry on failure + * (another cpu changed *ptr in between). on a successful cmpxchg eax + * is left unmodified, which is exactly the old value fetch-and-op + * must return; on failure eax is reloaded with the real current + * value by the instruction itself, which is exactly what the retry + * needs + */ +.globl __atomic_fetch_and_4 +__atomic_fetch_and_4: + movl (%rdi), %eax +.Lretry_and_4: + movl %eax, %ecx + andl %esi, %ecx + lock cmpxchg %ecx, (%rdi) + jnz .Lretry_and_4 + ret + +.globl __atomic_fetch_and_8 +__atomic_fetch_and_8: + movq (%rdi), %rax +.Lretry_and_8: + movq %rax, %rcx + andq %rsi, %rcx + lock cmpxchg %rcx, (%rdi) + jnz .Lretry_and_8 + ret + +.globl __atomic_fetch_or_4 +__atomic_fetch_or_4: + movl (%rdi), %eax +.Lretry_or_4: + movl %eax, %ecx + orl %esi, %ecx + lock cmpxchg %ecx, (%rdi) + jnz .Lretry_or_4 + ret + +.globl __atomic_fetch_or_8 +__atomic_fetch_or_8: + movq (%rdi), %rax +.Lretry_or_8: + movq %rax, %rcx + orq %rsi, %rcx + lock cmpxchg %rcx, (%rdi) + jnz .Lretry_or_8 + ret + +.globl __atomic_fetch_xor_4 +__atomic_fetch_xor_4: + movl (%rdi), %eax +.Lretry_xor_4: + movl %eax, %ecx + xor %esi, %ecx + lock cmpxchg %ecx, (%rdi) + jnz .Lretry_xor_4 + ret + +.globl __atomic_fetch_xor_8 +__atomic_fetch_xor_8: + movq (%rdi), %rax +.Lretry_xor_8: + movq %rax, %rcx + xor %rsi, %rcx + lock cmpxchg %rcx, (%rdi) + jnz .Lretry_xor_8 + ret + +/* __atomic_compare_exchange_N(ptr, expected, desired): the accumulator + * is loaded from *expected before cmpxchg, exactly matching the + * instructions own semantics (compare accumulator against *ptr; on + * match store desired and set zf; on mismatch load the accumulators + * own register with *ptrs real value and clear zf), so success needs + * no extra work at all and failure only needs writing the reloaded + * accumulator back out to *expected + */ +.globl __atomic_compare_exchange_4 +__atomic_compare_exchange_4: + movl (%rsi), %eax + lock cmpxchg %edx, (%rdi) + jz .Lcas4_ok + movl %eax, (%rsi) + movl $0, %eax + ret +.Lcas4_ok: + movl $1, %eax + ret + +.globl __atomic_compare_exchange_8 +__atomic_compare_exchange_8: + movq (%rsi), %rax + lock cmpxchg %rdx, (%rdi) + jz .Lcas8_ok + movq %rax, (%rsi) + movl $0, %eax + ret +.Lcas8_ok: + movl $1, %eax + ret diff --git a/shared/libblake3/blake3.c b/shared/libblake3/blake3.c @@ -0,0 +1,4525 @@ +/* see LICENSE file for copyright and license details */ + +#if defined(__x86_64__) && (defined(__clang__) || (defined(__GNUC__) && !defined(__TINYC__))) +#define BLAKE3_X86_SIMD 1 +#else +#define BLAKE3_X86_SIMD 0 +#endif + +#include "blake3.h" + +#include <assert.h> +#if BLAKE3_X86_SIMD +#include <immintrin.h> +#endif +#include <stdint.h> +#include <string.h> + +#define BLAKE3_VERSION_STRING "1.5.0" + +#if BLAKE3_X86_SIMD +#define MAX_SIMD_DEGREE 16 +#else +#define MAX_SIMD_DEGREE 1 +#endif + +#define MAX_SIMD_DEGREE_OR_2 (MAX_SIMD_DEGREE > 2 ? MAX_SIMD_DEGREE : 2) + +enum Blake3Flags { + CHUNK_START = 1 << 0, + CHUNK_END = 1 << 1, + PARENT = 1 << 2, + ROOT = 1 << 3, + KEYED_HASH = 1 << 4, + DERIVE_KEY_CONTEXT = 1 << 5, + DERIVE_KEY_MATERIAL = 1 << 6 +}; + +struct Output { + uint32_t input_cv[8]; + uint64_t counter; + uint8_t block[BLAKE3_BLOCK_LEN]; + uint8_t block_len; + uint8_t flags; +}; + +static const uint32_t IV[8] = { + 0x6A09E667UL, + 0xBB67AE85UL, + 0x3C6EF372UL, + 0xA54FF53AUL, + 0x510E527FUL, + 0x9B05688CUL, + 0x1F83D9ABUL, + 0x5BE0CD19UL +}; + +static const uint8_t MSG_SCHEDULE[7][16] = { + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + {2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8}, + {3, 4, 10, 12, 13, 2, 7, 14, 6, 5, 9, 0, 11, 15, 8, 1}, + {10, 7, 12, 9, 14, 3, 13, 15, 4, 0, 11, 2, 5, 8, 1, 6}, + {12, 13, 9, 11, 15, 10, 14, 8, 7, 2, 5, 3, 0, 1, 6, 4}, + {9, 14, 11, 5, 8, 12, 15, 1, 13, 3, 0, 10, 2, 6, 4, 7}, + {11, 15, 5, 0, 1, 9, 8, 6, 14, 10, 2, 12, 3, 4, 7, 13}, +}; + +static inline uint32_t +load32(const void *src) +{ + const uint8_t *p = (const uint8_t *)src; + + return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) | ((uint32_t)(p[2]) << 16) + | ((uint32_t)(p[3]) << 24); +} + +static inline void +store32(void *dst, uint32_t w) +{ + uint8_t *p = (uint8_t *)dst; + + p[0] = (uint8_t)(w >> 0); + p[1] = (uint8_t)(w >> 8); + p[2] = (uint8_t)(w >> 16); + p[3] = (uint8_t)(w >> 24); +} + +static inline void +store_cv_words(uint8_t bytes_out[32], uint32_t cv_words[8]) +{ + store32(&bytes_out[0 * 4], cv_words[0]); + store32(&bytes_out[1 * 4], cv_words[1]); + store32(&bytes_out[2 * 4], cv_words[2]); + store32(&bytes_out[3 * 4], cv_words[3]); + store32(&bytes_out[4 * 4], cv_words[4]); + store32(&bytes_out[5 * 4], cv_words[5]); + store32(&bytes_out[6 * 4], cv_words[6]); + store32(&bytes_out[7 * 4], cv_words[7]); +} + +static inline uint32_t +counter_low(uint64_t counter) +{ + return (uint32_t)counter; +} + +static inline uint32_t +counter_high(uint64_t counter) +{ + return (uint32_t)(counter >> 32); +} + +/* forward declarations */ +#if BLAKE3_X86_SIMD +void blake3_compress_in_place_sse2( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +); +void blake3_compress_xof_sse2( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +); +void blake3_hash_many_sse2( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); + +void blake3_compress_in_place_sse41( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +); +void blake3_compress_xof_sse41( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +); +void blake3_hash_many_sse41( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); + +void blake3_hash_many_avx2( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); + +void blake3_compress_in_place_avx512( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +); +void blake3_compress_xof_avx512( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +); +void blake3_hash_many_avx512( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); +#endif + +void blake3_compress_in_place_portable( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +); +void blake3_compress_xof_portable( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +); +void blake3_hash_many_portable( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); + +void blake3_compress_in_place( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +); +void blake3_compress_xof( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +); +void blake3_hash_many( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +); + +/* portable implementations */ +static inline uint32_t +rotr32(uint32_t w, uint32_t c) +{ + return (w >> c) | (w << (32 - c)); +} + +static inline void +g_portable(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y) +{ + state[a] = state[a] + state[b] + x; + state[d] = rotr32(state[d] ^ state[a], 16); + state[c] = state[c] + state[d]; + state[b] = rotr32(state[b] ^ state[c], 12); + state[a] = state[a] + state[b] + y; + state[d] = rotr32(state[d] ^ state[a], 8); + state[c] = state[c] + state[d]; + state[b] = rotr32(state[b] ^ state[c], 7); +} + +static inline void +round_fn_portable(uint32_t state[16], const uint32_t *msg, size_t round) +{ + const uint8_t *schedule = MSG_SCHEDULE[round]; + + g_portable(state, 0, 4, 8, 12, msg[schedule[0]], msg[schedule[1]]); + g_portable(state, 1, 5, 9, 13, msg[schedule[2]], msg[schedule[3]]); + g_portable(state, 2, 6, 10, 14, msg[schedule[4]], msg[schedule[5]]); + g_portable(state, 3, 7, 11, 15, msg[schedule[6]], msg[schedule[7]]); + + g_portable(state, 0, 5, 10, 15, msg[schedule[8]], msg[schedule[9]]); + g_portable(state, 1, 6, 11, 12, msg[schedule[10]], msg[schedule[11]]); + g_portable(state, 2, 7, 8, 13, msg[schedule[12]], msg[schedule[13]]); + g_portable(state, 3, 4, 9, 14, msg[schedule[14]], msg[schedule[15]]); +} + +static inline void +compress_pre_portable( + uint32_t state[16], + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + uint32_t block_words[16]; + + block_words[0] = load32(block + 4 * 0); + block_words[1] = load32(block + 4 * 1); + block_words[2] = load32(block + 4 * 2); + block_words[3] = load32(block + 4 * 3); + block_words[4] = load32(block + 4 * 4); + block_words[5] = load32(block + 4 * 5); + block_words[6] = load32(block + 4 * 6); + block_words[7] = load32(block + 4 * 7); + block_words[8] = load32(block + 4 * 8); + block_words[9] = load32(block + 4 * 9); + block_words[10] = load32(block + 4 * 10); + block_words[11] = load32(block + 4 * 11); + block_words[12] = load32(block + 4 * 12); + block_words[13] = load32(block + 4 * 13); + block_words[14] = load32(block + 4 * 14); + block_words[15] = load32(block + 4 * 15); + + state[0] = cv[0]; + state[1] = cv[1]; + state[2] = cv[2]; + state[3] = cv[3]; + state[4] = cv[4]; + state[5] = cv[5]; + state[6] = cv[6]; + state[7] = cv[7]; + state[8] = IV[0]; + state[9] = IV[1]; + state[10] = IV[2]; + state[11] = IV[3]; + state[12] = counter_low(counter); + state[13] = counter_high(counter); + state[14] = (uint32_t)block_len; + state[15] = (uint32_t)flags; + + round_fn_portable(state, &block_words[0], 0); + round_fn_portable(state, &block_words[0], 1); + round_fn_portable(state, &block_words[0], 2); + round_fn_portable(state, &block_words[0], 3); + round_fn_portable(state, &block_words[0], 4); + round_fn_portable(state, &block_words[0], 5); + round_fn_portable(state, &block_words[0], 6); +} + +void +blake3_compress_in_place_portable( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + uint32_t state[16]; + + compress_pre_portable(state, cv, block, block_len, counter, flags); + cv[0] = state[0] ^ state[8]; + cv[1] = state[1] ^ state[9]; + cv[2] = state[2] ^ state[10]; + cv[3] = state[3] ^ state[11]; + cv[4] = state[4] ^ state[12]; + cv[5] = state[5] ^ state[13]; + cv[6] = state[6] ^ state[14]; + cv[7] = state[7] ^ state[15]; +} + +void +blake3_compress_xof_portable( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +) +{ + uint32_t state[16]; + + compress_pre_portable(state, cv, block, block_len, counter, flags); + + store32(&out[0 * 4], state[0] ^ state[8]); + store32(&out[1 * 4], state[1] ^ state[9]); + store32(&out[2 * 4], state[2] ^ state[10]); + store32(&out[3 * 4], state[3] ^ state[11]); + store32(&out[4 * 4], state[4] ^ state[12]); + store32(&out[5 * 4], state[5] ^ state[13]); + store32(&out[6 * 4], state[6] ^ state[14]); + store32(&out[7 * 4], state[7] ^ state[15]); + store32(&out[8 * 4], state[8] ^ cv[0]); + store32(&out[9 * 4], state[9] ^ cv[1]); + store32(&out[10 * 4], state[10] ^ cv[2]); + store32(&out[11 * 4], state[11] ^ cv[3]); + store32(&out[12 * 4], state[12] ^ cv[4]); + store32(&out[13 * 4], state[13] ^ cv[5]); + store32(&out[14 * 4], state[14] ^ cv[6]); + store32(&out[15 * 4], state[15] ^ cv[7]); +} + +static inline void +hash_one_portable( + const uint8_t *input, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t out[BLAKE3_OUT_LEN] +) +{ + uint32_t cv[8]; + uint8_t block_flags; + + memcpy(cv, key, BLAKE3_KEY_LEN); + block_flags = flags | flags_start; + while (blocks > 0) { + if (blocks == 1) { + block_flags |= flags_end; + } + blake3_compress_in_place_portable(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); + input = &input[BLAKE3_BLOCK_LEN]; + blocks -= 1; + block_flags = flags; + } + store_cv_words(out, cv); +} + +void +blake3_hash_many_portable( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +) +{ + while (num_inputs > 0) { + hash_one_portable(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out); + if (increment_counter) { + counter += 1; + } + inputs += 1; + num_inputs -= 1; + out = &out[BLAKE3_OUT_LEN]; + } +} + +/* cpu features detection */ +enum { SSE2 = 1 << 0, SSE41 = 1 << 1, AVX2 = 1 << 2, AVX512 = 1 << 3 }; + +static int blake3_cpu_features = 0; +static int blake3_cpu_detected = 0; + +#if BLAKE3_X86_SIMD +#include <cpuid.h> + +static void +blake3_cpuid(uint32_t out[4], uint32_t id, uint32_t sid) +{ + __cpuid_count(id, sid, out[0], out[1], out[2], out[3]); +} + +static uint64_t +blake3_xgetbv(void) +{ + uint32_t eax, edx; + + __asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(0)); + return ((uint64_t)edx << 32) | eax; +} +#endif + +static void +blake3_detect_cpu_features(void) +{ +#if BLAKE3_X86_SIMD + enum { EAX, EBX, ECX, EDX }; + uint32_t regs[4]; + uint64_t xcr0; + int features = 0; + + blake3_cpuid(regs, 1, 0); + if (regs[EDX] & (1UL << 26)) + features |= SSE2; + if (regs[ECX] & (1UL << 19)) + features |= SSE41; + /* osxsave */ + if (regs[ECX] & (1UL << 27)) { + blake3_cpuid(regs, 0, 0); + if (regs[EAX] >= 7) { + blake3_cpuid(regs, 7, 0); + xcr0 = blake3_xgetbv(); + /* avx2 and xcr0 sse, avx */ + if ((regs[EBX] & (1UL << 5)) && (xcr0 & 0x06) == 0x06) + features |= AVX2; + /* avx512f, avx512vl and xcr0 opmask, zmm_hi256, + * hi16_zmm */ + if ((regs[EBX] & (1UL << 31 | 1UL << 16)) && (xcr0 & 0xe0) == 0xe0) + features |= AVX512; + } + } + blake3_cpu_features = features; +#endif + blake3_cpu_detected = 1; +} + +#if BLAKE3_X86_SIMD +__attribute__((constructor)) static void +blake3_init_cpu(void) +{ + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); +} +#endif + +#if BLAKE3_X86_SIMD +#if defined(__clang__) +#pragma clang attribute push(__attribute__((target("sse2"))), apply_to = function) +#elif defined(__GNUC__) +#pragma GCC push_options +#pragma GCC target("sse2") +#endif +#define DEGREE_SSE2 4 + +#define _mm_shuffle_ps2(a, b, c) \ + (_mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c)))) + +static inline __m128i +loadu_sse2(const uint8_t src[16]) +{ + return _mm_loadu_si128((const __m128i *)src); +} + +static inline void +storeu_sse2(__m128i src, uint8_t dest[16]) +{ + _mm_storeu_si128((__m128i *)dest, src); +} + +static inline __m128i +addv_sse2(__m128i a, __m128i b) +{ + return _mm_add_epi32(a, b); +} + +static inline __m128i +xorv_sse2(__m128i a, __m128i b) +{ + return _mm_xor_si128(a, b); +} + +static inline __m128i +set1_sse2(uint32_t x) +{ + return _mm_set1_epi32((int32_t)x); +} + +static inline __m128i +set4_sse2(uint32_t a, uint32_t b, uint32_t c, uint32_t d) +{ + return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); +} + +static inline __m128i +rot16_sse2(__m128i x) +{ + return _mm_shufflehi_epi16(_mm_shufflelo_epi16(x, 0xB1), 0xB1); +} + +static inline __m128i +rot12_sse2(__m128i x) +{ + return xorv_sse2(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12)); +} + +static inline __m128i +rot8_sse2(__m128i x) +{ + return xorv_sse2(_mm_srli_epi32(x, 8), _mm_slli_epi32(x, 32 - 8)); +} + +static inline __m128i +rot7_sse2(__m128i x) +{ + return xorv_sse2(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7)); +} + +static inline void +g1_sse2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = addv_sse2(addv_sse2(*row0, m), *row1); + *row3 = xorv_sse2(*row3, *row0); + *row3 = rot16_sse2(*row3); + *row2 = addv_sse2(*row2, *row3); + *row1 = xorv_sse2(*row1, *row2); + *row1 = rot12_sse2(*row1); +} + +static inline void +g2_sse2(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = addv_sse2(addv_sse2(*row0, m), *row1); + *row3 = xorv_sse2(*row3, *row0); + *row3 = rot8_sse2(*row3); + *row2 = addv_sse2(*row2, *row3); + *row1 = xorv_sse2(*row1, *row2); + *row1 = rot7_sse2(*row1); +} + +static inline void +diagonalize_sse2(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); +} + +static inline void +undiagonalize_sse2(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); +} + +static inline __m128i +blend_epi16_sse2(__m128i a, __m128i b, const int16_t imm8) +{ + const __m128i bits = _mm_set_epi16(0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01); + __m128i mask = _mm_set1_epi16(imm8); + + mask = _mm_and_si128(mask, bits); + mask = _mm_cmpeq_epi16(mask, bits); + return _mm_or_si128(_mm_and_si128(mask, b), _mm_andnot_si128(mask, a)); +} + +static inline void +compress_pre_sse2( + __m128i rows[4], + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i m0, m1, m2, m3; + __m128i t0, t1, t2, t3, tt; + + rows[0] = loadu_sse2((uint8_t *)&cv[0]); + rows[1] = loadu_sse2((uint8_t *)&cv[4]); + rows[2] = set4_sse2(IV[0], IV[1], IV[2], IV[3]); + rows[3] = + set4_sse2(counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags); + + m0 = loadu_sse2(&block[sizeof(__m128i) * 0]); + m1 = loadu_sse2(&block[sizeof(__m128i) * 1]); + m2 = loadu_sse2(&block[sizeof(__m128i) * 2]); + m3 = loadu_sse2(&block[sizeof(__m128i) * 3]); + + /* round 1 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 2 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 3 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 4 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 5 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 6 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 7 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = blend_epi16_sse2(tt, t1, 0xCC); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse2(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = blend_epi16_sse2(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse2(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse2(&rows[0], &rows[2], &rows[3]); +} + +void +blake3_compress_in_place_sse2( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i rows[4]; + + compress_pre_sse2(rows, cv, block, block_len, counter, flags); + storeu_sse2(xorv_sse2(rows[0], rows[2]), (uint8_t *)&cv[0]); + storeu_sse2(xorv_sse2(rows[1], rows[3]), (uint8_t *)&cv[4]); +} + +void +blake3_compress_xof_sse2( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out_buf[64] +) +{ + __m128i rows[4]; + + compress_pre_sse2(rows, cv, block, block_len, counter, flags); + storeu_sse2(xorv_sse2(rows[0], rows[2]), &out_buf[0]); + storeu_sse2(xorv_sse2(rows[1], rows[3]), &out_buf[16]); + storeu_sse2(xorv_sse2(rows[2], loadu_sse2((uint8_t *)&cv[0])), &out_buf[32]); + storeu_sse2(xorv_sse2(rows[3], loadu_sse2((uint8_t *)&cv[4])), &out_buf[48]); +} + +static inline void +round_fn_sse2(__m128i v[16], __m128i m[16], size_t r) +{ + v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = addv_sse2(v[0], v[4]); + v[1] = addv_sse2(v[1], v[5]); + v[2] = addv_sse2(v[2], v[6]); + v[3] = addv_sse2(v[3], v[7]); + v[12] = xorv_sse2(v[12], v[0]); + v[13] = xorv_sse2(v[13], v[1]); + v[14] = xorv_sse2(v[14], v[2]); + v[15] = xorv_sse2(v[15], v[3]); + v[12] = rot16_sse2(v[12]); + v[13] = rot16_sse2(v[13]); + v[14] = rot16_sse2(v[14]); + v[15] = rot16_sse2(v[15]); + v[8] = addv_sse2(v[8], v[12]); + v[9] = addv_sse2(v[9], v[13]); + v[10] = addv_sse2(v[10], v[14]); + v[11] = addv_sse2(v[11], v[15]); + v[4] = xorv_sse2(v[4], v[8]); + v[5] = xorv_sse2(v[5], v[9]); + v[6] = xorv_sse2(v[6], v[10]); + v[7] = xorv_sse2(v[7], v[11]); + v[4] = rot12_sse2(v[4]); + v[5] = rot12_sse2(v[5]); + v[6] = rot12_sse2(v[6]); + v[7] = rot12_sse2(v[7]); + v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = addv_sse2(v[0], v[4]); + v[1] = addv_sse2(v[1], v[5]); + v[2] = addv_sse2(v[2], v[6]); + v[3] = addv_sse2(v[3], v[7]); + v[12] = xorv_sse2(v[12], v[0]); + v[13] = xorv_sse2(v[13], v[1]); + v[14] = xorv_sse2(v[14], v[2]); + v[15] = xorv_sse2(v[15], v[3]); + v[12] = rot8_sse2(v[12]); + v[13] = rot8_sse2(v[13]); + v[14] = rot8_sse2(v[14]); + v[15] = rot8_sse2(v[15]); + v[8] = addv_sse2(v[8], v[12]); + v[9] = addv_sse2(v[9], v[13]); + v[10] = addv_sse2(v[10], v[14]); + v[11] = addv_sse2(v[11], v[15]); + v[4] = xorv_sse2(v[4], v[8]); + v[5] = xorv_sse2(v[5], v[9]); + v[6] = xorv_sse2(v[6], v[10]); + v[7] = xorv_sse2(v[7], v[11]); + v[4] = rot7_sse2(v[4]); + v[5] = rot7_sse2(v[5]); + v[6] = rot7_sse2(v[6]); + v[7] = rot7_sse2(v[7]); + + v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = addv_sse2(v[0], v[5]); + v[1] = addv_sse2(v[1], v[6]); + v[2] = addv_sse2(v[2], v[7]); + v[3] = addv_sse2(v[3], v[4]); + v[15] = xorv_sse2(v[15], v[0]); + v[12] = xorv_sse2(v[12], v[1]); + v[13] = xorv_sse2(v[13], v[2]); + v[14] = xorv_sse2(v[14], v[3]); + v[15] = rot16_sse2(v[15]); + v[12] = rot16_sse2(v[12]); + v[13] = rot16_sse2(v[13]); + v[14] = rot16_sse2(v[14]); + v[10] = addv_sse2(v[10], v[15]); + v[11] = addv_sse2(v[11], v[12]); + v[8] = addv_sse2(v[8], v[13]); + v[9] = addv_sse2(v[9], v[14]); + v[5] = xorv_sse2(v[5], v[10]); + v[6] = xorv_sse2(v[6], v[11]); + v[7] = xorv_sse2(v[7], v[8]); + v[4] = xorv_sse2(v[4], v[9]); + v[5] = rot12_sse2(v[5]); + v[6] = rot12_sse2(v[6]); + v[7] = rot12_sse2(v[7]); + v[4] = rot12_sse2(v[4]); + v[0] = addv_sse2(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = addv_sse2(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = addv_sse2(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = addv_sse2(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = addv_sse2(v[0], v[5]); + v[1] = addv_sse2(v[1], v[6]); + v[2] = addv_sse2(v[2], v[7]); + v[3] = addv_sse2(v[3], v[4]); + v[15] = xorv_sse2(v[15], v[0]); + v[12] = xorv_sse2(v[12], v[1]); + v[13] = xorv_sse2(v[13], v[2]); + v[14] = xorv_sse2(v[14], v[3]); + v[15] = rot8_sse2(v[15]); + v[12] = rot8_sse2(v[12]); + v[13] = rot8_sse2(v[13]); + v[14] = rot8_sse2(v[14]); + v[10] = addv_sse2(v[10], v[15]); + v[11] = addv_sse2(v[11], v[12]); + v[8] = addv_sse2(v[8], v[13]); + v[9] = addv_sse2(v[9], v[14]); + v[5] = xorv_sse2(v[5], v[10]); + v[6] = xorv_sse2(v[6], v[11]); + v[7] = xorv_sse2(v[7], v[8]); + v[4] = xorv_sse2(v[4], v[9]); + v[5] = rot7_sse2(v[5]); + v[6] = rot7_sse2(v[6]); + v[7] = rot7_sse2(v[7]); + v[4] = rot7_sse2(v[4]); +} + +static inline void +transpose_vecs_sse2(__m128i vecs[DEGREE_SSE2]) +{ + __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]); + __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]); + __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]); + __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]); + + __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01); + __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01); + __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23); + __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23); + + vecs[0] = abcd_0; + vecs[1] = abcd_1; + vecs[2] = abcd_2; + vecs[3] = abcd_3; +} + +static inline void +transpose_msg_vecs_sse2(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) +{ + size_t i; + + out_msg[0] = loadu_sse2(&inputs[0][block_offset + 0 * sizeof(__m128i)]); + out_msg[1] = loadu_sse2(&inputs[1][block_offset + 0 * sizeof(__m128i)]); + out_msg[2] = loadu_sse2(&inputs[2][block_offset + 0 * sizeof(__m128i)]); + out_msg[3] = loadu_sse2(&inputs[3][block_offset + 0 * sizeof(__m128i)]); + out_msg[4] = loadu_sse2(&inputs[0][block_offset + 1 * sizeof(__m128i)]); + out_msg[5] = loadu_sse2(&inputs[1][block_offset + 1 * sizeof(__m128i)]); + out_msg[6] = loadu_sse2(&inputs[2][block_offset + 1 * sizeof(__m128i)]); + out_msg[7] = loadu_sse2(&inputs[3][block_offset + 1 * sizeof(__m128i)]); + out_msg[8] = loadu_sse2(&inputs[0][block_offset + 2 * sizeof(__m128i)]); + out_msg[9] = loadu_sse2(&inputs[1][block_offset + 2 * sizeof(__m128i)]); + out_msg[10] = loadu_sse2(&inputs[2][block_offset + 2 * sizeof(__m128i)]); + out_msg[11] = loadu_sse2(&inputs[3][block_offset + 2 * sizeof(__m128i)]); + out_msg[12] = loadu_sse2(&inputs[0][block_offset + 3 * sizeof(__m128i)]); + out_msg[13] = loadu_sse2(&inputs[1][block_offset + 3 * sizeof(__m128i)]); + out_msg[14] = loadu_sse2(&inputs[2][block_offset + 3 * sizeof(__m128i)]); + out_msg[15] = loadu_sse2(&inputs[3][block_offset + 3 * sizeof(__m128i)]); + + for (i = 0; i < 4; i++) { + _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); + } + transpose_vecs_sse2(&out_msg[0]); + transpose_vecs_sse2(&out_msg[4]); + transpose_vecs_sse2(&out_msg[8]); + transpose_vecs_sse2(&out_msg[12]); +} + +static inline void +load_counters_sse2(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) +{ + const __m128i mask = _mm_set1_epi32(-increment_counter); + const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); + const __m128i add1 = _mm_and_si128(mask, add0); + __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); + __m128i carry = _mm_cmpgt_epi32( + _mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), _mm_xor_si128(l, _mm_set1_epi32(0x80000000)) + ); + __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); + + *out_lo = l; + *out_hi = h; +} + +void +blake3_hash4_sse2( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m128i h_vecs[8]; + __m128i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_sse2(key[0]); + h_vecs[1] = set1_sse2(key[1]); + h_vecs[2] = set1_sse2(key[2]); + h_vecs[3] = set1_sse2(key[3]); + h_vecs[4] = set1_sse2(key[4]); + h_vecs[5] = set1_sse2(key[5]); + h_vecs[6] = set1_sse2(key[6]); + h_vecs[7] = set1_sse2(key[7]); + + load_counters_sse2(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m128i block_len_vec; + __m128i block_flags_vec; + __m128i msg_vecs[16]; + __m128i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_sse2(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_sse2(block_flags); + transpose_msg_vecs_sse2(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_sse2(IV[0]); + v[9] = set1_sse2(IV[1]); + v[10] = set1_sse2(IV[2]); + v[11] = set1_sse2(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn_sse2(v, msg_vecs, 0); + round_fn_sse2(v, msg_vecs, 1); + round_fn_sse2(v, msg_vecs, 2); + round_fn_sse2(v, msg_vecs, 3); + round_fn_sse2(v, msg_vecs, 4); + round_fn_sse2(v, msg_vecs, 5); + round_fn_sse2(v, msg_vecs, 6); + + h_vecs[0] = xorv_sse2(v[0], v[8]); + h_vecs[1] = xorv_sse2(v[1], v[9]); + h_vecs[2] = xorv_sse2(v[2], v[10]); + h_vecs[3] = xorv_sse2(v[3], v[11]); + h_vecs[4] = xorv_sse2(v[4], v[12]); + h_vecs[5] = xorv_sse2(v[5], v[13]); + h_vecs[6] = xorv_sse2(v[6], v[14]); + h_vecs[7] = xorv_sse2(v[7], v[15]); + + block_flags = flags; + } + + transpose_vecs_sse2(&h_vecs[0]); + transpose_vecs_sse2(&h_vecs[4]); + storeu_sse2(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); + storeu_sse2(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); + storeu_sse2(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); + storeu_sse2(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); + storeu_sse2(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); + storeu_sse2(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); + storeu_sse2(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); + storeu_sse2(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); +} + +static inline void +hash_one_sse2( + const uint8_t *input, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t out_bytes[BLAKE3_OUT_LEN] +) +{ + uint32_t cv[8]; + uint8_t block_flags; + + memcpy(cv, key, BLAKE3_KEY_LEN); + block_flags = flags | flags_start; + while (blocks > 0) { + if (blocks == 1) { + block_flags |= flags_end; + } + blake3_compress_in_place_sse2(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); + input = &input[BLAKE3_BLOCK_LEN]; + blocks -= 1; + block_flags = flags; + } + memcpy(out_bytes, cv, BLAKE3_OUT_LEN); +} + +void +blake3_hash_many_sse2( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + while (num_inputs >= DEGREE_SSE2) { + blake3_hash4_sse2( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += DEGREE_SSE2; + } + inputs += DEGREE_SSE2; + num_inputs -= DEGREE_SSE2; + out_bytes = &out_bytes[DEGREE_SSE2 * BLAKE3_OUT_LEN]; + } + while (num_inputs > 0) { + hash_one_sse2(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); + if (increment_counter) { + counter += 1; + } + inputs += 1; + num_inputs -= 1; + out_bytes = &out_bytes[BLAKE3_OUT_LEN]; + } +} +#if defined(__clang__) +#pragma clang attribute pop +#elif defined(__GNUC__) +#pragma GCC pop_options +#endif + +#if defined(__clang__) +#pragma clang attribute push(__attribute__((target("sse4.1"))), apply_to = function) +#elif defined(__GNUC__) +#pragma GCC push_options +#pragma GCC target("sse4.1") +#endif +#define DEGREE_SSE41 4 + +#define _mm_shuffle_ps2_sse41(a, b, c) \ + (_mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(a), _mm_castsi128_ps(b), (c)))) + +static inline __m128i +loadu_sse41(const uint8_t src[16]) +{ + return _mm_loadu_si128((const __m128i *)src); +} + +static inline void +storeu_sse41(__m128i src, uint8_t dest[16]) +{ + _mm_storeu_si128((__m128i *)dest, src); +} + +static inline __m128i +addv_sse41(__m128i a, __m128i b) +{ + return _mm_add_epi32(a, b); +} + +static inline __m128i +xorv_sse41(__m128i a, __m128i b) +{ + return _mm_xor_si128(a, b); +} + +static inline __m128i +set1_sse41(uint32_t x) +{ + return _mm_set1_epi32((int32_t)x); +} + +static inline __m128i +set4_sse41(uint32_t a, uint32_t b, uint32_t c, uint32_t d) +{ + return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); +} + +static inline __m128i +rot16_sse41(__m128i x) +{ + return _mm_shuffle_epi8(x, _mm_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2)); +} + +static inline __m128i +rot12_sse41(__m128i x) +{ + return xorv_sse41(_mm_srli_epi32(x, 12), _mm_slli_epi32(x, 32 - 12)); +} + +static inline __m128i +rot8_sse41(__m128i x) +{ + return _mm_shuffle_epi8(x, _mm_set_epi8(12, 15, 14, 13, 8, 11, 10, 9, 4, 7, 6, 5, 0, 3, 2, 1)); +} + +static inline __m128i +rot7_sse41(__m128i x) +{ + return xorv_sse41(_mm_srli_epi32(x, 7), _mm_slli_epi32(x, 32 - 7)); +} + +static inline void +g1_sse41(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = addv_sse41(addv_sse41(*row0, m), *row1); + *row3 = xorv_sse41(*row3, *row0); + *row3 = rot16_sse41(*row3); + *row2 = addv_sse41(*row2, *row3); + *row1 = xorv_sse41(*row1, *row2); + *row1 = rot12_sse41(*row1); +} + +static inline void +g2_sse41(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = addv_sse41(addv_sse41(*row0, m), *row1); + *row3 = xorv_sse41(*row3, *row0); + *row3 = rot8_sse41(*row3); + *row2 = addv_sse41(*row2, *row3); + *row1 = xorv_sse41(*row1, *row2); + *row1 = rot7_sse41(*row1); +} + +static inline void +diagonalize_sse41(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); +} + +static inline void +undiagonalize_sse41(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); +} + +static inline void +compress_pre_sse41( + __m128i rows[4], + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i m0, m1, m2, m3; + __m128i t0, t1, t2, t3, tt; + + rows[0] = loadu_sse41((uint8_t *)&cv[0]); + rows[1] = loadu_sse41((uint8_t *)&cv[4]); + rows[2] = set4_sse41(IV[0], IV[1], IV[2], IV[3]); + rows[3] = + set4_sse41(counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags); + + m0 = loadu_sse41(&block[sizeof(__m128i) * 0]); + m1 = loadu_sse41(&block[sizeof(__m128i) * 1]); + m2 = loadu_sse41(&block[sizeof(__m128i) * 2]); + m3 = loadu_sse41(&block[sizeof(__m128i) * 3]); + + /* round 1 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 2 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 3 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 4 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 5 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 6 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 7 */ + t0 = _mm_shuffle_ps2_sse41(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2_sse41(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + tt = _mm_shuffle_epi32(m0, _MM_SHUFFLE(0, 0, 3, 3)); + t1 = _mm_blend_epi16(tt, t1, 0xCC); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_sse41(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + tt = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(1, 3, 2, 0)); + g1_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + tt = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(tt, _MM_SHUFFLE(0, 1, 3, 2)); + g2_sse41(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_sse41(&rows[0], &rows[2], &rows[3]); +} + +void +blake3_compress_in_place_sse41( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i rows[4]; + + compress_pre_sse41(rows, cv, block, block_len, counter, flags); + storeu_sse41(xorv_sse41(rows[0], rows[2]), (uint8_t *)&cv[0]); + storeu_sse41(xorv_sse41(rows[1], rows[3]), (uint8_t *)&cv[4]); +} + +void +blake3_compress_xof_sse41( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out_buf[64] +) +{ + __m128i rows[4]; + + compress_pre_sse41(rows, cv, block, block_len, counter, flags); + storeu_sse41(xorv_sse41(rows[0], rows[2]), &out_buf[0]); + storeu_sse41(xorv_sse41(rows[1], rows[3]), &out_buf[16]); + storeu_sse41(xorv_sse41(rows[2], loadu_sse41((uint8_t *)&cv[0])), &out_buf[32]); + storeu_sse41(xorv_sse41(rows[3], loadu_sse41((uint8_t *)&cv[4])), &out_buf[48]); +} + +static inline void +round_fn_sse41(__m128i v[16], __m128i m[16], size_t r) +{ + v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = addv_sse41(v[0], v[4]); + v[1] = addv_sse41(v[1], v[5]); + v[2] = addv_sse41(v[2], v[6]); + v[3] = addv_sse41(v[3], v[7]); + v[12] = xorv_sse41(v[12], v[0]); + v[13] = xorv_sse41(v[13], v[1]); + v[14] = xorv_sse41(v[14], v[2]); + v[15] = xorv_sse41(v[15], v[3]); + v[12] = rot16_sse41(v[12]); + v[13] = rot16_sse41(v[13]); + v[14] = rot16_sse41(v[14]); + v[15] = rot16_sse41(v[15]); + v[8] = addv_sse41(v[8], v[12]); + v[9] = addv_sse41(v[9], v[13]); + v[10] = addv_sse41(v[10], v[14]); + v[11] = addv_sse41(v[11], v[15]); + v[4] = xorv_sse41(v[4], v[8]); + v[5] = xorv_sse41(v[5], v[9]); + v[6] = xorv_sse41(v[6], v[10]); + v[7] = xorv_sse41(v[7], v[11]); + v[4] = rot12_sse41(v[4]); + v[5] = rot12_sse41(v[5]); + v[6] = rot12_sse41(v[6]); + v[7] = rot12_sse41(v[7]); + v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = addv_sse41(v[0], v[4]); + v[1] = addv_sse41(v[1], v[5]); + v[2] = addv_sse41(v[2], v[6]); + v[3] = addv_sse41(v[3], v[7]); + v[12] = xorv_sse41(v[12], v[0]); + v[13] = xorv_sse41(v[13], v[1]); + v[14] = xorv_sse41(v[14], v[2]); + v[15] = xorv_sse41(v[15], v[3]); + v[12] = rot8_sse41(v[12]); + v[13] = rot8_sse41(v[13]); + v[14] = rot8_sse41(v[14]); + v[15] = rot8_sse41(v[15]); + v[8] = addv_sse41(v[8], v[12]); + v[9] = addv_sse41(v[9], v[13]); + v[10] = addv_sse41(v[10], v[14]); + v[11] = addv_sse41(v[11], v[15]); + v[4] = xorv_sse41(v[4], v[8]); + v[5] = xorv_sse41(v[5], v[9]); + v[6] = xorv_sse41(v[6], v[10]); + v[7] = xorv_sse41(v[7], v[11]); + v[4] = rot7_sse41(v[4]); + v[5] = rot7_sse41(v[5]); + v[6] = rot7_sse41(v[6]); + v[7] = rot7_sse41(v[7]); + + v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = addv_sse41(v[0], v[5]); + v[1] = addv_sse41(v[1], v[6]); + v[2] = addv_sse41(v[2], v[7]); + v[3] = addv_sse41(v[3], v[4]); + v[15] = xorv_sse41(v[15], v[0]); + v[12] = xorv_sse41(v[12], v[1]); + v[13] = xorv_sse41(v[13], v[2]); + v[14] = xorv_sse41(v[14], v[3]); + v[15] = rot16_sse41(v[15]); + v[12] = rot16_sse41(v[12]); + v[13] = rot16_sse41(v[13]); + v[14] = rot16_sse41(v[14]); + v[10] = addv_sse41(v[10], v[15]); + v[11] = addv_sse41(v[11], v[12]); + v[8] = addv_sse41(v[8], v[13]); + v[9] = addv_sse41(v[9], v[14]); + v[5] = xorv_sse41(v[5], v[10]); + v[6] = xorv_sse41(v[6], v[11]); + v[7] = xorv_sse41(v[7], v[8]); + v[4] = xorv_sse41(v[4], v[9]); + v[5] = rot12_sse41(v[5]); + v[6] = rot12_sse41(v[6]); + v[7] = rot12_sse41(v[7]); + v[4] = rot12_sse41(v[4]); + v[0] = addv_sse41(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = addv_sse41(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = addv_sse41(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = addv_sse41(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = addv_sse41(v[0], v[5]); + v[1] = addv_sse41(v[1], v[6]); + v[2] = addv_sse41(v[2], v[7]); + v[3] = addv_sse41(v[3], v[4]); + v[15] = xorv_sse41(v[15], v[0]); + v[12] = xorv_sse41(v[12], v[1]); + v[13] = xorv_sse41(v[13], v[2]); + v[14] = xorv_sse41(v[14], v[3]); + v[15] = rot8_sse41(v[15]); + v[12] = rot8_sse41(v[12]); + v[13] = rot8_sse41(v[13]); + v[14] = rot8_sse41(v[14]); + v[10] = addv_sse41(v[10], v[15]); + v[11] = addv_sse41(v[11], v[12]); + v[8] = addv_sse41(v[8], v[13]); + v[9] = addv_sse41(v[9], v[14]); + v[5] = xorv_sse41(v[5], v[10]); + v[6] = xorv_sse41(v[6], v[11]); + v[7] = xorv_sse41(v[7], v[8]); + v[4] = xorv_sse41(v[4], v[9]); + v[5] = rot7_sse41(v[5]); + v[6] = rot7_sse41(v[6]); + v[7] = rot7_sse41(v[7]); + v[4] = rot7_sse41(v[4]); +} + +static inline void +transpose_vecs_sse41(__m128i vecs[DEGREE_SSE41]) +{ + __m128i ab_01 = _mm_unpacklo_epi32(vecs[0], vecs[1]); + __m128i ab_23 = _mm_unpackhi_epi32(vecs[0], vecs[1]); + __m128i cd_01 = _mm_unpacklo_epi32(vecs[2], vecs[3]); + __m128i cd_23 = _mm_unpackhi_epi32(vecs[2], vecs[3]); + + __m128i abcd_0 = _mm_unpacklo_epi64(ab_01, cd_01); + __m128i abcd_1 = _mm_unpackhi_epi64(ab_01, cd_01); + __m128i abcd_2 = _mm_unpacklo_epi64(ab_23, cd_23); + __m128i abcd_3 = _mm_unpackhi_epi64(ab_23, cd_23); + + vecs[0] = abcd_0; + vecs[1] = abcd_1; + vecs[2] = abcd_2; + vecs[3] = abcd_3; +} + +static inline void +transpose_msg_vecs_sse41(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) +{ + size_t i; + + out_msg[0] = loadu_sse41(&inputs[0][block_offset + 0 * sizeof(__m128i)]); + out_msg[1] = loadu_sse41(&inputs[1][block_offset + 0 * sizeof(__m128i)]); + out_msg[2] = loadu_sse41(&inputs[2][block_offset + 0 * sizeof(__m128i)]); + out_msg[3] = loadu_sse41(&inputs[3][block_offset + 0 * sizeof(__m128i)]); + out_msg[4] = loadu_sse41(&inputs[0][block_offset + 1 * sizeof(__m128i)]); + out_msg[5] = loadu_sse41(&inputs[1][block_offset + 1 * sizeof(__m128i)]); + out_msg[6] = loadu_sse41(&inputs[2][block_offset + 1 * sizeof(__m128i)]); + out_msg[7] = loadu_sse41(&inputs[3][block_offset + 1 * sizeof(__m128i)]); + out_msg[8] = loadu_sse41(&inputs[0][block_offset + 2 * sizeof(__m128i)]); + out_msg[9] = loadu_sse41(&inputs[1][block_offset + 2 * sizeof(__m128i)]); + out_msg[10] = loadu_sse41(&inputs[2][block_offset + 2 * sizeof(__m128i)]); + out_msg[11] = loadu_sse41(&inputs[3][block_offset + 2 * sizeof(__m128i)]); + out_msg[12] = loadu_sse41(&inputs[0][block_offset + 3 * sizeof(__m128i)]); + out_msg[13] = loadu_sse41(&inputs[1][block_offset + 3 * sizeof(__m128i)]); + out_msg[14] = loadu_sse41(&inputs[2][block_offset + 3 * sizeof(__m128i)]); + out_msg[15] = loadu_sse41(&inputs[3][block_offset + 3 * sizeof(__m128i)]); + + for (i = 0; i < 4; i++) { + _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); + } + transpose_vecs_sse41(&out_msg[0]); + transpose_vecs_sse41(&out_msg[4]); + transpose_vecs_sse41(&out_msg[8]); + transpose_vecs_sse41(&out_msg[12]); +} + +static inline void +load_counters_sse41(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) +{ + const __m128i mask = _mm_set1_epi32(-increment_counter); + const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); + const __m128i add1 = _mm_and_si128(mask, add0); + __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); + __m128i carry = _mm_cmpgt_epi32( + _mm_xor_si128(add1, _mm_set1_epi32(0x80000000)), _mm_xor_si128(l, _mm_set1_epi32(0x80000000)) + ); + __m128i h = _mm_sub_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); + + *out_lo = l; + *out_hi = h; +} + +void +blake3_hash4_sse41( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m128i h_vecs[8]; + __m128i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_sse41(key[0]); + h_vecs[1] = set1_sse41(key[1]); + h_vecs[2] = set1_sse41(key[2]); + h_vecs[3] = set1_sse41(key[3]); + h_vecs[4] = set1_sse41(key[4]); + h_vecs[5] = set1_sse41(key[5]); + h_vecs[6] = set1_sse41(key[6]); + h_vecs[7] = set1_sse41(key[7]); + + load_counters_sse41(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m128i block_len_vec; + __m128i block_flags_vec; + __m128i msg_vecs[16]; + __m128i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_sse41(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_sse41(block_flags); + transpose_msg_vecs_sse41(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_sse41(IV[0]); + v[9] = set1_sse41(IV[1]); + v[10] = set1_sse41(IV[2]); + v[11] = set1_sse41(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn_sse41(v, msg_vecs, 0); + round_fn_sse41(v, msg_vecs, 1); + round_fn_sse41(v, msg_vecs, 2); + round_fn_sse41(v, msg_vecs, 3); + round_fn_sse41(v, msg_vecs, 4); + round_fn_sse41(v, msg_vecs, 5); + round_fn_sse41(v, msg_vecs, 6); + + h_vecs[0] = xorv_sse41(v[0], v[8]); + h_vecs[1] = xorv_sse41(v[1], v[9]); + h_vecs[2] = xorv_sse41(v[2], v[10]); + h_vecs[3] = xorv_sse41(v[3], v[11]); + h_vecs[4] = xorv_sse41(v[4], v[12]); + h_vecs[5] = xorv_sse41(v[5], v[13]); + h_vecs[6] = xorv_sse41(v[6], v[14]); + h_vecs[7] = xorv_sse41(v[7], v[15]); + + block_flags = flags; + } + + transpose_vecs_sse41(&h_vecs[0]); + transpose_vecs_sse41(&h_vecs[4]); + storeu_sse41(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); + storeu_sse41(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); + storeu_sse41(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); + storeu_sse41(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); + storeu_sse41(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); + storeu_sse41(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); + storeu_sse41(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); + storeu_sse41(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); +} + +static inline void +hash_one_sse41( + const uint8_t *input, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t out_bytes[BLAKE3_OUT_LEN] +) +{ + uint32_t cv[8]; + uint8_t block_flags; + + memcpy(cv, key, BLAKE3_KEY_LEN); + block_flags = flags | flags_start; + while (blocks > 0) { + if (blocks == 1) { + block_flags |= flags_end; + } + blake3_compress_in_place_sse41(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); + input = &input[BLAKE3_BLOCK_LEN]; + blocks -= 1; + block_flags = flags; + } + memcpy(out_bytes, cv, BLAKE3_OUT_LEN); +} + +void +blake3_hash_many_sse41( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + while (num_inputs >= DEGREE_SSE41) { + blake3_hash4_sse41( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += DEGREE_SSE41; + } + inputs += DEGREE_SSE41; + num_inputs -= DEGREE_SSE41; + out_bytes = &out_bytes[DEGREE_SSE41 * BLAKE3_OUT_LEN]; + } + while (num_inputs > 0) { + hash_one_sse41(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); + if (increment_counter) { + counter += 1; + } + inputs += 1; + num_inputs -= 1; + out_bytes = &out_bytes[BLAKE3_OUT_LEN]; + } +} +#if defined(__clang__) +#pragma clang attribute pop +#elif defined(__GNUC__) +#pragma GCC pop_options +#endif + +#if defined(__clang__) +#pragma clang attribute push(__attribute__((target("avx2"))), apply_to = function) +#elif defined(__GNUC__) +#pragma GCC push_options +#pragma GCC target("avx2") +#endif +#define DEGREE_AVX2 8 + +static inline __m256i +loadu_avx2(const uint8_t src[32]) +{ + return _mm256_loadu_si256((const __m256i *)src); +} + +static inline void +storeu_avx2(__m256i src, uint8_t dest[32]) +{ + _mm256_storeu_si256((__m256i *)dest, src); +} + +static inline __m256i +addv_avx2(__m256i a, __m256i b) +{ + return _mm256_add_epi32(a, b); +} + +static inline __m256i +xorv_avx2(__m256i a, __m256i b) +{ + return _mm256_xor_si256(a, b); +} + +static inline __m256i +set1_avx2(uint32_t x) +{ + return _mm256_set1_epi32((int32_t)x); +} + +static inline __m256i +rot16_avx2(__m256i x) +{ + return _mm256_shuffle_epi8( + x, + _mm256_set_epi8( + 13, + 12, + 15, + 14, + 9, + 8, + 11, + 10, + 5, + 4, + 7, + 6, + 1, + 0, + 3, + 2, + 13, + 12, + 15, + 14, + 9, + 8, + 11, + 10, + 5, + 4, + 7, + 6, + 1, + 0, + 3, + 2 + ) + ); +} + +static inline __m256i +rot12_avx2(__m256i x) +{ + return _mm256_or_si256(_mm256_srli_epi32(x, 12), _mm256_slli_epi32(x, 32 - 12)); +} + +static inline __m256i +rot8_avx2(__m256i x) +{ + return _mm256_shuffle_epi8( + x, + _mm256_set_epi8( + 12, + 15, + 14, + 13, + 8, + 11, + 10, + 9, + 4, + 7, + 6, + 5, + 0, + 3, + 2, + 1, + 12, + 15, + 14, + 13, + 8, + 11, + 10, + 9, + 4, + 7, + 6, + 5, + 0, + 3, + 2, + 1 + ) + ); +} + +static inline __m256i +rot7_avx2(__m256i x) +{ + return _mm256_or_si256(_mm256_srli_epi32(x, 7), _mm256_slli_epi32(x, 32 - 7)); +} + +static inline void +round_fn_avx2(__m256i v[16], __m256i m[16], size_t r) +{ + v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = addv_avx2(v[0], v[4]); + v[1] = addv_avx2(v[1], v[5]); + v[2] = addv_avx2(v[2], v[6]); + v[3] = addv_avx2(v[3], v[7]); + v[12] = xorv_avx2(v[12], v[0]); + v[13] = xorv_avx2(v[13], v[1]); + v[14] = xorv_avx2(v[14], v[2]); + v[15] = xorv_avx2(v[15], v[3]); + v[12] = rot16_avx2(v[12]); + v[13] = rot16_avx2(v[13]); + v[14] = rot16_avx2(v[14]); + v[15] = rot16_avx2(v[15]); + v[8] = addv_avx2(v[8], v[12]); + v[9] = addv_avx2(v[9], v[13]); + v[10] = addv_avx2(v[10], v[14]); + v[11] = addv_avx2(v[11], v[15]); + v[4] = xorv_avx2(v[4], v[8]); + v[5] = xorv_avx2(v[5], v[9]); + v[6] = xorv_avx2(v[6], v[10]); + v[7] = xorv_avx2(v[7], v[11]); + v[4] = rot12_avx2(v[4]); + v[5] = rot12_avx2(v[5]); + v[6] = rot12_avx2(v[6]); + v[7] = rot12_avx2(v[7]); + v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = addv_avx2(v[0], v[4]); + v[1] = addv_avx2(v[1], v[5]); + v[2] = addv_avx2(v[2], v[6]); + v[3] = addv_avx2(v[3], v[7]); + v[12] = xorv_avx2(v[12], v[0]); + v[13] = xorv_avx2(v[13], v[1]); + v[14] = xorv_avx2(v[14], v[2]); + v[15] = xorv_avx2(v[15], v[3]); + v[12] = rot8_avx2(v[12]); + v[13] = rot8_avx2(v[13]); + v[14] = rot8_avx2(v[14]); + v[15] = rot8_avx2(v[15]); + v[8] = addv_avx2(v[8], v[12]); + v[9] = addv_avx2(v[9], v[13]); + v[10] = addv_avx2(v[10], v[14]); + v[11] = addv_avx2(v[11], v[15]); + v[4] = xorv_avx2(v[4], v[8]); + v[5] = xorv_avx2(v[5], v[9]); + v[6] = xorv_avx2(v[6], v[10]); + v[7] = xorv_avx2(v[7], v[11]); + v[4] = rot7_avx2(v[4]); + v[5] = rot7_avx2(v[5]); + v[6] = rot7_avx2(v[6]); + v[7] = rot7_avx2(v[7]); + + v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = addv_avx2(v[0], v[5]); + v[1] = addv_avx2(v[1], v[6]); + v[2] = addv_avx2(v[2], v[7]); + v[3] = addv_avx2(v[3], v[4]); + v[15] = xorv_avx2(v[15], v[0]); + v[12] = xorv_avx2(v[12], v[1]); + v[13] = xorv_avx2(v[13], v[2]); + v[14] = xorv_avx2(v[14], v[3]); + v[15] = rot16_avx2(v[15]); + v[12] = rot16_avx2(v[12]); + v[13] = rot16_avx2(v[13]); + v[14] = rot16_avx2(v[14]); + v[10] = addv_avx2(v[10], v[15]); + v[11] = addv_avx2(v[11], v[12]); + v[8] = addv_avx2(v[8], v[13]); + v[9] = addv_avx2(v[9], v[14]); + v[5] = xorv_avx2(v[5], v[10]); + v[6] = xorv_avx2(v[6], v[11]); + v[7] = xorv_avx2(v[7], v[8]); + v[4] = xorv_avx2(v[4], v[9]); + v[5] = rot12_avx2(v[5]); + v[6] = rot12_avx2(v[6]); + v[7] = rot12_avx2(v[7]); + v[4] = rot12_avx2(v[4]); + v[0] = addv_avx2(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = addv_avx2(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = addv_avx2(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = addv_avx2(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = addv_avx2(v[0], v[5]); + v[1] = addv_avx2(v[1], v[6]); + v[2] = addv_avx2(v[2], v[7]); + v[3] = addv_avx2(v[3], v[4]); + v[15] = xorv_avx2(v[15], v[0]); + v[12] = xorv_avx2(v[12], v[1]); + v[13] = xorv_avx2(v[13], v[2]); + v[14] = xorv_avx2(v[14], v[3]); + v[15] = rot8_avx2(v[15]); + v[12] = rot8_avx2(v[12]); + v[13] = rot8_avx2(v[13]); + v[14] = rot8_avx2(v[14]); + v[10] = addv_avx2(v[10], v[15]); + v[11] = addv_avx2(v[11], v[12]); + v[8] = addv_avx2(v[8], v[13]); + v[9] = addv_avx2(v[9], v[14]); + v[5] = xorv_avx2(v[5], v[10]); + v[6] = xorv_avx2(v[6], v[11]); + v[7] = xorv_avx2(v[7], v[8]); + v[4] = xorv_avx2(v[4], v[9]); + v[5] = rot7_avx2(v[5]); + v[6] = rot7_avx2(v[6]); + v[7] = rot7_avx2(v[7]); + v[4] = rot7_avx2(v[4]); +} + +static inline void +transpose_vecs_avx2(__m256i vecs[DEGREE_AVX2]) +{ + __m256i ab_0145 = _mm256_unpacklo_epi32(vecs[0], vecs[1]); + __m256i ab_2367 = _mm256_unpackhi_epi32(vecs[0], vecs[1]); + __m256i cd_0145 = _mm256_unpacklo_epi32(vecs[2], vecs[3]); + __m256i cd_2367 = _mm256_unpackhi_epi32(vecs[2], vecs[3]); + __m256i ef_0145 = _mm256_unpacklo_epi32(vecs[4], vecs[5]); + __m256i ef_2367 = _mm256_unpackhi_epi32(vecs[4], vecs[5]); + __m256i gh_0145 = _mm256_unpacklo_epi32(vecs[6], vecs[7]); + __m256i gh_2367 = _mm256_unpackhi_epi32(vecs[6], vecs[7]); + + __m256i abcd_04 = _mm256_unpacklo_epi64(ab_0145, cd_0145); + __m256i abcd_15 = _mm256_unpackhi_epi64(ab_0145, cd_0145); + __m256i abcd_26 = _mm256_unpacklo_epi64(ab_2367, cd_2367); + __m256i abcd_37 = _mm256_unpackhi_epi64(ab_2367, cd_2367); + __m256i efgh_04 = _mm256_unpacklo_epi64(ef_0145, gh_0145); + __m256i efgh_15 = _mm256_unpackhi_epi64(ef_0145, gh_0145); + __m256i efgh_26 = _mm256_unpacklo_epi64(ef_2367, gh_2367); + __m256i efgh_37 = _mm256_unpackhi_epi64(ef_2367, gh_2367); + + vecs[0] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x20); + vecs[1] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x20); + vecs[2] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x20); + vecs[3] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x20); + vecs[4] = _mm256_permute2x128_si256(abcd_04, efgh_04, 0x31); + vecs[5] = _mm256_permute2x128_si256(abcd_15, efgh_15, 0x31); + vecs[6] = _mm256_permute2x128_si256(abcd_26, efgh_26, 0x31); + vecs[7] = _mm256_permute2x128_si256(abcd_37, efgh_37, 0x31); +} + +static inline void +transpose_msg_vecs_avx2(const uint8_t *const *inputs, size_t block_offset, __m256i out_msg[16]) +{ + size_t i; + + out_msg[0] = loadu_avx2(&inputs[0][block_offset + 0 * sizeof(__m256i)]); + out_msg[1] = loadu_avx2(&inputs[1][block_offset + 0 * sizeof(__m256i)]); + out_msg[2] = loadu_avx2(&inputs[2][block_offset + 0 * sizeof(__m256i)]); + out_msg[3] = loadu_avx2(&inputs[3][block_offset + 0 * sizeof(__m256i)]); + out_msg[4] = loadu_avx2(&inputs[4][block_offset + 0 * sizeof(__m256i)]); + out_msg[5] = loadu_avx2(&inputs[5][block_offset + 0 * sizeof(__m256i)]); + out_msg[6] = loadu_avx2(&inputs[6][block_offset + 0 * sizeof(__m256i)]); + out_msg[7] = loadu_avx2(&inputs[7][block_offset + 0 * sizeof(__m256i)]); + out_msg[8] = loadu_avx2(&inputs[0][block_offset + 1 * sizeof(__m256i)]); + out_msg[9] = loadu_avx2(&inputs[1][block_offset + 1 * sizeof(__m256i)]); + out_msg[10] = loadu_avx2(&inputs[2][block_offset + 1 * sizeof(__m256i)]); + out_msg[11] = loadu_avx2(&inputs[3][block_offset + 1 * sizeof(__m256i)]); + out_msg[12] = loadu_avx2(&inputs[4][block_offset + 1 * sizeof(__m256i)]); + out_msg[13] = loadu_avx2(&inputs[5][block_offset + 1 * sizeof(__m256i)]); + out_msg[14] = loadu_avx2(&inputs[6][block_offset + 1 * sizeof(__m256i)]); + out_msg[15] = loadu_avx2(&inputs[7][block_offset + 1 * sizeof(__m256i)]); + + for (i = 0; i < 8; i++) { + _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); + } + transpose_vecs_avx2(&out_msg[0]); + transpose_vecs_avx2(&out_msg[8]); +} + +static inline void +load_counters_avx2(uint64_t counter, int increment_counter, __m256i *out_lo, __m256i *out_hi) +{ + const __m256i mask = _mm256_set1_epi32(-increment_counter); + const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); + const __m256i add1 = _mm256_and_si256(mask, add0); + __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1); + __m256i carry = _mm256_xor_si256(add1, _mm256_set1_epi32(0x80000000)); + __m256i comp = _mm256_xor_si256(l, _mm256_set1_epi32(0x80000000)); + __m256i gt = _mm256_cmpgt_epi32(carry, comp); + __m256i h = _mm256_sub_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), gt); + + *out_lo = l; + *out_hi = h; +} + +void +blake3_hash8_avx2( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m256i h_vecs[8]; + __m256i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_avx2(key[0]); + h_vecs[1] = set1_avx2(key[1]); + h_vecs[2] = set1_avx2(key[2]); + h_vecs[3] = set1_avx2(key[3]); + h_vecs[4] = set1_avx2(key[4]); + h_vecs[5] = set1_avx2(key[5]); + h_vecs[6] = set1_avx2(key[6]); + h_vecs[7] = set1_avx2(key[7]); + + load_counters_avx2(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m256i block_len_vec; + __m256i block_flags_vec; + __m256i msg_vecs[16]; + __m256i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_avx2(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_avx2(block_flags); + transpose_msg_vecs_avx2(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_avx2(IV[0]); + v[9] = set1_avx2(IV[1]); + v[10] = set1_avx2(IV[2]); + v[11] = set1_avx2(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn_avx2(v, msg_vecs, 0); + round_fn_avx2(v, msg_vecs, 1); + round_fn_avx2(v, msg_vecs, 2); + round_fn_avx2(v, msg_vecs, 3); + round_fn_avx2(v, msg_vecs, 4); + round_fn_avx2(v, msg_vecs, 5); + round_fn_avx2(v, msg_vecs, 6); + + h_vecs[0] = xorv_avx2(v[0], v[8]); + h_vecs[1] = xorv_avx2(v[1], v[9]); + h_vecs[2] = xorv_avx2(v[2], v[10]); + h_vecs[3] = xorv_avx2(v[3], v[11]); + h_vecs[4] = xorv_avx2(v[4], v[12]); + h_vecs[5] = xorv_avx2(v[5], v[13]); + h_vecs[6] = xorv_avx2(v[6], v[14]); + h_vecs[7] = xorv_avx2(v[7], v[15]); + + block_flags = flags; + } + + transpose_vecs_avx2(h_vecs); + storeu_avx2(h_vecs[0], &out_bytes[0 * sizeof(__m256i)]); + storeu_avx2(h_vecs[1], &out_bytes[1 * sizeof(__m256i)]); + storeu_avx2(h_vecs[2], &out_bytes[2 * sizeof(__m256i)]); + storeu_avx2(h_vecs[3], &out_bytes[3 * sizeof(__m256i)]); + storeu_avx2(h_vecs[4], &out_bytes[4 * sizeof(__m256i)]); + storeu_avx2(h_vecs[5], &out_bytes[5 * sizeof(__m256i)]); + storeu_avx2(h_vecs[6], &out_bytes[6 * sizeof(__m256i)]); + storeu_avx2(h_vecs[7], &out_bytes[7 * sizeof(__m256i)]); +} + +void +blake3_hash_many_avx2( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + while (num_inputs >= DEGREE_AVX2) { + blake3_hash8_avx2( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += DEGREE_AVX2; + } + inputs += DEGREE_AVX2; + num_inputs -= DEGREE_AVX2; + out_bytes = &out_bytes[DEGREE_AVX2 * BLAKE3_OUT_LEN]; + } + blake3_hash_many_sse41( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out_bytes + ); +} +#if defined(__clang__) +#pragma clang attribute pop +#elif defined(__GNUC__) +#pragma GCC pop_options +#endif + +#if defined(__clang__) +#pragma clang attribute push(__attribute__((target("avx512f,avx512vl"))), apply_to = function) +#elif defined(__GNUC__) +#pragma GCC push_options +#pragma GCC target("avx512f,avx512vl") +#endif +static inline __m128i +loadu_128_avx512(const uint8_t src[16]) +{ + return _mm_loadu_si128((const __m128i *)src); +} + +static inline __m256i +loadu_256_avx512(const uint8_t src[32]) +{ + return _mm256_loadu_si256((const __m256i *)src); +} + +static inline __m512i +loadu_512_avx512(const uint8_t src[64]) +{ + return _mm512_loadu_si512((const __m512i *)src); +} + +static inline void +storeu_128_avx512(__m128i src, uint8_t dest[16]) +{ + _mm_storeu_si128((__m128i *)dest, src); +} + +static inline void +storeu_256_avx512(__m256i src, uint8_t dest[32]) +{ + _mm256_storeu_si256((__m256i *)dest, src); +} + +static inline __m128i +add_128_avx512(__m128i a, __m128i b) +{ + return _mm_add_epi32(a, b); +} + +static inline __m256i +add_256_avx512(__m256i a, __m256i b) +{ + return _mm256_add_epi32(a, b); +} + +static inline __m512i +add_512_avx512(__m512i a, __m512i b) +{ + return _mm512_add_epi32(a, b); +} + +static inline __m128i +xor_128_avx512(__m128i a, __m128i b) +{ + return _mm_xor_si128(a, b); +} + +static inline __m256i +xor_256_avx512(__m256i a, __m256i b) +{ + return _mm256_xor_si256(a, b); +} + +static inline __m512i +xor_512_avx512(__m512i a, __m512i b) +{ + return _mm512_xor_si512(a, b); +} + +static inline __m128i +set1_128_avx512(uint32_t x) +{ + return _mm_set1_epi32((int32_t)x); +} + +static inline __m256i +set1_256_avx512(uint32_t x) +{ + return _mm256_set1_epi32((int32_t)x); +} + +static inline __m512i +set1_512_avx512(uint32_t x) +{ + return _mm512_set1_epi32((int32_t)x); +} + +static inline __m128i +set4_avx512(uint32_t a, uint32_t b, uint32_t c, uint32_t d) +{ + return _mm_setr_epi32((int32_t)a, (int32_t)b, (int32_t)c, (int32_t)d); +} + +static inline __m128i +rot16_128_avx512(__m128i x) +{ + return _mm_ror_epi32(x, 16); +} + +static inline __m256i +rot16_256_avx512(__m256i x) +{ + return _mm256_ror_epi32(x, 16); +} + +static inline __m512i +rot16_512_avx512(__m512i x) +{ + return _mm512_ror_epi32(x, 16); +} + +static inline __m128i +rot12_128_avx512(__m128i x) +{ + return _mm_ror_epi32(x, 12); +} + +static inline __m256i +rot12_256_avx512(__m256i x) +{ + return _mm256_ror_epi32(x, 12); +} + +static inline __m512i +rot12_512_avx512(__m512i x) +{ + return _mm512_ror_epi32(x, 12); +} + +static inline __m128i +rot8_128_avx512(__m128i x) +{ + return _mm_ror_epi32(x, 8); +} + +static inline __m256i +rot8_256_avx512(__m256i x) +{ + return _mm256_ror_epi32(x, 8); +} + +static inline __m512i +rot8_512_avx512(__m512i x) +{ + return _mm512_ror_epi32(x, 8); +} + +static inline __m128i +rot7_128_avx512(__m128i x) +{ + return _mm_ror_epi32(x, 7); +} + +static inline __m256i +rot7_256_avx512(__m256i x) +{ + return _mm256_ror_epi32(x, 7); +} + +static inline __m512i +rot7_512_avx512(__m512i x) +{ + return _mm512_ror_epi32(x, 7); +} + +static inline void +g1_avx512(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = add_128_avx512(add_128_avx512(*row0, m), *row1); + *row3 = xor_128_avx512(*row3, *row0); + *row3 = rot16_128_avx512(*row3); + *row2 = add_128_avx512(*row2, *row3); + *row1 = xor_128_avx512(*row1, *row2); + *row1 = rot12_128_avx512(*row1); +} + +static inline void +g2_avx512(__m128i *row0, __m128i *row1, __m128i *row2, __m128i *row3, __m128i m) +{ + *row0 = add_128_avx512(add_128_avx512(*row0, m), *row1); + *row3 = xor_128_avx512(*row3, *row0); + *row3 = rot8_128_avx512(*row3); + *row2 = add_128_avx512(*row2, *row3); + *row1 = xor_128_avx512(*row1, *row2); + *row1 = rot7_128_avx512(*row1); +} + +static inline void +diagonalize_avx512(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(2, 1, 0, 3)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(0, 3, 2, 1)); +} + +static inline void +undiagonalize_avx512(__m128i *row0, __m128i *row2, __m128i *row3) +{ + *row0 = _mm_shuffle_epi32(*row0, _MM_SHUFFLE(0, 3, 2, 1)); + *row3 = _mm_shuffle_epi32(*row3, _MM_SHUFFLE(1, 0, 3, 2)); + *row2 = _mm_shuffle_epi32(*row2, _MM_SHUFFLE(2, 1, 0, 3)); +} + +static inline void +compress_pre_avx512( + __m128i rows[4], + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i m0, m1, m2, m3; + __m128i t0, t1, t2, t3; + + rows[0] = loadu_128_avx512((const uint8_t *)&cv[0]); + rows[1] = loadu_128_avx512((const uint8_t *)&cv[4]); + rows[2] = set4_avx512(IV[0], IV[1], IV[2], IV[3]); + rows[3] = set4_avx512( + counter_low(counter), counter_high(counter), (uint32_t)block_len, (uint32_t)flags + ); + + m0 = loadu_128_avx512(&block[sizeof(__m128i) * 0]); + m1 = loadu_128_avx512(&block[sizeof(__m128i) * 1]); + m2 = loadu_128_avx512(&block[sizeof(__m128i) * 2]); + m3 = loadu_128_avx512(&block[sizeof(__m128i) * 3]); + + /* round 1 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(2, 0, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 3, 1)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(2, 0, 2, 0)); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(2, 1, 0, 3)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 1, 3, 1)); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(2, 1, 0, 3)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 2 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 3 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 4 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 5 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 6 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); + m0 = t0; + m1 = t1; + m2 = t2; + m3 = t3; + + /* round 7 */ + t0 = _mm_shuffle_ps2(m0, m1, _MM_SHUFFLE(3, 1, 1, 2)); + t0 = _mm_shuffle_epi32(t0, _MM_SHUFFLE(0, 3, 2, 1)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t0); + t1 = _mm_shuffle_ps2(m2, m3, _MM_SHUFFLE(3, 3, 2, 2)); + t1 = _mm_blend_epi16(m0, t1, 0xCC); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t1); + diagonalize_avx512(&rows[0], &rows[2], &rows[3]); + t2 = _mm_unpacklo_epi64(m3, m1); + t2 = _mm_blend_epi16(t2, m2, 0xC0); + t2 = _mm_shuffle_epi32(t2, _MM_SHUFFLE(1, 3, 2, 0)); + g1_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t2); + t3 = _mm_unpackhi_epi32(m1, m3); + t3 = _mm_unpacklo_epi32(m2, t3); + t3 = _mm_shuffle_epi32(t3, _MM_SHUFFLE(0, 1, 3, 2)); + g2_avx512(&rows[0], &rows[1], &rows[2], &rows[3], t3); + undiagonalize_avx512(&rows[0], &rows[2], &rows[3]); +} + +void +blake3_compress_in_place_avx512( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + __m128i rows[4]; + + compress_pre_avx512(rows, cv, block, block_len, counter, flags); + storeu_128_avx512(xor_128_avx512(rows[0], rows[2]), (uint8_t *)&cv[0]); + storeu_128_avx512(xor_128_avx512(rows[1], rows[3]), (uint8_t *)&cv[4]); +} + +void +blake3_compress_xof_avx512( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out_buf[64] +) +{ + __m128i rows[4]; + + compress_pre_avx512(rows, cv, block, block_len, counter, flags); + storeu_128_avx512(xor_128_avx512(rows[0], rows[2]), &out_buf[0]); + storeu_128_avx512(xor_128_avx512(rows[1], rows[3]), &out_buf[16]); + storeu_128_avx512( + xor_128_avx512(rows[2], loadu_128_avx512((const uint8_t *)&cv[0])), &out_buf[32] + ); + storeu_128_avx512( + xor_128_avx512(rows[3], loadu_128_avx512((const uint8_t *)&cv[4])), &out_buf[48] + ); +} + +static inline void +round_fn4_avx512(__m128i v[16], __m128i m[16], size_t r) +{ + v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = add_128_avx512(v[0], v[4]); + v[1] = add_128_avx512(v[1], v[5]); + v[2] = add_128_avx512(v[2], v[6]); + v[3] = add_128_avx512(v[3], v[7]); + v[12] = xor_128_avx512(v[12], v[0]); + v[13] = xor_128_avx512(v[13], v[1]); + v[14] = xor_128_avx512(v[14], v[2]); + v[15] = xor_128_avx512(v[15], v[3]); + v[12] = rot16_128_avx512(v[12]); + v[13] = rot16_128_avx512(v[13]); + v[14] = rot16_128_avx512(v[14]); + v[15] = rot16_128_avx512(v[15]); + v[8] = add_128_avx512(v[8], v[12]); + v[9] = add_128_avx512(v[9], v[13]); + v[10] = add_128_avx512(v[10], v[14]); + v[11] = add_128_avx512(v[11], v[15]); + v[4] = xor_128_avx512(v[4], v[8]); + v[5] = xor_128_avx512(v[5], v[9]); + v[6] = xor_128_avx512(v[6], v[10]); + v[7] = xor_128_avx512(v[7], v[11]); + v[4] = rot12_128_avx512(v[4]); + v[5] = rot12_128_avx512(v[5]); + v[6] = rot12_128_avx512(v[6]); + v[7] = rot12_128_avx512(v[7]); + v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = add_128_avx512(v[0], v[4]); + v[1] = add_128_avx512(v[1], v[5]); + v[2] = add_128_avx512(v[2], v[6]); + v[3] = add_128_avx512(v[3], v[7]); + v[12] = xor_128_avx512(v[12], v[0]); + v[13] = xor_128_avx512(v[13], v[1]); + v[14] = xor_128_avx512(v[14], v[2]); + v[15] = xor_128_avx512(v[15], v[3]); + v[12] = rot8_128_avx512(v[12]); + v[13] = rot8_128_avx512(v[13]); + v[14] = rot8_128_avx512(v[14]); + v[15] = rot8_128_avx512(v[15]); + v[8] = add_128_avx512(v[8], v[12]); + v[9] = add_128_avx512(v[9], v[13]); + v[10] = add_128_avx512(v[10], v[14]); + v[11] = add_128_avx512(v[11], v[15]); + v[4] = xor_128_avx512(v[4], v[8]); + v[5] = xor_128_avx512(v[5], v[9]); + v[6] = xor_128_avx512(v[6], v[10]); + v[7] = xor_128_avx512(v[7], v[11]); + v[4] = rot7_128_avx512(v[4]); + v[5] = rot7_128_avx512(v[5]); + v[6] = rot7_128_avx512(v[6]); + v[7] = rot7_128_avx512(v[7]); + + v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = add_128_avx512(v[0], v[5]); + v[1] = add_128_avx512(v[1], v[6]); + v[2] = add_128_avx512(v[2], v[7]); + v[3] = add_128_avx512(v[3], v[4]); + v[15] = xor_128_avx512(v[15], v[0]); + v[12] = xor_128_avx512(v[12], v[1]); + v[13] = xor_128_avx512(v[13], v[2]); + v[14] = xor_128_avx512(v[14], v[3]); + v[15] = rot16_128_avx512(v[15]); + v[12] = rot16_128_avx512(v[12]); + v[13] = rot16_128_avx512(v[13]); + v[14] = rot16_128_avx512(v[14]); + v[10] = add_128_avx512(v[10], v[15]); + v[11] = add_128_avx512(v[11], v[12]); + v[8] = add_128_avx512(v[8], v[13]); + v[9] = add_128_avx512(v[9], v[14]); + v[5] = xor_128_avx512(v[5], v[10]); + v[6] = xor_128_avx512(v[6], v[11]); + v[7] = xor_128_avx512(v[7], v[8]); + v[4] = xor_128_avx512(v[4], v[9]); + v[5] = rot12_128_avx512(v[5]); + v[6] = rot12_128_avx512(v[6]); + v[7] = rot12_128_avx512(v[7]); + v[4] = rot12_128_avx512(v[4]); + v[0] = add_128_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = add_128_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = add_128_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = add_128_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = add_128_avx512(v[0], v[5]); + v[1] = add_128_avx512(v[1], v[6]); + v[2] = add_128_avx512(v[2], v[7]); + v[3] = add_128_avx512(v[3], v[4]); + v[15] = xor_128_avx512(v[15], v[0]); + v[12] = xor_128_avx512(v[12], v[1]); + v[13] = xor_128_avx512(v[13], v[2]); + v[14] = xor_128_avx512(v[14], v[3]); + v[15] = rot8_128_avx512(v[15]); + v[12] = rot8_128_avx512(v[12]); + v[13] = rot8_128_avx512(v[13]); + v[14] = rot8_128_avx512(v[14]); + v[10] = add_128_avx512(v[10], v[15]); + v[11] = add_128_avx512(v[11], v[12]); + v[8] = add_128_avx512(v[8], v[13]); + v[9] = add_128_avx512(v[9], v[14]); + v[5] = xor_128_avx512(v[5], v[10]); + v[6] = xor_128_avx512(v[6], v[11]); + v[7] = xor_128_avx512(v[7], v[8]); + v[4] = xor_128_avx512(v[4], v[9]); + v[5] = rot7_128_avx512(v[5]); + v[6] = rot7_128_avx512(v[6]); + v[7] = rot7_128_avx512(v[7]); + v[4] = rot7_128_avx512(v[4]); +} + +static inline void +round_fn8_avx512(__m256i v[16], __m256i m[16], size_t r) +{ + v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = add_256_avx512(v[0], v[4]); + v[1] = add_256_avx512(v[1], v[5]); + v[2] = add_256_avx512(v[2], v[6]); + v[3] = add_256_avx512(v[3], v[7]); + v[12] = xor_256_avx512(v[12], v[0]); + v[13] = xor_256_avx512(v[13], v[1]); + v[14] = xor_256_avx512(v[14], v[2]); + v[15] = xor_256_avx512(v[15], v[3]); + v[12] = rot16_256_avx512(v[12]); + v[13] = rot16_256_avx512(v[13]); + v[14] = rot16_256_avx512(v[14]); + v[15] = rot16_256_avx512(v[15]); + v[8] = add_256_avx512(v[8], v[12]); + v[9] = add_256_avx512(v[9], v[13]); + v[10] = add_256_avx512(v[10], v[14]); + v[11] = add_256_avx512(v[11], v[15]); + v[4] = xor_256_avx512(v[4], v[8]); + v[5] = xor_256_avx512(v[5], v[9]); + v[6] = xor_256_avx512(v[6], v[10]); + v[7] = xor_256_avx512(v[7], v[11]); + v[4] = rot12_256_avx512(v[4]); + v[5] = rot12_256_avx512(v[5]); + v[6] = rot12_256_avx512(v[6]); + v[7] = rot12_256_avx512(v[7]); + v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = add_256_avx512(v[0], v[4]); + v[1] = add_256_avx512(v[1], v[5]); + v[2] = add_256_avx512(v[2], v[6]); + v[3] = add_256_avx512(v[3], v[7]); + v[12] = xor_256_avx512(v[12], v[0]); + v[13] = xor_256_avx512(v[13], v[1]); + v[14] = xor_256_avx512(v[14], v[2]); + v[15] = xor_256_avx512(v[15], v[3]); + v[12] = rot8_256_avx512(v[12]); + v[13] = rot8_256_avx512(v[13]); + v[14] = rot8_256_avx512(v[14]); + v[15] = rot8_256_avx512(v[15]); + v[8] = add_256_avx512(v[8], v[12]); + v[9] = add_256_avx512(v[9], v[13]); + v[10] = add_256_avx512(v[10], v[14]); + v[11] = add_256_avx512(v[11], v[15]); + v[4] = xor_256_avx512(v[4], v[8]); + v[5] = xor_256_avx512(v[5], v[9]); + v[6] = xor_256_avx512(v[6], v[10]); + v[7] = xor_256_avx512(v[7], v[11]); + v[4] = rot7_256_avx512(v[4]); + v[5] = rot7_256_avx512(v[5]); + v[6] = rot7_256_avx512(v[6]); + v[7] = rot7_256_avx512(v[7]); + + v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = add_256_avx512(v[0], v[5]); + v[1] = add_256_avx512(v[1], v[6]); + v[2] = add_256_avx512(v[2], v[7]); + v[3] = add_256_avx512(v[3], v[4]); + v[15] = xor_256_avx512(v[15], v[0]); + v[12] = xor_256_avx512(v[12], v[1]); + v[13] = xor_256_avx512(v[13], v[2]); + v[14] = xor_256_avx512(v[14], v[3]); + v[15] = rot16_256_avx512(v[15]); + v[12] = rot16_256_avx512(v[12]); + v[13] = rot16_256_avx512(v[13]); + v[14] = rot16_256_avx512(v[14]); + v[10] = add_256_avx512(v[10], v[15]); + v[11] = add_256_avx512(v[11], v[12]); + v[8] = add_256_avx512(v[8], v[13]); + v[9] = add_256_avx512(v[9], v[14]); + v[5] = xor_256_avx512(v[5], v[10]); + v[6] = xor_256_avx512(v[6], v[11]); + v[7] = xor_256_avx512(v[7], v[8]); + v[4] = xor_256_avx512(v[4], v[9]); + v[5] = rot12_256_avx512(v[5]); + v[6] = rot12_256_avx512(v[6]); + v[7] = rot12_256_avx512(v[7]); + v[4] = rot12_256_avx512(v[4]); + v[0] = add_256_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = add_256_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = add_256_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = add_256_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = add_256_avx512(v[0], v[5]); + v[1] = add_256_avx512(v[1], v[6]); + v[2] = add_256_avx512(v[2], v[7]); + v[3] = add_256_avx512(v[3], v[4]); + v[15] = xor_256_avx512(v[15], v[0]); + v[12] = xor_256_avx512(v[12], v[1]); + v[13] = xor_256_avx512(v[13], v[2]); + v[14] = xor_256_avx512(v[14], v[3]); + v[15] = rot8_256_avx512(v[15]); + v[12] = rot8_256_avx512(v[12]); + v[13] = rot8_256_avx512(v[13]); + v[14] = rot8_256_avx512(v[14]); + v[10] = add_256_avx512(v[10], v[15]); + v[11] = add_256_avx512(v[11], v[12]); + v[8] = add_256_avx512(v[8], v[13]); + v[9] = add_256_avx512(v[9], v[14]); + v[5] = xor_256_avx512(v[5], v[10]); + v[6] = xor_256_avx512(v[6], v[11]); + v[7] = xor_256_avx512(v[7], v[8]); + v[4] = xor_256_avx512(v[4], v[9]); + v[5] = rot7_256_avx512(v[5]); + v[6] = rot7_256_avx512(v[6]); + v[7] = rot7_256_avx512(v[7]); + v[4] = rot7_256_avx512(v[4]); +} + +static inline void +round_fn16_avx512(__m512i v[16], __m512i m[16], size_t r) +{ + v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][0]]); + v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][2]]); + v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][4]]); + v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][6]]); + v[0] = add_512_avx512(v[0], v[4]); + v[1] = add_512_avx512(v[1], v[5]); + v[2] = add_512_avx512(v[2], v[6]); + v[3] = add_512_avx512(v[3], v[7]); + v[12] = xor_512_avx512(v[12], v[0]); + v[13] = xor_512_avx512(v[13], v[1]); + v[14] = xor_512_avx512(v[14], v[2]); + v[15] = xor_512_avx512(v[15], v[3]); + v[12] = rot16_512_avx512(v[12]); + v[13] = rot16_512_avx512(v[13]); + v[14] = rot16_512_avx512(v[14]); + v[15] = rot16_512_avx512(v[15]); + v[8] = add_512_avx512(v[8], v[12]); + v[9] = add_512_avx512(v[9], v[13]); + v[10] = add_512_avx512(v[10], v[14]); + v[11] = add_512_avx512(v[11], v[15]); + v[4] = xor_512_avx512(v[4], v[8]); + v[5] = xor_512_avx512(v[5], v[9]); + v[6] = xor_512_avx512(v[6], v[10]); + v[7] = xor_512_avx512(v[7], v[11]); + v[4] = rot12_512_avx512(v[4]); + v[5] = rot12_512_avx512(v[5]); + v[6] = rot12_512_avx512(v[6]); + v[7] = rot12_512_avx512(v[7]); + v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][1]]); + v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][3]]); + v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][5]]); + v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][7]]); + v[0] = add_512_avx512(v[0], v[4]); + v[1] = add_512_avx512(v[1], v[5]); + v[2] = add_512_avx512(v[2], v[6]); + v[3] = add_512_avx512(v[3], v[7]); + v[12] = xor_512_avx512(v[12], v[0]); + v[13] = xor_512_avx512(v[13], v[1]); + v[14] = xor_512_avx512(v[14], v[2]); + v[15] = xor_512_avx512(v[15], v[3]); + v[12] = rot8_512_avx512(v[12]); + v[13] = rot8_512_avx512(v[13]); + v[14] = rot8_512_avx512(v[14]); + v[15] = rot8_512_avx512(v[15]); + v[8] = add_512_avx512(v[8], v[12]); + v[9] = add_512_avx512(v[9], v[13]); + v[10] = add_512_avx512(v[10], v[14]); + v[11] = add_512_avx512(v[11], v[15]); + v[4] = xor_512_avx512(v[4], v[8]); + v[5] = xor_512_avx512(v[5], v[9]); + v[6] = xor_512_avx512(v[6], v[10]); + v[7] = xor_512_avx512(v[7], v[11]); + v[4] = rot7_512_avx512(v[4]); + v[5] = rot7_512_avx512(v[5]); + v[6] = rot7_512_avx512(v[6]); + v[7] = rot7_512_avx512(v[7]); + + v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][8]]); + v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][10]]); + v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][12]]); + v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][14]]); + v[0] = add_512_avx512(v[0], v[5]); + v[1] = add_512_avx512(v[1], v[6]); + v[2] = add_512_avx512(v[2], v[7]); + v[3] = add_512_avx512(v[3], v[4]); + v[15] = xor_512_avx512(v[15], v[0]); + v[12] = xor_512_avx512(v[12], v[1]); + v[13] = xor_512_avx512(v[13], v[2]); + v[14] = xor_512_avx512(v[14], v[3]); + v[15] = rot16_512_avx512(v[15]); + v[12] = rot16_512_avx512(v[12]); + v[13] = rot16_512_avx512(v[13]); + v[14] = rot16_512_avx512(v[14]); + v[10] = add_512_avx512(v[10], v[15]); + v[11] = add_512_avx512(v[11], v[12]); + v[8] = add_512_avx512(v[8], v[13]); + v[9] = add_512_avx512(v[9], v[14]); + v[5] = xor_512_avx512(v[5], v[10]); + v[6] = xor_512_avx512(v[6], v[11]); + v[7] = xor_512_avx512(v[7], v[8]); + v[4] = xor_512_avx512(v[4], v[9]); + v[5] = rot12_512_avx512(v[5]); + v[6] = rot12_512_avx512(v[6]); + v[7] = rot12_512_avx512(v[7]); + v[4] = rot12_512_avx512(v[4]); + v[0] = add_512_avx512(v[0], m[(size_t)MSG_SCHEDULE[r][9]]); + v[1] = add_512_avx512(v[1], m[(size_t)MSG_SCHEDULE[r][11]]); + v[2] = add_512_avx512(v[2], m[(size_t)MSG_SCHEDULE[r][13]]); + v[3] = add_512_avx512(v[3], m[(size_t)MSG_SCHEDULE[r][15]]); + v[0] = add_512_avx512(v[0], v[5]); + v[1] = add_512_avx512(v[1], v[6]); + v[2] = add_512_avx512(v[2], v[7]); + v[3] = add_512_avx512(v[3], v[4]); + v[15] = xor_512_avx512(v[15], v[0]); + v[12] = xor_512_avx512(v[12], v[1]); + v[13] = xor_512_avx512(v[13], v[2]); + v[14] = xor_512_avx512(v[14], v[3]); + v[15] = rot8_512_avx512(v[15]); + v[12] = rot8_512_avx512(v[12]); + v[13] = rot8_512_avx512(v[13]); + v[14] = rot8_512_avx512(v[14]); + v[10] = add_512_avx512(v[10], v[15]); + v[11] = add_512_avx512(v[11], v[12]); + v[8] = add_512_avx512(v[8], v[13]); + v[9] = add_512_avx512(v[9], v[14]); + v[5] = xor_512_avx512(v[5], v[10]); + v[6] = xor_512_avx512(v[6], v[11]); + v[7] = xor_512_avx512(v[7], v[8]); + v[4] = xor_512_avx512(v[4], v[9]); + v[5] = rot7_512_avx512(v[5]); + v[6] = rot7_512_avx512(v[6]); + v[7] = rot7_512_avx512(v[7]); + v[4] = rot7_512_avx512(v[4]); +} + +#define LO_IMM8 0x88 +#define HI_IMM8 0xdd + +static inline __m512i +unpack_lo_128_avx512(__m512i a, __m512i b) +{ + return _mm512_shuffle_i32x4(a, b, LO_IMM8); +} + +static inline __m512i +unpack_hi_128_avx512(__m512i a, __m512i b) +{ + return _mm512_shuffle_i32x4(a, b, HI_IMM8); +} + +static inline void +transpose_vecs_512_avx512(__m512i vecs[16]) +{ + __m512i ab_0 = _mm512_unpacklo_epi32(vecs[0], vecs[1]); + __m512i ab_2 = _mm512_unpackhi_epi32(vecs[0], vecs[1]); + __m512i cd_0 = _mm512_unpacklo_epi32(vecs[2], vecs[3]); + __m512i cd_2 = _mm512_unpackhi_epi32(vecs[2], vecs[3]); + __m512i ef_0 = _mm512_unpacklo_epi32(vecs[4], vecs[5]); + __m512i ef_2 = _mm512_unpackhi_epi32(vecs[4], vecs[5]); + __m512i gh_0 = _mm512_unpacklo_epi32(vecs[6], vecs[7]); + __m512i gh_2 = _mm512_unpackhi_epi32(vecs[6], vecs[7]); + __m512i ij_0 = _mm512_unpacklo_epi32(vecs[8], vecs[9]); + __m512i ij_2 = _mm512_unpackhi_epi32(vecs[8], vecs[9]); + __m512i kl_0 = _mm512_unpacklo_epi32(vecs[10], vecs[11]); + __m512i kl_2 = _mm512_unpackhi_epi32(vecs[10], vecs[11]); + __m512i mn_0 = _mm512_unpacklo_epi32(vecs[12], vecs[13]); + __m512i mn_2 = _mm512_unpackhi_epi32(vecs[12], vecs[13]); + __m512i op_0 = _mm512_unpacklo_epi32(vecs[14], vecs[15]); + __m512i op_2 = _mm512_unpackhi_epi32(vecs[14], vecs[15]); + + __m512i abcd_0 = _mm512_unpacklo_epi64(ab_0, cd_0); + __m512i abcd_1 = _mm512_unpackhi_epi64(ab_0, cd_0); + __m512i abcd_2 = _mm512_unpacklo_epi64(ab_2, cd_2); + __m512i abcd_3 = _mm512_unpackhi_epi64(ab_2, cd_2); + __m512i efgh_0 = _mm512_unpacklo_epi64(ef_0, gh_0); + __m512i efgh_1 = _mm512_unpackhi_epi64(ef_0, gh_0); + __m512i efgh_2 = _mm512_unpacklo_epi64(ef_2, gh_2); + __m512i efgh_3 = _mm512_unpackhi_epi64(ef_2, gh_2); + __m512i ijkl_0 = _mm512_unpacklo_epi64(ij_0, kl_0); + __m512i ijkl_1 = _mm512_unpackhi_epi64(ij_0, kl_0); + __m512i ijkl_2 = _mm512_unpacklo_epi64(ij_2, kl_2); + __m512i ijkl_3 = _mm512_unpackhi_epi64(ij_2, kl_2); + __m512i mnop_0 = _mm512_unpacklo_epi64(mn_0, op_0); + __m512i mnop_1 = _mm512_unpackhi_epi64(mn_0, op_0); + __m512i mnop_2 = _mm512_unpacklo_epi64(mn_2, op_2); + __m512i mnop_3 = _mm512_unpackhi_epi64(mn_2, op_2); + + __m512i abcdefgh_0 = unpack_lo_128_avx512(abcd_0, efgh_0); + __m512i abcdefgh_1 = unpack_lo_128_avx512(abcd_1, efgh_1); + __m512i abcdefgh_2 = unpack_lo_128_avx512(abcd_2, efgh_2); + __m512i abcdefgh_3 = unpack_lo_128_avx512(abcd_3, efgh_3); + __m512i abcdefgh_4 = unpack_hi_128_avx512(abcd_0, efgh_0); + __m512i abcdefgh_5 = unpack_hi_128_avx512(abcd_1, efgh_1); + __m512i abcdefgh_6 = unpack_hi_128_avx512(abcd_2, efgh_2); + __m512i abcdefgh_7 = unpack_hi_128_avx512(abcd_3, efgh_3); + __m512i ijklmnop_0 = unpack_lo_128_avx512(ijkl_0, mnop_0); + __m512i ijklmnop_1 = unpack_lo_128_avx512(ijkl_1, mnop_1); + __m512i ijklmnop_2 = unpack_lo_128_avx512(ijkl_2, mnop_2); + __m512i ijklmnop_3 = unpack_lo_128_avx512(ijkl_3, mnop_3); + __m512i ijklmnop_4 = unpack_hi_128_avx512(ijkl_0, mnop_0); + __m512i ijklmnop_5 = unpack_hi_128_avx512(ijkl_1, mnop_1); + __m512i ijklmnop_6 = unpack_hi_128_avx512(ijkl_2, mnop_2); + __m512i ijklmnop_7 = unpack_hi_128_avx512(ijkl_3, mnop_3); + + vecs[0] = unpack_lo_128_avx512(abcdefgh_0, ijklmnop_0); + vecs[1] = unpack_lo_128_avx512(abcdefgh_1, ijklmnop_1); + vecs[2] = unpack_lo_128_avx512(abcdefgh_2, ijklmnop_2); + vecs[3] = unpack_lo_128_avx512(abcdefgh_3, ijklmnop_3); + vecs[4] = unpack_lo_128_avx512(abcdefgh_4, ijklmnop_4); + vecs[5] = unpack_lo_128_avx512(abcdefgh_5, ijklmnop_5); + vecs[6] = unpack_lo_128_avx512(abcdefgh_6, ijklmnop_6); + vecs[7] = unpack_lo_128_avx512(abcdefgh_7, ijklmnop_7); + vecs[8] = unpack_hi_128_avx512(abcdefgh_0, ijklmnop_0); + vecs[9] = unpack_hi_128_avx512(abcdefgh_1, ijklmnop_1); + vecs[10] = unpack_hi_128_avx512(abcdefgh_2, ijklmnop_2); + vecs[11] = unpack_hi_128_avx512(abcdefgh_3, ijklmnop_3); + vecs[12] = unpack_hi_128_avx512(abcdefgh_4, ijklmnop_4); + vecs[13] = unpack_hi_128_avx512(abcdefgh_5, ijklmnop_5); + vecs[14] = unpack_hi_128_avx512(abcdefgh_6, ijklmnop_6); + vecs[15] = unpack_hi_128_avx512(abcdefgh_7, ijklmnop_7); +} + +static inline void +transpose_msg_vecs16_avx512(const uint8_t *const *inputs, size_t block_offset, __m512i out_msg[16]) +{ + size_t i; + + out_msg[0] = loadu_512_avx512(&inputs[0][block_offset]); + out_msg[1] = loadu_512_avx512(&inputs[1][block_offset]); + out_msg[2] = loadu_512_avx512(&inputs[2][block_offset]); + out_msg[3] = loadu_512_avx512(&inputs[3][block_offset]); + out_msg[4] = loadu_512_avx512(&inputs[4][block_offset]); + out_msg[5] = loadu_512_avx512(&inputs[5][block_offset]); + out_msg[6] = loadu_512_avx512(&inputs[6][block_offset]); + out_msg[7] = loadu_512_avx512(&inputs[7][block_offset]); + out_msg[8] = loadu_512_avx512(&inputs[8][block_offset]); + out_msg[9] = loadu_512_avx512(&inputs[9][block_offset]); + out_msg[10] = loadu_512_avx512(&inputs[10][block_offset]); + out_msg[11] = loadu_512_avx512(&inputs[11][block_offset]); + out_msg[12] = loadu_512_avx512(&inputs[12][block_offset]); + out_msg[13] = loadu_512_avx512(&inputs[13][block_offset]); + out_msg[14] = loadu_512_avx512(&inputs[14][block_offset]); + out_msg[15] = loadu_512_avx512(&inputs[15][block_offset]); + + for (i = 0; i < 16; i++) { + _mm_prefetch((const void *)&inputs[i][block_offset + 256], _MM_HINT_T0); + } + transpose_vecs_512_avx512(out_msg); +} + +static inline void +load_counters16_avx512(uint64_t counter, int increment_counter, __m512i *out_lo, __m512i *out_hi) +{ + const __m512i mask = _mm512_set1_epi32(-increment_counter); + const __m512i deltas = _mm512_set_epi32(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + const __m512i masked_deltas = _mm512_and_si512(deltas, mask); + const __m512i low_words = _mm512_add_epi32(_mm512_set1_epi32((int32_t)counter), masked_deltas); + const __m512i carries = + _mm512_srli_epi32(_mm512_andnot_si512(low_words, _mm512_set1_epi32((int32_t)counter)), 31); + const __m512i high_words = _mm512_add_epi32(_mm512_set1_epi32((int32_t)(counter >> 32)), carries); + + *out_lo = low_words; + *out_hi = high_words; +} + +void +blake3_hash16_avx512( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m512i h_vecs[8]; + __m512i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_512_avx512(key[0]); + h_vecs[1] = set1_512_avx512(key[1]); + h_vecs[2] = set1_512_avx512(key[2]); + h_vecs[3] = set1_512_avx512(key[3]); + h_vecs[4] = set1_512_avx512(key[4]); + h_vecs[5] = set1_512_avx512(key[5]); + h_vecs[6] = set1_512_avx512(key[6]); + h_vecs[7] = set1_512_avx512(key[7]); + + load_counters16_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m512i block_len_vec; + __m512i block_flags_vec; + __m512i msg_vecs[16]; + __m512i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_512_avx512(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_512_avx512(block_flags); + transpose_msg_vecs16_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_512_avx512(IV[0]); + v[9] = set1_512_avx512(IV[1]); + v[10] = set1_512_avx512(IV[2]); + v[11] = set1_512_avx512(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn16_avx512(v, msg_vecs, 0); + round_fn16_avx512(v, msg_vecs, 1); + round_fn16_avx512(v, msg_vecs, 2); + round_fn16_avx512(v, msg_vecs, 3); + round_fn16_avx512(v, msg_vecs, 4); + round_fn16_avx512(v, msg_vecs, 5); + round_fn16_avx512(v, msg_vecs, 6); + + h_vecs[0] = xor_512_avx512(v[0], v[8]); + h_vecs[1] = xor_512_avx512(v[1], v[9]); + h_vecs[2] = xor_512_avx512(v[2], v[10]); + h_vecs[3] = xor_512_avx512(v[3], v[11]); + h_vecs[4] = xor_512_avx512(v[4], v[12]); + h_vecs[5] = xor_512_avx512(v[5], v[13]); + h_vecs[6] = xor_512_avx512(v[6], v[14]); + h_vecs[7] = xor_512_avx512(v[7], v[15]); + + block_flags = flags; + } + + __m512i padded[16] = { + h_vecs[0], + h_vecs[1], + h_vecs[2], + h_vecs[3], + h_vecs[4], + h_vecs[5], + h_vecs[6], + h_vecs[7], + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + set1_512_avx512(0), + }; + transpose_vecs_512_avx512(padded); + _mm256_mask_storeu_epi32( + &out_bytes[0 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[0]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[1 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[1]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[2 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[2]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[3 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[3]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[4 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[4]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[5 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[5]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[6 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[6]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[7 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[7]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[8 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[8]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[9 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[9]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[10 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[10]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[11 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[11]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[12 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[12]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[13 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[13]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[14 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[14]) + ); + _mm256_mask_storeu_epi32( + &out_bytes[15 * sizeof(__m256i)], (__mmask8)-1, _mm512_castsi512_si256(padded[15]) + ); +} + +static inline void +transpose_msg_vecs8_avx512(const uint8_t *const *inputs, size_t block_offset, __m256i out_msg[16]) +{ + out_msg[0] = loadu_256_avx512(&inputs[0][block_offset]); + out_msg[1] = loadu_256_avx512(&inputs[1][block_offset]); + out_msg[2] = loadu_256_avx512(&inputs[2][block_offset]); + out_msg[3] = loadu_256_avx512(&inputs[3][block_offset]); + out_msg[4] = loadu_256_avx512(&inputs[4][block_offset]); + out_msg[5] = loadu_256_avx512(&inputs[5][block_offset]); + out_msg[6] = loadu_256_avx512(&inputs[6][block_offset]); + out_msg[7] = loadu_256_avx512(&inputs[7][block_offset]); + out_msg[8] = loadu_256_avx512(&inputs[0][block_offset + 32]); + out_msg[9] = loadu_256_avx512(&inputs[1][block_offset + 32]); + out_msg[10] = loadu_256_avx512(&inputs[2][block_offset + 32]); + out_msg[11] = loadu_256_avx512(&inputs[3][block_offset + 32]); + out_msg[12] = loadu_256_avx512(&inputs[4][block_offset + 32]); + out_msg[13] = loadu_256_avx512(&inputs[5][block_offset + 32]); + out_msg[14] = loadu_256_avx512(&inputs[6][block_offset + 32]); + out_msg[15] = loadu_256_avx512(&inputs[7][block_offset + 32]); + + transpose_vecs_avx2(out_msg); +} + +static inline void +load_counters8_avx512(uint64_t counter, int increment_counter, __m256i *out_lo, __m256i *out_hi) +{ + const __m256i mask = _mm256_set1_epi32(-increment_counter); + const __m256i add0 = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); + const __m256i add1 = _mm256_and_si256(mask, add0); + __m256i l = _mm256_add_epi32(_mm256_set1_epi32((int32_t)counter), add1); + __m256i carry = + _mm256_srli_epi32(_mm256_andnot_si256(l, _mm256_set1_epi32((int32_t)counter)), 31); + __m256i h = _mm256_add_epi32(_mm256_set1_epi32((int32_t)(counter >> 32)), carry); + + *out_lo = l; + *out_hi = h; +} + +void +blake3_hash8_avx512( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m256i h_vecs[8]; + __m256i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_256_avx512(key[0]); + h_vecs[1] = set1_256_avx512(key[1]); + h_vecs[2] = set1_256_avx512(key[2]); + h_vecs[3] = set1_256_avx512(key[3]); + h_vecs[4] = set1_256_avx512(key[4]); + h_vecs[5] = set1_256_avx512(key[5]); + h_vecs[6] = set1_256_avx512(key[6]); + h_vecs[7] = set1_256_avx512(key[7]); + + load_counters8_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m256i block_len_vec; + __m256i block_flags_vec; + __m256i msg_vecs[16]; + __m256i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_256_avx512(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_256_avx512(block_flags); + transpose_msg_vecs8_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_256_avx512(IV[0]); + v[9] = set1_256_avx512(IV[1]); + v[10] = set1_256_avx512(IV[2]); + v[11] = set1_256_avx512(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn8_avx512(v, msg_vecs, 0); + round_fn8_avx512(v, msg_vecs, 1); + round_fn8_avx512(v, msg_vecs, 2); + round_fn8_avx512(v, msg_vecs, 3); + round_fn8_avx512(v, msg_vecs, 4); + round_fn8_avx512(v, msg_vecs, 5); + round_fn8_avx512(v, msg_vecs, 6); + + h_vecs[0] = xor_256_avx512(v[0], v[8]); + h_vecs[1] = xor_256_avx512(v[1], v[9]); + h_vecs[2] = xor_256_avx512(v[2], v[10]); + h_vecs[3] = xor_256_avx512(v[3], v[11]); + h_vecs[4] = xor_256_avx512(v[4], v[12]); + h_vecs[5] = xor_256_avx512(v[5], v[13]); + h_vecs[6] = xor_256_avx512(v[6], v[14]); + h_vecs[7] = xor_256_avx512(v[7], v[15]); + + block_flags = flags; + } + + transpose_vecs_avx2(h_vecs); + storeu_256_avx512(h_vecs[0], &out_bytes[0 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[1], &out_bytes[1 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[2], &out_bytes[2 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[3], &out_bytes[3 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[4], &out_bytes[4 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[5], &out_bytes[5 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[6], &out_bytes[6 * sizeof(__m256i)]); + storeu_256_avx512(h_vecs[7], &out_bytes[7 * sizeof(__m256i)]); +} + +static inline void +transpose_msg_vecs4_avx512(const uint8_t *const *inputs, size_t block_offset, __m128i out_msg[16]) +{ + out_msg[0] = loadu_128_avx512(&inputs[0][block_offset]); + out_msg[1] = loadu_128_avx512(&inputs[1][block_offset]); + out_msg[2] = loadu_128_avx512(&inputs[2][block_offset]); + out_msg[3] = loadu_128_avx512(&inputs[3][block_offset]); + out_msg[4] = loadu_128_avx512(&inputs[0][block_offset + 16]); + out_msg[5] = loadu_128_avx512(&inputs[1][block_offset + 16]); + out_msg[6] = loadu_128_avx512(&inputs[2][block_offset + 16]); + out_msg[7] = loadu_128_avx512(&inputs[3][block_offset + 16]); + out_msg[8] = loadu_128_avx512(&inputs[0][block_offset + 32]); + out_msg[9] = loadu_128_avx512(&inputs[1][block_offset + 32]); + out_msg[10] = loadu_128_avx512(&inputs[2][block_offset + 32]); + out_msg[11] = loadu_128_avx512(&inputs[3][block_offset + 32]); + out_msg[12] = loadu_128_avx512(&inputs[0][block_offset + 48]); + out_msg[13] = loadu_128_avx512(&inputs[1][block_offset + 48]); + out_msg[14] = loadu_128_avx512(&inputs[2][block_offset + 48]); + out_msg[15] = loadu_128_avx512(&inputs[3][block_offset + 48]); + + transpose_vecs_sse2(out_msg); +} + +static inline void +load_counters4_avx512(uint64_t counter, int increment_counter, __m128i *out_lo, __m128i *out_hi) +{ + const __m128i mask = _mm_set1_epi32(-increment_counter); + const __m128i add0 = _mm_set_epi32(3, 2, 1, 0); + const __m128i add1 = _mm_and_si128(mask, add0); + __m128i l = _mm_add_epi32(_mm_set1_epi32((int32_t)counter), add1); + __m128i carry = _mm_srli_epi32(_mm_andnot_si128(l, _mm_set1_epi32((int32_t)counter)), 31); + __m128i h = _mm_add_epi32(_mm_set1_epi32((int32_t)(counter >> 32)), carry); + + *out_lo = l; + *out_hi = h; +} + +void +blake3_hash4_avx512( + const uint8_t *const *inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + __m128i h_vecs[8]; + __m128i counter_low_vec, counter_high_vec; + uint8_t block_flags; + size_t block; + + h_vecs[0] = set1_128_avx512(key[0]); + h_vecs[1] = set1_128_avx512(key[1]); + h_vecs[2] = set1_128_avx512(key[2]); + h_vecs[3] = set1_128_avx512(key[3]); + h_vecs[4] = set1_128_avx512(key[4]); + h_vecs[5] = set1_128_avx512(key[5]); + h_vecs[6] = set1_128_avx512(key[6]); + h_vecs[7] = set1_128_avx512(key[7]); + + load_counters4_avx512(counter, increment_counter, &counter_low_vec, &counter_high_vec); + block_flags = flags | flags_start; + + for (block = 0; block < blocks; block++) { + __m128i block_len_vec; + __m128i block_flags_vec; + __m128i msg_vecs[16]; + __m128i v[16]; + + if (block + 1 == blocks) { + block_flags |= flags_end; + } + block_len_vec = set1_128_avx512(BLAKE3_BLOCK_LEN); + block_flags_vec = set1_128_avx512(block_flags); + transpose_msg_vecs4_avx512(inputs, block * BLAKE3_BLOCK_LEN, msg_vecs); + + v[0] = h_vecs[0]; + v[1] = h_vecs[1]; + v[2] = h_vecs[2]; + v[3] = h_vecs[3]; + v[4] = h_vecs[4]; + v[5] = h_vecs[5]; + v[6] = h_vecs[6]; + v[7] = h_vecs[7]; + v[8] = set1_128_avx512(IV[0]); + v[9] = set1_128_avx512(IV[1]); + v[10] = set1_128_avx512(IV[2]); + v[11] = set1_128_avx512(IV[3]); + v[12] = counter_low_vec; + v[13] = counter_high_vec; + v[14] = block_len_vec; + v[15] = block_flags_vec; + + round_fn4_avx512(v, msg_vecs, 0); + round_fn4_avx512(v, msg_vecs, 1); + round_fn4_avx512(v, msg_vecs, 2); + round_fn4_avx512(v, msg_vecs, 3); + round_fn4_avx512(v, msg_vecs, 4); + round_fn4_avx512(v, msg_vecs, 5); + round_fn4_avx512(v, msg_vecs, 6); + + h_vecs[0] = xor_128_avx512(v[0], v[8]); + h_vecs[1] = xor_128_avx512(v[1], v[9]); + h_vecs[2] = xor_128_avx512(v[2], v[10]); + h_vecs[3] = xor_128_avx512(v[3], v[11]); + h_vecs[4] = xor_128_avx512(v[4], v[12]); + h_vecs[5] = xor_128_avx512(v[5], v[13]); + h_vecs[6] = xor_128_avx512(v[6], v[14]); + h_vecs[7] = xor_128_avx512(v[7], v[15]); + + block_flags = flags; + } + + transpose_vecs_sse2(h_vecs); + storeu_128_avx512(h_vecs[0], &out_bytes[0 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[1], &out_bytes[2 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[2], &out_bytes[4 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[3], &out_bytes[6 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[4], &out_bytes[1 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[5], &out_bytes[3 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[6], &out_bytes[5 * sizeof(__m128i)]); + storeu_128_avx512(h_vecs[7], &out_bytes[7 * sizeof(__m128i)]); +} + +static inline void +hash_one_avx512( + const uint8_t *input, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t out_bytes[BLAKE3_OUT_LEN] +) +{ + uint32_t cv[8]; + uint8_t block_flags; + + memcpy(cv, key, BLAKE3_KEY_LEN); + block_flags = flags | flags_start; + while (blocks > 0) { + if (blocks == 1) { + block_flags |= flags_end; + } + blake3_compress_in_place_avx512(cv, input, BLAKE3_BLOCK_LEN, counter, block_flags); + input = &input[BLAKE3_BLOCK_LEN]; + blocks -= 1; + block_flags = flags; + } + memcpy(out_bytes, cv, BLAKE3_OUT_LEN); +} + +void +blake3_hash_many_avx512( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out_bytes +) +{ + while (num_inputs >= 16) { + blake3_hash16_avx512( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += 16; + } + inputs += 16; + num_inputs -= 16; + out_bytes = &out_bytes[16 * BLAKE3_OUT_LEN]; + } + while (num_inputs >= 8) { + blake3_hash8_avx512( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += 8; + } + inputs += 8; + num_inputs -= 8; + out_bytes = &out_bytes[8 * BLAKE3_OUT_LEN]; + } + while (num_inputs >= 4) { + blake3_hash4_avx512( + inputs, blocks, key, counter, increment_counter, flags, flags_start, flags_end, out_bytes + ); + if (increment_counter) { + counter += 4; + } + inputs += 4; + num_inputs -= 4; + out_bytes = &out_bytes[4 * BLAKE3_OUT_LEN]; + } + while (num_inputs > 0) { + hash_one_avx512(inputs[0], blocks, key, counter, flags, flags_start, flags_end, out_bytes); + if (increment_counter) { + counter += 1; + } + inputs += 1; + num_inputs -= 1; + out_bytes = &out_bytes[BLAKE3_OUT_LEN]; + } +} +#if defined(__clang__) +#pragma clang attribute pop +#elif defined(__GNUC__) +#pragma GCC pop_options +#endif +#endif + +/* dispatch functions */ +void +blake3_compress_in_place( + uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ +#if BLAKE3_X86_SIMD + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); + if (blake3_cpu_features & AVX512) { + blake3_compress_in_place_avx512(cv, block, block_len, counter, flags); + return; + } + if (blake3_cpu_features & SSE41) { + blake3_compress_in_place_sse41(cv, block, block_len, counter, flags); + return; + } + if (blake3_cpu_features & SSE2) { + blake3_compress_in_place_sse2(cv, block, block_len, counter, flags); + return; + } +#endif + blake3_compress_in_place_portable(cv, block, block_len, counter, flags); +} + +void +blake3_compress_xof( + const uint32_t cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags, + uint8_t out[64] +) +{ +#if BLAKE3_X86_SIMD + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); + if (blake3_cpu_features & AVX512) { + blake3_compress_xof_avx512(cv, block, block_len, counter, flags, out); + return; + } + if (blake3_cpu_features & SSE41) { + blake3_compress_xof_sse41(cv, block, block_len, counter, flags, out); + return; + } + if (blake3_cpu_features & SSE2) { + blake3_compress_xof_sse2(cv, block, block_len, counter, flags, out); + return; + } +#endif + blake3_compress_xof_portable(cv, block, block_len, counter, flags, out); +} + +void +blake3_hash_many( + const uint8_t *const *inputs, + size_t num_inputs, + size_t blocks, + const uint32_t key[8], + uint64_t counter, + int increment_counter, + uint8_t flags, + uint8_t flags_start, + uint8_t flags_end, + uint8_t *out +) +{ +#if BLAKE3_X86_SIMD + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); + if (blake3_cpu_features & AVX512) { + blake3_hash_many_avx512( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out + ); + return; + } + if (blake3_cpu_features & AVX2) { + blake3_hash_many_avx2( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out + ); + return; + } + if (blake3_cpu_features & SSE41) { + blake3_hash_many_sse41( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out + ); + return; + } + if (blake3_cpu_features & SSE2) { + blake3_hash_many_sse2( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out + ); + return; + } +#endif + blake3_hash_many_portable( + inputs, + num_inputs, + blocks, + key, + counter, + increment_counter, + flags, + flags_start, + flags_end, + out + ); +} + +size_t +blake3_simd_degree(void) +{ +#if BLAKE3_X86_SIMD + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); + if (blake3_cpu_features & AVX512) + return 16; + if (blake3_cpu_features & AVX2) + return 8; + if (blake3_cpu_features & SSE41) + return 4; + if (blake3_cpu_features & SSE2) + return 4; +#endif + return 1; +} + +/* core hasher implementation */ +const char * +blake3_version(void) +{ + return BLAKE3_VERSION_STRING; +} + +static inline void +chunk_state_init(struct Blake3ChunkState *self, const uint32_t key[8], uint8_t flags) +{ + memcpy(self->cv, key, BLAKE3_KEY_LEN); + self->chunk_counter = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + self->buf_len = 0; + self->blocks_compressed = 0; + self->flags = flags; +} + +static inline void +chunk_state_reset(struct Blake3ChunkState *self, const uint32_t key[8], uint64_t chunk_counter) +{ + memcpy(self->cv, key, BLAKE3_KEY_LEN); + self->chunk_counter = chunk_counter; + self->blocks_compressed = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + self->buf_len = 0; +} + +static inline size_t +chunk_state_len(const struct Blake3ChunkState *self) +{ + return (BLAKE3_BLOCK_LEN * (size_t)self->blocks_compressed) + ((size_t)self->buf_len); +} + +static inline size_t +chunk_state_fill_buf(struct Blake3ChunkState *self, const uint8_t *input, size_t input_len) +{ + size_t take = BLAKE3_BLOCK_LEN - ((size_t)self->buf_len); + uint8_t *dest; + + if (take > input_len) { + take = input_len; + } + dest = self->buf + ((size_t)self->buf_len); + memcpy(dest, input, take); + self->buf_len += (uint8_t)take; + return take; +} + +static inline uint8_t +chunk_state_maybe_start_flag(const struct Blake3ChunkState *self) +{ + if (self->blocks_compressed == 0) { + return CHUNK_START; + } else { + return 0; + } +} + +static inline struct Output +make_output( + const uint32_t input_cv[8], + const uint8_t block[BLAKE3_BLOCK_LEN], + uint8_t block_len, + uint64_t counter, + uint8_t flags +) +{ + struct Output ret; + + memcpy(ret.input_cv, input_cv, 32); + memcpy(ret.block, block, BLAKE3_BLOCK_LEN); + ret.block_len = block_len; + ret.counter = counter; + ret.flags = flags; + return ret; +} + +static inline void +output_chaining_value(const struct Output *self, uint8_t cv[32]) +{ + uint32_t cv_words[8]; + + memcpy(cv_words, self->input_cv, 32); + blake3_compress_in_place(cv_words, self->block, self->block_len, self->counter, self->flags); + store_cv_words(cv, cv_words); +} + +static inline void +output_root_bytes(const struct Output *self, uint64_t seek, uint8_t *out, size_t out_len) +{ + uint64_t output_block_counter = seek / 64; + size_t offset_within_block = seek % 64; + uint8_t wide_buf[64]; + size_t available_bytes; + size_t memcpy_len; + + while (out_len > 0) { + blake3_compress_xof( + self->input_cv, + self->block, + self->block_len, + output_block_counter, + self->flags | ROOT, + wide_buf + ); + available_bytes = 64 - offset_within_block; + if (out_len > available_bytes) { + memcpy_len = available_bytes; + } else { + memcpy_len = out_len; + } + memcpy(out, wide_buf + offset_within_block, memcpy_len); + out += memcpy_len; + out_len -= memcpy_len; + output_block_counter += 1; + offset_within_block = 0; + } +} + +static inline void +chunk_state_update(struct Blake3ChunkState *self, const uint8_t *input, size_t input_len) +{ + size_t take; + + if (self->buf_len > 0) { + take = chunk_state_fill_buf(self, input, input_len); + input += take; + input_len -= take; + if (input_len > 0) { + blake3_compress_in_place( + self->cv, + self->buf, + BLAKE3_BLOCK_LEN, + self->chunk_counter, + self->flags | chunk_state_maybe_start_flag(self) + ); + self->blocks_compressed += 1; + self->buf_len = 0; + memset(self->buf, 0, BLAKE3_BLOCK_LEN); + } + } + + while (input_len > BLAKE3_BLOCK_LEN) { + blake3_compress_in_place( + self->cv, + input, + BLAKE3_BLOCK_LEN, + self->chunk_counter, + self->flags | chunk_state_maybe_start_flag(self) + ); + self->blocks_compressed += 1; + input += BLAKE3_BLOCK_LEN; + input_len -= BLAKE3_BLOCK_LEN; + } + + take = chunk_state_fill_buf(self, input, input_len); + input += take; + input_len -= take; +} + +static inline struct Output +chunk_state_output(const struct Blake3ChunkState *self) +{ + uint8_t block_flags = self->flags | chunk_state_maybe_start_flag(self) | CHUNK_END; + + return make_output(self->cv, self->buf, self->buf_len, self->chunk_counter, block_flags); +} + +static inline struct Output +parent_output(const uint8_t block[BLAKE3_BLOCK_LEN], const uint32_t key[8], uint8_t flags) +{ + return make_output(key, block, BLAKE3_BLOCK_LEN, 0, flags | PARENT); +} + +static unsigned int +highest_one(uint64_t x) +{ +#if defined(__GNUC__) || defined(__clang__) + return 63 ^ __builtin_clzll(x); +#else + unsigned int c = 0; + if (x & 0xffffffff00000000ULL) { + x >>= 32; + c += 32; + } + if (x & 0x00000000ffff0000ULL) { + x >>= 16; + c += 16; + } + if (x & 0x000000000000ff00ULL) { + x >>= 8; + c += 8; + } + if (x & 0x00000000000000f0ULL) { + x >>= 4; + c += 4; + } + if (x & 0x000000000000000cULL) { + x >>= 2; + c += 2; + } + if (x & 0x0000000000000002ULL) { + c += 1; + } + return c; +#endif +} + +static inline uint64_t +round_down_to_power_of_2(uint64_t x) +{ + return 1ULL << highest_one(x | 1); +} + +static inline size_t +left_len(size_t content_len) +{ + size_t full_chunks = (content_len - 1) / BLAKE3_CHUNK_LEN; + + return round_down_to_power_of_2(full_chunks) * BLAKE3_CHUNK_LEN; +} + +static inline size_t +compress_chunks_parallel( + const uint8_t *input, + size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, + uint8_t flags, + uint8_t *out +) +{ + const uint8_t *chunks_array[MAX_SIMD_DEGREE]; + size_t input_position = 0; + size_t chunks_array_len = 0; + + assert(0 < input_len); + assert(input_len <= MAX_SIMD_DEGREE * BLAKE3_CHUNK_LEN); + + while (input_len - input_position >= BLAKE3_CHUNK_LEN) { + chunks_array[chunks_array_len] = &input[input_position]; + input_position += BLAKE3_CHUNK_LEN; + chunks_array_len += 1; + } + + blake3_hash_many( + chunks_array, + chunks_array_len, + BLAKE3_CHUNK_LEN / BLAKE3_BLOCK_LEN, + key, + chunk_counter, + 1, + flags, + CHUNK_START, + CHUNK_END, + out + ); + + if (input_len > input_position) { + uint64_t counter = chunk_counter + (uint64_t)chunks_array_len; + struct Blake3ChunkState chunk_state; + struct Output output; + + chunk_state_init(&chunk_state, key, flags); + chunk_state.chunk_counter = counter; + chunk_state_update(&chunk_state, &input[input_position], input_len - input_position); + output = chunk_state_output(&chunk_state); + output_chaining_value(&output, &out[chunks_array_len * BLAKE3_OUT_LEN]); + return chunks_array_len + 1; + } else { + return chunks_array_len; + } +} + +static inline size_t +compress_parents_parallel( + const uint8_t *child_chaining_values, + size_t num_chaining_values, + const uint32_t key[8], + uint8_t flags, + uint8_t *out +) +{ + const uint8_t *parents_array[MAX_SIMD_DEGREE_OR_2]; + size_t parents_array_len = 0; + + assert(2 <= num_chaining_values); + assert(num_chaining_values <= 2 * MAX_SIMD_DEGREE_OR_2); + + while (num_chaining_values - (2 * parents_array_len) >= 2) { + parents_array[parents_array_len] = + &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN]; + parents_array_len += 1; + } + + blake3_hash_many(parents_array, parents_array_len, 1, key, 0, 0, flags | PARENT, 0, 0, out); + + if (num_chaining_values > 2 * parents_array_len) { + memcpy( + &out[parents_array_len * BLAKE3_OUT_LEN], + &child_chaining_values[2 * parents_array_len * BLAKE3_OUT_LEN], + BLAKE3_OUT_LEN + ); + return parents_array_len + 1; + } else { + return parents_array_len; + } +} + +/* splits input in two at the largest power-of-2 chunk boundary and + * recurses on each half independently, writing each side's chaining + * values into its own slice of out. this, not an n-way iterate-then- + * merge, is what actually keeps the chaining-value count bounded at + * every level: an earlier iterative reconstruction of this function + * let cvs_written grow to roughly degree^2 for exact power-of-2 input + * lengths (64kib was the first size it broke on), overrunning the + * bound compress_parents_parallel assumes. fixed by matching the + * upstream reference implementation's actual recursive shape instead + * of re-deriving it */ +static inline size_t +blake3_compress_subtree_wide( + const uint8_t *input, + size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, + uint8_t flags, + uint8_t *out +) +{ + size_t left_input_len, right_input_len; + const uint8_t *right_input; + uint64_t right_chunk_counter; + uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN]; + size_t degree; + uint8_t *right_cvs; + size_t left_n, right_n; + + if (input_len <= (size_t)blake3_simd_degree() * BLAKE3_CHUNK_LEN) { + return compress_chunks_parallel(input, input_len, key, chunk_counter, flags, out); + } + + left_input_len = left_len(input_len); + right_input_len = input_len - left_input_len; + right_input = &input[left_input_len]; + right_chunk_counter = chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN); + + /* MAX_SIMD_DEGREE_OR_2 accounts for the degree=1 special case below, + * which always returns 2 outputs even though degree itself is 1 */ + degree = blake3_simd_degree(); + if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) { + degree = 2; + } + right_cvs = &cv_array[degree * BLAKE3_OUT_LEN]; + + left_n = + blake3_compress_subtree_wide(input, left_input_len, key, chunk_counter, flags, cv_array); + right_n = blake3_compress_subtree_wide( + right_input, right_input_len, key, right_chunk_counter, flags, right_cvs + ); + + /* degree=1: left_n and right_n are both 1, return both cvs directly + * rather than compressing them, so the caller always sees at least 2 */ + if (left_n == 1) { + memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); + return 2; + } + + return compress_parents_parallel(cv_array, left_n + right_n, key, flags, out); +} + +static void +compress_subtree_to_parent_node( + const uint8_t *input, + size_t input_len, + const uint32_t key[8], + uint64_t chunk_counter, + uint8_t flags, + uint8_t out[2 * BLAKE3_OUT_LEN] +) +{ + uint8_t cv_array[2 * MAX_SIMD_DEGREE_OR_2 * BLAKE3_OUT_LEN]; + size_t num_cvs = + blake3_compress_subtree_wide(input, input_len, key, chunk_counter, flags, cv_array); + + assert(num_cvs >= 2); + assert(num_cvs <= MAX_SIMD_DEGREE_OR_2); + while (num_cvs > 2) { + num_cvs = compress_parents_parallel(cv_array, num_cvs, key, flags, cv_array); + } + memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); +} + +static inline void +hasher_init_base(struct Blake3Hasher *self, const uint32_t key[8], uint8_t flags) +{ + memcpy(self->key, key, BLAKE3_KEY_LEN); + chunk_state_init(&self->chunk, key, flags); + self->cv_stack_len = 0; +} + +void +blake3_hasher_init(struct Blake3Hasher *self) +{ + if (!blake3_cpu_detected) + blake3_detect_cpu_features(); + hasher_init_base(self, IV, 0); +} + +static inline void +load_key_words(const uint8_t key[BLAKE3_KEY_LEN], uint32_t key_words[8]) +{ + key_words[0] = load32(&key[0 * 4]); + key_words[1] = load32(&key[1 * 4]); + key_words[2] = load32(&key[2 * 4]); + key_words[3] = load32(&key[3 * 4]); + key_words[4] = load32(&key[4 * 4]); + key_words[5] = load32(&key[5 * 4]); + key_words[6] = load32(&key[6 * 4]); + key_words[7] = load32(&key[7 * 4]); +} + +void +blake3_hasher_init_keyed(struct Blake3Hasher *self, const uint8_t key[BLAKE3_KEY_LEN]) +{ + uint32_t key_words[8]; + + load_key_words(key, key_words); + hasher_init_base(self, key_words, KEYED_HASH); +} + +void +blake3_hasher_init_derive_key_raw( + struct Blake3Hasher *self, const void *context, size_t context_len +) +{ + struct Blake3Hasher context_hasher; + uint8_t context_key[BLAKE3_KEY_LEN]; + uint32_t context_key_words[8]; + + hasher_init_base(&context_hasher, IV, DERIVE_KEY_CONTEXT); + blake3_hasher_update(&context_hasher, context, context_len); + blake3_hasher_finalize(&context_hasher, context_key, BLAKE3_KEY_LEN); + load_key_words(context_key, context_key_words); + hasher_init_base(self, context_key_words, DERIVE_KEY_MATERIAL); +} + +static inline unsigned int +popcnt(uint64_t x) +{ +#if defined(__GNUC__) || defined(__clang__) + return __builtin_popcountll(x); +#else + unsigned int count = 0; + while (x != 0) { + count += 1; + x &= x - 1; + } + return count; +#endif +} + +void +blake3_hasher_init_derive_key(struct Blake3Hasher *self, const char *context) +{ + blake3_hasher_init_derive_key_raw(self, context, strlen(context)); +} + +static inline void +hasher_merge_cv_stack(struct Blake3Hasher *self, uint64_t total_len) +{ + size_t post_merge_stack_len = (size_t)popcnt(total_len); + + while (self->cv_stack_len > post_merge_stack_len) { + uint8_t *parent_node = &self->cv_stack[(self->cv_stack_len - 2) * BLAKE3_OUT_LEN]; + struct Output output = parent_output(parent_node, self->key, self->chunk.flags); + + output_chaining_value(&output, parent_node); + self->cv_stack_len -= 1; + } +} + +static inline void +hasher_push_cv(struct Blake3Hasher *self, uint8_t new_cv[BLAKE3_OUT_LEN], uint64_t chunk_counter) +{ + hasher_merge_cv_stack(self, chunk_counter); + memcpy(&self->cv_stack[self->cv_stack_len * BLAKE3_OUT_LEN], new_cv, BLAKE3_OUT_LEN); + self->cv_stack_len += 1; +} + +void +blake3_hasher_update(struct Blake3Hasher *self, const void *input, size_t input_len) +{ + const uint8_t *input_bytes; + + if (input_len == 0) { + return; + } + + input_bytes = (const uint8_t *)input; + + if (chunk_state_len(&self->chunk) > 0) { + size_t take = BLAKE3_CHUNK_LEN - chunk_state_len(&self->chunk); + + if (take > input_len) { + take = input_len; + } + chunk_state_update(&self->chunk, input_bytes, take); + input_bytes += take; + input_len -= take; + if (input_len > 0) { + struct Output output = chunk_state_output(&self->chunk); + uint8_t chunk_cv[32]; + + output_chaining_value(&output, chunk_cv); + hasher_push_cv(self, chunk_cv, self->chunk.chunk_counter); + chunk_state_reset(&self->chunk, self->key, self->chunk.chunk_counter + 1); + } else { + return; + } + } + + while (input_len > BLAKE3_CHUNK_LEN) { + size_t subtree_len = round_down_to_power_of_2(input_len); + uint64_t count_so_far = self->chunk.chunk_counter * BLAKE3_CHUNK_LEN; + uint64_t subtree_chunks; + + while ((((uint64_t)(subtree_len - 1)) & count_so_far) != 0) { + subtree_len /= 2; + } + subtree_chunks = subtree_len / BLAKE3_CHUNK_LEN; + if (subtree_len <= BLAKE3_CHUNK_LEN) { + struct Blake3ChunkState chunk_state; + struct Output output; + uint8_t cv[BLAKE3_OUT_LEN]; + + chunk_state_init(&chunk_state, self->key, self->chunk.flags); + chunk_state.chunk_counter = self->chunk.chunk_counter; + chunk_state_update(&chunk_state, input_bytes, subtree_len); + output = chunk_state_output(&chunk_state); + output_chaining_value(&output, cv); + hasher_push_cv(self, cv, chunk_state.chunk_counter); + } else { + uint8_t cv_pair[2 * BLAKE3_OUT_LEN]; + + compress_subtree_to_parent_node( + input_bytes, subtree_len, self->key, self->chunk.chunk_counter, self->chunk.flags, cv_pair + ); + hasher_push_cv(self, cv_pair, self->chunk.chunk_counter); + hasher_push_cv( + self, &cv_pair[BLAKE3_OUT_LEN], self->chunk.chunk_counter + (subtree_chunks / 2) + ); + } + self->chunk.chunk_counter += subtree_chunks; + input_bytes += subtree_len; + input_len -= subtree_len; + } + + if (input_len > 0) { + chunk_state_update(&self->chunk, input_bytes, input_len); + hasher_merge_cv_stack(self, self->chunk.chunk_counter); + } +} + +void +blake3_hasher_finalize_seek( + const struct Blake3Hasher *self, uint64_t seek, uint8_t *out, size_t out_len +) +{ + struct Output output; + size_t cvs_remaining; + + if (out_len == 0) { + return; + } + + if (self->cv_stack_len == 0) { + output = chunk_state_output(&self->chunk); + output_root_bytes(&output, seek, out, out_len); + return; + } + + if (chunk_state_len(&self->chunk) > 0) { + cvs_remaining = self->cv_stack_len; + output = chunk_state_output(&self->chunk); + } else { + cvs_remaining = self->cv_stack_len - 2; + output = parent_output(&self->cv_stack[cvs_remaining * 32], self->key, self->chunk.flags); + } + + while (cvs_remaining > 0) { + uint8_t parent_block[BLAKE3_BLOCK_LEN]; + + cvs_remaining -= 1; + memcpy(parent_block, &self->cv_stack[cvs_remaining * 32], 32); + output_chaining_value(&output, &parent_block[32]); + output = parent_output(parent_block, self->key, self->chunk.flags); + } + output_root_bytes(&output, seek, out, out_len); +} + +void +blake3_hasher_finalize(const struct Blake3Hasher *self, uint8_t *out, size_t out_len) +{ + blake3_hasher_finalize_seek(self, 0, out, out_len); +} + +void +blake3_hasher_reset(struct Blake3Hasher *self) +{ + chunk_state_reset(&self->chunk, self->key, 0); + self->cv_stack_len = 0; +} + diff --git a/shared/libblake3/blake3.h b/shared/libblake3/blake3.h @@ -0,0 +1,43 @@ +/* see LICENSE file for copyright and license details */ +#ifndef ARUU_LIBBLAKE3_H +#define ARUU_LIBBLAKE3_H + +#include <stddef.h> +#include <stdint.h> + +#define BLAKE3_KEY_LEN 32 +#define BLAKE3_OUT_LEN 32 +#define BLAKE3_BLOCK_LEN 64 +#define BLAKE3_CHUNK_LEN 1024 +#define BLAKE3_MAX_DEPTH 54 + +struct Blake3ChunkState { + uint32_t cv[8]; + uint64_t chunk_counter; + uint8_t buf[BLAKE3_BLOCK_LEN]; + uint8_t buf_len; + uint8_t blocks_compressed; + uint8_t flags; +}; + +struct Blake3Hasher { + uint32_t key[8]; + struct Blake3ChunkState chunk; + uint8_t cv_stack_len; + uint8_t cv_stack[(BLAKE3_MAX_DEPTH + 1) * BLAKE3_OUT_LEN]; +}; + +void blake3_hasher_init(struct Blake3Hasher *self); +void blake3_hasher_init_keyed(struct Blake3Hasher *self, const uint8_t key[BLAKE3_KEY_LEN]); +void blake3_hasher_init_derive_key(struct Blake3Hasher *self, const char *context); +void blake3_hasher_init_derive_key_raw(struct Blake3Hasher *self, const void *context, + size_t context_len); +void blake3_hasher_update(struct Blake3Hasher *self, const void *input, size_t input_len); +void blake3_hasher_finalize(const struct Blake3Hasher *self, uint8_t *out, size_t out_len); +void blake3_hasher_finalize_seek(const struct Blake3Hasher *self, uint64_t seek, uint8_t *out, + size_t out_len); +void blake3_hasher_reset(struct Blake3Hasher *self); + +const char *blake3_version(void); + +#endif diff --git a/shared/libint128/int128_x64.s b/shared/libint128/int128_x64.s @@ -0,0 +1,106 @@ +/* x86-64 __int128 multiply/divide/remainder, called from cc1-emitted + * code (see cmd/dev/cc/qbe.c's funcdiv128). qbe has no widening + * multiply and no divide wider than 64 bits, and division needs a bit + * serial long-division loop no ir-level codegen could express, so both + * live here instead. names and abi match compiler-rt's own + * __multi3/__udivmodti4, so a real libgcc could stand in unchanged. + * division always takes the slower, always-correct bit serial path + * rather than a divisor-fits-in-64-bits shortcut, the same "correct + * first" choice this project's atomics runtime makes by always + * compiling to seq_cst instead of a weaker order + */ + +.text + +/* truncated 128 bit product: a_hi*b_hi is entirely above bit 128 and + * never computed. one widening mul (for the low*low term's own high + * word) plus two truncating imul (the cross terms) + */ +.globl __multi3 +__multi3: + /* a: rdi=a_lo rsi=a_hi b: rdx=b_lo rcx=b_hi */ + movq %rsi, %r8 + imul %rdx, %r8 /* a_hi * b_lo, low 64 */ + movq %rdi, %r9 + imul %rcx, %r9 /* a_lo * b_hi, low 64 */ + movq %rdi, %rax + mul %rdx /* rdx:rax = a_lo * b_lo, full 128 bit */ + addq %r8, %rdx + addq %r9, %rdx + ret + +/* unsigned quotient in rax:rdx, remainder written to *rem. bit serial + * restoring division: 128 iterations, each pulling the next dividend + * bit into the remainder (a 128 bit left shift built from shl/shr/or, + * no shld/rcl in this assembler) and setting the matching quotient bit + * once the remainder is large enough to subtract the divisor back out + * (subtract-with-borrow built from cmp/setb/sub, no sbb here either; + * the same technique qbe.c uses for branchless __int128 subtraction) + */ +.globl __udivmodti4 +__udivmodti4: + /* a: rdi=a_lo rsi=a_hi b: rdx=b_lo rcx=b_hi rem: r8 */ + push %r12 + push %r13 + push %r8 + xorq %r8, %r8 /* q_lo = 0 */ + xorq %r9, %r9 /* q_hi = 0 */ + xorq %r10, %r10 /* r_lo = 0 */ + xorq %r11, %r11 /* r_hi = 0 */ + movq $128, %rax +.Ludivloop: + /* r12 = bit_i(a), the msb about to fall out of the 128 bit + dividend as it shifts left */ + movq %rsi, %r12 + shrq $63, %r12 + + /* a <<= 1 (128 bit): lo's old msb feeds hi's new lsb */ + movq %rdi, %r13 + shrq $63, %r13 + shlq $1, %rdi + shlq $1, %rsi + orq %r13, %rsi + + /* r = (r << 1) | bit_i(a) */ + movq %r10, %r13 + shrq $63, %r13 + shlq $1, %r10 + shlq $1, %r11 + orq %r13, %r11 + orq %r12, %r10 + + /* q <<= 1, making room for this iteration's quotient bit */ + movq %r8, %r13 + shrq $63, %r13 + shlq $1, %r8 + shlq $1, %r9 + orq %r13, %r9 + + /* r >= b (128 bit unsigned)? */ + cmpq %rcx, %r11 + ja .Ludivcommit + jb .Ludivskip + cmpq %rdx, %r10 + jb .Ludivskip +.Ludivcommit: + /* r -= b, with the borrow from the low word carried into the + high word's subtraction by hand (no sbb in this assembler) */ + cmpq %rdx, %r10 + setb %r13b + movzbq %r13b, %r13 + subq %rdx, %r10 + subq %rcx, %r11 + subq %r13, %r11 + orq $1, %r8 +.Ludivskip: + subq $1, %rax + jnz .Ludivloop + + pop %rdi + movq %r10, (%rdi) + movq %r11, 8(%rdi) + movq %r8, %rax + movq %r9, %rdx + pop %r13 + pop %r12 + ret diff --git a/shared/libredline/redline.c b/shared/libredline/redline.c @@ -768,7 +768,7 @@ completeLine(struct redlineState *ls, int keypressed) /* 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; diff --git a/shared/libtcutil/ar/archive.c b/shared/libtcutil/ar/archive.c @@ -0,0 +1,220 @@ +#include "archive.h" + +#include <ar.h> +#include <assert.h> +#include <stdlib.h> /* strtoul */ +#include <string.h> + +#include "../tcutil.h" + +/* read 4-byte big-endian uint32 */ +static uint32_t +read4be(FILE *fp) +{ + unsigned char buf[4]; + read_or_die(fp, buf, -1, sizeof(buf), "read4be"); + return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]; +} + +static uint32_t * +read_file_offsets(FILE *fp, uint32_t symbol_count) +{ + uint32_t *file_offsets; + uint32_t *p; + uint32_t i; + unsigned char *q; + uint32_t offset; + + file_offsets = malloc_or_die(sizeof(*file_offsets) * symbol_count); + read_or_die(fp, file_offsets, -1, sizeof(*file_offsets) * symbol_count, "Offsets"); + /* convert big endian to machine endian */ + p = file_offsets; + for (i = 0; i < symbol_count; ++i) { + q = (unsigned char *)p; + offset = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3]; + *p++ = offset; + } + return file_offsets; +} + +static int +compare_uint32(const void *a, const void *b) +{ + uint32_t x = *(const uint32_t *)a; + struct ArContent *content = (struct ArContent *)b; + uint32_t y = content->file_offset; + return x < y ? -1 : x > y ? 1 : 0; +} + +/* build unique sorted array of arcontent from raw file offsets */ +static struct ArContent * +allocate_contents_buffer(const uint32_t *file_offsets, uint32_t symbol_count, size_t *plen) +{ + uint32_t *offsets; + ssize_t len, capa; + uint32_t i; + struct ArContent *contents; + ssize_t j; + + offsets = NULL; + len = 0; + capa = 0; + + for (i = 0; i < symbol_count; ++i) { + uint32_t value = file_offsets[i]; + ssize_t lo = -1, hi = len; + ssize_t m; + + /* binary search for insertion point */ + while (hi - lo > 1) { + m = lo + ((hi - lo) >> 1); + if (offsets[m] < value) + lo = m; + else + hi = m; + } + + if (hi >= len || offsets[hi] != value) { + if (capa <= len) { + capa <<= 1; + if (capa <= 0) + capa = 8; + offsets = realloc_or_die(offsets, sizeof(*offsets) * capa); + } + memmove(&offsets[hi + 1], &offsets[hi], (len - hi) * sizeof(*offsets)); + offsets[hi] = value; + ++len; + } + } + + contents = calloc_or_die(sizeof(*contents) * len); + for (j = 0; j < len; ++j) { + contents[j].obj = NULL; + contents[j].file_offset = offsets[j]; + } + free(offsets); + + *plen = len; + return contents; +} + +struct Archive * +load_archive(const char *filename) +{ + FILE *fp; + struct Archive *ar; + char mag[SARMAG]; + struct ar_hdr ghdr; + uint32_t symbol_count; + uint32_t *file_offsets; + size_t content_count; + struct ArContent *contents; + struct ArSymbol *symbols; + uint32_t i; + size_t pos; + size_t strtablen; + char *strtab; + char *p; + + if (!is_file(filename) || (fp = fopen(filename, "rb")) == NULL) + return NULL; + + ar = calloc_or_die(sizeof(*ar)); + ar->fp = fp; + ar->symbol_count = 0; + ar->symbols = NULL; + table_init(&ar->symbol_table); + ar->contents = new_vector(); + + read_or_die(fp, mag, -1, sizeof(mag), "Magic"); + if (memcmp(mag, ARMAG, sizeof(mag)) != 0) + error("Magic expected"); + + read_or_die(fp, &ghdr, -1, sizeof(ghdr), "Global header"); + if (memcmp(ghdr.ar_fmag, ARFMAG, sizeof(ghdr.ar_fmag)) != 0) + error("FMagic expected"); + + symbol_count = read4be(fp); + ar->symbol_count = symbol_count; + if (symbol_count > 0) { + file_offsets = read_file_offsets(fp, symbol_count); + contents = allocate_contents_buffer(file_offsets, symbol_count, &content_count); + + symbols = malloc_or_die(sizeof(*symbols) * symbol_count); + ar->symbols = symbols; + for (i = 0; i < symbol_count; ++i) { + uint32_t value = file_offsets[i]; + struct ArContent *result; + uint32_t index; + + result = bsearch(&value, contents, content_count, sizeof(*contents), compare_uint32); + assert(result != NULL); + index = result - contents; + symbols[i].content = &contents[index]; + } + + pos = ftell(fp); + assert(pos < contents[0].file_offset); + strtablen = contents[0].file_offset - pos; + strtab = malloc_or_die(strtablen); /* freed locally, not stored */ + read_or_die(fp, strtab, -1, strtablen, "struct Strtab"); + p = strtab; + for (i = 0; i < symbol_count; ++i) { + char *q; + struct ArSymbol *symbol; + const struct Name *name; + + q = memchr(p, '\0', &strtab[strtablen] - p); + if (q == NULL) + error("Illegal strtab"); + + symbol = &symbols[i]; + name = alloc_name(p, q, 0); + table_put(&ar->symbol_table, name, symbol); + + p = q + 1; + } + + free(file_offsets); + } + return ar; +} + +void * +load_archive_content( + struct Archive *ar, struct ArSymbol *symbol, void *(*load)(FILE *, const char *, size_t) +) +{ + struct ArContent *content; + struct ar_hdr hdr; + char *p; + char sizestr[sizeof(hdr.ar_size) + 1]; + void *obj; + + content = symbol->content; + if (content->obj != NULL) + return content->obj; + + fseek(ar->fp, content->file_offset, SEEK_SET); + + read_or_die(ar->fp, &hdr, -1, sizeof(hdr), "hdr"); + if (memcmp(hdr.ar_fmag, ARFMAG, sizeof(hdr.ar_fmag)) != 0) + error("Malformed archive"); + + memcpy(content->name, hdr.ar_name, sizeof(hdr.ar_name)); + p = memchr(content->name, '/', sizeof(hdr.ar_name)); + if (p != NULL) + *p = '\0'; + + memcpy(sizestr, hdr.ar_size, sizeof(hdr.ar_size)); + sizestr[sizeof(hdr.ar_size)] = '\0'; + content->size = strtoul(sizestr, NULL, 10); + + obj = (*load)(ar->fp, content->name, content->size); + if (obj == NULL) + error("Failed to extract .o: %.*s", (int)sizeof(content->name), content->name); + content->obj = obj; + vec_push(ar->contents, content); + + return obj; +} diff --git a/shared/libtcutil/ar/archive.h b/shared/libtcutil/ar/archive.h @@ -0,0 +1,37 @@ +/* ar archive reading: symbol table and member extraction */ + +#ifndef ARUU_TCUTIL_ARCHIVE_H +#define ARUU_TCUTIL_ARCHIVE_H + +#include <stdint.h> +#include <stdio.h> + +#include "../table.h" + +struct Vector; + +struct ArContent { + void *obj; + size_t size; + uint32_t file_offset; + char name[16]; +}; + +struct ArSymbol { + struct ArContent *content; +}; + +struct Archive { + FILE *fp; + uint32_t symbol_count; + struct ArSymbol *symbols; + struct Table symbol_table; + struct Vector *contents; /* <struct arcontent*> */ +}; + +struct Archive *load_archive(const char *filename); +void *load_archive_content( + struct Archive *ar, struct ArSymbol *symbol, void *(*load)(FILE *, const char *, size_t) +); + +#endif /* ARUU_TCUTIL_ARCHIVE_H */ diff --git a/shared/libtcutil/elf/elfutil.c b/shared/libtcutil/elf/elfutil.c @@ -0,0 +1,55 @@ +#include "../../../cmd/dev/config.h" + +#include "elfutil.h" + +#ifndef ELF_NOT_SUPPORTED +void +out_elf_header(FILE *fp, uintptr_t entry, int phnum, int shnum, int flags, uintptr_t shoff) +{ + Elf64_Ehdr ehdr = { + .e_ident = + {ELFMAG0, ELFMAG1, ELFMAG2, ELFMAG3, ELFCLASS64, ELFDATA2LSB, EV_CURRENT, ELFOSABI_SYSV}, + .e_type = phnum > 0 ? ET_EXEC : ET_REL, + .e_machine = MACHINE_TYPE, + .e_version = EV_CURRENT, + .e_entry = entry, + .e_phoff = phnum > 0 ? sizeof(Elf64_Ehdr) : 0, + .e_shoff = shoff, + .e_flags = flags, + .e_ehsize = sizeof(Elf64_Ehdr), + .e_phentsize = phnum > 0 ? sizeof(Elf64_Phdr) : 0, + .e_phnum = phnum, + .e_shentsize = shnum > 0 ? sizeof(Elf64_Shdr) : 0, + .e_shnum = shnum, + .e_shstrndx = shnum > 0 ? shnum - 1 : SHN_UNDEF, /* shstrndx is last */ + }; + + fwrite(&ehdr, sizeof(Elf64_Ehdr), 1, fp); +} + +void +out_program_header( + FILE *fp, + int type, + uintptr_t offset, + uintptr_t vaddr, + size_t filesz, + size_t memsz, + int flags, + size_t align +) +{ + Elf64_Phdr phdr = { + .p_type = type, + .p_offset = offset, + .p_vaddr = vaddr, + .p_paddr = vaddr, + .p_filesz = filesz, + .p_memsz = memsz, + .p_flags = flags, + .p_align = align, + }; + + fwrite(&phdr, sizeof(Elf64_Phdr), 1, fp); +} +#endif /* !ELF_NOT_SUPPORTED */ diff --git a/shared/libtcutil/elf/elfutil.h b/shared/libtcutil/elf/elfutil.h @@ -0,0 +1,26 @@ +/* ELF header and program header output */ + +#ifndef ARUU_TCUTIL_ELFUTIL_H +#define ARUU_TCUTIL_ELFUTIL_H + +#include <stdio.h> /* FILE */ + +#ifdef __APPLE__ +#include "../../../include/elf.h" +#else +#include <elf.h> +#endif + +void out_elf_header(FILE *fp, uintptr_t entry, int phnum, int shnum, int flags, uintptr_t shoff); +void out_program_header( + FILE *fp, + int type, + uintptr_t offset, + uintptr_t vaddr, + size_t filesz, + size_t memsz, + int flags, + size_t align +); + +#endif /* ARUU_TCUTIL_ELFUTIL_H */ diff --git a/shared/libtcutil/table.c b/shared/libtcutil/table.c @@ -0,0 +1,284 @@ +#include "table.h" + +#include <assert.h> +#include <stdlib.h> /* malloc */ +#include <string.h> + +/* fnv-1a */ +static uint32_t +hash_string(const char *key, int length) +{ + const unsigned char *u = (const unsigned char *)key; + uint32_t hash = 2166136261u; + int i; + + for (i = 0; i < length; ++i) + hash = (hash ^ u[i]) * 16777619u; + return hash; +} + +/* struct name: global interning table */ + +static struct Table name_table; + +static const struct Name * +find_name_table(const char *chars, int bytes, uint32_t hash) +{ + const struct Table *table; + uint32_t index; + struct TableEntry *entry; + const struct Name *key; + + table = &name_table; + if (table->count == 0) + return NULL; + + for (index = hash % table->capacity;; index = (index + 1) % table->capacity) { + entry = &table->entries[index]; + key = entry->key; + if (key == NULL) { + if (entry->value == NULL) + return NULL; + } else if (key->bytes == bytes && key->hash == hash && memcmp(key->chars, chars, bytes) == 0) { + return key; + } + } +} + +const struct Name * +alloc_name(const char *begin, const char *end, int make_copy) +{ + int bytes; + uint32_t hash; + const struct Name *name; + char *new_str; + struct Name *new_name; + + bytes = end != NULL ? (int)(end - begin) : (int)strlen(begin); + hash = hash_string(begin, bytes); + name = find_name_table(begin, bytes, hash); + if (name == NULL) { + if (make_copy) { + new_str = malloc(bytes); + if (new_str == NULL) + return NULL; + memcpy(new_str, begin, bytes); + begin = new_str; + } + new_name = malloc(sizeof(*new_name)); + if (new_name == NULL) { + if (make_copy) + free((void *)begin); + } else { + new_name->chars = begin; + new_name->bytes = bytes; + new_name->hash = hash; + table_put(&name_table, new_name, new_name); + name = new_name; + } + } + return name; +} + +const struct Name * +alloc_cname(const char *cstr) +{ + return alloc_name(cstr, NULL, 0); +} + +int +equal_name(const struct Name *name1, const struct Name *name2) +{ + /* all names are interned, compare by pointer */ + return name1 == name2; +} + +/* struct table: open-addressing hash table */ + +static struct TableEntry * +find_entry(struct TableEntry *entries, int capacity, const struct Name *key) +{ + struct TableEntry *tombstone; + uint32_t index; + struct TableEntry *entry; + + tombstone = NULL; + for (index = key->hash % capacity;; index = (index + 1) % capacity) { + entry = &entries[index]; + if (entry->key == NULL) { + if (entry->value == NULL) + return tombstone != NULL ? tombstone : entry; + /* tombstone */ + if (tombstone == NULL) + tombstone = entry; + } else if (entry->key == key) { + return entry; + } + } +} + +static void +adjust_capacity(struct Table *table, int new_capacity) +{ + struct TableEntry *new_entries; + int i; + struct TableEntry *old_entries; + int old_capacity; + int new_count; + + new_entries = malloc(sizeof(struct TableEntry) * new_capacity); + if (new_entries == NULL) + return; + for (i = 0; i < new_capacity; ++i) { + new_entries[i].key = NULL; + new_entries[i].value = NULL; + } + + old_entries = table->entries; + old_capacity = table->capacity; + new_count = 0; + for (i = 0; i < old_capacity; ++i) { + struct TableEntry *entry; + struct TableEntry *dest; + + entry = &old_entries[i]; + if (entry->key == NULL) + continue; + + dest = find_entry(new_entries, new_capacity, entry->key); + dest->key = entry->key; + dest->value = entry->value; + ++new_count; + } + + free(old_entries); + table->entries = new_entries; + table->capacity = new_capacity; + table->count = table->used = new_count; +} + +struct Table * +alloc_table(void) +{ + struct Table *table = malloc(sizeof(*table)); + if (table != NULL) + table_init(table); + return table; +} + +void +table_init(struct Table *table) +{ + assert(table != NULL); + table->entries = NULL; + table->count = 0; + table->used = 0; + table->capacity = 0; +} + +void * +table_get(struct Table *table, const struct Name *key) +{ + struct TableEntry *entry; + + assert(table != NULL); + if (table->count == 0) + return NULL; + + entry = find_entry(table->entries, table->capacity, key); + if (entry->key == NULL) + return NULL; + + return entry->value; +} + +int +table_try_get(struct Table *table, const struct Name *key, void **output) +{ + struct TableEntry *entry; + + assert(table != NULL); + if (table->count == 0) + return 0; + + entry = find_entry(table->entries, table->capacity, key); + if (entry->key == NULL) + return 0; + + if (output != NULL) + *output = entry->value; + return 1; +} + +int +table_put(struct Table *table, const struct Name *key, void *value) +{ + const int min_capacity = 15; + int capacity; + struct TableEntry *entry; + int is_new_key; + + assert(table != NULL); + if (table->used >= table->capacity / 2) { + capacity = table->capacity * 2 - 1; /* keep odd */ + if (capacity < min_capacity) + capacity = min_capacity; + adjust_capacity(table, capacity); + } + + entry = find_entry(table->entries, table->capacity, key); + is_new_key = entry->key == NULL; + if (is_new_key) { + ++table->count; + if (entry->value == NULL) + ++table->used; + } + + entry->key = key; + entry->value = value; + return is_new_key; +} + +int +table_delete(struct Table *table, const struct Name *key) +{ + struct TableEntry *entry; + + assert(table != NULL); + if (table->count == 0) + return 0; + + entry = find_entry(table->entries, table->capacity, key); + if (entry->key == NULL) + return 0; + + --table->count; + /* mark as tombstone */ + entry->key = NULL; + entry->value = entry; + + return 1; +} + +int +table_iterate(const struct Table *table, int iterator, const struct Name **pkey, void **pvalue) +{ + int capacity; + const struct TableEntry *entry; + const struct Name *key; + + assert(table != NULL); + capacity = table->capacity; + for (; iterator < capacity; ++iterator) { + entry = &table->entries[iterator]; + key = entry->key; + if (key != NULL) { + if (pkey != NULL) + *pkey = key; + if (pvalue != NULL) + *pvalue = entry->value; + return iterator + 1; + } + } + return -1; +} diff --git a/shared/libtcutil/table.h b/shared/libtcutil/table.h @@ -0,0 +1,46 @@ +/* interned names and open-addressing hash table */ + +#ifndef ARUU_TCUTIL_TABLE_H +#define ARUU_TCUTIL_TABLE_H + +#include <stdint.h> /* uint32_t */ + +/* interned name: chars and hash are immutable once allocated + * equality is pointer identity (see equal_name) */ +struct Name { + const char *chars; + int bytes; + uint32_t hash; +}; + +const struct Name *alloc_name(const char *begin, const char *end, int make_copy); +const struct Name *alloc_cname(const char *cstr); +int equal_name(const struct Name *name1, const struct Name *name2); + +/* for printf: printf("%.*s\n", names(name)) */ +#define NAMES(name) ((name)->bytes), ((name)->chars) + +/* open-addressing hash table with linear probing */ +struct TableEntry { + const struct Name *key; + void *value; +}; + +struct Table { + struct TableEntry *entries; + int capacity; + int count; + int used; /* includes tombstones */ +}; + +struct Table *alloc_table(void); +void table_init(struct Table *table); +void *table_get(struct Table *table, const struct Name *key); +int table_try_get(struct Table *table, const struct Name *key, void **output); +int table_put(struct Table *table, const struct Name *key, void *value); +int table_delete(struct Table *table, const struct Name *key); +int table_iterate( + const struct Table *table, int iterator, const struct Name **name, void **value +); /* returns -1 at end */ + +#endif /* ARUU_TCUTIL_TABLE_H */ diff --git a/shared/libtcutil/tcutil.c b/shared/libtcutil/tcutil.c @@ -0,0 +1,1055 @@ +#include "../../cmd/dev/config.h" +#include "table.h" +#include "tcutil.h" +#include "version.h" + +#include <assert.h> +#include <ctype.h> +#include <limits.h> /* CHAR_BIT */ +#include <stdarg.h> +#include <stdlib.h> /* malloc */ +#include <string.h> /* strcmp */ +#include <sys/stat.h> + +/* riscv toolchain lacks getline, provides __getline instead */ +#if defined(__riscv) && !defined(__TC) +static inline ssize_t +getline(char **lineptr, size_t *n, FILE *stream) +{ + return __getline(lineptr, n, stream); +} +#endif + +/* character classification */ + +int +isalnum_(int c) +{ + return isalnum(c) || c == '_'; +} + +int +isutf8first(int c_) +{ + unsigned int c = c_; + if (c < 0xc0) + return 0; + if (c >= 0xfc) + return 6; + if (c >= 0xf8) + return 5; + if (c >= 0xf0) + return 4; + if (c >= 0xe0) + return 3; + return 2; +} + +int +isutf8follow(int c) +{ + return c >= 0x80 && c < 0xc0; +} + +int +isoctal(int c) +{ + return '0' <= c && c <= '7'; +} + +int +xvalue(char c) +{ + return ('0' <= c && c <= '9') ? c - '0' + : ('A' <= c && c <= 'F') ? c - ('A' - 10) + : ('a' <= c && c <= 'f') ? c - ('a' - 10) + : -1; +} + +int +starts_with(const char *str, const char *prefix) +{ + size_t len = strlen(prefix); + return strncmp(str, prefix, len) == 0; +} + +int +most_significant_bit(size_t x) +{ + int bit; + + assert(x > 0); +#if defined(__GNUC__) || defined(__TC) + if (sizeof(size_t) == sizeof(unsigned int)) { + return (int)(sizeof(x) * CHAR_BIT - 1) - __builtin_clz(x); + } else if (sizeof(size_t) == sizeof(unsigned long)) { + return (int)(sizeof(x) * CHAR_BIT - 1) - __builtin_clzl(x); + } +#endif + for (bit = 0;; ++bit) { + x >>= 1; + if (x <= 0) + return bit; + } +} + +/* string and path helpers */ + +void * +read_or_die(FILE *fp, void *buf, long offset, size_t size, const char *msg) +{ + if (buf == NULL) + buf = malloc_or_die(size); + if ((offset >= 0 && fseek(fp, offset, SEEK_SET) != 0) || fread(buf, 1, size, fp) != size) + error(msg); + return buf; +} + +void * +malloc_or_die(size_t size) +{ + void *p = malloc(size); + if (p == NULL) { + fprintf(stderr, "memory overflow\n"); + exit(1); + } + return p; +} + +void * +calloc_or_die(size_t size) +{ + void *p = calloc(1, size); + if (p == NULL) { + fprintf(stderr, "memory overflow\n"); + exit(1); + } + return p; +} + +void * +realloc_or_die(void *ptr, size_t size) +{ + void *p = realloc(ptr, size); + if (p == NULL) { + fprintf(stderr, "memory overflow\n"); + exit(1); + } + return p; +} + +const struct Name * +alloc_label(void) +{ + static int label_no; + char buf[2 + sizeof(int) * 3 + 1]; + + ++label_no; + snprintf(buf, sizeof(buf), "l.%04d", label_no); + return alloc_name(buf, NULL, 1); +} + +ssize_t +getline_chomp(char **lineptr, size_t *n, FILE *stream) +{ + ssize_t len; + char *line; + + len = getline(lineptr, n, stream); + if (len > 0) { + line = *lineptr; + /* chomp CR, LF, CR+LF */ + if (line[len - 1] == '\n') + line[--len] = '\0'; + if (len > 0 && line[len - 1] == '\r') + line[--len] = '\0'; + } + return len; +} + +static ssize_t +getline_cat(char **lineptr, size_t *n, FILE *stream, size_t curlen) +{ + char *nextline = NULL; + size_t capa = 0; + ssize_t len; + char *oldline; + char *reallocated; + + len = getline_chomp(&nextline, &capa, stream); + if (len == -1) + return -1; + if (len > 0) { + oldline = *lineptr; + reallocated = realloc(oldline, curlen + len + 1); + if (reallocated == NULL) + return -1; + + memcpy(reallocated + curlen, nextline, len + 1); + *lineptr = reallocated; + *n = curlen + len; /* nul not included */ + free(nextline); + } + return curlen + len; +} + +ssize_t +getline_cont(char **lineptr, size_t *capa, FILE *stream, int *plineno) +{ + int lineno = *plineno; + ssize_t len; + ssize_t nextlen; + + len = getline_chomp(lineptr, capa, stream); + if (len != -1) { + /* handle backslash continuation */ + while (++lineno, len > 0 && (*lineptr)[len - 1] == '\\') { + (*lineptr)[--len] = '\0'; + nextlen = getline_cat(lineptr, capa, stream, len); + if (nextlen == -1) + break; + len = nextlen; + } + } + *plineno = lineno; + return len; +} + +int +is_fullpath(const char *filename) +{ + const char *p; + + if (*filename != '/') + return 0; + for (p = filename;;) { + p = strstr(p, "/.."); + if (p == NULL) + return 1; + if (p[3] == '/' || p[3] == '\0') + return 0; + p += 3; + } +} + +char * +join_paths(const char *paths[]) +{ + struct StringBuffer sb; + const char **pp; + const char *p; + const char *last_path; + int parent_count; + enum Top { + OTHER, + ROOTDIR, /* / */ + CURDIR, /* */ + }; + enum Top top; + + sb_init(&sb); + parent_count = 0; + top = OTHER; + last_path = NULL; + + for (pp = paths; (p = *pp++) != NULL;) { + const char *q; + int end; + ptrdiff_t len; + + last_path = p; + if (*p == '/') { /* absolute, reset */ + sb_init(&sb); + parent_count = 0; + top = ROOTDIR; + } + + for (end = 0; !end;) { + while (*p == '/') + ++p; + if (*p == '\0') + break; + + q = strchr(p, '/'); + if (q == NULL) { /* last component */ + q = p + strlen(p); + end = 1; + } + len = q - p; + if (len == 1 && *p == '.') { + if (sb.elems->len == 0 && top == OTHER) + top = CURDIR; + } else if (len == 2 && strncmp(p, "..", 2) == 0) { + if (sb.elems->len > 0) { + void *elem = vec_pop(sb.elems); + free(elem); + } else { + if (top == ROOTDIR) + return NULL; /* illegal */ + ++parent_count; + top = OTHER; + } + } else { + sb_append(&sb, p, q); + } + p = q; + } + } + + for (; parent_count > 0; --parent_count) + sb_prepend(&sb, "..", NULL); + switch (top) { + case OTHER: + case CURDIR: + if (sb.elems->len == 0) + sb_prepend(&sb, ".", NULL); + break; + case ROOTDIR: + sb_prepend(&sb, sb.elems->len > 0 ? "" : "/", NULL); + break; + } + if (last_path != NULL) { + size_t len = strlen(last_path); + if (len > 0 && last_path[len - 1] == '/' && !(top == ROOTDIR && sb.elems->len == 1)) + sb_append(&sb, "", NULL); + } + return sb_join(&sb, "/"); +} + +char * +get_ext(const char *filename) +{ + const char *last_slash; + char *dot; + + last_slash = strrchr(filename, '/'); + if (last_slash == NULL) + last_slash = filename; + dot = strrchr(last_slash, '.'); + return dot != NULL ? (char *)&dot[1] : (char *)&last_slash[strlen(last_slash)]; +} + +char * +change_ext(const char *path, const char *ext) +{ + const char *p; + const char *q; + size_t len; + size_t ext_len; + char *s; + + p = strrchr(path, '/'); + if (p == NULL) + p = path; + + q = strrchr(p, '.'); + len = q != NULL ? (size_t)(q - path) : strlen(path); + ext_len = strlen(ext); + s = malloc(len + 1 + ext_len + 1); + if (s != NULL) { + memcpy(s, path, len); + s[len] = '.'; + strcpy(s + (len + 1), ext); + } + return s; +} + +void +put_padding(FILE *fp, long start) +{ + long cur; + long size; + long i; + + cur = ftell(fp); + if (cur < 0) + return; /* todo: error */ + if (start > cur) { + size = start - cur; + for (i = 0; i < size; ++i) + fputc(0x00, fp); + } +} + +int +is_file(const char *path) +{ + struct stat st; + return stat(path, &st) == 0 && S_ISREG(st.st_mode); /* follows symlinks */ +} + +void +show_version(const char *exe, int arch) +{ + /* order must match TC_ARCH_* constants in config.h */ + static const char *const archs[] = { + NULL, + "x86_64", + "arm64", + "riscv64", + "wasm", + }; + + if (exe == NULL) { + printf("%s\n", VERSION); + } else if (arch <= 0) { + printf("%s version %s\n", exe, VERSION); + } else { + printf( + "%s version %s\n" + "Target: %s\n", + exe, + VERSION, + archs[arch] + ); + } +} + +_Noreturn void +error(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fprintf(stderr, "\n"); + exit(1); +} + +void +show_error_line(const char *line, const char *p, int len) +{ + size_t pos; + size_t i; + + fprintf(stderr, "%s\n", line); + pos = p - line; + if (pos <= strlen(line)) { + for (i = 0; i < pos; ++i) + fputc(line[i] == '\t' ? '\t' : ' ', stderr); + fprintf(stderr, "^"); + for (i = 1; i < (size_t)len; ++i) + fprintf(stderr, "~"); + fprintf(stderr, "\n"); + } +} + +/* value range checks for immediate operands */ + +int +is_im8(int64_t x) +{ + return x <= (((int64_t)1 << 7) - 1) && x >= -((int64_t)1 << 7); +} + +int +is_im16(int64_t x) +{ + return x <= (((int64_t)1 << 15) - 1) && x >= -((int64_t)1 << 15); +} + +int +is_im32(int64_t x) +{ + return x <= (((int64_t)1 << 31) - 1) && x >= -((int64_t)1 << 31); +} + +const char * +skip_whitespaces(const char *s) +{ + for (;;) { + while (isspace(*s)) + ++s; + /* gas allows block comments and line comments wherever whitespace is valid */ + if (s[0] == '/' && s[1] == '*') { + s += 2; + while (*s != '\0' && !(s[0] == '*' && s[1] == '/')) + ++s; + if (*s != '\0') + s += 2; + continue; + } + if (s[0] == '/' && s[1] == '/') { + while (*s != '\0') + ++s; + continue; + } + break; + } + return s; +} + +/* detect block comment start without consuming it via skip_whitespaces */ +const char * +block_comment_start(const char *p) +{ + while (isspace(*p)) + ++p; + return (*p == '/' && p[1] == '*') ? p : NULL; +} + +const char * +block_comment_end(const char *p) +{ + for (;;) { + p = strchr(p, '*'); + if (p == NULL) + return NULL; + if (*(++p) == '/') + return p + 1; + } +} + +int64_t +wrap_value(int64_t value, int size, int is_unsigned) +{ + if (is_unsigned) { + switch (size) { + case 1: + value = (uint8_t)value; + break; + case 2: + value = (uint16_t)value; + break; + case 4: + value = (uint32_t)value; + break; + default: + break; + } + } else { + switch (size) { + case 1: + value = (int8_t)value; + break; + case 2: + value = (int16_t)value; + break; + case 4: + value = (int32_t)value; + break; + default: + break; + } + } + return value; +} + +/* container: growable pointer vector */ + +struct Vector * +new_vector(void) +{ + struct Vector *vec = malloc_or_die(sizeof(struct Vector)); + vec_init(vec); + return vec; +} + +void +free_vector(struct Vector *vec) +{ + free(vec->data); + free(vec); +} + +void +vec_init(struct Vector *vec) +{ + vec->data = NULL; + vec->capacity = 0; + vec->len = 0; +} + +void +vec_clear(struct Vector *vec) +{ + vec->len = 0; +} + +void +vec_push(struct Vector *vec, const void *elem) +{ + if (vec->capacity <= vec->len) { + if (vec->capacity <= 0) + vec->capacity = 16; + else + vec->capacity <<= 1; + vec->data = realloc_or_die(vec->data, sizeof(*vec->data) * vec->capacity); + } + vec->data[vec->len++] = (void *)elem; +} + +void * +vec_pop(struct Vector *vec) +{ + return vec->len > 0 ? vec->data[--vec->len] : NULL; +} + +void +vec_insert(struct Vector *vec, int pos, const void *elem) +{ + int len = vec->len; + + if (pos < 0 || pos > len) + return; + + if (pos < len) { + vec_push(vec, NULL); + memmove(&vec->data[pos + 1], &vec->data[pos], sizeof(void *) * (len - pos)); + vec->data[pos] = (void *)elem; + } else { + vec_push(vec, elem); + } +} + +void +vec_remove_at(struct Vector *vec, int index) +{ + int d; + + if (index < 0 || index >= vec->len) + return; + d = vec->len - index - 1; + if (d > 0) + memmove(&vec->data[index], &vec->data[index + 1], d * sizeof(*vec->data)); + --vec->len; +} + +int +vec_contains(struct Vector *vec, void *elem) +{ + int i, len; + + len = vec->len; + for (i = 0; i < len; ++i) { + if (vec->data[i] == elem) + return 1; + } + return 0; +} + +void +vec_concat(struct Vector *dst, const struct Vector *src) +{ + int i; + + for (i = 0; i < src->len; ++i) + vec_push(dst, src->data[i]); +} + +/* container: growable byte buffer */ + +void +data_release(struct DataStorage *data) +{ + if (data->chunk_stack != NULL) { + free_vector(data->chunk_stack); + data->chunk_stack = NULL; + } + if (data->buf != NULL) { + free(data->buf); + data_init(data); + } +} + +void +data_init(struct DataStorage *data) +{ + data->chunk_stack = NULL; + data->buf = NULL; + data->capacity = 0; + data->len = 0; +} + +void +data_reserve(struct DataStorage *data, size_t capacity) +{ + const size_t min_cap = 16; + size_t c; + + if (data->capacity < capacity) { + c = data->capacity << 1; + if (c > capacity) + capacity = c; + if (min_cap > capacity) + capacity = min_cap; + data->buf = realloc_or_die(data->buf, sizeof(*data->buf) * capacity); + data->capacity = capacity; + } +} + +void +data_insert(struct DataStorage *data, ssize_t pos_, const void *buf, size_t size) +{ + size_t pos; + size_t newlen; + + pos = pos_ == -1 ? data->len : (size_t)pos_; + assert(pos <= data->len); + newlen = data->len + size; + data_reserve(data, newlen); + if (pos < data->len) + memmove(data->buf + pos + size, data->buf + pos, data->len - pos); + memcpy(data->buf + pos, buf, size); + data->len = newlen; +} + +void +data_append(struct DataStorage *data, const void *buf, size_t size) +{ + data_insert(data, -1, buf, size); +} + +void +data_push(struct DataStorage *data, unsigned char c) +{ + unsigned char buf[1] = {c}; + data_insert(data, -1, buf, 1); +} + +void +data_align(struct DataStorage *data, int align) +{ + size_t len; + size_t aligned_len; + size_t add; + void *zero; + + len = data->len; + aligned_len = ALIGN(len, align); + add = aligned_len - len; + if (add <= 0) + return; + + zero = calloc_or_die(add); + data_append(data, zero, add); + free(zero); + + assert(data->len == aligned_len); +} + +void +data_concat(struct DataStorage *dst, struct DataStorage *src) +{ + data_insert(dst, -1, src->buf, src->len); +} + +void +data_leb128(struct DataStorage *data, ssize_t pos, int64_t val) +{ + unsigned char buf[12], *p = buf; + const int64_t max = (int64_t)1 << 6; + + for (;;) { + if (val < max && val >= -max) { + *p++ = val & 0x7f; + data_insert(data, pos, buf, p - buf); + return; + } + *p++ = (val & 0x7f) | 0x80; + val >>= 7; + } +} + +void +data_uleb128(struct DataStorage *data, ssize_t pos, uint64_t val) +{ + unsigned char buf[12], *p = buf; + const uint64_t max = (uint64_t)1 << 7; + + for (;;) { + if (val < max) { + *p++ = val & 0x7f; + data_insert(data, pos, buf, p - buf); + return; + } + *p++ = (val & 0x7f) | 0x80; + val >>= 7; + } +} + +void +data_string(struct DataStorage *data, const void *str, size_t len) +{ + data_uleb128(data, -1, len); + data_append(data, (const unsigned char *)str, len); +} + +void +data_varint32(struct DataStorage *data, ssize_t pos, int64_t val) +{ + unsigned char buf[5], *p = buf; + int i; + + for (i = 0; i < 4; ++i) { + *p++ = (val & 0x7f) | 0x80; + val >>= 7; + } + *p++ = val & 0x7f; + data_insert(data, pos, buf, p - buf); +} + +void +data_varuint32(struct DataStorage *data, ssize_t pos, uint64_t val) +{ + unsigned char buf[5], *p = buf; + int i; + + for (i = 0; i < 4; ++i) { + *p++ = (val & 0x7f) | 0x80; + val >>= 7; + } + *p++ = val & 0x7f; + data_insert(data, pos, buf, p - buf); +} + +void +data_open_chunk(struct DataStorage *data) +{ + struct Vector *stack = data->chunk_stack; + if (stack == NULL) + data->chunk_stack = stack = new_vector(); + vec_push(stack, INT2VOIDP(data->len)); +} + +void +data_close_chunk(struct DataStorage *data, ssize_t num) +{ + struct Vector *stack = data->chunk_stack; + size_t pos; + + assert(stack != NULL && stack->len > 0); + pos = VOIDP2INT(vec_pop(stack)); + if (num == (ssize_t)-1) + num = data->len - pos; + data_uleb128(data, pos, num); +} + +/* container: rope-style string builder */ + +struct StringElement { + const char *start; + size_t len; +}; + +void +sb_init(struct StringBuffer *sb) +{ + sb->elems = new_vector(); +} + +void +sb_clear(struct StringBuffer *sb) +{ + vec_clear(sb->elems); +} + +int +sb_empty(struct StringBuffer *sb) +{ + return sb->elems->len == 0; +} + +void +sb_insert(struct StringBuffer *sb, int pos, const char *start, const char *end) +{ + struct StringElement *elem = malloc(sizeof(*elem)); + + if (elem != NULL) { + elem->start = start; + elem->len = end != NULL ? (size_t)(end - start) : strlen(start); + assert(0 <= pos && pos <= sb->elems->len); + vec_insert(sb->elems, pos, elem); + } +} + +char * +sb_join(struct StringBuffer *sb, const char *separator) +{ + size_t total_len; + int count; + int i; + size_t sepalen; + char *str; + char *p; + + total_len = 0; + count = sb->elems->len; + for (i = 0; i < count; ++i) { + struct StringElement *elem = sb->elems->data[i]; + total_len += elem->len; + } + sepalen = separator != NULL ? strlen(separator) : 0; + if (count > 0 && sepalen > 0) + total_len += sepalen * (count - 1); + + str = malloc(total_len + 1); + if (str != NULL) { + p = str; + for (i = 0; i < count; ++i) { + struct StringElement *elem; + if (i > 0 && sepalen > 0) { + memcpy(p, separator, sepalen); + p += sepalen; + } + elem = sb->elems->data[i]; + memcpy(p, elem->start, elem->len); + p += elem->len; + } + *p = '\0'; + } + return str; +} + +/* string escaping for assembler output */ + +static const char * +escape_hex(int c) +{ + char *s = malloc_or_die(5); + /* hex escapes are not length-limited so following hex chars would + * be consumed, must use octal which is always 3 digits */ + snprintf(s, 5, "\\%03o", c & 0xff); + return s; +} + +static const char * +escape(int c) +{ + switch (c) { + case '\0': + return "\\000"; /* octal, at most 3 digits in assembler */ + case '\n': + return "\\n"; + case '\r': + return "\\r"; + case '\t': + return "\\t"; + case '"': + return "\\\""; + case '\\': + return "\\\\"; + default: + if (c < 0x20 || c >= 0x7f) + return escape_hex(c); + return NULL; + } +} + +void +escape_string(const char *str, size_t size, struct StringBuffer *sb) +{ + const char *s, *p; + const char *end; + const char *e; + int hex; + + end = str + size; + hex = 0; + for (s = p = str; p < end; ++p) { + if (hex && isxdigit(*p)) { + e = escape_hex(*p); + } else { + e = escape(*p); + if (e == NULL) { + hex = 0; + continue; + } + } + + if (p > s) + sb_append(sb, s, p); + sb_append(sb, e, NULL); + s = p + 1; + hex = e[1] == 'x'; + } + if (p > s) { + assert(!hex); + sb_append(sb, s, p); + } +} + +/* option parser: long-option style for toolchain commands */ + +int optind; +int optopt; +int opterr = 1; +char *optarg; + +int +optparse(int argc, char *const argv[], const struct option *opts) +{ +#define ERROR(...) \ + do { \ + if (opterr) \ + fprintf(stderr, __VA_ARGS__); \ + } while (0) + + char *arg; + char *p; + char *q; + char c; + int opt; + size_t len; + + if (optind == 0) + optind = 1; + + if (optind >= argc) + return -1; + + optarg = NULL; + optopt = 0; + + arg = argv[optind]; + p = arg; + if (*p != '-' || p[1] == '\0') + return -1; + + p += 1; + ++optind; + for (; opts->name != NULL; ++opts) { + len = strlen(opts->name); + if (strncmp(p, opts->name, len) == 0) { + opt = opts->val; + if (opt == 0) + opt = arg[1]; + q = p + len; + c = *q; + if (opts->has_arg) { + if (c != '\0') { + optarg = q + (c == '=' ? 1 : 0); + } else if (opts->has_arg == required_argument) { + if (optind < argc) { + optarg = argv[optind++]; + } else { + ERROR( + "%s: option '--%s' " + "requires an argument\n", + argv[0], + opts->name + ); + break; + } + } + } else { + if (c != '\0') { + if (c != '=') + continue; + ERROR( + "%s: option '--%s' doesn't allow " + "an argument\n", + argv[0], + opts->name + ); + break; + } + } + return opt; + } + } + + optopt = arg[1]; + return '?'; +#undef ERROR +} diff --git a/shared/libtcutil/tcutil.h b/shared/libtcutil/tcutil.h @@ -0,0 +1,169 @@ +/* toolchain utility library: memory, paths, containers, option parsing */ + +#ifndef ARUU_TCUTIL_H +#define ARUU_TCUTIL_H + +#include <stddef.h> /* size_t */ +#include <stdint.h> /* intptr_t */ +#include <stdio.h> /* FILE */ +#include <sys/types.h> /* ssize_t */ + +/* macros also defined by shared/util.h, undef to avoid redefinition warning */ +#undef MIN +#undef MAX +#undef ALIGN + +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ALIGN(x, align) (((x) + (align) - 1) & -(align)) /* align must be power of 2 */ +#define UNUSED(x) ((void)(x)) +#define IS_POWER_OF_2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) +#define INT2VOIDP(i) ((void *)(intptr_t)(i)) +#define UINT2VOIDP(i) ((void *)(uintptr_t)(i)) +#define VOIDP2INT(p) ((intptr_t)(p)) +#define VOIDP2UINT(p) ((uintptr_t)(p)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) + +struct Name; + +/* character classification */ +int isalnum_(int c); +int isutf8first(int c); +int isutf8follow(int c); +int isoctal(int c); +int xvalue(char c); + +/* string and path helpers */ +int starts_with(const char *str, const char *prefix); +int is_fullpath(const char *filename); +char *join_paths(const char *paths[]); +char *get_ext(const char *filename); +char *change_ext(const char *path, const char *ext); +const char *skip_whitespaces(const char *s); +const char *block_comment_start(const char *p); +const char *block_comment_end(const char *p); + +/* file I/O helpers */ +void *read_or_die(FILE *fp, void *buf, long offset, size_t size, const char *msg); +void put_padding(FILE *fp, long start); +int is_file(const char *path); +ssize_t getline_chomp(char **lineptr, size_t *n, FILE *stream); +ssize_t getline_cont(char **lineptr, size_t *n, FILE *stream, int *plineno); + +/* memory: toolchain-local, same contract as aruu emalloc/ecalloc/erealloc + * kept separate so the toolchain can build standalone without libutil */ +void *malloc_or_die(size_t size); +void *calloc_or_die(size_t size); +void *realloc_or_die(void *ptr, size_t size); + +/* diagnostics */ +void show_version(const char *exe, int arch); +_Noreturn void error(const char *fmt, ...); +void show_error_line(const char *line, const char *p, int len); + +/* value range checks for immediate operands */ +int is_im8(int64_t x); +int is_im16(int64_t x); +int is_im32(int64_t x); +int64_t wrap_value(int64_t value, int size, int is_unsigned); +int most_significant_bit(size_t x); + +/* name interning (see table.h for struct name) */ +const struct Name *alloc_label(void); + +/* container: growable pointer vector */ +struct Vector { + void **data; + int capacity; + int len; +}; + +struct Vector *new_vector(void); +void free_vector(struct Vector *vec); +void vec_init(struct Vector *vec); +void vec_clear(struct Vector *vec); +void vec_push(struct Vector *vec, const void *elem); +void *vec_pop(struct Vector *vec); +void vec_insert(struct Vector *vec, int pos, const void *elem); +void vec_remove_at(struct Vector *vec, int index); +int vec_contains(struct Vector *vec, void *elem); +void vec_concat(struct Vector *dst, const struct Vector *src); + +/* container: growable byte buffer */ +struct DataStorage { + struct Vector *chunk_stack; + unsigned char *buf; + size_t capacity; + size_t len; +}; + +void data_release(struct DataStorage *data); +void data_init(struct DataStorage *data); +void data_reserve(struct DataStorage *data, size_t capacity); +void data_insert(struct DataStorage *data, ssize_t pos, const void *buf, size_t size); +void data_append(struct DataStorage *data, const void *buf, size_t size); +void data_push(struct DataStorage *data, unsigned char c); +void data_align(struct DataStorage *data, int align); +void data_concat(struct DataStorage *dst, struct DataStorage *src); +void data_leb128(struct DataStorage *data, ssize_t pos, int64_t val); +void data_uleb128(struct DataStorage *data, ssize_t pos, uint64_t val); +void data_string(struct DataStorage *data, const void *str, size_t len); +void data_open_chunk(struct DataStorage *data); +void data_close_chunk(struct DataStorage *data, ssize_t num); +void data_varint32(struct DataStorage *data, ssize_t pos, int64_t val); +void data_varuint32(struct DataStorage *data, ssize_t pos, uint64_t val); + +/* container: rope-style string builder */ +struct StringBuffer { + struct Vector *elems; +}; + +void sb_init(struct StringBuffer *sb); +void sb_clear(struct StringBuffer *sb); +int sb_empty(struct StringBuffer *sb); +void sb_insert(struct StringBuffer *sb, int pos, const char *start, const char *end); +char *sb_join(struct StringBuffer *sb, const char *separator); + +static inline void +sb_append(struct StringBuffer *sb, const char *start, const char *end) +{ + sb_insert(sb, sb->elems->len, start, end); +} + +static inline void +sb_prepend(struct StringBuffer *sb, const char *start, const char *end) +{ + sb_insert(sb, 0, start, end); +} + +static inline char * +sb_to_string(struct StringBuffer *sb) +{ + return sb_join(sb, NULL); +} + +void escape_string(const char *str, size_t size, struct StringBuffer *sb); + +/* convenience macro for join_paths */ +#define JOIN_PATHS(...) join_paths((const char *[]){__VA_ARGS__, NULL}) + +/* option parser: long-option style for toolchain commands + * has_arg values: 0 = none, 1 = required, 2 = optional */ +#define no_argument 0 +#define required_argument 1 +#define optional_argument 2 + +struct option { + const char *name; + int has_arg; + int val; +}; + +extern int optind; +extern int opterr; +extern int optopt; +extern char *optarg; + +int optparse(int argc, char *const argv[], const struct option *opts); + +#endif /* ARUU_TCUTIL_H */ diff --git a/shared/libutf/fgetrune.c b/shared/libutf/fgetrune.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutf/fputrune.c b/shared/libutf/fputrune.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutf/isalnumrune.c b/shared/libutf/isalnumrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/isalpharune.c b/shared/libutf/isalpharune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/isblankrune.c b/shared/libutf/isblankrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/iscntrlrune.c b/shared/libutf/iscntrlrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/isdigitrune.c b/shared/libutf/isdigitrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/isgraphrune.c b/shared/libutf/isgraphrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/isprintrune.c b/shared/libutf/isprintrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/ispunctrune.c b/shared/libutf/ispunctrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/isspacerune.c b/shared/libutf/isspacerune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/istitlerune.c b/shared/libutf/istitlerune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/isxdigitrune.c b/shared/libutf/isxdigitrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include "../utf.h" #include "runetype.h" diff --git a/shared/libutf/lowerrune.c b/shared/libutf/lowerrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/rune.c b/shared/libutf/rune.c @@ -1,22 +1,22 @@ -/* MIT/X Consortium Copyright (c) 2012 Connor Lane Smith <cls@lubutu.com> +/* MIT/X consortium copyright (c) 2012 connor lane smith <cls@lubutu.com> * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation + * permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "software"), + * to deal in the software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * and/or sell copies of the software, and to permit persons to whom the + * software is furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * DEALINGS IN THE SOFTWARE */ #include "../utf.h" @@ -77,7 +77,7 @@ charntorune(Rune *p, const char *s, size_t len) unsigned int i, n; Rune r; - if (len == 0) /* can't even look at s[0] */ + if (len == 0) /* cant even look at s[0] */ return 0; switch ((n = UTFSEQ(s[0]))) { @@ -107,7 +107,7 @@ charntorune(Rune *p, const char *s, size_t len) for (i = 1; i < MIN(n, len); i++) if ((s[i] & 0xC0) == 0x80) { /* add bits from continuation byte to rune value - * cannot overflow: 6 byte sequences contain 31 bits */ + * cannot overflow: 6 byte sequences contain 31 bits */ r = (r << 6) | (s[i] & 0x3F); /* 10xxxxxx */ } else { /* expected continuation */ *p = Runeerror; diff --git a/shared/libutf/runetype.c b/shared/libutf/runetype.c @@ -1,23 +1,23 @@ -/* MIT/X Consortium Copyright (c) 2012 Connor Lane Smith <cls@lubutu.com> - * (c) 2015 Laslo Hunhold <dev@frign.de> +/* MIT/X consortium copyright (c) 2012 connor lane smith <cls@lubutu.com> + * (c) 2015 laslo hunhold <dev@frign.de> * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation + * permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "software"), + * to deal in the software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * and/or sell copies of the software, and to permit persons to whom the + * software is furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * DEALINGS IN THE SOFTWARE */ #include "../utf.h" diff --git a/shared/libutf/runetype.h b/shared/libutf/runetype.h @@ -1,23 +1,23 @@ -/* MIT/X Consortium Copyright (c) 2012 Connor Lane Smith <cls@lubutu.com> - * (c) 2015 Laslo Hunhold <dev@frign.de> +/* MIT/X consortium copyright (c) 2012 connor lane smith <cls@lubutu.com> + * (c) 2015 laslo hunhold <dev@frign.de> * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation + * permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "software"), + * to deal in the software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * and/or sell copies of the software, and to permit persons to whom the + * software is furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * DEALINGS IN THE SOFTWARE */ #define nelem(x) (sizeof(x) / sizeof *(x)) diff --git a/shared/libutf/upperrune.c b/shared/libutf/upperrune.c @@ -1,4 +1,4 @@ -/* Automatically generated by mkrunetype.awk */ +/* automatically generated by mkrunetype.awk */ #include <stdlib.h> #include "../utf.h" diff --git a/shared/libutf/utf.c b/shared/libutf/utf.c @@ -1,22 +1,22 @@ -/* MIT/X Consortium Copyright (c) 2012 Connor Lane Smith <cls@lubutu.com> +/* MIT/X consortium copyright (c) 2012 connor lane smith <cls@lubutu.com> * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation + * permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "software"), + * to deal in the software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * and/or sell copies of the software, and to permit persons to whom the + * software is furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * DEALINGS IN THE SOFTWARE */ #include "../utf.h" #include <string.h> diff --git a/shared/libutf/utftorunestr.c b/shared/libutf/utftorunestr.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../utf.h" size_t diff --git a/shared/libutil/agetcwd.c b/shared/libutil/agetcwd.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> #include "../util.h" diff --git a/shared/libutil/agetline.c b/shared/libutil/agetline.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> #include <string.h> diff --git a/shared/libutil/apathmax.c b/shared/libutil/apathmax.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/concat.c b/shared/libutil/concat.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> #include "../util.h" diff --git a/shared/libutil/confirm.c b/shared/libutil/confirm.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <stdarg.h> diff --git a/shared/libutil/cp.c b/shared/libutil/cp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <dirent.h> #include <errno.h> #include <fcntl.h> diff --git a/shared/libutil/crypt.c b/shared/libutil/crypt.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <fcntl.h> #include <stdint.h> #include <stdio.h> diff --git a/shared/libutil/diffutil.c b/shared/libutil/diffutil.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../diffutil.h" #include "../text.h" #include "../util.h" diff --git a/shared/libutil/diskutil.c b/shared/libutil/diskutil.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../diskutil.h" #include "../util.h" @@ -158,7 +158,7 @@ blockdev_get_list(void) info->minor = minor; /* search tree topology to link partition node under proper - * target parent disk */ + * target parent disk */ is_part = 0; for (curr = head; curr; curr = curr->next) { size_t len = strlen(curr->name); @@ -499,6 +499,8 @@ static const struct FsType fstypes[] = { {"vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11}, /* ntfs */ {"ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0}, + /* iso9660: "CD001" at the primary volume descriptor, LBA 16 */ + {"iso9660", 32769, 5, 0x3130304443ULL, 0, 0, 0, 32808, 32}, /* xfs */ {"xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12}, /* btrfs */ diff --git a/shared/libutil/ealloc.c b/shared/libutil/ealloc.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdlib.h> #include <string.h> diff --git a/shared/libutil/enmasse.c b/shared/libutil/enmasse.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <libgen.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/eprintf.c b/shared/libutil/eprintf.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/estrtod.c b/shared/libutil/estrtod.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/estrtol.c b/shared/libutil/estrtol.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/estrtoul.c b/shared/libutil/estrtoul.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/shared/libutil/explicit_bzero.c b/shared/libutil/explicit_bzero.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <string.h> #include "../util.h" diff --git a/shared/libutil/fconcat.c b/shared/libutil/fconcat.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include "../text.h" diff --git a/shared/libutil/fnck.c b/shared/libutil/fnck.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include "../util.h" diff --git a/shared/libutil/fshut.c b/shared/libutil/fshut.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> @@ -9,11 +9,11 @@ fshut(FILE *fp, const char *fname) { int ret = 0; - /* fflush() is undefined for input streams by ISO C, - * but not POSIX 2008 if you ignore ISO C overrides. - * Leave it unchecked and rely on the following - * functions to detect errors. - */ + /* fflush() is undefined for input streams by ISO c, + * but not POSIX 2008 if you ignore ISO c overrides + * leave it unchecked and rely on the following + * functions to detect errors + */ fflush(fp); if (ferror(fp) && !ret) { diff --git a/shared/libutil/getlines.c b/shared/libutil/getlines.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <stdlib.h> #include <string.h> diff --git a/shared/libutil/hexval.c b/shared/libutil/hexval.c @@ -0,0 +1,14 @@ +/* see LICENSE file for copyright and license details */ +#include "../util.h" + +int +hexval(int c) +{ + if ('0' <= c && c <= '9') + return c - '0'; + if ('a' <= c && c <= 'f') + return c - 'a' + 10; + if ('A' <= c && c <= 'F') + return c - 'A' + 10; + return -1; +} diff --git a/shared/libutil/human.c b/shared/libutil/human.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdint.h> #include <stdio.h> #include <string.h> diff --git a/shared/libutil/linecmp.c b/shared/libutil/linecmp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include <string.h> diff --git a/shared/libutil/memmem.c b/shared/libutil/memmem.c @@ -1,31 +1,31 @@ -/* $OpenBSD: memmem.c,v 1.4 2015/08/31 02:53:57 guenther Exp $ */ +/* $openbsd: memmem.c,v 1.4 2015/08/31 02:53:57 guenther exp $ */ /* - * Copyright (c) 2005 Pascal Gloor <pascal.gloor@spale.com> + * copyright (c) 2005 pascal gloor <pascal.gloor@spale.com> * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote - * products derived from this software without specific prior written - * permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. the name of the author may not be used to endorse or promote + * products derived from this software without specific prior written + * permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE */ #include <string.h> @@ -33,7 +33,7 @@ #include "../util.h" /* - * Find the first occurrence of the byte string s in byte string l. + * find the first occurrence of the byte string s in byte string l */ void * diff --git a/shared/libutil/mkdirp.c b/shared/libutil/mkdirp.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <errno.h> diff --git a/shared/libutil/mode.c b/shared/libutil/mode.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdlib.h> #include <string.h> #include <sys/stat.h> diff --git a/shared/libutil/parseoffset.c b/shared/libutil/parseoffset.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <errno.h> #include <inttypes.h> @@ -45,6 +45,9 @@ parseoffset(const char *str) case 'G': scale = 1024L * 1024L * 1024L; break; + case 'T': + scale = 1024L * 1024L * 1024L * 1024L; + break; default: weprintf("parseoffset %s: invalid suffix '%s'\n", str, end); return -1; diff --git a/shared/libutil/passwd.c b/shared/libutil/passwd.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../passwd.h" #include "../paths.h" #include "../text.h" @@ -78,6 +78,17 @@ pw_check(const struct passwd *pw, const char *pass) weprintf("denied\n"); return -1; } + /* same empty-hash fast path as above, re-checked here: stored was + * just reassigned from the shadow entry's own field, and an empty + * shadow hash means "passwordless account", not "match nothing" + * (falling through to crypt() with an empty salt does the latter, + * since crypt("", "") is never itself the empty string) */ + if (stored[0] == '\0') { + if (pass[0] == '\0') + return 1; + weprintf("incorrect password\n"); + return 0; + } } #endif @@ -260,7 +271,12 @@ update_shadow(const char *name, const char *newhash) return -1; } - while ((spw = getspent())) { + /* fgetspent(fp) reads from the stream we already opened above; + * getspent() reads an implicit global shadow stream that musl + * never actually backs with this (or any) file and always + * returns null for, silently turning every update into a + * "no matching entry" failure */ + while ((spw = fgetspent(fp))) { cur = *spw; if (strcmp(cur.sp_namp, name) == 0) { cur.sp_pwdp = (char *)newhash; diff --git a/shared/libutil/proc.c b/shared/libutil/proc.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <errno.h> @@ -85,7 +85,7 @@ parsestat(pid_t pid, struct procstat *ps) &ps->rss, &ps->rsslim ); - /* Filter out '(' and ')' from comm */ + /* filter out '(' and ')' from comm */ if ((len = strlen(ps->comm)) > 0) len--; ps->comm[len] = '\0'; diff --git a/shared/libutil/putword.c b/shared/libutil/putword.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stdio.h> #include "../util.h" diff --git a/shared/libutil/reallocarray.c b/shared/libutil/reallocarray.c @@ -1,9 +1,9 @@ /* - * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> + * copyright (c) 2008 otto moerbeek <otto@drijf.net> * - * Permission to use, copy, modify, and distribute this software for any + * permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. + * copyright notice and this permission notice appear in all copies * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF @@ -11,7 +11,7 @@ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE */ #include <errno.h> @@ -22,7 +22,7 @@ #include "../util.h" /* - * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX + * this is sqrt(size_max+1), as s1*s2 <= SIZE_MAX * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW */ #define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4)) diff --git a/shared/libutil/recurse.c b/shared/libutil/recurse.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <dirent.h> #include <errno.h> #include <fcntl.h> diff --git a/shared/libutil/recurse_dir.c b/shared/libutil/recurse_dir.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <dirent.h> #include <limits.h> #include <stdio.h> diff --git a/shared/libutil/rm.c b/shared/libutil/rm.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <errno.h> diff --git a/shared/libutil/sig.c b/shared/libutil/sig.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../sig.h" #include <signal.h> diff --git a/shared/libutil/strcasestr.c b/shared/libutil/strcasestr.c @@ -1,24 +1,24 @@ /* - * Copyright 2005-2014 Rich Felker, et al. + * copyright 2005-2014 rich felker, et al * - * Permission is hereby granted, free of charge, to any person obtaining + * permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including + * "software"), to deal in the software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to + * distribute, sublicense, and/or sell copies of the software, and to + * permit persons to whom the software is furnished to do so, subject to * the following conditions: * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * MERCHANTABILITY, FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #include <string.h> #include <strings.h> diff --git a/shared/libutil/strlcat.c b/shared/libutil/strlcat.c @@ -1,9 +1,9 @@ /* - * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> + * copyright (c) 1998 todd c. miller <todd.miller@courtesan.com> * - * Permission to use, copy, modify, and distribute this software for any + * permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. + * copyright notice and this permission notice appear in all copies * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF @@ -11,7 +11,7 @@ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE */ #include <string.h> @@ -20,11 +20,11 @@ #include "../util.h" /* - * Appends src to string dst of size siz (unlike strncat, siz is the - * full size of dst, not space left). At most siz-1 characters - * will be copied. Always NUL terminates (unless siz <= strlen(dst)). - * Returns strlen(src) + MIN(siz, strlen(initial dst)). - * If retval >= siz, truncation occurred. + * appends src to string dst of size siz (unlike strncat, siz is the + * full size of dst, not space left). at most siz-1 characters + * will be copied. always NUL terminates (unless siz <= strlen(dst)) + * returns strlen(src) + min(siz, strlen(initial dst)) + * if retval >= siz, truncation occurred */ size_t strlcat(char *dst, const char *src, size_t siz) @@ -33,7 +33,7 @@ strlcat(char *dst, const char *src, size_t siz) const char *s = src; size_t n = siz; size_t dlen; - /* Find the end of dst and adjust bytes left but don't go past end */ + /* find the end of dst and adjust bytes left but dont go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; diff --git a/shared/libutil/strlcpy.c b/shared/libutil/strlcpy.c @@ -1,9 +1,9 @@ /* - * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> + * copyright (c) 1998 todd c. miller <todd.miller@courtesan.com> * - * Permission to use, copy, modify, and distribute this software for any + * permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. + * copyright notice and this permission notice appear in all copies * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF @@ -11,7 +11,7 @@ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE */ #include <string.h> @@ -20,9 +20,9 @@ #include "../util.h" /* - * Copy src to string dst of size siz. At most siz-1 characters - * will be copied. Always NUL terminates (unless siz == 0). - * Returns strlen(src); if retval >= siz, truncation occurred. + * copy src to string dst of size siz. at most siz-1 characters + * will be copied. always NUL terminates (unless siz == 0) + * returns strlen(src); if retval >= siz, truncation occurred */ size_t strlcpy(char *dst, const char *src, size_t siz) @@ -30,17 +30,17 @@ strlcpy(char *dst, const char *src, size_t siz) char *d = dst; const char *s = src; size_t n = siz; - /* Copy as many bytes as will fit */ + /* copy as many bytes as will fit */ if (n != 0) { while (--n != 0) { if ((*d++ = *s++) == '\0') break; } } - /* Not enough room in dst, add NUL and traverse rest of src */ + /* not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) - *d = '\0'; /* NUL-terminate dst */ + *d = '\0'; /* nul-terminate dst */ while (*s++) ; } diff --git a/shared/libutil/strnsubst.c b/shared/libutil/strnsubst.c @@ -1,9 +1,9 @@ /* - * Copyright (c) 2002 J. Mallett. All rights reserved. - * You may do whatever you want with this file as long as + * copyright (c) 2002 j. mallett. all rights reserved + * you may do whatever you want with this file as long as * the above copyright and this notice remain intact, along * with the following statement: - * For the man who taught me vi, and who got too old, too young. + * for the man who taught me vi, and who got too old, too young */ #include <stdio.h> @@ -13,14 +13,14 @@ #include "../util.h" /* - * Replaces str with a string consisting of str with match replaced with + * replaces str with a string consisting of str with match replaced with * replstr as many times as can be done before the constructed string is - * maxsize bytes large. It does not free the string pointed to by str, it + * maxsize bytes large. it does not free the string pointed to by str, it * is up to the calling program to be sure that the original contents of - * str as well as the new contents are handled in an appropriate manner. - * If replstr is NULL, then that internally is changed to a nil-string, so - * that we can still pretend to do somewhat meaningful substitution. - * No value is returned. + * str as well as the new contents are handled in an appropriate manner + * if replstr is NULL, then that internally is changed to a nil-string, so + * that we can still pretend to do somewhat meaningful substitution + * no value is returned */ void strnsubst(char **str, const char *match, const char *replstr, size_t maxsize) diff --git a/shared/libutil/strsep.c b/shared/libutil/strsep.c @@ -1,24 +1,24 @@ /* - * Copyright 2005-2014 Rich Felker, et al. + * copyright 2005-2014 rich felker, et al * - * Permission is hereby granted, free of charge, to any person obtaining + * permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including + * "software"), to deal in the software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to + * distribute, sublicense, and/or sell copies of the software, and to + * permit persons to whom the software is furnished to do so, subject to * the following conditions: * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * MERCHANTABILITY, FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ #include <string.h> diff --git a/shared/libutil/strtonum.c b/shared/libutil/strtonum.c @@ -1,12 +1,12 @@ -/* $OpenBSD: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu Exp $ */ +/* $openbsd: strtonum.c,v 1.7 2013/04/17 18:40:58 tedu exp $ */ /* - * Copyright (c) 2004 Ted Unangst and Todd Miller - * All rights reserved. + * copyright (c) 2004 ted unangst and todd miller + * all rights reserved * - * Permission to use, copy, modify, and distribute this software for any + * permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. + * copyright notice and this permission notice appear in all copies * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF @@ -14,7 +14,7 @@ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE */ #include <errno.h> diff --git a/shared/libutil/tty.c b/shared/libutil/tty.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <sys/stat.h> #include <sys/sysmacros.h> #include <sys/types.h> diff --git a/shared/libutil/unescape.c b/shared/libutil/unescape.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <ctype.h> #include <string.h> diff --git a/shared/libutil/wexec.c b/shared/libutil/wexec.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include "../wexec.h" #include "../config.h" #include "../paths.h" @@ -199,7 +199,7 @@ wwhich(const char *name) path = wexec_getenv("PATH"); if (path == NULL) - path = "/usr/local/bin:/usr/bin:/bin"; + path = ARUU_PATH_DEFPATH; nlen = strlen(name); p = path; @@ -327,7 +327,8 @@ fork_exec(const char *path, char *const *argv, int use_path) execvp(path, argv); else execv(path, argv); - _exit(127); + weprintf(use_path ? "execvp %s:" : "execv %s:", path); + _exit((errno == ENOENT) ? 127 : 126); } if (waitpid(pid, &st, 0) < 0) { weprintf("waitpid:"); @@ -435,7 +436,8 @@ wpopen(const char *name, char *const *argv, const char *mode) } #endif execvp(name, argv); - _exit(127); + weprintf("execvp %s:", name); + _exit((errno == ENOENT) ? 127 : 126); } else { sh_argv[0] = "sh"; sh_argv[1] = "-c"; @@ -462,7 +464,8 @@ wpopen(const char *name, char *const *argv, const char *mode) } #endif execvp("sh", sh_argv); - _exit(127); + weprintf("execvp sh:"); + _exit((errno == ENOENT) ? 127 : 126); } } diff --git a/shared/libutil/writeall.c b/shared/libutil/writeall.c @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <unistd.h> #include "../util.h" diff --git a/shared/passwd.h b/shared/passwd.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #ifndef ARUU_PASSWD_H #define ARUU_PASSWD_H diff --git a/shared/paths.h b/shared/paths.h @@ -1,12 +1,12 @@ -/* See LICENSE file for copyright and license details. */ +/* 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" + * portable paths. override at compile time for non-fhs systems: + * -daruu_path_etc="/config" * - * OS-specific paths (procfs, sysfs) are prefixed ARUU_LINUX_PATH_* + * 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 @@ -62,8 +62,14 @@ #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" + +#ifndef ARUU_PATH_STDPATH +#define ARUU_PATH_STDPATH ARUU_PATH_BIN ":" ARUU_PATH_USR_BIN +#endif + +#ifndef ARUU_PATH_DEFPATH +#define ARUU_PATH_DEFPATH ARUU_PATH_BIN ":" ARUU_PATH_USR_BIN +#endif #if defined(__linux__) #define ARUU_LINUX_PATH_PROC "/proc" diff --git a/shared/proc.h b/shared/proc.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ struct procstat { int pid; char comm[PATH_MAX + 2]; /* + 2 for '(' and ')' */ diff --git a/shared/queue.h b/shared/queue.h @@ -1,85 +1,85 @@ -/* $OpenBSD: queue.h,v 1.38 2013/07/03 15:05:21 fgsch Exp $ */ -/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ +/* $openbsd: queue.h,v 1.38 2013/07/03 15:05:21 fgsch exp $ */ +/* $netbsd: queue.h,v 1.11 1996/05/16 05:17:14 mycroft exp $ */ /* - * Copyright (c) 1991, 1993 - * The Regents of the University of California. All rights reserved. + * copyright (c) 1991, 1993 + * the regents of the university of california. all rights reserved * - * Redistribution and use in source and binary forms, with or without + * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. + * 1. redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer + * 2. redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution + * 3. neither the name of the university nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR a PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. + * SUCH DAMAGE * - * @(#)queue.h 8.5 (Berkeley) 8/20/94 + * @(#)queue.h 8.5 (berkeley) 8/20/94 */ #ifndef _SYS_QUEUE_H_ #define _SYS_QUEUE_H_ /* - * This file defines five types of data structures: singly-linked lists, - * lists, simple queues, tail queues, and circular queues. + * this file defines five types of data structures: singly-linked lists, + * lists, simple queues, tail queues, and circular queues * * - * A singly-linked list is headed by a single forward pointer. The elements + * a singly-linked list is headed by a single forward pointer. the elements * are singly linked for minimum space and pointer manipulation overhead at - * the expense of O(n) removal for arbitrary elements. New elements can be - * added to the list after an existing element or at the head of the list. - * Elements being removed from the head of the list should use the explicit - * macro for this purpose for optimum efficiency. A singly-linked list may - * only be traversed in the forward direction. Singly-linked lists are ideal + * the expense of o(n) removal for arbitrary elements. new elements can be + * added to the list after an existing element or at the head of the list + * elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. a singly-linked list may + * only be traversed in the forward direction. singly-linked lists are ideal * for applications with large datasets and few or no removals or for - * implementing a LIFO queue. + * implementing a LIFO queue * - * A list is headed by a single forward pointer (or an array of forward - * pointers for a hash table header). The elements are doubly linked + * a list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). the elements are doubly linked * so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before - * or after an existing element or at the head of the list. A list - * may only be traversed in the forward direction. + * traverse the list. new elements can be added to the list before + * or after an existing element or at the head of the list. a list + * may only be traversed in the forward direction * - * A simple queue is headed by a pair of pointers, one the head of the - * list and the other to the tail of the list. The elements are singly + * a simple queue is headed by a pair of pointers, one the head of the + * list and the other to the tail of the list. the elements are singly * linked to save space, so elements can only be removed from the - * head of the list. New elements can be added to the list before or after + * head of the list. new elements can be added to the list before or after * an existing element, at the head of the list, or at the end of the - * list. A simple queue may only be traversed in the forward direction. + * list. a simple queue may only be traversed in the forward direction * - * A tail queue is headed by a pair of pointers, one to the head of the - * list and the other to the tail of the list. The elements are doubly + * a tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. the elements are doubly * linked so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before or + * traverse the list. new elements can be added to the list before or * after an existing element, at the head of the list, or at the end of - * the list. A tail queue may be traversed in either direction. + * the list. a tail queue may be traversed in either direction * - * A circle queue is headed by a pair of pointers, one to the head of the - * list and the other to the tail of the list. The elements are doubly + * a circle queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. the elements are doubly * linked so that an arbitrary element can be removed without a need to - * traverse the list. New elements can be added to the list before or after - * an existing element, at the head of the list, or at the end of the list. - * A circle queue may be traversed in either direction, but has a more - * complex end of list detection. + * traverse the list. new elements can be added to the list before or after + * an existing element, at the head of the list, or at the end of the list + * a circle queue may be traversed in either direction, but has a more + * complex end of list detection * - * For details on the use of these macros, see the queue(3) manual page. + * for details on the use of these macros, see the queue(3) manual page */ #if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC)) @@ -89,7 +89,7 @@ #endif /* - * Singly-linked List definitions. + * singly-linked list definitions */ #define SLIST_HEAD(name, type) \ struct name { \ @@ -104,7 +104,7 @@ } /* - * Singly-linked List access methods. + * singly-linked list access methods */ #define SLIST_FIRST(head) ((head)->slh_first) #define SLIST_END(head) NULL @@ -118,7 +118,7 @@ for ((var) = SLIST_FIRST(head); (var) && ((tvar) = SLIST_NEXT(var, field), 1); (var) = (tvar)) /* - * Singly-linked List functions. + * singly-linked list functions */ #define SLIST_INIT(head) \ { \ @@ -162,7 +162,7 @@ } while (0) /* - * List definitions. + * list definitions */ #define LIST_HEAD(name, type) \ struct name { \ @@ -178,7 +178,7 @@ } /* - * List access methods + * list access methods */ #define LIST_FIRST(head) ((head)->lh_first) #define LIST_END(head) NULL @@ -192,7 +192,7 @@ for ((var) = LIST_FIRST(head); (var) && ((tvar) = LIST_NEXT(var, field), 1); (var) = (tvar)) /* - * List functions. + * list functions */ #define LIST_INIT(head) \ do { \ @@ -243,7 +243,7 @@ } while (0) /* - * Simple queue definitions. + * simple queue definitions */ #define SIMPLEQ_HEAD(name, type) \ struct name { \ @@ -259,7 +259,7 @@ } /* - * Simple queue access methods. + * simple queue access methods */ #define SIMPLEQ_FIRST(head) ((head)->sqh_first) #define SIMPLEQ_END(head) NULL @@ -273,7 +273,7 @@ for ((var) = SIMPLEQ_FIRST(head); (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); (var) = (tvar)) /* - * Simple queue functions. + * simple queue functions */ #define SIMPLEQ_INIT(head) \ do { \ @@ -315,7 +315,7 @@ } while (0) /* - * XOR Simple queue definitions. + * XOR simple queue definitions */ #define XSIMPLEQ_HEAD(name, type) \ struct name { \ @@ -330,7 +330,7 @@ } /* - * XOR Simple queue access methods. + * XOR simple queue access methods */ #define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ (unsigned long)(ptr))) #define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first)) @@ -347,7 +347,7 @@ (var) = (tvar)) /* - * XOR Simple queue functions. + * XOR simple queue functions */ #define XSIMPLEQ_INIT(head) \ do { \ @@ -392,7 +392,7 @@ } while (0) /* - * Tail queue definitions. + * tail queue definitions */ #define TAILQ_HEAD(name, type) \ struct name { \ @@ -437,7 +437,7 @@ (var) = (tvar)) /* - * Tail queue functions. + * tail queue functions */ #define TAILQ_INIT(head) \ do { \ @@ -505,7 +505,7 @@ } while (0) /* - * Circular queue definitions. + * circular queue definitions */ #define CIRCLEQ_HEAD(name, type) \ struct name { \ @@ -522,7 +522,7 @@ } /* - * Circular queue access methods + * circular queue access methods */ #define CIRCLEQ_FIRST(head) ((head)->cqh_first) #define CIRCLEQ_LAST(head) ((head)->cqh_last) @@ -548,7 +548,7 @@ (var) = (tvar)) /* - * Circular queue functions. + * circular queue functions */ #define CIRCLEQ_INIT(head) \ do { \ diff --git a/shared/reboot.h b/shared/reboot.h @@ -1,5 +1,5 @@ /* - * Magic values required to use _reboot() system call. + * magic values required to use _reboot() system call */ #define LINUX_REBOOT_MAGIC1 0xfee1dead @@ -9,16 +9,16 @@ #define LINUX_REBOOT_MAGIC2C 537993216 /* - * Commands accepted by the _reboot() system call. + * commands accepted by the _reboot() system call * - * RESTART Restart system using default command and mode. - * HALT Stop OS and give system control to ROM monitor, if any. - * CAD_ON Ctrl-Alt-Del sequence causes RESTART command. - * CAD_OFF Ctrl-Alt-Del sequence sends SIGINT to init task. - * POWER_OFF Stop OS and remove all power from system, if possible. - * RESTART2 Restart system using given command string. - * SW_SUSPEND Suspend system using software suspend if compiled in. - * KEXEC Restart system using a previously loaded Linux kernel + * RESTART restart system using default command and mode + * HALT stop OS and give system control to ROM monitor, if any + * CAD_ON ctrl-alt-del sequence causes RESTART command + * CAD_OFF ctrl-alt-del sequence sends SIGINT to init task + * POWER_OFF stop OS and remove all power from system, if possible + * RESTART2 restart system using given command string + * SW_SUSPEND suspend system using software suspend if compiled in + * KEXEC restart system using a previously loaded linux kernel */ #define LINUX_REBOOT_CMD_RESTART 0x01234567 diff --git a/shared/rtc.h b/shared/rtc.h @@ -1,7 +1,7 @@ /* - * The struct used to pass data via the following ioctl. Similar to the + * the struct used to pass data via the following ioctl. similar to the * struct tm in <time.h>, but it needs to be here so that the kernel - * source is self contained, allowing cross-compiles, etc. etc. + * source is self contained, allowing cross-compiles, etc. etc */ struct rtc_time { @@ -16,5 +16,5 @@ struct rtc_time { int tm_isdst; }; -#define RTC_RD_TIME _IOR('p', 0x09, struct rtc_time) /* Read RTC time */ -#define RTC_SET_TIME _IOW('p', 0x0a, struct rtc_time) /* Set RTC time */ +#define RTC_RD_TIME _IOR('p', 0x09, struct rtc_time) /* read RTC time */ +#define RTC_SET_TIME _IOW('p', 0x0a, struct rtc_time) /* set RTC time */ diff --git a/shared/sha224.h b/shared/sha224.h @@ -3,7 +3,7 @@ #include "sha256.h" #include <stdint.h> -#define sha224 sha256 /*struct*/ +#define sha224 sha256 /* struct */ enum { SHA224_DIGEST_LENGTH = 28 }; diff --git a/shared/sha384.h b/shared/sha384.h @@ -3,7 +3,7 @@ #include "sha512.h" #include <stdint.h> -#define sha384 sha512 /*struct*/ +#define sha384 sha512 /* struct */ enum { SHA384_DIGEST_LENGTH = 48 }; diff --git a/shared/sha512-224.h b/shared/sha512-224.h @@ -3,7 +3,7 @@ #include "sha512.h" #include <stdint.h> -#define sha512_224 sha512 /*struct*/ +#define sha512_224 sha512 /* struct */ enum { SHA512_224_DIGEST_LENGTH = 28 }; diff --git a/shared/sha512-256.h b/shared/sha512-256.h @@ -3,7 +3,7 @@ #include "sha512.h" #include <stdint.h> -#define sha512_256 sha512 /*struct*/ +#define sha512_256 sha512 /* struct */ enum { SHA512_256_DIGEST_LENGTH = 32 }; diff --git a/shared/sig.h b/shared/sig.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #ifndef SIG_H_ #define SIG_H_ diff --git a/shared/text.h b/shared/text.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #include <stddef.h> #include <stdio.h> diff --git a/shared/tls.h b/shared/tls.h @@ -7,8 +7,8 @@ struct TlsSocket; /* tls_connect takes an already connected socket fd and upgrades it to tls - if check_cert is 0 certificate validation is bypassed - returns a new tls socket or null on error */ + * if check_cert is 0 certificate validation is bypassed + * returns a new tls socket or null on error */ struct TlsSocket *tlss_connect(int fd, const char *host, int check_cert, int is_tls); /* standard read and write wrapping either libtls, bearssl or plain fallback */ diff --git a/shared/utf.h b/shared/utf.h @@ -1,22 +1,22 @@ -/* MIT/X Consortium Copyright (c) 2012 Connor Lane Smith <cls@lubutu.com> +/* MIT/X consortium copyright (c) 2012 connor lane smith <cls@lubutu.com> * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation + * permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "software"), + * to deal in the software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: + * and/or sell copies of the software, and to permit persons to whom the + * software is furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. + * the above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the software * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * FITNESS FOR a PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * DEALINGS IN THE SOFTWARE */ #include <stdio.h> diff --git a/shared/util.h b/shared/util.h @@ -1,4 +1,7 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ +#ifndef UTIL_H +#define UTIL_H + #include <sys/types.h> #include <regex.h> @@ -82,6 +85,7 @@ int concat(int, const char *, int, const char *); void enmasse(int, char **, int (*)(const char *, const char *, int)); void fnck(const char *, const char *, int (*)(const char *, const char *, int), int); mode_t getumask(void); +int hexval(int); char *humansize(off_t); mode_t parsemode(const char *, mode_t, mode_t); off_t parseoffset(const char *); @@ -176,3 +180,5 @@ int net_set_name(const char *, const char *); #define exit(code) wexec_exit(code) #define _exit(code) wexec_exit(code) #endif + +#endif diff --git a/shared/wexec.h b/shared/wexec.h @@ -1,4 +1,4 @@ -/* See LICENSE file for copyright and license details. */ +/* see LICENSE file for copyright and license details */ #ifndef ARUU_WEXEC_H #define ARUU_WEXEC_H