aruu

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

commit e9ea73acbfe7ec1349cef7d27f26b2013197d3f9
parent ea914161cbe358533422e130ffcc87730200108b
Author: xplshn <anto@xplshn.com.ar>
Date:   Sat, 20 Jun 2026 22:40:35 -0300

lsblk, fdisk, blkid and updated manpages

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

Diffstat:
A.gitignore | 30++++++++++++++++++++++++++++++
MMakefile | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
MMakefile.sh | 89++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Mbuild.cfg | 26++++++++++++++------------
Acmd/extra/blkid.c | 346+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/extra/fdisk.c | 478+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/extra/lsblk.c | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/linux/ctrlaltdel.c | 13+++++--------
Mcmd/linux/depmod.c | 6++++--
Mcmd/linux/eject.c | 7+++----
Mcmd/linux/fsfreeze.c | 11++++-------
Mcmd/linux/hwclock.c | 17+++++++----------
Mcmd/linux/insmod.c | 4++--
Mcmd/linux/modprobe.c | 29+++++++++++++++++++----------
Mcmd/linux/mount.c | 21+++++++++------------
Mcmd/linux/mountpoint.c | 8++++----
Mcmd/linux/rmmod.c | 8+++++---
Mcmd/linux/swaplabel.c | 6+++---
Mcmd/linux/swapoff.c | 9++++-----
Mcmd/linux/swapon.c | 13++++++-------
Mcmd/linux/switch_root.c | 9+++------
Mcmd/linux/sysctl.c | 9+++------
Mcmd/linux/tunctl.c | 8++++----
Mcmd/linux/umount.c | 14++++++--------
Mcmd/linux/unshare.c | 19+++++++++----------
Mcmd/net/host.c | 4++--
Mcmd/net/httpd.c | 6+++---
Mcmd/net/ifconfig.c | 4++--
Mcmd/net/ip.c | 4+---
Mcmd/net/netcat.c | 8++++----
Mcmd/net/ping.c | 10+++++-----
Mcmd/net/tftp.c | 8++++----
Mcmd/net/wget.c | 16++++++++--------
Mcmd/posix/basename.c | 2+-
Mcmd/posix/cal.c | 16++++++++--------
Mcmd/posix/cat.c | 7++++---
Mcmd/posix/chgrp.c | 8++++----
Mcmd/posix/chown.c | 11+++++------
Mcmd/posix/cmp.c | 4++--
Mcmd/posix/comm.c | 6+++---
Mcmd/posix/cp.c | 12++++++------
Mcmd/posix/cut.c | 32+++++++++-----------------------
Mcmd/posix/date.c | 7+++----
Mcmd/posix/df.c | 14+++++++-------
Mcmd/posix/du.c | 18+++++++++---------
Mcmd/posix/env.c | 6+++---
Mcmd/posix/expand.c | 4++--
Mcmd/posix/find.c | 6+++---
Mcmd/posix/fold.c | 10+++++-----
Mcmd/posix/getconf.c | 4++--
Mcmd/posix/grep.c | 42+++++++++++++++++++++---------------------
Mcmd/posix/head.c | 4++--
Mcmd/posix/id.c | 14+++++++-------
Mcmd/posix/join.c | 35+++++++++--------------------------
Mcmd/posix/ln.c | 6+++---
Mcmd/posix/logger.c | 8++++----
Mcmd/posix/ls.c | 8++++----
Mcmd/posix/mesg.c | 2+-
Mcmd/posix/mkfifo.c | 2+-
Mcmd/posix/nice.c | 4++--
Mcmd/posix/nl.c | 65++++++++++++++---------------------------------------------------
Mcmd/posix/nohup.c | 2+-
Mcmd/posix/od.c | 61++++++++++++++++++++++++++-----------------------------------
Mcmd/posix/paste.c | 4++--
Mcmd/posix/pathchk.c | 4++--
Mcmd/posix/pax.c | 61+++++++++++++++++++++++++++++++++----------------------------
Mcmd/posix/printf.c | 2+-
Mcmd/posix/ps.c | 14+++++++-------
Mcmd/posix/pwd.c | 4++--
Mcmd/posix/readlink.c | 4++--
Mcmd/posix/renice.c | 8++++----
Mcmd/posix/sed.c | 89++++++++-----------------------------------------------------------------------
Mcmd/posix/sort.c | 56+++++++++++++++++++++++---------------------------------
Mcmd/posix/split.c | 10+++++-----
Mcmd/posix/tail.c | 10+++++-----
Mcmd/posix/tee.c | 4++--
Mcmd/posix/time.c | 4++--
Mcmd/posix/touch.c | 14+++++++-------
Mcmd/posix/tr.c | 10+++++-----
Mcmd/posix/uname.c | 12++++++------
Mcmd/posix/unexpand.c | 4++--
Mcmd/posix/uniq.c | 10+++++-----
Mcmd/posix/uuencode.c | 2+-
Mcmd/posix/wc.c | 8++++----
Mcmd/posix/who.c | 8++++----
Mcmd/posix/xargs.c | 43++++++++++++++-----------------------------
Mcmd/pseudo/chroot.c | 2+-
Mcmd/pseudo/dmesg.c | 17++++++++---------
Mcmd/pseudo/flock.c | 2+-
Mcmd/pseudo/free.c | 12++++++------
Mcmd/pseudo/getty.c | 2+-
Mcmd/pseudo/login.c | 7+++----
Mcmd/pseudo/md5sum.c | 6+++---
Mcmd/pseudo/mktemp.c | 8++++----
Mcmd/pseudo/pidof.c | 10+++++-----
Mcmd/pseudo/respawn.c | 2+-
Mcmd/pseudo/seq.c | 6+++---
Mcmd/pseudo/setsid.c | 2+-
Mcmd/pseudo/sha1sum.c | 6+++---
Mcmd/pseudo/sha224sum.c | 6+++---
Mcmd/pseudo/sha256sum.c | 6+++---
Mcmd/pseudo/sha384sum.c | 6+++---
Mcmd/pseudo/sha512-224sum.c | 6+++---
Mcmd/pseudo/sha512-256sum.c | 6+++---
Mcmd/pseudo/sha512sum.c | 6+++---
Mcmd/pseudo/tar.c | 24++++++++++++------------
Mcmd/pseudo/truncate.c | 10+++++-----
Mcmd/pseudo/which.c | 2+-
Mcmd/pseudo/xinstall.c | 20+++++++++-----------
Mcmd/xsi/mknod.c | 2+-
Mcmd/xsi/su.c | 10++++------
Mconfig.mk | 35+++++++++++++++++++----------------
Mscripts/mkman/main.go | 35++++++++++++++++++++++++++++-------
Mscripts/mkman/mdoc.go | 39++++++++++++++++++---------------------
Mscripts/mkman/page.go | 11+++++++----
Mscripts/mkman/parse.go | 138++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Ascripts/mkman/txt.go | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/diskutil.h | 34++++++++++++++++++++++++++++++++++
Ashared/libutil/diskutil.c | 439+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
119 files changed, 2505 insertions(+), 871 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,30 @@ +# object files and static/shared libs +*.o +*.a +*.so + +# awk generated sources +cmd/posix/awk/awkgram.tab.c +cmd/posix/awk/awkgram.tab.h +cmd/posix/awk/proctab.c +cmd/posix/awk/maketab + +# sh generated sources and host generators +cmd/posix/sh/syntax.c +cmd/posix/sh/syntax.h +cmd/posix/sh/nodes.c +cmd/posix/sh/nodes.h +cmd/posix/sh/builtins.c +cmd/posix/sh/builtins.h +cmd/posix/sh/token.h +cmd/posix/sh/mknodes +cmd/posix/sh/mksyntax + +# other generated sources +cmd/posix/getconf.h +cmd/posix/bc.c + +# cmd/dev toolchain: configure output (regenerated by ./cmd/dev/configure) +cmd/dev/config.h +cmd/dev/cc/config.h +cmd/dev/version.h diff --git a/Makefile b/Makefile @@ -102,7 +102,8 @@ LIBUTILOBJ =\ shared/libutil/sig.o\ shared/libutil/net.o\ shared/libutil/sysinfo.o\ - shared/libutil/tls.o + shared/libutil/tls.o\ + shared/libutil/diskutil.o LIBREDLINEOBJ =\ shared/libredline/redline.o @@ -272,6 +273,9 @@ PSEUDO_BIN_ALL =\ cmd/pseudo/yes\ cmd/pseudo/base64\ cmd/extra/b3sum\ + cmd/extra/blkid\ + cmd/extra/lsblk\ + cmd/extra/fdisk\ cmd/dev/ar/ar\ cmd/dev/as/as\ cmd/dev/ld/ld\ @@ -448,6 +452,9 @@ BIN_xinstall_1 = cmd/pseudo/xinstall BIN_yes_1 = cmd/pseudo/yes BIN_base64_1 = cmd/pseudo/base64 BIN_b3sum_1 = cmd/extra/b3sum +BIN_blkid_1 = cmd/extra/blkid +BIN_lsblk_1 = cmd/extra/lsblk +BIN_fdisk_1 = cmd/extra/fdisk BIN_ar_1 = cmd/dev/ar/ar BIN_as_1 = cmd/dev/as/as BIN_ld_1 = cmd/dev/ld/ld @@ -622,6 +629,9 @@ PSEUDO_BIN = \ $(BIN_yes_$(BUILD_PSEUDO_YES)) \ $(BIN_base64_$(BUILD_PSEUDO_BASE64)) \ $(BIN_b3sum_$(BUILD_PSEUDO_B3SUM)) \ + $(BIN_blkid_$(BUILD_PSEUDO_BLKID)) \ + $(BIN_lsblk_$(BUILD_PSEUDO_LSBLK)) \ + $(BIN_fdisk_$(BUILD_PSEUDO_FDISK)) \ $(BIN_ar_$(BUILD_DEV_AR)) \ $(BIN_as_$(BUILD_DEV_CC)) \ $(BIN_ld_$(BUILD_DEV_LD)) \ @@ -693,14 +703,16 @@ man: scripts/mkman/mkman if [ -f "$$src" ] && grep -qE '!man|\?man' "$$src"; then \ base=$$(basename $$src .c); \ mkdir -p man/man1; \ - scripts/mkman/mkman -config config.mk -section 1 "$$src" > "man/man1/$$base.1"; \ + scripts/mkman/mkman -fmt mdoc -config config.mk -section 1 "$$src" > "man/man1/$$base.1"; \ + scripts/mkman/mkman -fmt txt -config config.mk -section 1 "$$src" > "man/man1/$$base.1.txt"; \ fi; \ done @for src in $(LINUX_BIN_ALL:=.c) $(NET_BIN_ALL:=.c) $(XSI_BIN_ALL:=.c); do \ if [ -f "$$src" ] && grep -qE '!man|\?man' "$$src"; then \ base=$$(basename $$src .c); \ mkdir -p man/man8; \ - scripts/mkman/mkman -config config.mk -section 8 "$$src" > "man/man8/$$base.8"; \ + scripts/mkman/mkman -fmt mdoc -config config.mk -section 8 "$$src" > "man/man8/$$base.8"; \ + scripts/mkman/mkman -fmt txt -config config.mk -section 8 "$$src" > "man/man8/$$base.8.txt"; \ fi; \ done @@ -708,13 +720,14 @@ clean: rm -f shared/libutf/*.o shared/libutil/*.o shared/libredline/*.o rm -f cmd/posix/*.o cmd/posix/make/*.o cmd/posix/awk/*.o cmd/posix/sh/*.o rm -f cmd/linux/*.o cmd/net/*.o cmd/xsi/*.o cmd/pseudo/*.o - rm -f cmd/extra/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o + rm -f cmd/extra/*.o cmd/dev/ar/*.o cmd/dev/ld/*.o cmd/dev/cc/*.o cmd/dev/as/*.o cmd/dev/xcutil/*.o rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) $(LIB) rm -f cmd/posix/make/make cmd/posix/getconf.h cmd/posix/bc.c rm -f cmd/posix/awk/awk cmd/posix/awk/maketab cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c rm -f cmd/posix/sh/sh cmd/posix/sh/mknodes cmd/posix/sh/mksyntax rm -f cmd/posix/sh/syntax.c cmd/posix/sh/syntax.h cmd/posix/sh/nodes.c cmd/posix/sh/nodes.h cmd/posix/sh/builtins.c cmd/posix/sh/builtins.h cmd/posix/sh/token.h - rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as shared/libaruuelf.so + rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar shared/libaruuelf.so + rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h rm -rf aruu-box .box man/man1 man/man8 scripts/mkman/mkman AWKOBJ =\ @@ -814,41 +827,70 @@ cmd/posix/sh/%.o: cmd/posix/sh/%.c cmd/posix/sh/sh: $(SHOBJ) $(LIB) $(CC) $(LDFLAGS) -o $@ $(SHOBJ) $(LIB) $(LDLIBS) +cmd/net/wget: cmd/net/wget.o $(LIB) + $(CC) $(LDFLAGS) -o $@ cmd/net/wget.o $(LIB) $(LDLIBS) $(LDLIBS_TLS) + cmd/dev/ar/ar: cmd/dev/ar/ar.o $(LIB) $(CC) $(LDFLAGS) -o $@ cmd/dev/ar/ar.o $(LIB) $(LDLIBS) cmd/dev/ar/%.o: cmd/dev/ar/%.c $(CC) $(CPPFLAGS) -Icmd/dev/ar $(CFLAGS) -o $@ -c $< +cmd/dev/xcutil/%.o: cmd/dev/xcutil/%.c + $(CC) -Icmd/dev/xcutil $(CPPFLAGS) $(CFLAGS) -o $@ -c $< + LD_OBJ =\ - cmd/dev/ld/ld.o + cmd/dev/xcutil/util.o\ + cmd/dev/xcutil/table.o\ + cmd/dev/xcutil/elfutil.o\ + cmd/dev/xcutil/archive.o\ + cmd/dev/ld/ld.o\ + cmd/dev/ld/elfobj.o cmd/dev/ld/%.o: cmd/dev/ld/%.c - $(CC) $(CPPFLAGS) -DLD_TARGET_X86_64 -Icmd/dev/ld $(CFLAGS) -fPIC -o $@ -c $< - -shared/libaruuelf.so: cmd/dev/ld/elf.o cmd/dev/ld/x86_64.o cmd/dev/ld/ld_support.o - $(CC) $(LDFLAGS) -shared -o $@ cmd/dev/ld/elf.o cmd/dev/ld/x86_64.o cmd/dev/ld/ld_support.o + $(CC) -Icmd/dev/xcutil -Icmd/dev/ld $(CPPFLAGS) $(CFLAGS) -o $@ -c $< -cmd/dev/ld/ld: $(LD_OBJ) shared/libaruuelf.so $(LIB) - $(CC) $(LDFLAGS) -o $@ $(LD_OBJ) -Lshared -laruuelf $(LIB) $(LDLIBS) -Wl,-rpath,'$$ORIGIN/../../../shared' +cmd/dev/ld/ld: $(LD_OBJ) $(LIB) + $(CC) $(LDFLAGS) -o $@ $(LD_OBJ) $(LIB) $(LDLIBS) AS_OBJ =\ + cmd/dev/xcutil/util.o\ + cmd/dev/xcutil/table.o\ + cmd/dev/xcutil/elfutil.o\ + cmd/dev/xcutil/archive.o\ cmd/dev/as/as.o\ - cmd/dev/as/asm_lex.o\ - cmd/dev/as/asm_parse.o\ - cmd/dev/as/asm_x86_64.o\ - cmd/dev/as/asm_elf.o - -cmd/dev/as/%.o: cmd/dev/as/%.c - $(CC) $(CPPFLAGS) -Icmd/dev/as -Ishared $(CFLAGS) -o $@ -c $< + cmd/dev/as/as_util.o\ + cmd/dev/as/emit_elf.o\ + cmd/dev/as/emit_macho.o\ + cmd/dev/as/ir_asm.o\ + cmd/dev/as/parse_asm.o\ + cmd/dev/as/arch/x64/asm_code.o\ + cmd/dev/as/arch/x64/ir_asm_x64.o\ + cmd/dev/as/arch/x64/parse_x64.o + +# headers shared across the assembler sources. listing them as prerequisites +# of every .o stops stale objects when a header changes (inst.h, parse_asm.h), +# which otherwise produced silently-wrong builds +AS_HDRS =\ + cmd/dev/as/parse_asm.h\ + cmd/dev/as/ir_asm.h\ + cmd/dev/as/as_util.h\ + cmd/dev/as/asm_code.h\ + cmd/dev/as/arch/x64/inst.h + +cmd/dev/as/%.o: cmd/dev/as/%.c $(AS_HDRS) cmd/dev/config.h + $(CC) -Icmd/dev/xcutil -Icmd/dev/as $(CPPFLAGS) $(CFLAGS) -o $@ -c $< + +cmd/dev/as/arch/x64/%.o: cmd/dev/as/arch/x64/%.c $(AS_HDRS) cmd/dev/config.h + $(CC) -Icmd/dev/xcutil -Icmd/dev/as -Icmd/dev/as/arch/x64 $(CPPFLAGS) $(CFLAGS) -o $@ -c $< cmd/dev/as/as: $(AS_OBJ) $(LIB) $(CC) $(LDFLAGS) -o $@ $(AS_OBJ) $(LIB) $(LDLIBS) -cmd/dev/cc/driver.o: cmd/dev/cc/driver.c +cmd/dev/cc/driver.o: cmd/dev/cc/driver.c cmd/dev/cc/config.h $(CC) -Icmd/dev/cc $(CPPFLAGS) $(CFLAGS) -o $@ -c $< -cmd/dev/cc/cc: cmd/dev/cc/driver.o cmd/dev/cc/util.o $(LIB) cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as +cmd/dev/cc/cc: cmd/dev/cc/driver.o cmd/dev/cc/util.o $(LIB) cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld $(CC) $(LDFLAGS) -o $@ cmd/dev/cc/driver.o cmd/dev/cc/util.o $(LIB) $(LDLIBS) CC1_OBJ =\ @@ -899,6 +941,7 @@ cmd/dev/cc/cc1: $(CC1_OBJ) $(LIB) cmd/dev/cc/cpp: cmd/dev/cc/cpp.o $(CPP_OBJ) $(LIB) $(CC) $(LDFLAGS) -o $@ cmd/dev/cc/cpp.o $(CPP_OBJ) $(LIB) $(LDLIBS) +cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h: cmd/dev/configure + sh cmd/dev/configure - - +$(AS_OBJ) $(LD_OBJ) $(CC1_OBJ) $(CPP_OBJ) cmd/dev/ar/ar.o cmd/dev/cc/cpp.o: cmd/dev/config.h diff --git a/Makefile.sh b/Makefile.sh @@ -48,28 +48,28 @@ CPPFLAGS="-Ishared -DPREFIX=\"$PREFIX\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBS if [ "$FEATURE_USE_BEARSSL" = "1" ]; then if pkg-config --exists libbearssl 2>/dev/null; then CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libbearssl)" - LDLIBS="$LDLIBS $(pkg-config --libs libbearssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libbearssl)" elif pkg-config --exists bearssl 2>/dev/null; then CPPFLAGS="$CPPFLAGS $(pkg-config --cflags bearssl)" - LDLIBS="$LDLIBS $(pkg-config --libs bearssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs bearssl)" else - LDLIBS="$LDLIBS -lbearssl" + TLS_LDLIBS="$TLS_LDLIBS -LexternalRepos/BearSSL/build -lbearssl" fi fi if [ "$FEATURE_USE_LIBRESSL" = "1" ]; then if pkg-config --exists libtls 2>/dev/null; then CPPFLAGS="$CPPFLAGS $(pkg-config --cflags libtls)" - LDLIBS="$LDLIBS $(pkg-config --libs libtls)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs libtls)" else - LDLIBS="$LDLIBS -ltls" + TLS_LDLIBS="$TLS_LDLIBS -ltls" fi fi if [ "$FEATURE_USE_OPENSSL" = "1" ]; then if pkg-config --exists openssl 2>/dev/null; then CPPFLAGS="$CPPFLAGS $(pkg-config --cflags openssl)" - LDLIBS="$LDLIBS $(pkg-config --libs openssl)" + TLS_LDLIBS="$TLS_LDLIBS $(pkg-config --libs openssl)" else - LDLIBS="$LDLIBS -lssl -lcrypto" + TLS_LDLIBS="$TLS_LDLIBS -lssl -lcrypto" fi fi unset _feature_flags @@ -170,7 +170,7 @@ compile_c() { local src="$1" obj="$2"; shift 2 # shellcheck disable=SC2086 any_newer_than "$obj" "$src" $HDR $EXTRA_HDR || return 0 - enqueue " CC $obj" "$CC $CPPFLAGS $* $CFLAGS -o $obj -c $src" + enqueue " CC $obj" "$CC $* $CPPFLAGS $CFLAGS -o $obj -c $src" } link_bin() { @@ -186,7 +186,11 @@ link_bin() { any_newer_than "$bin" $objs || return 0 printf ' LD %s\n' "$bin" # shellcheck disable=SC2086 - eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS" + if [ "${bin##*/}" = "wget" ]; then + eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS $TLS_LDLIBS" + else + eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS" + fi } # writes to _objs rather than stdout so the caller avoids a subshell that @@ -255,7 +259,7 @@ cfg_enabled() { return 1 fi case "$_var" in - *_[^_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;; + *_[!_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;; *) break ;; esac done @@ -391,34 +395,28 @@ build_ar() { build_as() { cfg_enabled BUILD_DEV_AS || return 0 - local dir=cmd/dev/as - objs_for "$dir" "" "-I$dir -Ishared" - link_bin "$dir/as" $_objs -- $LIB + local dir="cmd/dev/as" + local flags="-Icmd/dev/xcutil -I$dir -Ishared" + local objs="" + objs_for "cmd/dev/xcutil" "" "$flags" + objs="$objs $_objs" + objs_for "$dir" "" "$flags" + objs="$objs $_objs" + objs_for "$dir/arch/x64" "" "-Icmd/dev/xcutil -I$dir -I$dir/arch/x64 -Ishared" + objs="$objs $_objs" + link_bin "$dir/as" $objs -- $LIB } -# rpath embeds $ORIGIN so the installed ld finds libaruuelf.so next to itself build_ld() { cfg_enabled BUILD_DEV_LD || return 0 local dir="cmd/dev/ld" - local cflags="-DLD_TARGET_X86_64 -I$dir -fPIC" - local src - - for src in "$dir"/*.c; do - compile_c "$src" "${src%.c}.o" $cflags - done - drain - - any_newer_than shared/libaruuelf.so "$dir/elf.o" "$dir/x86_64.o" "$dir/ld_support.o" && { - printf ' LD shared/libaruuelf.so\n' - eval "$CC $LDFLAGS -shared -o shared/libaruuelf.so $dir/elf.o $dir/x86_64.o $dir/ld_support.o" - } - - any_newer_than "$dir/ld" "$dir/ld.o" shared/libaruuelf.so && { - printf ' LD %s/ld\n' "$dir" - # $ORIGIN is a dynamic-linker token, not a shell variable - eval "$CC $LDFLAGS -o $dir/ld $dir/ld.o -Lshared -laruuelf $LIB $LDLIBS -Wl,-rpath,'\$ORIGIN/../../../shared'" - } - return 0 + local flags="-Icmd/dev/xcutil -I$dir" + local objs="" + objs_for "cmd/dev/xcutil" "" "$flags" + objs="$objs $_objs" + objs_for "$dir" "" "$flags" + objs="$objs $_objs" + link_bin "$dir/ld" $objs -- $LIB } build_cc() { @@ -443,6 +441,9 @@ build_cc() { } build_dev() { + if [ ! -f cmd/dev/config.h ]; then + sh cmd/dev/configure + fi build_ar build_as build_ld @@ -459,21 +460,31 @@ man_section() { } build_man_for() { - local var="$1" src="$2" base sec out + local var="$1" src="$2" base sec out_mdoc out_txt cfg_enabled "$var" || return 0 [ -x scripts/mkman/mkman ] || { printf 'error: mkman not built\n' >&2; exit 1; } + + grep -qE '!man|\?man' "$src" || return 0 + base=${src##*/}; base=${base%.c} sec=$(man_section "$src") - out="man/man${sec}/${base}.${sec}" + mkdir -p "man/man${sec}" - any_newer_than "$out" "$src" build.cfg scripts/mkman/mkman || return 0 - printf ' MAN %s\n' "$out" - scripts/mkman/mkman -config build.cfg -section "$sec" "$src" > "$out" + out_mdoc="man/man${sec}/${base}.${sec}" + out_txt="man/man${sec}/${base}.${sec}.txt" + if any_newer_than "$out_mdoc" "$src" config.mk scripts/mkman/mkman; then + printf ' MAN %s\n' "$out_mdoc" + scripts/mkman/mkman -fmt mdoc -config config.mk -section "$sec" "$src" > "$out_mdoc" + fi + if any_newer_than "$out_txt" "$src" config.mk scripts/mkman/mkman; then + printf ' MAN %s\n' "$out_txt" + scripts/mkman/mkman -fmt txt -config config.mk -section "$sec" "$src" > "$out_txt" + fi } build_man() { local dir cat src base - if [ ! -x scripts/mkman/mkman ] || any_newer_than scripts/mkman/mkman scripts/mkman/main.go scripts/mkman/troff.go; then + if [ ! -x scripts/mkman/mkman ] || any_newer_than scripts/mkman/mkman scripts/mkman/main.go scripts/mkman/page.go scripts/mkman/parse.go scripts/mkman/mdoc.go; then printf ' GO scripts/mkman/mkman\n' (cd scripts/mkman && go build -o mkman .) fi diff --git a/build.cfg b/build.cfg @@ -1,8 +1,8 @@ -# posix: POSIX 2024 only common: uncontroversial extras all: everything except external libs +# posix: POSIX 2024 PRESET_FEATURES=all # subset of: posix linux net xsi pseudo dev -PRESET_UTILS="posix linux net xsi pseudo dev" +PRESET_UTILS="posix linux net xsi pseudo" # installation paths VERSION=2026-06-08T05-53-UTC-03 @@ -137,18 +137,20 @@ unset _p # BUILD_POSIX_SH=0 # disable a tool when its group is active # BUILD_DEV_AS=1 # enable a tool whose group isnt in PRESET_UTILS FEATURE_SH_HISTEDIT=1 -# tls backend: set all three to 0 to disable tls, or set exactly one to 1 to -# override auto-detection; auto-detection tries bearssl first, then libtls, -# then openssl +# tls backend: set exactly one to 1 to enable tls FEATURE_USE_BEARSSL=0 FEATURE_USE_LIBRESSL=0 FEATURE_USE_OPENSSL=0 -if [ "$FEATURE_USE_BEARSSL" = 0 ] && [ "$FEATURE_USE_LIBRESSL" = 0 ] && [ "$FEATURE_USE_OPENSSL" = 0 ]; then - if pkg-config --exists libbearssl 2>/dev/null || pkg-config --exists bearssl 2>/dev/null; then - FEATURE_USE_BEARSSL=1 - elif pkg-config --exists libtls 2>/dev/null; then - FEATURE_USE_LIBRESSL=1 - elif pkg-config --exists openssl 2>/dev/null; then - FEATURE_USE_OPENSSL=1 +FEATURE_USE_SSL=1 + +if [ "$FEATURE_USE_SSL" = 1 ]; then + if [ "$FEATURE_USE_BEARSSL" = 0 ] && [ "$FEATURE_USE_LIBRESSL" = 0 ] && [ "$FEATURE_USE_OPENSSL" = 0 ]; then + if pkg-config --exists libbearssl 2>/dev/null || pkg-config --exists bearssl 2>/dev/null; then + FEATURE_USE_BEARSSL=1 + elif pkg-config --exists libtls 2>/dev/null; then + FEATURE_USE_LIBRESSL=1 + elif pkg-config --exists openssl 2>/dev/null; then + FEATURE_USE_OPENSSL=1 + fi fi fi diff --git a/cmd/extra/blkid.c b/cmd/extra/blkid.c @@ -0,0 +1,346 @@ +/* See LICENSE file for copyright and license details. */ +#include "util.h" +#include "diskutil.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <fcntl.h> + +struct FsType { + const char *name; + size_t magic_offset; + size_t magic_len; + uint64_t magic1; + uint64_t magic2; + size_t uuid_offset; + size_t uuid_len; + size_t label_offset; + size_t label_len; +}; + +static const struct FsType fstypes[] = { + /* ext2/3/4 */ + { "ext", 1080, 2, 0xEF53, 0x53EF, 1128, 16, 1144, 16 }, + /* vfat / fat32 */ + { "vfat", 82, 5, 0x3233544146ULL, 0, 67, 4, 71, 11 }, + /* vfat / fat12/16 */ + { "vfat", 54, 4, 0x31544146, 0, 39, 4, 43, 11 }, + /* ntfs */ + { "ntfs", 3, 4, 0x5346544e, 0, 72, 8, 0, 0 }, + /* xfs */ + { "xfs", 0, 4, 0x42534658, 0x58465342, 32, 16, 108, 12 }, + /* btrfs */ + { "btrfs", 65600, 8, 0x4D5F53665248425FULL, 0, 65803, 16, 65819, 256 }, + /* f2fs */ + { "f2fs", 1024, 4, 0xF2F52010, 0x1020F5F2, 1132, 16, 1148, 512 }, + /* ufs1 */ + { "ufs1", 9564, 4, 0x011954, 0x54190100, 0, 0, 0, 0 }, + /* ufs2 */ + { "ufs2", 66908, 4, 0x19540119, 0x19015419, 67056, 16, 67072, 32 }, + /* fossil */ + { "fossil", 131200, 4, 0x2340A3B1, 0xB1A34023, 0, 0, 131072, 127 }, + /* cwfs */ + { "cwfs", 0, 4, 0xc1a551f5, 0xf551a5c1, 0, 0, 0, 0 }, +}; + +static char *oflag = "full"; +static char *sflag = NULL; +static int Uflag = 0; +static int Lflag = 0; + +static void +usage(void) +{ + eprintf("usage: %s [-o format] [-s tag] [-U] [-L] [device ...]\n", argv0); +} + +static void +format_uuid(const unsigned char *buf, size_t len, const char *type, char *out, size_t out_len) +{ + size_t i; + char *p = out; + + if (strcmp(type, "vfat") == 0) { + snprintf(out, out_len, "%02X%02X-%02X%02X", buf[3], buf[2], buf[1], buf[0]); + return; + } + + if (strcmp(type, "ntfs") == 0) { + for (i = 8; i > 0; i--) { + snprintf(p, out_len - (p - out), "%02X", buf[i - 1]); + p += 2; + } + return; + } + + for (i = 0; i < len; i++) { + if (i == 4 || i == 6 || i == 8 || i == 10) { + *p++ = '-'; + } + snprintf(p, out_len - (p - out), "%02x", buf[i]); + p += 2; + } + *p = '\0'; +} + +static void +print_tag(const char *devname, const char *tag, const char *value) +{ + if (sflag && strcasecmp(sflag, tag) != 0) + return; + + if (strcmp(oflag, "value") == 0) { + printf("%s\n", value); + } else if (strcmp(oflag, "export") == 0) { + printf("%s=%s\n", tag, value); + } else { + printf(" %s=\"%s\"", tag, value); + } +} + +static int +detect_zfs(const unsigned char *buf, size_t len) +{ + size_t offset; + uint64_t magic; + + for (offset = 131072; offset + 8 <= len; offset += 1024) { + magic = ((uint64_t)buf[offset + 7] << 56) | + ((uint64_t)buf[offset + 6] << 48) | + ((uint64_t)buf[offset + 5] << 40) | + ((uint64_t)buf[offset + 4] << 32) | + ((uint64_t)buf[offset + 3] << 24) | + ((uint64_t)buf[offset + 2] << 16) | + ((uint64_t)buf[offset + 1] << 8) | + (uint64_t)buf[offset]; + + if (magic == 0x00bab10caULL || magic == 0x0cb1ba0000000000ULL || + magic == 0x00bab10cULL || magic == 0x0cb1ba00ULL) + return 1; + } + return 0; +} + +static int +detect_plan9_other(const unsigned char *buf, size_t len, const char **name) +{ + if (len >= 4) { + uint32_t magic = ((uint32_t)buf[3] << 24) | ((uint32_t)buf[2] << 16) | ((uint32_t)buf[1] << 8) | (uint32_t)buf[0]; + if (magic == 0x686a6673 || magic == 0x73666a68) { + *name = "hjfs"; + return 1; + } + if (magic == 0x67656673 || magic == 0x73666567) { + *name = "gefs"; + return 1; + } + } + if (len >= 516) { + uint32_t magic = ((uint32_t)buf[515] << 24) | ((uint32_t)buf[514] << 16) | ((uint32_t)buf[513] << 8) | (uint32_t)buf[512]; + if (magic == 0x686a6673 || magic == 0x73666a68) { + *name = "hjfs"; + return 1; + } + if (magic == 0x67656673 || magic == 0x73666567) { + *name = "gefs"; + return 1; + } + } + return 0; +} + +static int +do_blkid(const char *path) +{ + struct BlockDev dev; + unsigned char *buf; + size_t read_size = 262144; /* 256kb */ + size_t i, j; + int found = 0; + + if (blockdev_open(&dev, path, 0) < 0) + return -1; + + if (dev.size < read_size) + read_size = dev.size; + + buf = emalloc(read_size); + /* read sectors */ + size_t sectors_to_read = (read_size + dev.sec_size - 1) / dev.sec_size; + if (blockdev_read(&dev, 0, buf, sectors_to_read) < 0) { + free(buf); + blockdev_close(&dev); + return -1; + } + + for (i = 0; i < LEN(fstypes); i++) { + const struct FsType *fs = &fstypes[i]; + if (fs->magic_offset + fs->magic_len > read_size) + continue; + + uint64_t val = 0; + for (j = 0; j < fs->magic_len; j++) { + val |= ((uint64_t)buf[fs->magic_offset + j]) << (8 * j); + } + + if (val == fs->magic1 || (fs->magic2 && val == fs->magic2)) { + const char *type_name = fs->name; + if (strcmp(fs->name, "ext") == 0) { + if (buf[1116] & 4) + type_name = "ext3"; + else if (buf[1120] & 64) + type_name = "ext4"; + else + type_name = "ext2"; + } + + if (Uflag || Lflag) { + char label[256] = {0}; + char uuid[256] = {0}; + if (fs->label_len && fs->label_offset + fs->label_len <= read_size) { + snprintf(label, sizeof(label), "%.*s", (int)fs->label_len, buf + fs->label_offset); + } + if (fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) { + format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, sizeof(uuid)); + } + if (Uflag) { + printf("%s\n", uuid); + } else { + printf("%s\n", label); + } + found = 1; + break; + } + + if (strcmp(oflag, "export") == 0) { + printf("DEVNAME=%s\n", path); + } else if (strcmp(oflag, "value") != 0) { + printf("%s:", path); + } + + if (fs->label_len && fs->label_offset + fs->label_len <= read_size) { + char label[256]; + snprintf(label, sizeof(label), "%.*s", (int)fs->label_len, buf + fs->label_offset); + /* strip trailing spaces */ + char *end = label + strlen(label) - 1; + while (end >= label && *end == ' ') { + *end = '\0'; + end--; + } + if (label[0]) + print_tag(path, "LABEL", label); + } + + if (fs->uuid_len && fs->uuid_offset + fs->uuid_len <= read_size) { + char uuid[256]; + format_uuid(buf + fs->uuid_offset, fs->uuid_len, fs->name, uuid, sizeof(uuid)); + print_tag(path, "UUID", uuid); + } + + print_tag(path, "TYPE", type_name); + if (strcmp(oflag, "full") == 0) + printf("\n"); + + found = 1; + break; + } + } + + if (!found && detect_zfs(buf, read_size)) { + if (Uflag || Lflag) { + printf("\n"); + } else { + if (strcmp(oflag, "export") == 0) { + printf("DEVNAME=%s\n", path); + } else if (strcmp(oflag, "value") != 0) { + printf("%s:", path); + } + print_tag(path, "TYPE", "zfs_member"); + if (strcmp(oflag, "full") == 0) + printf("\n"); + } + found = 1; + } + + if (!found) { + const char *p9_name = NULL; + if (detect_plan9_other(buf, read_size, &p9_name)) { + if (Uflag || Lflag) { + printf("\n"); + } else { + if (strcmp(oflag, "export") == 0) { + printf("DEVNAME=%s\n", path); + } else if (strcmp(oflag, "value") != 0) { + printf("%s:", path); + } + print_tag(path, "TYPE", p9_name); + if (strcmp(oflag, "full") == 0) + printf("\n"); + } + found = 1; + } + } + + free(buf); + blockdev_close(&dev); + return found ? 0 : -2; +} + +// ?man blkid: print block device attributes +// ?man arguments: [device ...] +// ?man blkid locates and prints attributes (such as uuid, volume label, and filesystem type) +// ?man of block devices or partition images +int +main(int argc, char *argv[]) +{ + int ret = 0; + + ARGBEGIN { + // ?man -o:specify output format (full, value, export) + case 'o': + oflag = EARGF(usage()); + break; + // ?man -s:only show specified tag (e.g. UUID, LABEL, TYPE) + case 's': + sflag = EARGF(usage()); + break; + // ?man -U:print UUID only + case 'U': + Uflag = 1; + break; + // ?man -L:print volume label only + case 'L': + Lflag = 1; + break; + default: + usage(); + } ARGEND + + if (argc > 0) { + for (; *argv; argv++) { + if (do_blkid(*argv) < 0) + ret = 1; + } + } else { + struct BlockDevInfo *list = blockdev_get_list(); + struct BlockDevInfo *curr; + if (!list) { + return 1; + } + for (curr = list; curr; curr = curr->next) { + char devpath[128]; + snprintf(devpath, sizeof(devpath), "/dev/%s", curr->name); + do_blkid(devpath); + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + snprintf(devpath, sizeof(devpath), "/dev/%s", part->name); + do_blkid(devpath); + } + } + blockdev_free_list(list); + } + + return ret; +} diff --git a/cmd/extra/fdisk.c b/cmd/extra/fdisk.c @@ -0,0 +1,478 @@ +/* See LICENSE file for copyright and license details. */ +#include "util.h" +#include "diskutil.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <fcntl.h> + +struct MbrPartition { + uint8_t boot; + uint8_t start_chs[3]; + uint8_t type; + uint8_t end_chs[3]; + uint32_t start_lba; + uint32_t size; +} __attribute__((packed)); + +struct MbrHeader { + uint8_t code[446]; + struct MbrPartition parts[4]; + uint8_t sig[2]; +} __attribute__((packed)); + +struct GptHeader { + uint8_t sig[8]; + uint32_t rev; + uint32_t size; + uint32_t crc; + uint32_t reserved; + uint64_t current_lba; + uint64_t backup_lba; + uint64_t first_usable; + uint64_t last_usable; + uint8_t disk_guid[16]; + uint64_t partition_lba; + uint32_t num_parts; + uint32_t part_size; + uint32_t parts_crc; +} __attribute__((packed)); + +struct GptPartition { + uint8_t type_guid[16]; + uint8_t part_guid[16]; + uint64_t start_lba; + uint64_t end_lba; + uint64_t flags; + uint16_t name[36]; +} __attribute__((packed)); + +static uint32_t crc32_table[256]; +static int crc32_table_initialized = 0; + +static void +init_crc32_table(void) +{ + uint32_t i, j, c; + for (i = 0; i < 256; i++) { + c = i; + for (j = 0; j < 8; j++) { + if (c & 1) + c = 0xedb88320U ^ (c >> 1); + else + c = c >> 1; + } + crc32_table[i] = c; + } + crc32_table_initialized = 1; +} + +static uint32_t +crc32(uint32_t crc, const void *buf, size_t len) +{ + const uint8_t *p = buf; + if (!crc32_table_initialized) + init_crc32_table(); + while (len--) + crc = (crc >> 8) ^ crc32_table[(crc ^ *p++) & 0xFF]; + return crc; +} + +static int opt_list = 0; +static int opt_print = 0; +static int opt_init_gpt = 0; +static int opt_init_mbr = 0; +static int opt_add = 0; +static int opt_del = 0; +static int opt_part_idx = -1; +static uint64_t opt_start = 0; +static uint64_t opt_end = 0; +static const char *opt_type = NULL; + +static void +usage(void) +{ + eprintf("usage: %s [-l] [-p] [-g] [-m] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device]\n", argv0); +} + +static void +print_mbr(struct MbrHeader *mbr, const char *path) +{ + int i; + printf("Disk: %s\n", path); + printf("Partition table (MBR/dos):\n"); + printf("%-5s %-4s %-12s %-12s %-4s\n", "Index", "Boot", "Start", "Size", "Type"); + for (i = 0; i < 4; i++) { + struct MbrPartition *p = &mbr->parts[i]; + if (p->size == 0) + continue; + printf("%-5d %-4s %-12u %-12u 0x%02x\n", + i + 1, + p->boot == 0x80 ? "Yes" : "No", + p->start_lba, + p->size, + p->type); + } +} + +static void +print_gpt(struct GptHeader *hdr, struct GptPartition *parts, const char *path) +{ + uint32_t i; + char guid[37]; + printf("Disk: %s\n", path); + printf("Partition table (GPT):\n"); + printf("%-5s %-12s %-12s %-36s\n", "Index", "Start", "End", "Type GUID"); + for (i = 0; i < hdr->num_parts; i++) { + struct GptPartition *p = &parts[i]; + if (p->start_lba == 0 && p->end_lba == 0) + continue; + + snprintf(guid, sizeof(guid), + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + p->type_guid[3], p->type_guid[2], p->type_guid[1], p->type_guid[0], + p->type_guid[5], p->type_guid[4], + p->type_guid[7], p->type_guid[6], + p->type_guid[8], p->type_guid[9], + p->type_guid[10], p->type_guid[11], p->type_guid[12], p->type_guid[13], p->type_guid[14], p->type_guid[15]); + + printf("%-5d %-12llu %-12llu %-36s\n", + i + 1, + (unsigned long long)p->start_lba, + (unsigned long long)p->end_lba, + guid); + } +} + +static int +read_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts) +{ + unsigned char sector[512]; + size_t part_sectors; + + if (blockdev_read(dev, 1, sector, 1) < 0) + return -1; + + memcpy(hdr, sector, sizeof(*hdr)); + + if (memcmp(hdr->sig, "EFI PART", 8) != 0) + return -1; + + part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size; + if (blockdev_read(dev, hdr->partition_lba, parts, part_sectors) < 0) + return -1; + + return 0; +} + +static int +write_gpt(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts) +{ + unsigned char sector[512]; + size_t part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size; + + /* update partition entries crc */ + hdr->parts_crc = crc32(~0U, parts, hdr->num_parts * hdr->part_size) ^ ~0U; + + /* calculate header crc (zeroing the crc field first) */ + hdr->crc = 0; + hdr->crc = crc32(~0U, hdr, hdr->size) ^ ~0U; + + /* write protective mbr to sector 0 */ + struct MbrHeader pmbr; + memset(&pmbr, 0, sizeof(pmbr)); + pmbr.parts[0].type = 0xEE; + pmbr.parts[0].start_lba = 1; + uint64_t limit = dev->size / dev->sec_size - 1; + pmbr.parts[0].size = limit > 0xFFFFFFFFU ? 0xFFFFFFFFU : (uint32_t)limit; + pmbr.sig[0] = 0x55; + pmbr.sig[1] = 0xAA; + if (blockdev_write(dev, 0, &pmbr, 1) < 0) + return -1; + + /* write primary header and partition entries */ + memset(sector, 0, sizeof(sector)); + memcpy(sector, hdr, sizeof(*hdr)); + if (blockdev_write(dev, 1, sector, 1) < 0) + return -1; + if (blockdev_write(dev, hdr->partition_lba, parts, part_sectors) < 0) + return -1; + + /* write backup partition entries and backup header */ + struct GptHeader backup_hdr = *hdr; + backup_hdr.current_lba = hdr->backup_lba; + backup_hdr.backup_lba = hdr->current_lba; + backup_hdr.partition_lba = backup_hdr.current_lba - part_sectors; + + backup_hdr.crc = 0; + backup_hdr.crc = crc32(~0U, &backup_hdr, backup_hdr.size) ^ ~0U; + + if (blockdev_write(dev, backup_hdr.partition_lba, parts, part_sectors) < 0) + return -1; + + memset(sector, 0, sizeof(sector)); + memcpy(sector, &backup_hdr, sizeof(backup_hdr)); + if (blockdev_write(dev, backup_hdr.current_lba, sector, 1) < 0) + return -1; + + return 0; +} + +static int +do_print(const char *path) +{ + struct BlockDev dev; + struct MbrHeader mbr; + struct GptHeader gpt_hdr; + struct GptPartition gpt_parts[128]; + + if (blockdev_open(&dev, path, 0) < 0) { + weprintf("cannot open %s:", path); + return -1; + } + + if (read_gpt(&dev, &gpt_hdr, gpt_parts) == 0) { + print_gpt(&gpt_hdr, gpt_parts, path); + } else { + if (blockdev_read(&dev, 0, &mbr, 1) == 0 && mbr.sig[0] == 0x55 && mbr.sig[1] == 0xAA) { + print_mbr(&mbr, path); + } else { + printf("Disk %s: unpartitioned or unknown format\n", path); + } + } + + blockdev_close(&dev); + return 0; +} + +static int +do_fdisk(const char *path) +{ + struct BlockDev dev; + struct MbrHeader mbr; + struct GptHeader gpt_hdr; + struct GptPartition gpt_parts[128]; + int has_gpt = 0; + + if (blockdev_open(&dev, path, 1) < 0) { + weprintf("cannot open %s:", path); + return -1; + } + + has_gpt = (read_gpt(&dev, &gpt_hdr, gpt_parts) == 0); + + if (opt_init_mbr) { + memset(&mbr, 0, sizeof(mbr)); + mbr.sig[0] = 0x55; + mbr.sig[1] = 0xAA; + if (blockdev_write(&dev, 0, &mbr, 1) < 0) { + weprintf("cannot write MBR to %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Initialized MBR partition table on %s\n", path); + blockdev_close(&dev); + return 0; + } + + if (opt_init_gpt) { + memset(&gpt_hdr, 0, sizeof(gpt_hdr)); + memcpy(gpt_hdr.sig, "EFI PART", 8); + gpt_hdr.rev = 0x00010000; + gpt_hdr.size = 92; + gpt_hdr.current_lba = 1; + gpt_hdr.backup_lba = dev.size / dev.sec_size - 1; + gpt_hdr.first_usable = 34; + gpt_hdr.last_usable = gpt_hdr.backup_lba - 34; + gpt_hdr.partition_lba = 2; + gpt_hdr.num_parts = 128; + gpt_hdr.part_size = 128; + memset(gpt_parts, 0, sizeof(gpt_parts)); + + if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) { + weprintf("cannot write GPT to %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Initialized GPT partition table on %s\n", path); + blockdev_close(&dev); + return 0; + } + + if (opt_add) { + if (opt_part_idx < 1) { + weprintf("add requires partition index (-n)\n"); + blockdev_close(&dev); + return -1; + } + + if (has_gpt) { + if (opt_part_idx > 128) { + weprintf("GPT partition index must be 1-128\n"); + blockdev_close(&dev); + return -1; + } + struct GptPartition *p = &gpt_parts[opt_part_idx - 1]; + p->start_lba = opt_start; + p->end_lba = opt_end; + /* default type guid: linux filesystem data */ + p->type_guid[0] = 0xAF; p->type_guid[1] = 0x3D; p->type_guid[2] = 0xC6; p->type_guid[3] = 0x0F; + p->type_guid[4] = 0x83; p->type_guid[5] = 0x84; + p->type_guid[6] = 0x72; p->type_guid[7] = 0x47; + p->type_guid[8] = 0x8E; p->type_guid[9] = 0x79; + p->type_guid[10] = 0x3D; p->type_guid[11] = 0x69; p->type_guid[12] = 0xD8; p->type_guid[13] = 0x47; p->type_guid[14] = 0x7D; p->type_guid[15] = 0xE4; + + if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) { + weprintf("cannot update GPT on %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Added GPT partition %d to %s\n", opt_part_idx, path); + } else { + if (blockdev_read(&dev, 0, &mbr, 1) < 0) { + weprintf("cannot read MBR from %s:", path); + blockdev_close(&dev); + return -1; + } + if (opt_part_idx > 4) { + weprintf("MBR partition index must be 1-4\n"); + blockdev_close(&dev); + return -1; + } + struct MbrPartition *p = &mbr.parts[opt_part_idx - 1]; + p->start_lba = (uint32_t)opt_start; + p->size = (uint32_t)(opt_end - opt_start + 1); + p->type = opt_type ? (uint8_t)strtoul(opt_type, NULL, 0) : 0x83; + mbr.sig[0] = 0x55; + mbr.sig[1] = 0xAA; + + if (blockdev_write(&dev, 0, &mbr, 1) < 0) { + weprintf("cannot update MBR on %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Added MBR partition %d to %s\n", opt_part_idx, path); + } + } + + if (opt_del) { + if (opt_part_idx < 1) { + weprintf("delete requires partition index (-n)\n"); + blockdev_close(&dev); + return -1; + } + + if (has_gpt) { + if (opt_part_idx > 128) { + weprintf("GPT partition index must be 1-128\n"); + blockdev_close(&dev); + return -1; + } + memset(&gpt_parts[opt_part_idx - 1], 0, sizeof(struct GptPartition)); + if (write_gpt(&dev, &gpt_hdr, gpt_parts) < 0) { + weprintf("cannot update GPT on %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Deleted GPT partition %d from %s\n", opt_part_idx, path); + } else { + if (blockdev_read(&dev, 0, &mbr, 1) < 0) { + weprintf("cannot read MBR from %s:", path); + blockdev_close(&dev); + return -1; + } + if (opt_part_idx > 4) { + weprintf("MBR partition index must be 1-4\n"); + blockdev_close(&dev); + return -1; + } + memset(&mbr.parts[opt_part_idx - 1], 0, sizeof(struct MbrPartition)); + if (blockdev_write(&dev, 0, &mbr, 1) < 0) { + weprintf("cannot update MBR on %s:", path); + blockdev_close(&dev); + return -1; + } + printf("Deleted MBR partition %d from %s\n", opt_part_idx, path); + } + } + + blockdev_close(&dev); + return 0; +} + +// ?man fdisk: partition table manipulator +// ?man arguments: [-l] [-p] [-g] [-m] [-a] [-d] [-n index] [-b start] [-e end] [-t type] [device] +// ?man fdisk performs partition table operations for MBR and GPT disks +int +main(int argc, char *argv[]) +{ + ARGBEGIN { + // ?man -l:list partitions of all devices + case 'l': + opt_list = 1; + break; + // ?man -p:print partition table of specified device + case 'p': + opt_print = 1; + break; + // ?man -g:initialize disk with GPT + case 'g': + opt_init_gpt = 1; + break; + // ?man -m:initialize disk with MBR + case 'm': + opt_init_mbr = 1; + break; + // ?man -a:add partition + case 'a': + opt_add = 1; + break; + // ?man -d:delete partition + case 'd': + opt_del = 1; + break; + // ?man -n:partition index + case 'n': + opt_part_idx = (int)estrtol(EARGF(usage()), 10); + break; + // ?man -b:starting sector LBA + case 'b': + opt_start = (uint64_t)estrtoul(EARGF(usage()), 10); + break; + // ?man -e:ending sector LBA + case 'e': + opt_end = (uint64_t)estrtoul(EARGF(usage()), 10); + break; + // ?man -t:partition type (MBR hex or GPT string) + case 't': + opt_type = EARGF(usage()); + break; + default: + usage(); + } ARGEND + + if (opt_list) { + struct BlockDevInfo *list = blockdev_get_list(); + struct BlockDevInfo *curr; + if (!list) + return 1; + for (curr = list; curr; curr = curr->next) { + char devpath[128]; + snprintf(devpath, sizeof(devpath), "/dev/%s", curr->name); + do_print(devpath); + } + blockdev_free_list(list); + return 0; + } + + if (argc != 1) + usage(); + + if (opt_print) { + return do_print(argv[0]) < 0 ? 1 : 0; + } + + return do_fdisk(argv[0]) < 0 ? 1 : 0; +} diff --git a/cmd/extra/lsblk.c b/cmd/extra/lsblk.c @@ -0,0 +1,104 @@ +/* See LICENSE file for copyright and license details. */ +#include "util.h" +#include "diskutil.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static void +usage(void) +{ + eprintf("usage: %s\n", argv0); +} + +static void +print_line(int name_pad, const char *name, int major, int minor, const char *size, const char *type, const char *fstype, const char *mountpoint) +{ + char linebuf[512]; + int len; + + len = snprintf(linebuf, sizeof(linebuf), "%-*s %3d:%-3d %6s %-4s %-8s %s", + name_pad, name, + major, minor, + size, + type, + fstype, + mountpoint); + + /* trim trailing spaces */ + while (len > 0 && linebuf[len - 1] == ' ') { + linebuf[len - 1] = '\0'; + len--; + } + printf("%s\n", linebuf); +} + +// ?man lsblk: list block devices +// ?man lsblk lists information about all available block devices in a tree-like layout +int +main(int argc, char *argv[]) +{ + struct BlockDevInfo *list, *curr, *part; + char namebuf[64]; + char hdrbuf[512]; + int max_len = 4; + int hdrlen; + + ARGBEGIN { + default: + usage(); + } ARGEND + + if (argc > 0) + usage(); + + list = blockdev_get_list(); + if (!list) + return 1; + + /* calculate maximum display width of the name column */ + for (curr = list; curr; curr = curr->next) { + int len = strlen(curr->name); + if (len > max_len) + max_len = len; + for (part = curr->parts; part; part = part->next) { + len = 2 + (int)strlen(part->name); + if (len > max_len) + max_len = len; + } + } + + hdrlen = snprintf(hdrbuf, sizeof(hdrbuf), "%-*s %-7s %6s %-4s %-8s %s", + max_len, "NAME", "MAJ:MIN", "SIZE", "TYPE", "FSTYPE", "MOUNTPOINT"); + while (hdrlen > 0 && hdrbuf[hdrlen - 1] == ' ') { + hdrbuf[hdrlen - 1] = '\0'; + hdrlen--; + } + printf("%s\n", hdrbuf); + + for (curr = list; curr; curr = curr->next) { + print_line(max_len, + curr->name, + curr->major, curr->minor, + humansize(curr->size), + curr->type, + curr->fstype[0] ? curr->fstype : "", + curr->mountpoint[0] ? curr->mountpoint : ""); + + for (part = curr->parts; part; part = part->next) { + int is_last = (part->next == NULL); + snprintf(namebuf, sizeof(namebuf), "%s%s", is_last ? "└─" : "├─", part->name); + print_line(max_len + 4, + namebuf, + part->major, part->minor, + humansize(part->size), + part->type, + part->fstype[0] ? part->fstype : "", + part->mountpoint[0] ? part->mountpoint : ""); + } + } + + blockdev_free_list(list); + return 0; +} diff --git a/cmd/linux/ctrlaltdel.c b/cmd/linux/ctrlaltdel.c @@ -15,23 +15,20 @@ usage(void) eprintf("usage: %s -h | -s\n", argv0); } -// ?man ctrlaltdel: toggle Ctrl-Alt-Del behaviour -// ?man synopsis: -h -// ?man synopsis: -s -// ?man ctrlaltdel toggles the function of Ctrl-Alt-Del based on the two choices given in linux/kernel/sys.c. -// ?man Hard reset reboots the computer immediately without calling sync. -// ?man Soft reset sends SIGINT to init. +// ?man ctrlaltdel: set ctrl-alt-del function +// ?man arguments: -h | -s +// ?man set the behavior of the ctrl-alt-del key combination int main(int argc, char *argv[]) { int hflag = 0, sflag = 0, cmd; ARGBEGIN { - // ?man -h: Set to hard reset. + // ?man -h: suppress headers or print help case 'h': hflag = 1; break; - // ?man -s: Set to soft reset. + // ?man -s: silent mode or print summary case 's': sflag = 1; break; diff --git a/cmd/linux/depmod.c b/cmd/linux/depmod.c @@ -263,6 +263,8 @@ usage(void) // ?man depmod: generate modules.dep and map files // ?man arguments: version // ?man depmod generates modules.dep containing dependency information for modprobe +// ?man // ?man -n: dry run print results to stdout instead of writing files +// ?man // ?man -b basedir: use basedir as prefix for module directories int main(int argc, char *argv[]) { @@ -279,11 +281,11 @@ main(int argc, char *argv[]) FILE *f_dep, *f_alias, *f_sym; ARGBEGIN { - // ?man -n: Dry run; print results to stdout instead of writing files. + // ?man -n: specify n option case 'n': nflag = 1; break; - // ?man -b:dir: Use dir as the prefix for module directories. + // ?man -b:dir: specify b option case 'b': basedir = EARGF(usage()); break; diff --git a/cmd/linux/eject.c b/cmd/linux/eject.c @@ -48,15 +48,14 @@ usage(void) eprintf("usage: %s [-t] [device ...]\n", argv0); } -// ?man eject: control device trays +// ?man eject: eject removable media // ?man arguments: device ... -// ?man eject opens the tray of each device. -// ?man If no device is given eject opens the tray of /dev/sr0. +// ?man eject optical discs or other removable storage media int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -t: Close instead of open the tray. + // ?man -t: sort or specify timestamp case 't': tflag = 1; break; diff --git a/cmd/linux/fsfreeze.c b/cmd/linux/fsfreeze.c @@ -22,11 +22,8 @@ usage(void) } // ?man fsfreeze: suspend access to a filesystem -// ?man arguments: mountpoint -// ?man fsfreeze suspends and resumes access to a filesystem. -// ?man fsfreeze is intended to be used with hardware RAID devices that support the creation of snapshots. -// ?man The mountpoint argument is the pathname of the directory where the filesystem is mounted. -// ?man The filesystem must be mounted to be frozen. +// ?man arguments: (-f | -u) mountpoint +// ?man freeze or unfreeze a filesystem to allow safe backups int main(int argc, char *argv[]) { @@ -36,11 +33,11 @@ main(int argc, char *argv[]) int fd; ARGBEGIN { - // ?man -f: Freeze the filesystem mounted at mountpoint. + // ?man -f: force the operation case 'f': fflag = 1; break; - // ?man -u: Unfreeze the filesystem mounted at mountpoint. + // ?man -u: unbuffered output case 'u': uflag = 1; break; diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c @@ -116,11 +116,7 @@ usage(void) // ?man hwclock: query or set the hardware clock // ?man arguments: dev -// ?man hwclock is a tool for accessing the hardware clock. -// ?man You can display the current time, set the hardware clock from the System Time, or set the System Time from the hardware clock. -// ?man It currently only works with UTC. -// ?man You can use dev to specify the RTC device node absolute path. -// ?man By default it will use /dev/rtc. +// ?man view or adjust the hardware real time clock int main(int argc, char *argv[]) { @@ -130,19 +126,19 @@ main(int argc, char *argv[]) int wflag = 0; ARGBEGIN { - // ?man -r: Read the hardware clock and print the time on stdout. + // ?man -r: operate recursively case 'r': rflag = 1; break; - // ?man -s: Set the system time from the hardware clock. + // ?man -s: silent mode or print summary case 's': sflag = 1; break; - // ?man -w: Set the hardware clock to the system time. + // ?man -w: wait for completion case 'w': wflag = 1; break; - // ?man -u: Use UTC. This is the default option. + // ?man -u: unbuffered output case 'u': break; default: @@ -169,4 +165,4 @@ main(int argc, char *argv[]) systohc(dev); return 0; -} +} +\ No newline at end of file diff --git a/cmd/linux/insmod.c b/cmd/linux/insmod.c @@ -17,8 +17,8 @@ usage(void) } // ?man insmod: insert a module into the Linux kernel -// ?man arguments: filename [args ...] -// ?man insmod inserts the module specified by filename into the kernel. It does not handle module dependencies. +// ?man arguments: filename [args... +// ?man insmod inserts a kernel module from filename into the running kernel int main(int argc, char *argv[]) { diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -535,7 +535,7 @@ usage(void) } // ?man modprobe: add or remove modules from the Linux kernel -// ?man arguments: module [symbol=value ...] +// ?man arguments: module [symbol=value ... // ?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, @@ -551,39 +551,48 @@ main(int argc, char *argv[]) int i, ret = 0; ARGBEGIN { - // ?man -a: Load all modules named on the command line rather than stopping after the first. + // ?man -a: specify a option case 'a': + // ?man -a: Load all modules named on the command line (rather than stopping after the first). aflag = 1; break; - // ?man -r: Remove the named modules from the kernel. Dependencies are not automatically removed. + // ?man -r: specify r option case 'r': + // ?man -r: Remove the named modules from the kernel. Dependencies are not automatically removed. rflag = 1; break; - // ?man -q: Quiet mode. Suppress error messages. + // ?man -q: specify q option case 'q': + // ?man -q: Quiet mode. Suppress error messages. qflag = 1; break; - // ?man -v: Verbose mode. Print each action taken. + // ?man -v: specify v option case 'v': + // ?man -v: Verbose mode. Print each action taken. vflag = 1; break; - // ?man -l: List available modules matching the optional pattern, a fnmatch(3) glob. + // ?man -l: specify l option case 'l': + // ?man -l: List available modules matching the optional _pattern_ (a fnmatch(3) glob). lflag = 1; break; #if FEATURE_MODPROBE_SHOW_DEPENDS - // ?man -D: Print the sequence of insmod commands that would be used to load the module, without actually loading anything. + // ?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. Dflag = 1; break; #endif #if FEATURE_MODPROBE_BLACKLIST - // ?man -b: Skip modules listed as blacklist in /etc/modprobe.d/. + // ?man -b: specify b option case 'b': + // ?man -b: Skip modules listed as blacklist in /etc/modprobe.d/. bflag = 1; break; #endif #if FEATURE_MODPROBE_SYSLOG - // ?man -s: Log messages to syslog(3) facility LOG_DAEMON instead of standard error. + // ?man -s: specify s option case 's': + // ?man -s: Log messages to syslog(3) (facility LOG_DAEMON) instead of standard error. sflag = 1; break; #endif #if FEATURE_MODPROBE_DIR_OVERRIDE - // ?man -d:dir: Use dir as the base directory for module files instead of /lib/modules/release. + // ?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. strlist_append(&moddirs, EARGF(usage())); break; #endif default: diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -191,8 +191,8 @@ usage(void) } // ?man mount: mount a filesystem -// ?man arguments: [source] [target] -// ?man mount attaches the filesystem specified to the filesystem hierarchy. The umount command will detach it again. +// ?man arguments: source] [target +// ?man mount a filesystem to the directory tree int main(int argc, char *argv[]) { @@ -205,35 +205,32 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -B: Remount a subtree somewhere else (so that its contents are visible in both places). + // ?man -B: specify option flag case 'B': argflags |= MS_BIND; break; - // ?man -M: Move a subtree to some other place. + // ?man -M: specify option flag case 'M': argflags |= MS_MOVE; break; - // ?man -R: Remount a subtree and all possible submounts somewhere else (so that its contents are available in both places). + // ?man -R: operate recursively on directories case 'R': argflags |= MS_REC; break; - // ?man -a: Mount all filesystems mentioned in /etc/fstab. + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -o:options: Specify a comma separated string of filesystem specific options. + // ?man -o:str: specify output file case 'o': estrlcat(fsopts, EARGF(usage()), sizeof(fsopts)); parseopts(fsopts, &flags, data, sizeof(data)); break; - // ?man -t:fstype: Set the filesystem type. More than one type may be specified in a comma separated list. - // ?man The list of file system types can be prefixed with "no" to specify the file system types for which action should not be taken. - // ?man For example, mount -a -t nonfs,ext4 mounts all file systems except those of type NFS and EXT4. - // ?man mount will attempt to execute a program in your PATH mount.XXX where XXX is replaced by the type name. For example, NFS file systems are mounted by the program mount.nfs. + // ?man -t:str: sort or specify timestamp case 't': types = EARGF(usage()); break; - // ?man -n: Mount without writing in /etc/mtab. This is the default action. + // ?man -n: print line numbers or counts case 'n': break; default: diff --git a/cmd/linux/mountpoint.c b/cmd/linux/mountpoint.c @@ -21,7 +21,7 @@ usage(void) // ?man mountpoint: check if a directory is a mountpoint // ?man arguments: target -// ?man mountpoint checks if the directory is mentioned in the /proc/mounts file. +// ?man determine if a directory is a mountpoint int main(int argc, char *argv[]) { @@ -32,15 +32,15 @@ main(int argc, char *argv[]) struct stat st1, st2; ARGBEGIN { - // ?man -d: Print the major/minor device number of the filesystem on stdout. + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -q: Be quiet, don't print anything. + // ?man -q: quiet mode; suppress output case 'q': qflag = 1; break; - // ?man -x: Print the major/minor device number of the device on stdout. + // ?man -x: hex format or match whole lines case 'x': xflag = 1; break; diff --git a/cmd/linux/rmmod.c b/cmd/linux/rmmod.c @@ -18,7 +18,9 @@ usage(void) // ?man rmmod: remove a module from the Linux kernel // ?man arguments: module... -// ?man rmmod removes one or more modules from the kernel. +// ?man rmmod removes a kernel module from the running kernel +// ?man // ?man -f: force removal of a module even if it is busy or in use +// ?man // ?man -w: wait for the module to become unused before removing int main(int argc, char *argv[]) { @@ -27,11 +29,11 @@ main(int argc, char *argv[]) int flags = O_NONBLOCK; ARGBEGIN { - // ?man -f: This option can be extremely dangerous: it has no effect unless CONFIG_MODULE_FORCE_UNLOAD was set when the kernel was compiled. With this option, you can remove modules which are being used, or which are not designed to be removed, or have been marked as unsafe. + // ?man -f: specify f option case 'f': flags |= O_TRUNC; break; - // ?man -w: Normally, rmmod will refuse to unload modules which are in use. With this option, rmmod will isolate the module, and wait until the module is no longer used. Noone new will be able to use the module, but it's up to you to make sure the current users eventually finish with it. + // ?man -w: specify w option case 'w': flags &= ~O_NONBLOCK; break; diff --git a/cmd/linux/swaplabel.c b/cmd/linux/swaplabel.c @@ -24,9 +24,9 @@ usage(void) eprintf("usage: %s [-L label] device\n", argv0); } -// ?man swaplabel: set the label of a swap filesystem +// ?man swaplabel: print or change swap label // ?man arguments: device -// ?man swaplabel is used to change the label of a swap device or file. +// ?man display or modify the label and uuid of a swap device int main(int argc, char *argv[]) { @@ -38,7 +38,7 @@ main(int argc, char *argv[]) int i; ARGBEGIN { - // ?man -L:label: Change the label. + // ?man -L:str: specify option flag case 'L': setlabel = 1; label = EARGF(usage()); diff --git a/cmd/linux/swapoff.c b/cmd/linux/swapoff.c @@ -16,10 +16,9 @@ usage(void) eprintf("usage: %s -a | device\n", argv0); } -// ?man swapoff: disable devices and files for paging and swapping -// ?man synopsis: -a -// ?man synopsis: device -// ?man swapoff disables swapping on the specified devices and files. +// ?man swapoff: disable swap devices +// ?man arguments: -a | device +// ?man disable paging and swapping on specified devices int main(int argc, char *argv[]) { @@ -30,7 +29,7 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -a: Disable swapping on all known swap devices and files as found in /etc/fstab. + // ?man -a: print or show all entries case 'a': all = 1; break; diff --git a/cmd/linux/swapon.c b/cmd/linux/swapon.c @@ -16,10 +16,9 @@ usage(void) eprintf("usage: %s [-dp] -a | device\n", argv0); } -// ?man swapon: enable devices and files for paging and swapping -// ?man synopsis: [-d] [-p] -a -// ?man synopsis: [-d] [-p] device -// ?man swapon is used to specify devices on which paging and swapping are to take place. +// ?man swapon: enable swap devices +// ?man arguments: -a | device +// ?man enable paging and swapping on specified devices int main(int argc, char *argv[]) { @@ -31,15 +30,15 @@ main(int argc, char *argv[]) FILE *fp; ARGBEGIN { - // ?man -a: Make all devices marked as "swap" in /etc/fstab available, except for those with the "noauto" option. + // ?man -a: print or show all entries case 'a': all = 1; break; - // ?man -d: Discard freed swap pages before they are reused. + // ?man -d: specify directory case 'd': flags |= SWAP_FLAG_DISCARD; break; - // ?man -p: Set higher priority than the default for the new swap area. + // ?man -p: preserve file attributes case 'p': flags |= SWAP_FLAG_PREFER; break; diff --git a/cmd/linux/switch_root.c b/cmd/linux/switch_root.c @@ -67,11 +67,8 @@ usage(void) } // ?man switch_root: switch to another root filesystem -// ?man arguments: [newroot] [init] -// ?man switch_root removes all files and directories on the current root filesystem and overmounts it with newroot. -// ?man If a console is specified, redirect stdio and stderr to it. -// ?man After the switch, execute init. -// ?man switch_root can only be run as PID 1 in an initramfs or tmpfs with a regular and executable /sbin/init. +// ?man arguments: newroot] [init] (PID 1) +// ?man switch to another filesystem as the root of the mount tree int main(int argc, char *argv[]) { @@ -81,7 +78,7 @@ main(int argc, char *argv[]) struct statfs stfs; ARGBEGIN { - // ?man -c:console: Redirect stdio and stderr to console after switching to newroot. + // ?man -c:str: print count or perform stdout action case 'c': console = EARGF(usage()); break; diff --git a/cmd/linux/sysctl.c b/cmd/linux/sysctl.c @@ -160,12 +160,9 @@ usage(void) eprintf("usage: %s [-p file] variable[=value]...\n", argv0); } -// ?man sysctl: configure kernel parameters at runtime +// ?man sysctl: configure kernel parameters // ?man arguments: variable[=value]... -// ?man sysctl modifies kernel parameters at runtime. -// ?man The parameters available are those listed under /proc/sys. -// ?man Procfs is required for sysctl support in Linux. -// ?man You can use sysctl to both read and write sysctl data. +// ?man view and modify kernel parameters at runtime int main(int argc, char *argv[]) { @@ -177,7 +174,7 @@ main(int argc, char *argv[]) int r = 0; ARGBEGIN { - // ?man -p:file: Load the sysctl key=value pairs from file. + // ?man -p:file: preserve file attributes case 'p': file = EARGF(usage()); break; diff --git a/cmd/linux/tunctl.c b/cmd/linux/tunctl.c @@ -43,21 +43,21 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -d: Clear persistence on the interface. + // ?man -d: specify directory case 'd': dflag = 1; tflag = 0; break; - // ?man -t: Make the interface persistent. + // ?man -t: sort or specify timestamp case 't': tflag = 1; dflag = 0; break; - // ?man -T: Create a TAP device instead of a TUN device. + // ?man -T: specify option flag case 'T': Tflag = 1; break; - // ?man -u:owner: Set the owner of the persistent interface. + // ?man -u:str: unbuffered output case 'u': owner = EARGF(usage()); break; diff --git a/cmd/linux/umount.c b/cmd/linux/umount.c @@ -127,9 +127,7 @@ usage(void) // ?man umount: unmount filesystems // ?man arguments: target... -// ?man umount detaches the target filesystem or filesystems. -// ?man A file system is specified by giving the directory where it has been mounted. -// ?man Giving the special device on which the file system lives may also work, but is obsolete, mainly because it will fail in case this device was mounted on more than one directory. +// ?man unmount a filesystem from the directory tree int main(int argc, char *argv[]) { @@ -142,23 +140,23 @@ main(int argc, char *argv[]) #endif ARGBEGIN { - // ?man -a: All of the file systems described in /proc/mounts are unmounted. The proc filesystem is not unmounted. + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -f: Force unmount (in case of an unreachable NFS server). + // ?man -f: force the operation case 'f': flags |= MNT_FORCE; break; - // ?man -l: Lazy unmount. Detach the filesystem from the fs hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. + // ?man -l: list in long format case 'l': flags |= MNT_DETACH; break; - // ?man -n: Unmount without writing in /etc/mtab. This is the default action. + // ?man -n: print line numbers or counts case 'n': break; #if FEATURE_UMOUNT_OPTIONS - // ?man -O:opts: Only act on mounts matching opts. + // ?man -O:str: specify option flag case 'O': oflag = EARGF(usage()); break; diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c @@ -15,37 +15,36 @@ usage(void) eprintf("usage: %s [-muinpU] cmd [args...]\n", argv0); } -// ?man unshare: run program with some namespaces unshared from parent -// ?man arguments: cmd [args ...] -// ?man unshare unshares the indicated namespaces from the parent process and then executes the specified program. -// ?man The namespaces to be unshared are indicated via options. +// ?man unshare: run program in new namespaces +// ?man arguments: cmd [args... +// ?man run a program with some namespaces unshared from the parent int main(int argc, char *argv[]) { int flags = 0; ARGBEGIN { - // ?man -m: Unshare the mount namespace, so that the calling process has a private copy of its namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWNS flag. + // ?man -m: specify mode or limit case 'm': flags |= CLONE_NEWNS; break; - // ?man -u: Unshare the UTS IPC namespace, so that the calling process has a private copy of the UTS namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWUTS flag. + // ?man -u: unbuffered output case 'u': flags |= CLONE_NEWUTS; break; - // ?man -i: Unshare the System V IPC namespace, so that the calling process has a private copy of the System V IPC namespace which is not shared with any other process. This flag has the same effect as the clone CLONE_NEWIPC flag. + // ?man -i: interactive mode or prompt for confirmation case 'i': flags |= CLONE_NEWIPC; break; - // ?man -n: Unshare the network namespace, so that the calling process is moved into a new network namespace which is not shared with any previously existing process. This flag has the same effect as the clone CLONE_NEWNET flag. + // ?man -n: print line numbers or counts case 'n': flags |= CLONE_NEWNET; break; - // ?man -p: Create the process in a new PID namespace. This flag has the same effect as the clone CLONE_NEWPID flag. + // ?man -p: preserve file attributes case 'p': flags |= CLONE_NEWPID; break; - // ?man -U: The process will have a distinct set of UIDs, GIDs and capabilities. + // ?man -U: specify option flag case 'U': flags |= CLONE_NEWUSER; break; diff --git a/cmd/net/host.c b/cmd/net/host.c @@ -258,7 +258,7 @@ parse_response(const unsigned char *resp, int resp_len, const char *query_name) } // ?man host: dns lookup utility -// ?man arguments: name [server] +// ?man arguments: name [server // ?man look up hostnames and IP addresses using dns int main(int argc, char *argv[]) @@ -274,7 +274,7 @@ main(int argc, char *argv[]) int i, r; ARGBEGIN { - // ?man -t:type: Query DNS records of the given type. + // ?man -t:str: sort or specify timestamp case 't': tflag = EARGF(usage()); break; diff --git a/cmd/net/httpd.c b/cmd/net/httpd.c @@ -262,15 +262,15 @@ main(int argc, char *argv[]) char *enc; ARGBEGIN { - // ?man -e:str: Print the URL-encoded form of str and exit. + // ?man -e:str: specify expression or pattern case 'e': eflag = EARGF(usage()); break; - // ?man -d:str: Print the URL-decoded form of str and exit. + // ?man -d:str: specify directory case 'd': dflag = EARGF(usage()); break; - // ?man -v: Accepted for compatibility; no effect. + // ?man -v: verbose mode; show progress case 'v': break; default: diff --git a/cmd/net/ifconfig.c b/cmd/net/ifconfig.c @@ -98,7 +98,7 @@ list_interfaces(int all) } // ?man ifconfig: configure network interfaces -// ?man arguments: interface [action ...] +// ?man arguments: interface [action ... // ?man configure network interface parameters and view stats int main(int argc, char *argv[]) @@ -118,7 +118,7 @@ main(int argc, char *argv[]) unsigned int mask; ARGBEGIN { - // ?man -a: Show all interfaces, including those that are down. + // ?man -a: print or show all entries case 'a': aflag = 1; break; diff --git a/cmd/net/ip.c b/cmd/net/ip.c @@ -346,9 +346,7 @@ do_route(int argc, char *argv[]) } // ?man ip: show or configure routing and devices -// ?man synopsis: addr [args ...] -// ?man synopsis: link [args ...] -// ?man synopsis: route [args ...] +// ?man arguments: addr | link | route] [args... // ?man configure and view network devices, routing, and tunnels // ?man ## COMMANDS // ?man ### addr [show | list [dev <device>]] diff --git a/cmd/net/netcat.c b/cmd/net/netcat.c @@ -49,7 +49,7 @@ resolve(const char *host, const char *port, int family, int socktype, } // ?man netcat: read and write data across network connections -// ?man arguments: [host] [port] +// ?man arguments: host] [port // ?man arbitrary data transmission over tcp or udp int main(int argc, char *argv[]) @@ -70,15 +70,15 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -l: Listen for an incoming connection. + // ?man -l: list in long format case 'l': lflag = 1; break; - // ?man -p:port: Use port as the local port. + // ?man -p:str: preserve file attributes case 'p': local_port = EARGF(usage()); break; - // ?man -u: Use UDP instead of TCP. + // ?man -u: unbuffered output case 'u': uflag = 1; break; diff --git a/cmd/net/ping.c b/cmd/net/ping.c @@ -141,23 +141,23 @@ main(int argc, char *argv[]) socklen_t fromlen; ARGBEGIN { - // ?man -c:count: Stop after sending count requests. + // ?man -c:str: print count or perform stdout action case 'c': cflag = EARGF(usage()); break; - // ?man -i:interval: Wait interval seconds between requests. + // ?man -i:str: interactive mode or prompt for confirmation case 'i': iflag = EARGF(usage()); break; - // ?man -s:size: Send size bytes of payload data. + // ?man -s:str: silent mode or print summary case 's': sflag = EARGF(usage()); break; - // ?man -t:ttl: Set the IP time-to-live. + // ?man -t:str: sort or specify timestamp case 't': tflag = EARGF(usage()); break; - // ?man -w:deadline: Stop after deadline seconds. + // ?man -w:str: wait for completion case 'w': wflag = EARGF(usage()); break; diff --git a/cmd/net/tftp.c b/cmd/net/tftp.c @@ -261,19 +261,19 @@ main(int argc, char *argv[]) int ret; ARGBEGIN { - // ?man -h:host: Connect to host. + // ?man -h:str: suppress headers or print help case 'h': host = EARGF(usage()); break; - // ?man -p:port: Use port instead of the default tftp service. + // ?man -p:str: preserve file attributes case 'p': port = EARGF(usage()); break; - // ?man -x: Download file from the server. + // ?man -x: hex format or match whole lines case 'x': fn = getfile; break; - // ?man -c: Upload file to the server. + // ?man -c: print count or perform stdout action case 'c': fn = putfile; break; diff --git a/cmd/net/wget.c b/cmd/net/wget.c @@ -327,35 +327,35 @@ main(int argc, char *argv[]) size_t i; ARGBEGIN { - // ?man -O:str: Write output to str instead of the default file name. + // ?man -O:str: specify output file path case 'O': Oflag = EARGF(usage()); break; - // ?man -P:str: Write output files under directory str. + // ?man -P:str: specify output directory prefix case 'P': Pflag = EARGF(usage()); break; - // ?man -T:num: Set the network read and connect timeout to num seconds. + // ?man -T:num: set network read and connect timeout case 'T': timeout_sec = estrtonum(EARGF(usage()), 0, 100000); break; - // ?man -U:str: Set the User-Agent header to str. + // ?man -U:str: set User-Agent header case 'U': user_agent = EARGF(usage()); break; - // ?man -c: Continue retrieval of an aborted transfer. + // ?man -c: continue retrieval of aborted transfer case 'c': cflag = 1; break; - // ?man -q: Quiet mode. Suppress stderr output. + // ?man -q: quiet mode to suppress stderr output case 'q': qflag = 1; break; - // ?man -S: Print server response headers to stderr. + // ?man -S: print server response headers to stderr case 'S': Sflag = 1; break; - /* long options handle TLS verification, extra headers, POST data, and spider mode */ + // ?man --: specify - option case '-': if (strcmp(argv[0], "-no-check-certificate") == 0) { no_check_certificate = 1; diff --git a/cmd/posix/basename.c b/cmd/posix/basename.c @@ -14,7 +14,7 @@ usage(void) } // ?man basename: strip directory and suffix from filenames -// ?man arguments: path [suffix] +// ?man arguments: path [suffix // ?man print filename with leading directories and optional suffix removed int main(int argc, char *argv[]) diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c @@ -179,11 +179,11 @@ main(int argc, char *argv[]) ARGBEGIN { #ifdef FEATURE_CAL_EXT - // ?man -1: print the current month + // ?man -1: specify option flag case '1': nmons = 1; break; - // ?man -3: print the previous, current, and next month + // ?man -3: specify option flag case '3': nmons = 3; if (--month == 0) { @@ -191,28 +191,28 @@ main(int argc, char *argv[]) year--; } break; - // ?man -c:num: print num calendars in a row + // ?man -c:num: print count or perform stdout action case 'c': ncols = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -f:num: use num as the first day of the week, where 0 is Sunday + // ?man -f:num: force the operation case 'f': fday = estrtonum(EARGF(usage()), 0, 6); break; - // ?man -m: use Monday as the first day of the week + // ?man -m: specify mode or limit case 'm': /* Monday */ fday = 1; break; - // ?man -n:num: output num months starting with the current month + // ?man -n:num: print line numbers or counts case 'n': nmons = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -s: use Sunday as the first day of the week + // ?man -s: silent mode or print summary case 's': /* Sunday */ fday = 0; break; #endif - // ?man -y: print the entire year + // ?man -y: specify option flag case 'y': month = 1; nmons = 12; diff --git a/cmd/posix/cat.c b/cmd/posix/cat.c @@ -15,8 +15,8 @@ usage(void) } // ?man cat: concatenate files and print to standard output -// ?man arguments: [file ...] -// ?man cat reads each file in sequence and writes its contents to standard output +// ?man arguments: file ... +// ?man cat reads each file in sequence and writes it to standard output // ?man if no file is given, or a file is -, standard input is read int main(int argc, char *argv[]) @@ -24,8 +24,9 @@ main(int argc, char *argv[]) int fd, ret = 0; ARGBEGIN { - // ?man -u: accepted for posix compatibility; output is always unbuffered + // ?man -u: specify u option case 'u': + // ?man -u: ignored; accepted for posix compatibility; output is always unbuffered break; default: usage(); diff --git a/cmd/posix/chgrp.c b/cmd/posix/chgrp.c @@ -48,7 +48,7 @@ main(int argc, char *argv[]) struct recursor r = { .fn = chgrp, .maxdepth = 1, .follow = 'P' }; ARGBEGIN { - // ?man -h: operate on symbolic links themselves instead of their targets + // ?man -h: affect symbolic links instead of referenced files case 'h': hflag = 1; break; @@ -56,11 +56,11 @@ main(int argc, char *argv[]) case 'R': r.maxdepth = 0; break; - // ?man -H: dereference command-line symbolic links during recursive traversal + // ?man -H: specify option flag case 'H': - // ?man -L: dereference all symbolic links during recursive traversal + // ?man -L: specify option flag case 'L': - // ?man -P: preserve symbolic links during recursive traversal + // ?man -P: specify option flag case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/chown.c b/cmd/posix/chown.c @@ -45,8 +45,7 @@ usage(void) } // ?man chown: change ownership -// ?man synopsis: owner[:[group]] file ... -// ?man synopsis: :group file ... +// ?man arguments: owner[:[group]] file ... // ?man change the user and group ownership of files and directories int main(int argc, char *argv[]) @@ -57,7 +56,7 @@ main(int argc, char *argv[]) char *owner, *group; ARGBEGIN { - // ?man -h: operate on symbolic links themselves instead of their targets + // ?man -h: affect symbolic links instead of referenced files case 'h': hflag = 1; break; @@ -67,11 +66,11 @@ main(int argc, char *argv[]) case 'R': r.maxdepth = 0; break; - // ?man -H: dereference command-line symbolic links during recursive traversal + // ?man -H: specify option flag case 'H': - // ?man -L: dereference all symbolic links during recursive traversal + // ?man -L: specify option flag case 'L': - // ?man -P: preserve symbolic links during recursive traversal + // ?man -P: specify option flag case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/cmp.c b/cmd/posix/cmp.c @@ -24,11 +24,11 @@ main(int argc, char *argv[]) int ret = 0, lflag = 0, sflag = 0, same = 1, b[2]; ARGBEGIN { - // ?man -l: print the byte number and differing bytes for every difference + // ?man -l: list in long format case 'l': lflag = 1; break; - // ?man -s: print nothing and return status only + // ?man -s: silent mode or print summary case 's': sflag = 1; break; diff --git a/cmd/posix/comm.c b/cmd/posix/comm.c @@ -44,11 +44,11 @@ main(int argc, char *argv[]) int ret = 0, i, diff = 0, seenline = 0; ARGBEGIN { - // ?man -1: suppress lines unique to file1 + // ?man -1: specify option flag case '1': - // ?man -2: suppress lines unique to file2 + // ?man -2: specify option flag case '2': - // ?man -3: suppress lines common to both files + // ?man -3: specify option flag case '3': show &= 0x07 ^ (1 << (ARGC() - '1')); break; diff --git a/cmd/posix/cp.c b/cmd/posix/cp.c @@ -25,7 +25,7 @@ main(int argc, char *argv[]) case 'i': cp_iflag = 1; break; - // ?man -a: preserve devices, sockets, and fifos; implies -pPR + // ?man -a: archive mode; equivalent to -dpR case 'a': cp_follow = 'P'; cp_aflag = cp_pflag = cp_rflag = 1; @@ -34,7 +34,7 @@ main(int argc, char *argv[]) case 'f': cp_fflag = 1; break; - // ?man -p: preserve mode, timestamps, and ownership + // ?man -p: preserve file attributes case 'p': cp_pflag = 1; break; @@ -44,15 +44,15 @@ main(int argc, char *argv[]) case 'R': cp_rflag = 1; break; - // ?man -v: write each copied source and destination path + // ?man -v: verbose mode; show progress case 'v': cp_vflag = 1; break; - // ?man -H: dereference source arguments that are symbolic links + // ?man -H: specify option flag case 'H': - // ?man -L: dereference all symbolic links + // ?man -L: specify option flag case 'L': - // ?man -P: preserve symbolic links + // ?man -P: specify option flag case 'P': cp_follow = ARGC(); break; diff --git a/cmd/posix/cut.c b/cmd/posix/cut.c @@ -161,20 +161,9 @@ usage(void) argv0, argv0, argv0); } -// ?man cut: extract columns of data -// ?man synopsis: -b list [-n] [file ...] -// ?man synopsis: -c list [file ...] -// ?man synopsis: -f list [-d delim] [-s] [file ...] -// ?man cut out bytes, characters or delimited fields from each line of file and -// ?man write to stdout. -// ?man If no file is given or file is '-', cut reads from stdin. -// ?man list is a comma or space separated list of numbers and ranges starting -// ?man from 1. -// ?man Ranges have the form 'N-M'. If N or M is missing, beginning or end -// ?man of line is assumed. -// ?man Numbers and ranges may be repeated, overlapping and in any order. -// ?man Selected input is written in the same order it is read -// ?man and is written exactly once. +// ?man cut: cut out fields from lines +// ?man arguments: -b list [file ... +// ?man print selected parts of lines from files int main(int argc, char *argv[]) { @@ -182,30 +171,27 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -b:list: list specifies byte | character positions. + // ?man -b: specify block size or base directory case 'b': - // ?man -c:list: list specifies byte | character positions. + // ?man -c: print count or perform stdout action case 'c': - // ?man -f:list: list specifies field numbers. - // ?man Lines not containing field delimiters are passed through, unless -s is specified. + // ?man -f:mode: force the operation case 'f': mode = ARGC(); parselist(EARGF(usage())); break; - // ?man -d:delim: Use delim as field delimiter, which can be an arbitrary string. - // ?man Default is '\\t'. + // ?man -d:str: specify directory case 'd': delim = EARGF(usage()); if (!*delim) eprintf("empty delimiter\n"); delimlen = unescape(delim); break; - // ?man -n: Do not split multibyte characters. - // ?man A character is written when its last byte is selected. + // ?man -n: print line numbers or counts case 'n': nflag = 1; break; - // ?man -s: Suppress lines not containing field delimiters. + // ?man -s: silent mode or print summary case 's': sflag = 1; break; diff --git a/cmd/posix/date.c b/cmd/posix/date.c @@ -64,8 +64,7 @@ setdate(const char *s, struct tm *now) } // ?man date: print or set system date and time -// ?man synopsis: [-u] [-d time] [+format] -// ?man synopsis: [-u] [-d time] [mmddHHMM[[CC]yy]] +// ?man arguments: +format | mmddHHMM[[CC]yy // ?man display or configure the system date and time int main(int argc, char *argv[]) @@ -79,11 +78,11 @@ main(int argc, char *argv[]) eprintf("time:"); ARGBEGIN { - // ?man -d:time: print time as seconds since the Unix epoch + // ?man -d:num: specify directory case 'd': t = estrtonum(EARGF(usage()), 0, LLONG_MAX); break; - // ?man -u: print or set UTC time instead of local time + // ?man -u: unbuffered output case 'u': if (setenv("TZ", "UTC0", 1) < 0) eprintf("setenv:"); diff --git a/cmd/posix/df.c b/cmd/posix/df.c @@ -91,8 +91,8 @@ usage(void) eprintf("usage: %s [-a]\n", argv0); } -// ?man df: show file system usage -// ?man df displays the amount of disk space available on a file system. If no arguments are given, df shows all the file systems using 512-byte blocks. +// ?man df: report disk space usage +// ?man display free and used disk space on filesystems int main(int argc, char *argv[]) { @@ -101,24 +101,24 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -a: Show all file systems including dummy ones. This is the default option. + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -h: Not implemented. + // ?man -h: suppress headers or print help case 'h': hflag = 1; kflag = 0; break; - // ?man -k: Print sizes in 1024-byte blocks. + // ?man -k: specify option flag case 'k': kflag = 1; hflag = 0; blksize = 1024; break; - // ?man -s: Accepted for compatibility; not implemented. + // ?man -s: silent mode or print summary case 's': - // ?man -i: Not implemented. + // ?man -i: interactive mode or prompt for confirmation case 'i': eprintf("not implemented\n"); break; diff --git a/cmd/posix/du.c b/cmd/posix/du.c @@ -122,36 +122,36 @@ main(int argc, char *argv[]) char *bsize; ARGBEGIN { - // ?man -a: display an entry for each file in the hierarchy + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -d:depth: limit output to depth levels of subdirectories + // ?man -d:num: specify directory case 'd': dflag = 1; maxdepth = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -h: print sizes in human-readable units + // ?man -h: suppress headers or print help case 'h': hflag = 1; break; - // ?man -k: report sizes in kilobytes instead of 512-byte blocks + // ?man -k: specify option flag case 'k': kflag = 1; break; - // ?man -s: display only the total for each specified file + // ?man -s: silent mode or print summary case 's': sflag = 1; break; - // ?man -x: stay on the current file system + // ?man -x: hex format or match whole lines case 'x': r.flags |= SAMEDEV; break; - // ?man -H: follow symbolic links given on the command line + // ?man -H: specify option flag case 'H': - // ?man -L: follow all symbolic links + // ?man -L: specify option flag case 'L': - // ?man -P: do not follow symbolic links + // ?man -P: specify option flag case 'P': r.follow = ARGC(); break; diff --git a/cmd/posix/env.c b/cmd/posix/env.c @@ -18,7 +18,7 @@ usage(void) } // ?man env: run command in modified environment -// ?man arguments: [name=value ...] [cmd [arg ...]] +// ?man arguments: ... [var=value] ... [cmd [arg ... // ?man set environment variables and run a command int main(int argc, char *argv[]) @@ -26,11 +26,11 @@ main(int argc, char *argv[]) int savederrno; ARGBEGIN { - // ?man -i: ignore the inherited environment and start from an empty one + // ?man -i: interactive mode or prompt for confirmation case 'i': *environ = NULL; break; - // ?man -u:name: remove name from the environment + // ?man -u:str: unbuffered output case 'u': if (unsetenv(EARGF(usage())) < 0) eprintf("unsetenv:"); diff --git a/cmd/posix/expand.c b/cmd/posix/expand.c @@ -98,11 +98,11 @@ main(int argc, char *argv[]) char *tl = "8"; ARGBEGIN { - // ?man -i: only expand tabs at the start of lines + // ?man -i: interactive mode or prompt for confirmation case 'i': iflag = 1; break; - // ?man -t:list: use list as the tab size or tab stops + // ?man -t:str: sort or specify timestamp case 't': tl = EARGF(usage()); if (!*tl) diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -1421,7 +1421,7 @@ usage(void) } // ?man find: search for files -// ?man arguments: path ... [expression ...] +// ?man arguments: path ... [expression ... // ?man search for files in a directory hierarchy int main(int argc, char **argv) @@ -1434,12 +1434,12 @@ main(int argc, char **argv) gflags.mindepth = -1; ARGBEGIN { - // ?man -H: dereference symbolic links given on the command line + // ?man -H: specify option flag case 'H': gflags.h = 1; gflags.l = 0; break; - // ?man -L: dereference all symbolic links encountered + // ?man -L: specify option flag case 'L': gflags.l = 1; gflags.h = 0; diff --git a/cmd/posix/fold.c b/cmd/posix/fold.c @@ -85,7 +85,7 @@ usage(void) } // ?man fold: wrap lines to fit width -// ?man arguments: file ... +// ?man arguments: FILE ... // ?man wrap input lines to fit a specified width int main(int argc, char *argv[]) @@ -94,19 +94,19 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -b: count bytes rather than characters + // ?man -b: specify block size or base directory case 'b': bflag = 1; break; - // ?man -s: break at the last space within the width when possible + // ?man -s: silent mode or print summary case 's': sflag = 1; break; - // ?man -w:num: wrap lines at num columns instead of 80 + // ?man -w:num: wait for completion case 'w': width = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - /* -num is accepted as shorthand for -w num */ + // ?man ARGNUM: specify RGNUM option ARGNUM: if (!(width = ARGNUMF())) eprintf("illegal width value, too small\n"); diff --git a/cmd/posix/getconf.c b/cmd/posix/getconf.c @@ -23,7 +23,7 @@ usage(void) } // ?man getconf: query configuration variables -// ?man arguments: var [path] +// ?man arguments: var [path // ?man query system configuration variables int main(int argc, char *argv[]) @@ -34,7 +34,7 @@ main(int argc, char *argv[]) char *str; ARGBEGIN { - // ?man -v:spec: accepted for compatibility; ignored + // ?man -v:str: verbose mode; show progress case 'v': /* ignore */ EARGF(usage()); diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c @@ -244,7 +244,7 @@ usage(void) } // ?man grep: search files for a pattern -// ?man arguments: pattern [file ...] +// ?man arguments: pattern] [file ... // ?man grep searches the named input files for lines matching the given pattern // ?man if no files are named, or a file is -, standard input is searched // ?man by default, matching lines are written to standard output @@ -260,54 +260,54 @@ main(int argc, char *argv[]) ARGBEGIN { #if FEATURE_GREP_CONTEXT - // ?man -A:num: print num lines of trailing context after each match + // ?man -A:num: specify A option case 'A': // ?man -A num: print num lines of trailing context after each match Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -B:num: print num lines of leading context before each match + // ?man -B:num: specify B option case 'B': // ?man -B num: print num lines of leading context before each match Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -C:num: print num lines of context before and after each match + // ?man -C:num: specify C option case 'C': // ?man -C num: print num lines of context before and after each match; equivalent to -A num -B num Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - /* -num is accepted as shorthand for -C num */ + // ?man ARGNUM: specify RGNUM option ARGNUM: Aflag = Bflag = ARGNUMF(); break; #endif #if FEATURE_GREP_MAX_COUNT - // ?man -m:num: stop reading a file after num matching lines + // ?man -m:num: specify m option case 'm': // ?man -m num: stop reading a file after num matching lines mval = estrtonum(EARGF(usage()), 0, LONG_MAX); break; #endif - // ?man -E: interpret pattern as an extended regular expression + // ?man -E: specify E option case 'E': // ?man -E: interpret pattern as an extended regular expression Eflag = 1; Fflag = 0; flags |= REG_EXTENDED; break; - // ?man -F: interpret patterns as fixed strings + // ?man -F: specify F option case 'F': // ?man -F: interpret pattern as a list of fixed strings separated by newlines Fflag = 1; Eflag = 0; flags &= ~REG_EXTENDED; break; - // ?man -H: always print file names with matching lines + // ?man -H: specify H option case 'H': // ?man -H: always print the file name with matching lines Hflag = 1; hflag = 0; break; - // ?man -e:pattern: specify a pattern to match; may be given multiple times + // ?man -e:file: specify e option case 'e': // ?man -e pattern: specify a pattern to match; may be given multiple times arg = EARGF(usage()); @@ -317,7 +317,7 @@ main(int argc, char *argv[]) efshut(fp, arg); eflag = 1; break; - // ?man -f:file: read patterns from file, one per line + // ?man -f:file: specify f option case 'f': // ?man -f file: read patterns from file, one per line arg = EARGF(usage()); @@ -328,51 +328,51 @@ main(int argc, char *argv[]) efshut(fp, arg); fflag = 1; break; - // ?man -h: never print file names with matching lines + // ?man -h: specify h option case 'h': // ?man -h: never print file names with matching lines hflag = 1; Hflag = 0; break; - // ?man -c: print only a count of matching lines per file + // ?man -c: specify c option case 'c': // ?man -c: print only a count of matching lines per file /* FALLTHROUGH */ - // ?man -l: print only the names of files with at least one match + // ?man -l: specify l option case 'l': // ?man -l: print only the names of files with at least one matching line /* FALLTHROUGH */ - // ?man -n: prefix each matching line with its line number + // ?man -n: specify n option case 'n': // ?man -n: prefix each matching line with its line number within its file /* FALLTHROUGH */ - // ?man -q: print nothing and return success on the first match + // ?man -q: specify q option case 'q': // ?man -q: quiet mode; exit immediately with status 0 on first match and write nothing mode = ARGC(); break; - // ?man -i: perform case-insensitive matching + // ?man -i: specify i option case 'i': // ?man -i: perform case-insensitive matching flags |= REG_ICASE; iflag = 1; break; - // ?man -s: suppress errors for nonexistent or unreadable files + // ?man -s: specify s option case 's': // ?man -s: suppress error messages about nonexistent or unreadable files sflag = 1; break; - // ?man -v: select lines that do not match + // ?man -v: specify v option case 'v': // ?man -v: invert the sense of matching to select non-matching lines vflag = 1; break; - // ?man -w: match only whole words + // ?man -w: specify w option case 'w': // ?man -w: match only whole words wflag = 1; break; - // ?man -x: match only whole lines + // ?man -x: specify x option case 'x': // ?man -x: match only whole lines xflag = 1; diff --git a/cmd/posix/head.c b/cmd/posix/head.c @@ -41,11 +41,11 @@ main(int argc, char *argv[]) int ret = 0, newline = 0, many = 0; ARGBEGIN { - // ?man -n:num: display the first num lines of each file + // ?man -n:num: print line numbers or counts case 'n': n = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - /* -num is accepted as shorthand for -n num */ + // ?man ARGNUM: specify RGNUM option ARGNUM: n = ARGNUMF(); break; diff --git a/cmd/posix/id.c b/cmd/posix/id.c @@ -135,26 +135,26 @@ usage(void) eprintf("usage: %s [-n] [-g | -u | -G] [user | uid]\n", argv0); } -// ?man id: print real and effective user and group ids -// ?man synopsis: [-n] [-g | -u | -G] [user | uid] -// ?man id prints user and group information of the calling process to standard output. If a login name or uid is specified, the user and group information of that user is displayed. +// ?man id: print user and group ids +// ?man arguments: user | uid +// ?man display real and effective user and group identities int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -g: Print only the effective group ID. + // ?man -g: specify option flag case 'g': gflag = 1; break; - // ?man -u: Print only the effective user ID. + // ?man -u: unbuffered output case 'u': uflag = 1; break; - // ?man -G: Display group information as whitespace separated numbers, in no particular order. + // ?man -G: specify option flag case 'G': Gflag = 1; break; - // ?man -n: Print names instead of ID numbers, for -g, -u, and -G. + // ?man -n: print line numbers or counts case 'n': nflag = 1; break; diff --git a/cmd/posix/join.c b/cmd/posix/join.c @@ -451,17 +451,8 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) } -// ?man join: relational database operator -// ?man join lines from file1 and file2 on a matching field. -// ?man If one of the input files is '-', standard input is read for that file. -// ?man Files are read sequentially and are assumed to be sorted on the join -// ?man field. -// ?man join does not check the order of input, and joining two unsorted files will -// ?man produce unexpected output. -// ?man By default, input lines are matched on the first blank-separated -// ?man field; output lines are space-separated and consist of the join field -// ?man followed by the remaining fields from file1, -// ?man then the remaining fields from file2. +// ?man join: join lines on common field +// ?man join lines of two sorted files on a common field int main(int argc, char *argv[]) { @@ -471,15 +462,15 @@ main(int argc, char *argv[]) char *fno; ARGBEGIN { - // ?man -1:field: Join on the fieldth field of file 1. + // ?man -1:num: specify option flag case '1': jf[0] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -2:field: Join on the fieldth field of file 2. + // ?man -2:num: specify option flag case '2': jf[1] = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -a:fileno: Print unpairable lines from file fileno in addition to normal output. + // ?man -a:str: print or show all entries case 'a': fno = EARGF(usage()); if (strcmp(fno, "1") == 0) @@ -489,29 +480,21 @@ main(int argc, char *argv[]) else usage(); break; - // ?man -e:string: When used with -o, replace empty fields in the output list with string. + // ?man -e:str: specify expression or pattern case 'e': replace = EARGF(usage()); break; - // ?man -o:list: Format output according to the string list. - // ?man Each element of list may be either fileno.field or 0 representing the join field. - // ?man Elements in list may be separated by blanks or commas. - // ?man For example, - // ?man join -o "0 2.1 1.3" - // ?man would print the join field, the first field of file2, - // ?man then the third field of file1. - // ?man Only paired lines are formatted with the -o option. - // ?man Unpairable lines selected with -a or -v are printed raw. + // ?man -o:str: specify output file case 'o': oflag = 1; initolist(&output); makeolist(&output, EARGF(usage())); break; - // ?man -t:delim: Use the arbitrary string delim as field delimiter for both input and output. + // ?man -t:str: sort or specify timestamp case 't': sep = EARGF(usage()); break; - // ?man -v:fileno: Print unpairable lines from file fileno instead of normal output. + // ?man -v:str: verbose mode; show progress case 'v': pairs = 0; fno = EARGF(usage()); diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c @@ -19,7 +19,7 @@ usage(void) } // ?man ln: make links between files -// ?man arguments: target [name] +// ?man arguments: target [name // ?man create hard or symbolic links between files int main(int argc, char *argv[]) @@ -34,11 +34,11 @@ main(int argc, char *argv[]) case 'f': fflag = 1; break; - // ?man -L: hard-link the target of a symbolic link rather than the link itself + // ?man -L: specify option flag case 'L': flags |= AT_SYMLINK_FOLLOW; break; - // ?man -P: hard-link a symbolic link itself rather than its target + // ?man -P: specify option flag case 'P': flags &= ~AT_SYMLINK_FOLLOW; break; diff --git a/cmd/posix/logger.c b/cmd/posix/logger.c @@ -56,19 +56,19 @@ main(int argc, char *argv[]) char *buf = NULL, *tag = NULL; ARGBEGIN { - // ?man -i: include the logger process ID with each message + // ?man -i: interactive mode or prompt for confirmation case 'i': logflags |= LOG_PID; break; - // ?man -p:priority: log with the given facility.level priority + // ?man -p:str: preserve file attributes case 'p': priority = decodepri(EARGF(usage())); break; - // ?man -s: also write each message to standard error + // ?man -s: silent mode or print summary case 's': logflags |= LOG_PERROR; break; - // ?man -t:tag: add tag to each logged message + // ?man -t:str: sort or specify timestamp case 't': tag = EARGF(usage()); break; diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c @@ -406,11 +406,11 @@ entcmp(const void *va, const void *vb) const struct entry *a = va, *b = vb; switch (sort) { - // ?man -S: sort files by size in decreasing order + // ?man -S: sort by file size case 'S': cmp = b->size - a->size; break; - // ?man -t: sort files by modification time + // ?man -t: sort by modification time case 't': if (!(cmp = b->t.tv_sec - a->t.tv_sec)) cmp = b->t.tv_nsec - a->t.tv_nsec; @@ -552,7 +552,7 @@ usage(void) } // ?man ls: list directory contents -// ?man arguments: [file ...] +// ?man arguments: [file ... // ?man list information about files and directories int main(int argc, char *argv[]) @@ -706,7 +706,7 @@ main(int argc, char *argv[]) uflag = 1; cflag = 0; break; - /* --color[=when] is accepted as a long-option extension */ + // ?man --: specify - option case '-': #if FEATURE_LS_COLOR // ?man --color [when]: control coloring diff --git a/cmd/posix/mesg.c b/cmd/posix/mesg.c @@ -17,7 +17,7 @@ usage(void) } // ?man mesg: control write access -// ?man synopsis: [n | y] +// ?man arguments: n|y // ?man allow or disallow other users to write to the terminal int main(int argc, char *argv[]) diff --git a/cmd/posix/mkfifo.c b/cmd/posix/mkfifo.c @@ -23,7 +23,7 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -m:mode: set the file mode of newly created named pipes + // ?man -m:mode: specify mode or limit case 'm': mode = parsemode(EARGF(usage()), mode, umask(0)); break; diff --git a/cmd/posix/nice.c b/cmd/posix/nice.c @@ -24,7 +24,7 @@ usage(void) } // ?man nice: run command with modified priority -// ?man arguments: cmd [arg ...] +// ?man arguments: cmd [arg ... // ?man run a command with modified scheduling priority int main(int argc, char *argv[]) @@ -32,7 +32,7 @@ main(int argc, char *argv[]) int val = 10, r, savederrno; ARGBEGIN { - // ?man -n:num: change niceness by num + // ?man -n:num: print line numbers or counts case 'n': val = estrtonum(EARGF(usage()), PRIO_MIN, PRIO_MAX); break; diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c @@ -73,7 +73,7 @@ nl(const char *fname, FILE *fp) if (line.data[0] != '\n') donumber = 1; break; - /* pexpr line-matching mode */ + // ?man -p: preserve file attributes case 'p': if (!regexec(preg + section, line.data, 0, NULL, 0)) donumber = 1; @@ -118,20 +118,8 @@ getlinetype(char *type, regex_t *preg) return type[0]; } -// ?man nl: line numbering filter -// ?man nl reads lines from file and writes them to stdout, numbering non-empty lines. -// ?man If no file is given nl reads from stdin. -// ?man nl treats the input text as a collection of logical pages divided into -// ?man logical page sections. -// ?man Each logical page consists of a header section, a body -// ?man section and a footer section. -// ?man Sections may be empty. -// ?man The start of each section is indicated by a single delimiting line, one of: -// ?man ::: header -// ?man :: body -// ?man : footer -// ?man If the input text contains no delimiting line then all of the input text -// ?man belongs to a single logical page body section. +// ?man nl: number lines +// ?man number the lines of files int main(int argc, char *argv[]) { @@ -141,9 +129,7 @@ main(int argc, char *argv[]) char *d, *formattype, *formatblit; ARGBEGIN { - // ?man -d:delim: Set delim as the delimiter for logical pages. - // ?man If delim is only one character, nl appends \":\" to it. - // ?man The default is \"\\:\". + // ?man -d:str: specify directory case 'd': switch (utflen((d = EARGF(usage())))) { case 0: @@ -162,47 +148,27 @@ main(int argc, char *argv[]) break; } break; - // ?man -f:type: Define which lines to number in the head | body | footer section: - // ?man a All lines. - // ?man n No lines. - // ?man t Only non-empty lines. - // ?man This is the default. - // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . + // ?man -f:str: force the operation case 'f': type[0] = getlinetype(EARGF(usage()), preg); break; - // ?man -b:type: Define which lines to number in the head | body | footer section: - // ?man a All lines. - // ?man n No lines. - // ?man t Only non-empty lines. - // ?man This is the default. - // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . + // ?man -b:str: specify block size or base directory case 'b': type[1] = getlinetype(EARGF(usage()), preg + 1); break; - // ?man -h:type: Define which lines to number in the head | body | footer section: - // ?man a All lines. - // ?man n No lines. - // ?man t Only non-empty lines. - // ?man This is the default. - // ?man pexpr Only lines matching expr according to regex 7 or re_format 7 . + // ?man -h:str: suppress headers or print help case 'h': type[2] = getlinetype(EARGF(usage()), preg + 2); break; - // ?man -i:num: Set the increment between numbered lines to num . + // ?man -i:num: interactive mode or prompt for confirmation case 'i': incr = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -l:num: Set the number of adjacent blank lines to be considered as one to num . - // ?man The default is 1. + // ?man -l:num: list in long format case 'l': blines = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -n:format: Set the line number output format to one of: - // ?man ln Left justified. - // ?man rn Right justified. - // ?man This is the default. - // ?man rz Right justified with leading zeroes. + // ?man -n:str: print line numbers or counts case 'n': formattype = EARGF(usage()); estrlcpy(format, "%", sizeof(format)); @@ -220,23 +186,20 @@ main(int argc, char *argv[]) estrlcat(format, formatblit, sizeof(format)); estrlcat(format, "*ld", sizeof(format)); break; - // ?man -p: Do not reset line number for logical pages. + // ?man -p: preserve file attributes case 'p': pflag = 1; break; - // ?man -s:sep: Use sep to separate line numbers and lines. - // ?man The default is \"\\t\". + // ?man -s:str: silent mode or print summary case 's': sep = EARGF(usage()); seplen = unescape(sep); break; - // ?man -v:num: Start counting lines from num . - // ?man The default is 1. + // ?man -v:num: verbose mode; show progress case 'v': startnum = estrtonum(EARGF(usage()), 0, MIN((unsigned long long)LLONG_MAX, (unsigned long long)SIZE_MAX)); break; - // ?man -w:num: Set the width of the line number to num . - // ?man The default is 6. + // ?man -w:num: wait for completion case 'w': width = estrtonum(EARGF(usage()), 1, INT_MAX); break; diff --git a/cmd/posix/nohup.c b/cmd/posix/nohup.c @@ -17,7 +17,7 @@ usage(void) } // ?man nohup: run command immune to hangups -// ?man arguments: cmd [arg ...] +// ?man arguments: cmd [arg ... // ?man run a command that persists after logging out int main(int argc, char *argv[]) diff --git a/cmd/posix/od.c b/cmd/posix/od.c @@ -61,7 +61,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) }; switch (format) { - // equivalent to -t a + // ?man -a: print or show all entries case 'a': c = *s & ~128; /* clear high bit as required by standard */ if (c < LEN(namedict) || c == 127) { @@ -70,7 +70,7 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) printf(" %3c", c); } break; - // equivalent to -t c + // ?man -c: print count or perform stdout action case 'c': if (strchr("\a\b\t\n\v\f\r\0", *s)) { printf(" %3s", escdict[*s]); @@ -214,9 +214,8 @@ usage(void) "[-j skip] [-t outputformat] [file ...]\n", argv0); } -// ?man od: octal dump -// ?man od writes an octal dump of each file to stdout. -// ?man If no file is given od reads from stdin. +// ?man od: dump files in formats +// ?man display file contents in octal, hex, or other formats int main(int argc, char *argv[]) { @@ -227,72 +226,65 @@ main(int argc, char *argv[]) big_endian = (*(uint16_t *)"\0\xff" == 0xff); ARGBEGIN { - // ?man -A:addressformat: addressformat is one of d|o|x|n and sets the address to be - // ?man either in decimal, octal, hexadecimal or not printed at all. - // ?man The default is octal. + // ?man -A:str: specify option flag case 'A': s = EARGF(usage()); if (strlen(s) != 1 || !strchr("doxn", s[0])) usage(); addr_format = s[0]; break; - // ?man -b: Equivalent to -t o1 . + // ?man -b: specify block size or base directory case 'b': addtype('o', 1); break; - // ?man -d: Equivalent to -t u2 . + // ?man -d: specify directory case 'd': addtype('u', 2); break; #if FEATURE_OD_ENDIAN - // ?man -E: Force Little Endian ( e ) or Big Endian ( E ) system-independently. + // ?man -E: specify option flag case 'E': - // ?man -e: Force Little Endian ( e ) or Big Endian ( E ) system-independently. + // ?man -e: specify expression or pattern case 'e': big_endian = (ARGC() == 'E'); break; #endif - // ?man -j:skip: Ignore the first skip bytes of input. + // ?man -j:str: specify option flag case 'j': if ((skip = parseoffset(EARGF(usage()))) < 0) usage(); break; - // ?man -N:num: read at most num bytes of input + // ?man -N:str: specify option flag case 'N': if ((max = parseoffset(EARGF(usage()))) < 0) usage(); break; - // ?man -o: Equivalent to -t o2 . + // ?man -o: specify output file case 'o': addtype('o', 2); break; - // ?man -s: Equivalent to -t d2 . + // ?man -s: silent mode or print summary case 's': addtype('d', 2); break; - // ?man -t:outputformat: outputformat is a list of a|c|d|o|u|x followed by a digit or C|S|I|L and sets - // ?man the content to be in named character, character, signed - // ?man decimal, octal, unsigned decimal, or - // ?man hexadecimal format, processing the given amount of bytes or the length - // ?man of Char, Short, Integer or Long. - // ?man The default is octal with 4 bytes. + // ?man -t:str: sort or specify timestamp case 't': s = EARGF(usage()); for (; *s; s++) { switch (*s) { - /* outputformat a is equivalent to -t a */ + // ?man -a: print or show all entries case 'a': - /* outputformat c is equivalent to -t c */ + // ?man -c: print count or perform stdout action case 'c': addtype(*s, 1); break; - /* outputformat d is equivalent to -t d */ + // ?man -d: specify directory case 'd': - /* outputformat o is equivalent to -t o */ + // ?man -o: specify output file case 'o': - /* outputformat u is equivalent to -t u */ + // ?man -u: unbuffered output case 'u': - /* outputformat x is equivalent to -t x */ + // ?man -x: hex format or match whole lines case 'x': fmt_char = *s; if (isdigit((unsigned char)*(s + 1))) { @@ -300,22 +292,22 @@ main(int argc, char *argv[]) s = end - 1; } else { switch (*(s + 1)) { - /* outputformat C uses sizeof(char) bytes */ + // ?man -C: specify option flag case 'C': len = sizeof(char); s++; break; - /* outputformat S uses sizeof(short) bytes */ + // ?man -S: specify option flag case 'S': len = sizeof(short); s++; break; - /* outputformat I uses sizeof(int) bytes */ + // ?man -I: specify option flag case 'I': len = sizeof(int); s++; break; - /* outputformat L uses sizeof(long) bytes */ + // ?man -L: specify option flag case 'L': len = sizeof(long); s++; @@ -331,12 +323,11 @@ main(int argc, char *argv[]) } } break; - // ?man -v: Always set. - // ?man Write all input data, including duplicate lines. + // ?man -v: verbose mode; show progress case 'v': /* always set, use uniq(1) to handle duplicate lines */ break; - // ?man -x: Equivalent to -t x2 . + // ?man -x: hex format or match whole lines case 'x': addtype('x', 2); break; diff --git a/cmd/posix/paste.c b/cmd/posix/paste.c @@ -99,11 +99,11 @@ main(int argc, char *argv[]) char *delim = "\t"; ARGBEGIN { - // ?man -s: read each file sequentially instead of in parallel + // ?man -s: silent mode or print summary case 's': seq = 1; break; - // ?man -d:list: replace newlines using escaped characters from list + // ?man -d:str: specify directory case 'd': delim = EARGF(usage()); delim_bytelen = unescape(delim); diff --git a/cmd/posix/pathchk.c b/cmd/posix/pathchk.c @@ -89,11 +89,11 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -p: check pathnames for portability across POSIX systems + // ?man -p: preserve file attributes case 'p': most = 1; break; - // ?man -P: also reject empty pathnames and leading hyphens + // ?man -P: specify option flag case 'P': extra = 1; break; diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c @@ -846,9 +846,11 @@ readpax(struct bufio *f, struct header *h) case 'g': readexthdr(f, &globexthdr, h->size); break; + // ?man -x: hex format or match whole lines case 'x': readexthdr(f, &exthdr, h->size); break; + // ?man -L: specify option flag case 'L': if ((exthdr.delete | opt.delete) & PATH) break; @@ -2082,7 +2084,9 @@ parsereplstr(char *str) for (;;) { switch (*++str) { case 'g': r->global = 1; break; + // ?man -p: preserve file attributes case 'p': r->print = 1; break; + // ?man -s: silent mode or print summary case 's': r->symlink = 0; break; case 'S': r->symlink = 1; break; case 0: goto done; @@ -2329,10 +2333,6 @@ handle_append(const char *filename, const char *algo, const char *format) } // ?man pax: portable archive interchange -// ?man synopsis: [-cdiknuvX] [-f archive] [-o options] [-p string] [-s replstr] [pattern ...] -// ?man synopsis: -r [-cdiknuvX] [-f archive] [-o options] [-p string] [-s replstr] [pattern ...] -// ?man synopsis: -w [-adituvX] [-b blocksize] [-f archive] [-o options] [-x format] [-j | -J | -z] [file ...] -// ?man synopsis: -rw [-diklntuvX] [-H | -L] [-p string] [-s replstr] [file ...] directory // ?man read, write, and list member files of archive files int main(int argc, char *argv[]) @@ -2349,108 +2349,113 @@ main(int argc, char *argv[]) size_t l; ARGBEGIN { - // ?man -a: append files to the end of an existing archive + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -b:blocksize: accepted for compatibility; block size is currently ignored + // ?man -b:str: specify block size or base directory case 'b': EARGF(usage()); break; - // ?man -c: invert the sense of path matching + // ?man -c: print count or perform stdout action case 'c': cflag = 1; break; - // ?man -d: do not match pathnames of directory entries against patterns + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -f:archive: read from or write to archive instead of standard input or output + // ?man -f:str: force the operation case 'f': name = EARGF(usage()); break; - // ?man -H: follow symbolic links named on the command line + // ?man -H: specify option flag case 'H': follow = 'H'; break; - // ?man -i: rename or skip files interactively + // ?man -i: interactive mode or prompt for confirmation case 'i': iflag = 1; break; - // ?man -j: compress or decompress the archive with bzip2 + // ?man -j: specify option flag case 'j': algo = "bzip2"; break; - // ?man -J: compress or decompress the archive with xz + // ?man -J: specify option flag case 'J': algo = "xz"; break; - // ?man -k: do not overwrite existing files + // ?man -k: specify option flag case 'k': kflag = 1; break; - // ?man -l: link files instead of copying them during pass mode when possible + // ?man -l: list in long format case 'l': lflag = 1; break; - // ?man -L: follow all symbolic links + // ?man -L: specify option flag case 'L': follow = 'L'; break; - // ?man -n: use only the first archive member that matches each pattern + // ?man -n: print line numbers or counts case 'n': nflag = 1; break; - // ?man -o:options: set format-specific archive options + // ?man -o:str: specify output file case 'o': parseopts(EARGF(usage())); break; - // ?man -p:string: control which file attributes are preserved in pass mode + // ?man -p:str: preserve file attributes case 'p': for (arg = EARGF(usage()); *arg; ++arg) { switch (*arg) { + // ?man -a: print or show all entries case 'a': preserve &= ~ATIME; break; + // ?man -e: specify expression or pattern case 'e': preserve = ~0; break; + // ?man -m: specify mode or limit case 'm': preserve &= ~MTIME; break; + // ?man -o: specify output file case 'o': preserve |= UID | GID; break; + // ?man -p: preserve file attributes case 'p': preserve |= MODE; break; default: fatal("unknown -p option"); } } break; - // ?man -r: read an archive and extract matching members + // ?man -r: operate recursively case 'r': mode |= READ; break; - // ?man -s:replstr: rename archive members or files using a substitution expression + // ?man -s:str: silent mode or print summary case 's': parsereplstr(EARGF(usage())); break; - // ?man -t: preserve access times of files read by pax + // ?man -t: sort or specify timestamp case 't': tflag = 1; break; - // ?man -u: copy or extract only files newer than existing destination files + // ?man -u: unbuffered output case 'u': uflag = 1; break; - // ?man -v: write verbose filenames while processing files + // ?man -v: verbose mode; show progress case 'v': vflag = 1; break; - // ?man -w: write an archive or enter pass mode + // ?man -w: wait for completion case 'w': mode |= WRITE; break; - // ?man -x:format: use the archive format format + // ?man -x:str: hex format or match whole lines case 'x': format = EARGF(usage()); break; - // ?man -X: stay on the current file system when descending directories + // ?man -X: specify option flag case 'X': Xflag = 1; break; - // ?man -z: compress or decompress the archive with gzip + // ?man -z: specify option flag case 'z': algo = "gzip"; break; diff --git a/cmd/posix/printf.c b/cmd/posix/printf.c @@ -75,7 +75,7 @@ usage(void) } // ?man printf: format and print data -// ?man arguments: format [arg ...] +// ?man arguments: format [arg ... // ?man format and print arguments to standard output int main(int argc, char *argv[]) diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c @@ -150,29 +150,29 @@ usage(void) eprintf("usage: %s [-aAdef]\n", argv0); } -// ?man ps: display process status -// ?man ps displays information about active processes. When given no options, ps prints information about processes of the current user that has a controlling terminal. +// ?man ps: report process status +// ?man display information about active system processes int main(int argc, char *argv[]) { ARGBEGIN { - // ?man -a: Select all processes except both session leaders and processes not associated with a terminal. + // ?man -a: print or show all entries case 'a': flags |= PS_aflag; break; - // ?man -A: Select all processes. Identical to -e. + // ?man -A: specify option flag case 'A': flags |= PS_Aflag; break; - // ?man -d: Select all processes except session leaders. + // ?man -d: specify directory case 'd': flags |= PS_dflag; break; - // ?man -e: Select all processes. Identical to -A. + // ?man -e: specify expression or pattern case 'e': flags |= PS_Aflag; break; - // ?man -f: Do full-format listing. + // ?man -f: force the operation case 'f': flags |= PS_fflag; break; diff --git a/cmd/posix/pwd.c b/cmd/posix/pwd.c @@ -38,9 +38,9 @@ main(int argc, char *argv[]) char mode = 'L'; ARGBEGIN { - // ?man -L: print the logical path using PWD when possible + // ?man -L: specify option flag case 'L': - // ?man -P: print the physical path with all symbolic links resolved + // ?man -P: specify option flag case 'P': mode = ARGC(); break; diff --git a/cmd/posix/readlink.c b/cmd/posix/readlink.c @@ -35,12 +35,12 @@ main(int argc, char *argv[]) ARGBEGIN { #if FEATURE_READLINK_REALPATH - // ?man -f: canonicalize path by following every symbolic link in its components + // ?man -f: force the operation case 'f': fflag = 1; break; #endif - // ?man -n: do not print the trailing newline + // ?man -n: print line numbers or counts case 'n': nflag = 1; break; diff --git a/cmd/posix/renice.c b/cmd/posix/renice.c @@ -55,19 +55,19 @@ main(int argc, char *argv[]) int who; ARGBEGIN { - // ?man -n:num: change niceness by num + // ?man -n:str: print line numbers or counts case 'n': adj = EARGF(usage()); break; - // ?man -g: treat each id as a process group ID + // ?man -g: specify option flag case 'g': which = PRIO_PGRP; break; - // ?man -p: treat each id as a process ID + // ?man -p: preserve file attributes case 'p': which = PRIO_PROCESS; break; - // ?man -u: treat each id as a user name or user ID + // ?man -u: unbuffered output case 'u': which = PRIO_USER; break; diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c @@ -1750,10 +1750,8 @@ old_next(void) } // ?man sed: stream editor -// ?man synopsis: [-nrE] script [file ...] -// ?man synopsis: [-nrE] -e script [-e script] ... [-f scriptfile] ... [file ...] -// ?man synopsis: [-nrE] [-e script] ... -f scriptfile [-f scriptfile] ... [file ...] -// ?man sed reads line oriented output from file or stdin, applies the editing commands supplied by script or scriptfile and writes the edited stream to stdout. +// ?man arguments: script [file ... +// ?man stream editor for filtering and transforming text int main(int argc, char *argv[]) { @@ -1761,30 +1759,30 @@ main(int argc, char *argv[]) int script = 0; ARGBEGIN { - // ?man -n: Suppress default printing at the end of each cycle. + // ?man -n: print line numbers or counts case 'n': gflags.n = 1; break; - // ?man -r: Use extended regular expressions + // ?man -r: operate recursively case 'r': - // ?man -E: Use extended regular expressions + // ?man -E: specify option flag case 'E': gflags.E = 1; break; - // ?man -e:script: Append script to the list of editing commands. + // ?man -e:str: specify expression or pattern case 'e': arg = EARGF(usage()); compile(arg, 0); script = 1; break; - // ?man -f:scriptfile: Append the commands from scriptfile to the list of editing commands. + // ?man -f:str: force the operation case 'f': arg = EARGF(usage()); compile(arg, 1); script = 1; break; #if FEATURE_SED_INPLACE - // ?man -i: edit files in place + // ?man -i: interactive mode or prompt for confirmation case 'i': iflag = 1; if (argv[0][1] != '\0') { @@ -1798,77 +1796,6 @@ main(int argc, char *argv[]) default : usage(); } ARGEND - // ?man ## Extended description - // ?man Editing commands take the form - // ?man - // ?man `[address[,address]]function` - // ?man - // ?man ### Addresses - // ?man Addresses are either blank, a positive decimal integer denoting a line - // ?man number, the character '$' denoting the last line of input, or a regular - // ?man expression. - // ?man A command with no addresses matches every line, one address matches - // ?man individual lines, and two addresses matches a range of lines from the - // ?man first to the second address inclusive. - // ?man ### Functions - // ?man `a [text]` - // ?man : Append text to output after end of current cycle. - // ?man `b [label]` - // ?man : Branch to label. If no label is provided branch to end of script. - // ?man `c [text]` - // ?man : Change. Delete addressed range and output text after end of current cycle. - // ?man `d` - // ?man : Delete pattern space and begin next cycle. - // ?man `D` - // ?man : Delete pattern space up to and including first newline and begin new cycle without reading input. If there is no newline, behave like d. - // ?man `g` - // ?man : Get. Replace the pattern space with the hold space. - // ?man `G` - // ?man : Get. Append a newline and the hold space to the pattern space. - // ?man `h` - // ?man : Hold. Replace the hold space with the pattern space. - // ?man `H` - // ?man : Hold. Append a newline and the pattern space to the hold space. - // ?man `i [text]` - // ?man : Insert text in output. - // ?man `l` - // ?man : List? Write the pattern space replacing known non printing characters with backslash escaped versions (`\\\\`, `\\a`, `\\b`, `\\f`, `\\r`, `\\t`, `\\v`). Print bad UTF-8 sequences as `\\ooo` where ooo is a three digit octal number. Mark end of lines with '$'. - // ?man `n` - // ?man : Next. Write pattern space (unless `-n`), read next line into pattern space, and continue current cycle. If there is no next line, quit. - // ?man `N` - // ?man : Next. Read next line, append newline and next line to pattern space, and continue cycle. If there is no next line, quit without printing current pattern space. - // ?man `p` - // ?man : Print current pattern space. - // ?man `P` - // ?man : Print current pattern space up to first newline. - // ?man `q` - // ?man : Quit. - // ?man `r file` - // ?man : Read file and write contents to output. - // ?man `s/re/text/flags` - // ?man : Find occurences of regular expression re in the pattern space and replace with text. A '&' in text is replaced with the entire match. A `\\d` where d is a decimal digit 1-9 is replaced with the corresponding match group from the regular expression. `\\n` represents a newline in both the regular expression and replacement text. A literal newline in the replacement text must be preceded by a `\\`. - // ?man ### Flags - // ?man `n` - // ?man : A positive decimal number denoting which match in the pattern space to replace. - // ?man `g` - // ?man : Global. Replace all matches in the pattern space. - // ?man `p` - // ?man : Print the pattern if a replacement was made. - // ?man `w file` - // ?man : Write the pattern space to file if a replacement was made. - // ?man `t [label]` - // ?man : Test. Branch to corresponding label if a substitution has been made since the last line was read or last t command was executed. If no label is provided branch to end of script. - // ?man `w file` - // ?man : Write pattern space to file. - // ?man `x` - // ?man : Exchange hold space and pattern space. - // ?man `y/set1/set2/` - // ?man : Replace each occurrence of a character from set 1 with the corresponding character from set 2. - // ?man `:label` - // ?man : Create a label for b and t commands. - // ?man `=` - // ?man : Write current input line number to output. - /* no script to run */ if (!script && !argc) usage(); diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c @@ -305,27 +305,27 @@ parse_flags(char **s, int *flags, int bflag) { while (isalpha((int)**s)) { switch (*((*s)++)) { - /* parse key-specific b modifier */ + // ?man -b: specify block size or base directory case 'b': *flags |= bflag; break; - /* parse key-specific d modifier */ + // ?man -d: specify directory case 'd': *flags |= MOD_D; break; - /* parse key-specific f modifier */ + // ?man -f: force the operation case 'f': *flags |= MOD_F; break; - /* parse key-specific i modifier */ + // ?man -i: interactive mode or prompt for confirmation case 'i': *flags |= MOD_I; break; - /* parse key-specific n modifier */ + // ?man -n: print line numbers or counts case 'n': *flags |= MOD_N; break; - /* parse key-specific r modifier */ + // ?man -r: operate recursively case 'r': *flags |= MOD_R; break; @@ -396,9 +396,8 @@ usage(void) } // ?man sort: sort lines -// ?man synopsis: [-Cbcdfimnru] [-o outfile] [-t delim] [-k key ...] [file ...] -// ?man sort writes the sorted concatenation of each file to stdout. -// ?man If no file is given sort reads from stdin. +// ?man arguments: -Cbcdfimnru +// ?man sort or merge lines of text files int main(int argc, char *argv[]) { @@ -409,44 +408,35 @@ main(int argc, char *argv[]) char *outfile = NULL; ARGBEGIN { - // ?man -C: Check that the concatenation of the given files is sorted rather than sorting them. - // ?man In this mode, no output is printed to stdout, and the exit status indicates the result of the check. + // ?man -C: specify option flag case 'C': Cflag = 1; break; - // ?man -b: Skip leading whitespace of columns when sorting. + // ?man -b: specify block size or base directory case 'b': global_flags |= MOD_STARTB | MOD_ENDB; break; - // ?man -c: The same as -C except that when disorder is detected, a message is written to stderr indicating the location of the disorder. + // ?man -c: print count or perform stdout action case 'c': cflag = 1; break; - // ?man -d: Skip non-whitespace and non-alphanumeric characters. + // ?man -d: specify directory case 'd': global_flags |= MOD_D; break; - // ?man -f: Ignore letter case when sorting. + // ?man -f: force the operation case 'f': global_flags |= MOD_F; break; - // ?man -i: Skip non-printable characters. + // ?man -i: interactive mode or prompt for confirmation case 'i': global_flags |= MOD_I; break; - // ?man -k:key: Specify a key definition of the form S[.s][f][,E[.e][f]] where S, - // ?man s, E and e are the starting column, starting character in that column, - // ?man ending column and the ending character of that column respectively. - // ?man If they are not specified, s refers to the first character of the - // ?man specified starting column, E refers to the last column of every line, - // ?man and e refers to the last character of the ending column. - // ?man f can be used to specify options (n, b) that only apply to this key - // ?man definition. - // ?man b is special in that it only applies to the column that it was specified after. + // ?man -k:str: specify option flag case 'k': addkeydef(EARGF(usage()), global_flags); break; - // ?man -m: Assume sorted input, merge only. + // ?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 @@ -454,37 +444,37 @@ main(int argc, char *argv[]) * while merging large sorted files. */ break; - // ?man -n: Perform a numeric sort. + // ?man -n: print line numbers or counts case 'n': global_flags |= MOD_N; break; - // ?man -o:outfile: Write output to outfile rather than stdout. + // ?man -o:file: specify output file case 'o': outfile = EARGF(usage()); break; - // ?man -r: Reverses the sort. + // ?man -r: operate recursively case 'r': global_flags |= MOD_R; break; #if FEATURE_SORT_STABLE - // ?man -s: stabilize the sort by preserving the input order of equal lines + // ?man -s: silent mode or print summary case 's': sflag = 1; break; #endif - // ?man -t:delim: Set delim as the field delimiter. + // ?man -t:str: sort or specify timestamp case 't': fieldsep = EARGF(usage()); if (!*fieldsep) eprintf("empty delimiter\n"); fieldseplen = unescape(fieldsep); break; - // ?man -u: Print equal lines only once. + // ?man -u: unbuffered output case 'u': uflag = 1; break; #if FEATURE_SORT_BIG - // ?man -z: treat input as NUL-separated records + // ?man -z: specify option flag case 'z': zflag = 1; break; diff --git a/cmd/posix/split.c b/cmd/posix/split.c @@ -47,7 +47,7 @@ usage(void) } // ?man split: split file into pieces -// ?man arguments: [file] [prefix] +// ?man arguments: | -l num // ?man split a file into fixed-size pieces int main(int argc, char *argv[]) @@ -58,11 +58,11 @@ main(int argc, char *argv[]) char name[NAME_MAX + 1], *prefix = "x", *file = NULL; ARGBEGIN { - // ?man -a:num: use num characters for generated filename suffixes + // ?man -a:num: print or show all entries case 'a': slen = estrtonum(EARGF(usage()), 0, INT_MAX); break; - // ?man -b:num: start a new file every num bytes + // ?man -b:str: specify block size or base directory case 'b': always = 1; if ((size = parseoffset(EARGF(usage()))) < 0) @@ -70,12 +70,12 @@ main(int argc, char *argv[]) if (!size) eprintf("size needs to be positive\n"); break; - // ?man -d: use decimal suffixes instead of alphabetic ones + // ?man -d: specify directory case 'd': base = 10; start = '0'; break; - // ?man -l:num: start a new file every num lines + // ?man -l:num: list in long format case 'l': always = 0; size = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SSIZE_MAX)); diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c @@ -168,15 +168,15 @@ main(int argc, char *argv[]) int (*tail)(int, const char *, size_t) = taketail; ARGBEGIN { - // ?man -f: continue writing appended data as the file grows + // ?man -f: force the operation case 'f': fflag = 1; break; - // ?man -c:num: display the last num bytes of each file + // ?man -c: print count or perform stdout action case 'c': - // ?man -m:num: display the last num characters of each file + // ?man -m: specify mode or limit case 'm': - // ?man -n:num: display the last num lines of each file + // ?man -n:num: print line numbers or counts case 'n': mode = ARGC(); numstr = EARGF(usage()); @@ -185,7 +185,7 @@ main(int argc, char *argv[]) if (strchr(numstr, '+')) tail = dropinit; break; - // ?man -num: display the last num lines of each file + // ?man ARGNUM: specify RGNUM option ARGNUM: n = ARGNUMF(); break; diff --git a/cmd/posix/tee.c b/cmd/posix/tee.c @@ -26,11 +26,11 @@ main(int argc, char *argv[]) char buf[BUFSIZ]; ARGBEGIN { - // ?man -a: append to each file instead of overwriting it + // ?man -a: print or show all entries case 'a': aflag = O_APPEND; break; - // ?man -i: ignore SIGINT + // ?man -i: interactive mode or prompt for confirmation case 'i': iflag = 1; break; diff --git a/cmd/posix/time.c b/cmd/posix/time.c @@ -17,7 +17,7 @@ usage(void) } // ?man time: time command execution -// ?man arguments: cmd [arg ...] +// ?man arguments: cmd [arg ... // ?man run a command and report its execution duration int main(int argc, char *argv[]) @@ -29,7 +29,7 @@ main(int argc, char *argv[]) int status, savederrno, ret = 0; ARGBEGIN { - // ?man -p: use the portable output format "real %f\\nuser %f\\nsys %f\\n" + // ?man -p: preserve file attributes case 'p': break; default: diff --git a/cmd/posix/touch.c b/cmd/posix/touch.c @@ -116,26 +116,26 @@ main(int argc, char *argv[]) char *ref = NULL; ARGBEGIN { - // ?man -a: change only the access time + // ?man -a: print or show all entries case 'a': aflag = 1; break; - // ?man -c: do not create files that do not exist + // ?man -c: print count or perform stdout action case 'c': cflag = 1; break; - // ?man -d: set the timestamp from a parsed date string + // ?man -d: specify directory case 'd': - // ?man -t:time: set the timestamp from [[CC]YY]MMDDhhmm[.SS] + // ?man -t:str: sort or specify timestamp case 't': times[0].tv_sec = parsetime(EARGF(usage())); times[0].tv_nsec = 0; break; - // ?man -m: change only the modification time + // ?man -m: specify mode or limit case 'm': mflag = 1; break; - // ?man -r:ref_file: use the timestamps from ref_file + // ?man -r:str: operate recursively case 'r': ref = EARGF(usage()); if (stat(ref, &st) < 0) @@ -143,7 +143,7 @@ main(int argc, char *argv[]) times[0] = st.st_atim; times[1] = st.st_mtim; break; - // ?man -T:time: set the timestamp from seconds since the Unix epoch + // ?man -T:num: specify option flag case 'T': times[0].tv_sec = estrtonum(EARGF(usage()), 0, LLONG_MAX); times[0].tv_nsec = 0; diff --git a/cmd/posix/tr.c b/cmd/posix/tr.c @@ -190,7 +190,7 @@ usage(void) } // ?man tr: translate characters -// ?man arguments: set1 [set2] +// ?man arguments: set1 [set2 // ?man translate, squeeze, or delete characters from standard input int main(int argc, char *argv[]) @@ -200,17 +200,17 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -c: use the complement of set1 + // ?man -c: print count or perform stdout action case 'c': - // ?man -C: use the complement of set1 + // ?man -C: specify option flag case 'C': cflag = 1; break; - // ?man -d: delete input characters that match set1 + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -s: squeeze repeated output characters that match set2, or set1 if -d is set + // ?man -s: silent mode or print summary case 's': sflag = 1; break; diff --git a/cmd/posix/uname.c b/cmd/posix/uname.c @@ -22,27 +22,27 @@ main(int argc, char *argv[]) int mflag = 0, nflag = 0, rflag = 0, sflag = 0, vflag = 0; ARGBEGIN { - // ?man -a: print all available system information + // ?man -a: print or show all entries case 'a': mflag = nflag = rflag = sflag = vflag = 1; break; - // ?man -m: print the machine hardware name + // ?man -m: specify mode or limit case 'm': mflag = 1; break; - // ?man -n: print the network node hostname + // ?man -n: print line numbers or counts case 'n': nflag = 1; break; - // ?man -r: print the operating system release + // ?man -r: operate recursively case 'r': rflag = 1; break; - // ?man -s: print the operating system name + // ?man -s: silent mode or print summary case 's': sflag = 1; break; - // ?man -v: print the operating system version + // ?man -v: verbose mode; show progress case 'v': vflag = 1; break; diff --git a/cmd/posix/unexpand.c b/cmd/posix/unexpand.c @@ -141,13 +141,13 @@ main(int argc, char *argv[]) char *tl = "8"; ARGBEGIN { - // ?man -t:list: use list as the tab size or tab stops + // ?man -t:str: sort or specify timestamp case 't': tl = EARGF(usage()); if (!*tl) eprintf("tablist cannot be empty\n"); /* fallthrough */ - // ?man -a: convert spaces to tabs throughout each line, not just leading blanks + // ?man -a: print or show all entries case 'a': aflag = 1; break; diff --git a/cmd/posix/uniq.c b/cmd/posix/uniq.c @@ -109,23 +109,23 @@ main(int argc, char *argv[]) char *fname[2] = { "<stdin>", "<stdout>" }; ARGBEGIN { - // ?man -c: prefix each output line with its number of consecutive occurrences + // ?man -c: print count or perform stdout action case 'c': countfmt = "%7ld "; break; - // ?man -d: print only duplicate lines + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -u: print only unique lines + // ?man -u: unbuffered output case 'u': uflag = 1; break; - // ?man -f:num: ignore the first num fields when comparing lines + // ?man -f:num: force the operation case 'f': fskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; - // ?man -s:num: ignore the first num characters when comparing lines + // ?man -s:num: silent mode or print summary case 's': sskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; diff --git a/cmd/posix/uuencode.c b/cmd/posix/uuencode.c @@ -99,7 +99,7 @@ usage(void) } // ?man uuencode: encode binary file -// ?man arguments: [file] name +// ?man arguments: file] name // ?man encode a binary file into ascii text int main(int argc, char *argv[]) diff --git a/cmd/posix/wc.c b/cmd/posix/wc.c @@ -79,19 +79,19 @@ main(int argc, char *argv[]) int ret = 0; ARGBEGIN { - // ?man -c: print the number of bytes + // ?man -c: print count or perform stdout action case 'c': cmode = 'c'; break; - // ?man -m: print the number of characters + // ?man -m: specify mode or limit case 'm': cmode = 'm'; break; - // ?man -l: print the number of lines + // ?man -l: list in long format case 'l': lflag = 1; break; - // ?man -w: print the number of words + // ?man -w: wait for completion case 'w': wflag = 1; break; diff --git a/cmd/posix/who.c b/cmd/posix/who.c @@ -17,8 +17,8 @@ usage(void) eprintf("usage: %s [-ml]\n", argv0); } -// ?man who: print who has logged on -// ?man who prints a list of who has logged on, their controlling tty, and the time at which they logged on. +// ?man who: show logged in users +// ?man display a list of users currently logged into the system int main(int argc, char *argv[]) { @@ -32,7 +32,7 @@ main(int argc, char *argv[]) time_t t; ARGBEGIN { - // ?man -m: Only show users on current tty. + // ?man -m: specify mode or limit case 'm': mflag = 1; tty = ttyname(0); @@ -41,7 +41,7 @@ main(int argc, char *argv[]) if ((ttmp = strrchr(tty, '/'))) tty = ttmp+1; break; - // ?man -l: Print LOGIN processes as well. + // ?man -l: list in long format case 'l': lflag = 1; break; diff --git a/cmd/posix/xargs.c b/cmd/posix/xargs.c @@ -263,21 +263,9 @@ usage(void) argv0); } -// ?man xargs: construct argument lists and execute command -// ?man synopsis: [-0prtx] [-E eofstr] [-I replstr] [-L maxlines] [-n num] [-P maxprocs] [-s num] [cmd [arg ...]] -// ?man xargs reads space, tab, newline and EOF delimited strings from stdin -// ?man and executes the specified cmd with the strings as arguments. -// ?man Any arguments specified on the command line are given to the command upon -// ?man each invocation, followed by some number of the arguments read from -// ?man stdin. -// ?man The command is repeatedly executed one or more times until stdin is exhausted. -// ?man Spaces, tabs and newlines may be embedded in arguments using single (`'') -// ?man or double (`"') quotes or backslashes ('\\'). -// ?man Single quotes escape all non-single quote characters, excluding newlines, up -// ?man to the matching single quote. -// ?man Double quotes escape all non-double quote characters, excluding newlines, up -// ?man to the matching double quote. -// ?man Any single character, including newlines, may be escaped by a backslash. +// ?man xargs: build and run command lines +// ?man arguments: -n +// ?man execute commands built from standard input arguments int main(int argc, char *argv[]) { @@ -295,45 +283,42 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -0: use NUL characters instead of blanks and newlines as argument separators + // ?man -0: specify option flag case '0': nulflag = 1; break; - // ?man -n:num: Use at most num arguments per command line. + // ?man -n:num: print line numbers or counts case 'n': nflag = 1; maxargs = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -p: prompt before running each constructed command line + // ?man -p: preserve file attributes case 'p': pflag = 1; break; - // ?man -r: Do not run the command if there are no arguments. - // ?man Normally the command is executed at least once even if there are no arguments. + // ?man -r: operate recursively case 'r': rflag = 1; break; - // ?man -s:num: Use at most num bytes per command line. + // ?man -s:num: silent mode or print summary case 's': argmaxsz = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -t: Write the command line to stderr before executing it. + // ?man -t: sort or specify timestamp case 't': tflag = 1; break; - // ?man -x: Terminate if the command line exceeds the system limit or the number of bytes given with the -s flag. + // ?man -x: hex format or match whole lines case 'x': xflag = 1; break; - // ?man -E:eofstr: Use eofstr as a logical EOF marker. + // ?man -E:str: specify option flag case 'E': eofstr = EARGF(usage()); break; - // ?man -I:replstr: Use replstr as the placeholder for the argument. - // ?man Sets the arguments count to 1 per command line. - // ?man It also implies the option x. + // ?man -I:str: specify option flag case 'I': Iflag = 1; xflag = 1; @@ -341,13 +326,13 @@ main(int argc, char *argv[]) maxargs = 1; replstr = EARGF(usage()); break; - // ?man -L:maxlines: use at most maxlines input lines per command line + // ?man -L:num: specify option flag case 'L': Lflag = 1; maxlines = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); break; - // ?man -P:maxprocs: run up to maxprocs commands at the same time + // ?man -P:num: specify option flag case 'P': maxprocs = estrtonum(EARGF(usage()), 1, MIN((unsigned long long)SIZE_MAX, (unsigned long long)LLONG_MAX)); diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c @@ -14,7 +14,7 @@ usage(void) } // ?man chroot: run command in new root -// ?man arguments: dir [cmd [arg ...]] +// ?man arguments: dir [cmd [arg ... // ?man run a command or shell with a substitute root directory int main(int argc, char *argv[]) diff --git a/cmd/pseudo/dmesg.c b/cmd/pseudo/dmesg.c @@ -31,9 +31,8 @@ usage(void) eprintf("usage: %s [-Ccr] [-n level]\n", argv0); } -// ?man dmesg: print or control the kernel ring buffer -// ?man dmesg examines or controls the kernel ring buffer. -// ?man By default it reads all the messages from the kernel ring buffer and prints them to stdout. +// ?man dmesg: print kernel ring buffer +// ?man display or control the kernel ring buffer messages int main(int argc, char *argv[]) { @@ -43,20 +42,19 @@ main(int argc, char *argv[]) long level; ARGBEGIN { - // ?man -C: Clear the ring buffer. + // ?man -C: specify option flag case 'C': if (clear_dmesg() < 0) eprintf("clear_dmesg:"); return 0; - // ?man -c: Clear the ring buffer after printing its contents. + // ?man -c: print count or perform stdout action case 'c': cflag = 1; break; - // ?man -r: Print the raw message buffer. + // ?man -r: operate recursively case 'r': break; - // ?man -n:level: Set the console level. - // ?man The log levels are defined in the file include/linux/kern_levels.h. + // ?man -n:num: print line numbers or counts case 'n': level = estrtol(EARGF(usage()), 10); if (set_console_level(level) < 0) @@ -90,4 +88,4 @@ main(int argc, char *argv[]) return 1; return 0; -} +} +\ No newline at end of file diff --git a/cmd/pseudo/flock.c b/cmd/pseudo/flock.c @@ -18,7 +18,7 @@ usage(void) } // ?man flock: manage locks -// ?man arguments: file cmd [arg ...] +// ?man arguments: file cmd [arg ... // ?man acquire or release locks from shell scripts int main(int argc, char *argv[]) diff --git a/cmd/pseudo/free.c b/cmd/pseudo/free.c @@ -23,27 +23,27 @@ usage(void) eprintf("usage: %s [-bkmg]\n", argv0); } -// ?man free: display amount of free and used memory in the system -// ?man free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel. +// ?man free: display memory usage +// ?man display the amount of free and used memory in the system int main(int argc, char *argv[]) { struct MemInfo mi; ARGBEGIN { - // ?man -b: Display the amount of memory in bytes. This is the default. + // ?man -b: specify block size or base directory case 'b': unit_shift = 0; break; - // ?man -k: Display the amount of memory in kilobytes. + // ?man -k: specify option flag case 'k': unit_shift = 10; break; - // ?man -m: Display the amount of memory in megabytes. + // ?man -m: specify mode or limit case 'm': unit_shift = 20; break; - // ?man -g: Display the amount of memory in gigabytes. + // ?man -g: specify option flag case 'g': unit_shift = 30; break; diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c @@ -27,7 +27,7 @@ usage(void) } // ?man getty: set terminal mode -// ?man arguments: [tty] [term] [cmd] [args ...] +// ?man arguments: tty] [term] [cmd] [args... // ?man set terminal line discipline, speed, and mode int main(int argc, char *argv[]) diff --git a/cmd/pseudo/login.c b/cmd/pseudo/login.c @@ -69,10 +69,9 @@ usage(void) eprintf("usage: %s [-p] username\n", argv0); } -// ?man login: log into the system +// ?man login: begin terminal session // ?man arguments: username -// ?man login logs the username into the system. -// ?man It sets HOME, SHELL, USER, LOGNAME and the PATH environment variables and invokes the login shell as specified in /etc/passwd. +// ?man authenticate and start a session on the system int main(int argc, char *argv[]) { @@ -84,7 +83,7 @@ main(int argc, char *argv[]) int pflag = 0; ARGBEGIN { - // ?man -p: Preserve the environment. + // ?man -p: preserve file attributes case 'p': pflag = 1; break; diff --git a/cmd/pseudo/md5sum.c b/cmd/pseudo/md5sum.c @@ -33,13 +33,13 @@ main(int argc, char *argv[]) uint8_t md[MD5_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/mktemp.c b/cmd/pseudo/mktemp.c @@ -27,11 +27,11 @@ main(int argc, char *argv[]) size_t len; ARGBEGIN { - // ?man -d: create a temporary directory instead of a file + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -p:directory: use directory as the path prefix and imply -t + // ?man -p:dir: preserve file attributes case 'p': pflag = 1; pdir = EARGF(usage()); @@ -40,11 +40,11 @@ main(int argc, char *argv[]) case 'q': qflag = 1; break; - // ?man -t: generate a path rooted in a temporary directory + // ?man -t: sort or specify timestamp case 't': tflag = 1; break; - // ?man -u: unlink the file before exiting + // ?man -u: unbuffered output case 'u': uflag = 1; break; diff --git a/cmd/pseudo/pidof.c b/cmd/pseudo/pidof.c @@ -28,9 +28,9 @@ usage(void) eprintf("usage: %s [-o pid1,pid2,...pidN] [-s] [program...]\n", argv0); } -// ?man pidof: find the process id of a running program -// ?man arguments: [program ...] -// ?man pidof finds the process id's of the named programs and prints them to stdout. +// ?man pidof: find process ids +// ?man arguments: -o pid1 +// ?man find the process identity numbers of running programs int main(int argc, char *argv[]) { @@ -44,11 +44,11 @@ main(int argc, char *argv[]) struct pidentry *pe; ARGBEGIN { - // ?man -s: Single shot - this instructs the program to only return one process id. + // ?man -s: silent mode or print summary case 's': sflag = 1; break; - // ?man -o:pid: Tell pidof to omit processes with that process id. The special pid %PPID can be used to name the parent process of the pidof program. + // ?man -o:str: specify output file case 'o': oflag = 1; arg = EARGF(usage()); diff --git a/cmd/pseudo/respawn.c b/cmd/pseudo/respawn.c @@ -32,7 +32,7 @@ usage(void) } // ?man respawn: restart command on exit -// ?man arguments: cmd [args ...] +// ?man arguments: cmd [args... // ?man run a command and restart it automatically when it exits int main(int argc, char *argv[]) diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c @@ -90,17 +90,17 @@ main(int argc, char *argv[]) const char *starts = "1", *steps = "1", *ends = "1", *sep = "\n"; ARGBEGIN { - // ?man -f:fmt: use fmt as the output format + // ?man -f:str: force the operation case 'f': if (!validfmt(tmp=EARGF(usage()))) eprintf("%s: invalid format\n", tmp); fmt = tmp; break; - // ?man -s:sep: print sep between output numbers + // ?man -s:str: silent mode or print summary case 's': sep = EARGF(usage()); break; - // ?man -w: pad all numbers to the same width + // ?man -w: wait for completion case 'w': wflag = 1; break; diff --git a/cmd/pseudo/setsid.c b/cmd/pseudo/setsid.c @@ -15,7 +15,7 @@ usage(void) } // ?man setsid: run in new session -// ?man arguments: cmd [arg ...] +// ?man arguments: cmd [arg ... // ?man run a program in a new session int main(int argc, char *argv[]) diff --git a/cmd/pseudo/sha1sum.c b/cmd/pseudo/sha1sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA1_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha224sum.c b/cmd/pseudo/sha224sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA224_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha256sum.c b/cmd/pseudo/sha256sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA256_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha384sum.c b/cmd/pseudo/sha384sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA384_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512-224sum.c b/cmd/pseudo/sha512-224sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_224_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512-256sum.c b/cmd/pseudo/sha512-256sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_256_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/sha512sum.c b/cmd/pseudo/sha512sum.c @@ -32,13 +32,13 @@ main(int argc, char *argv[]) uint8_t md[SHA512_DIGEST_LENGTH]; ARGBEGIN { - // ?man -b: accepted for compatibility; ignored + // ?man -b: specify block size or base directory case 'b': - // ?man -t: accepted for compatibility; ignored + // ?man -t: sort or specify timestamp case 't': /* ignore */ break; - // ?man -c: read checksums from files and verify them + // ?man -c: print count or perform stdout action case 'c': cryptfunc = cryptcheck; break; diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -801,8 +801,8 @@ usage(void) } // ?man tar: tape archiver -// ?man synopsis: [x | t | -x | -t] [-C dir] [-J | -Z | -a | -j | -z] [-m] [-p] [-f file] [file ...] -// ?man synopsis: [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] path ... [-f file] +// ?man arguments: x | t | -x | -t] [file ... +// ?man tar [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] [-T file] [-X file] path ... [-f file] // ?man manipulate tape archive files int main(int argc, char *argv[]) @@ -834,32 +834,32 @@ main(int argc, char *argv[]) case 't': mode = ARGC(); break; - // ?man -C:dir: change to dir before processing files + // ?man -C:dir: specify option flag case 'C': dir = EARGF(usage()); break; - // ?man -f:file: use file as the archive instead of standard input or output + // ?man -f:file: specify archive file case 'f': file = EARGF(usage()); break; - // ?man -m: do not preserve modification times when extracting + // ?man -m: specify mode or limit case 'm': mflag = 1; break; - // ?man -J: use xz compression or decompression + // ?man -J: specify option flag case 'J': - // ?man -Z: use compress compression or decompression + // ?man -Z: specify option flag case 'Z': - // ?man -a: use lzma compression or decompression + // ?man -a: print or show all entries case 'a': - // ?man -j: use bzip2 compression or decompression + // ?man -j: specify option flag case 'j': - // ?man -z: use gzip compression or decompression + // ?man -z: specify option flag case 'z': filtermode = ARGC(); filtertool = filtertools[filtermode]; break; - // ?man -h: follow symbolic links when archiving + // ?man -h: suppress headers or print help case 'h': #if FEATURE_TAR_CREATE r.follow = 'L'; @@ -869,7 +869,7 @@ main(int argc, char *argv[]) case 'v': vflag = 1; break; - // ?man -p: preserve permissions; this is the default behavior + // ?man -p: preserve file attributes case 'p': break; /* do nothing as already default behaviour */ #if FEATURE_TAR_TO_STDOUT diff --git a/cmd/pseudo/truncate.c b/cmd/pseudo/truncate.c @@ -16,9 +16,9 @@ usage(void) eprintf("usage: %s [-c] -s size file...\n", argv0); } -// ?man truncate: shrink or extend the size of a file to the specified size -// ?man synopsis: [-c] -s size file ... -// ?man truncate shrinks or extends the size of each file specified size. A file argument that does not exist is created. If a file is larger than the specified size, the extra data is lost. If a file is shorter, it is extended and the extended part reads as zero bytes. +// ?man truncate: set file size +// ?man arguments: -s size file... +// ?man shrink or extend a file to a specified size int main(int argc, char *argv[]) { @@ -27,12 +27,12 @@ main(int argc, char *argv[]) long size = 0; ARGBEGIN { - // ?man -s:size: Set or adjust the file size by size bytes. + // ?man -s:num: silent mode or print summary case 's': sflag = 1; size = estrtol(EARGF(usage()), 10); break; - // ?man -c: Do not create any files. + // ?man -c: print count or perform stdout action case 'c': cflag = 1; break; diff --git a/cmd/pseudo/which.c b/cmd/pseudo/which.c @@ -80,7 +80,7 @@ main(int argc, char *argv[]) int found = 0, foundall = 1; ARGBEGIN { - // ?man -a: search all PATH directories instead of stopping at the first match + // ?man -a: print or show all entries case 'a': aflag = 1; break; diff --git a/cmd/pseudo/xinstall.c b/cmd/pseudo/xinstall.c @@ -85,9 +85,7 @@ usage(void) } // ?man xinstall: copy files and set attributes -// ?man synopsis: [-g group] [-o owner] [-m mode] -d dir ... -// ?man synopsis: [-g group] [-o owner] [-m mode] [-D] -t dest source ... -// ?man synopsis: [-g group] [-o owner] [-m mode] [-D] source ... dest +// ?man arguments: (-d dir ... | (-t dest source ... | source ... dest)) // ?man copy files and set their permissions and ownership int main(int argc, char *argv[]) @@ -103,35 +101,35 @@ main(int argc, char *argv[]) char *p; ARGBEGIN { - // ?man -c: accepted for compatibility; has no effect + // ?man -c: print count or perform stdout action case 'c': /* no-op for compatibility */ break; - // ?man -d: create directories instead of installing files + // ?man -d: specify directory case 'd': dflag = 1; break; - // ?man -D: create leading directories for the destination before installing + // ?man -D: specify option flag case 'D': Dflag = 1; break; - // ?man -s: accepted for compatibility; has no effect + // ?man -s: silent mode or print summary case 's': /* no-op for compatibility */ break; - // ?man -g:group: set the installed file group to group + // ?man -g:str: specify option flag case 'g': gflag = EARGF(usage()); break; - // ?man -o:owner: set the installed file owner to owner + // ?man -o:str: specify output file case 'o': oflag = EARGF(usage()); break; - // ?man -m:mode: set the installed file mode to mode + // ?man -m:str: specify mode or limit case 'm': mflag = EARGF(usage()); break; - // ?man -t:dest: install source files into the destination directory dest + // ?man -t:str: sort or specify timestamp case 't': tflag = EARGF(usage()); break; diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c @@ -24,7 +24,7 @@ usage(void) } // ?man mknod: create special files -// ?man arguments: name <type> major minor +// ?man arguments: name b|c|u major minor // ?man create block or character special files int main(int argc, char *argv[]) diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c @@ -25,11 +25,9 @@ usage(void) eprintf("usage: %s [-lp] [username]\n", argv0); } -// ?man su: run a command with a substitute user and group ID +// ?man su: run command with substitute user id // ?man arguments: username -// ?man su allows to run commands with a substitute user and group ID. -// ?man When called without arguments, su defaults to running an interactive shell as root. -// ?man For backward compatibility su defaults to not change the current directory and to only set the environment variables HOME and SHELL plus USER and LOGNAME if the target username is not root. +// ?man run a shell or command with another user id int main(int argc, char *argv[]) { @@ -40,11 +38,11 @@ main(int argc, char *argv[]) uid_t uid; ARGBEGIN { - // ?man -l: Starts the shell as login shell with an environment similar to a real login. + // ?man -l: list in long format case 'l': lflag = 1; break; - // ?man -p: Preserves the whole environment. This option is ignored if the -l option is specified. + // ?man -p: preserve file attributes case 'p': pflag = 1; break; diff --git a/config.mk b/config.mk @@ -1,5 +1,4 @@ -VERSION = 2026-06-08T05-53-UTC-03 - +VERSION = 2026-06-17T10-19-UTC PREFIX = /usr/local MANPREFIX = $(PREFIX)/share/man @@ -7,7 +6,7 @@ RANLIB = ranlib AR = ar ARFLAGS = rc -# build toggles for groups of binaries +# build toggles BUILD_POSIX = 1 BUILD_LINUX = 1 BUILD_NET = 1 @@ -15,7 +14,7 @@ BUILD_XSI = 1 BUILD_PSEUDO = 1 BUILD_DEV = 0 -# posix tools +# include all sub-targets BUILD_POSIX_BASENAME = $(BUILD_POSIX) BUILD_POSIX_CAL = $(BUILD_POSIX) BUILD_POSIX_CAT = $(BUILD_POSIX) @@ -177,20 +176,25 @@ BUILD_PSEUDO_XINSTALL = $(BUILD_PSEUDO) BUILD_PSEUDO_YES = $(BUILD_PSEUDO) BUILD_PSEUDO_BASE64 = $(BUILD_PSEUDO) BUILD_PSEUDO_B3SUM = $(BUILD_PSEUDO) +BUILD_PSEUDO_BLKID = $(BUILD_PSEUDO) +BUILD_PSEUDO_LSBLK = $(BUILD_PSEUDO) +BUILD_PSEUDO_FDISK = $(BUILD_PSEUDO) BUILD_PSEUDO_DMESG = $(BUILD_PSEUDO) BUILD_PSEUDO_FALLOCATE = $(BUILD_PSEUDO) BUILD_PSEUDO_FREE = $(BUILD_PSEUDO) BUILD_PSEUDO_PIDOF = $(BUILD_PSEUDO) BUILD_PSEUDO_PWDX = $(BUILD_PSEUDO) BUILD_PSEUDO_UPTIME = $(BUILD_PSEUDO) + +# dev tools BUILD_DEV_AR = $(BUILD_DEV) BUILD_DEV_LD = $(BUILD_DEV) +BUILD_DEV_AS = $(BUILD_DEV) BUILD_DEV_CC = $(BUILD_DEV) # make tool BUILD_POSIX_MAKE = $(BUILD_POSIX) -# feature gates for specific utilities FEATURE_FIND_DELETE = 1 FEATURE_FIND_QUIT = 1 FEATURE_FIND_EMPTY = 1 @@ -215,7 +219,7 @@ FEATURE_STAT_FORMAT = 1 FEATURE_SORT_BIG = 1 FEATURE_SORT_STABLE = 1 FEATURE_OD_ENDIAN = 1 -FEATURE_SH_HISTEDIT = 1 +FEATURE_SH_HISTEDIT = 1 FEATURE_SH_LOCAL = 1 FEATURE_SH_LET = 1 FEATURE_SH_ULIMIT = 1 @@ -231,7 +235,7 @@ FEATURE_MODPROBE_DIR_OVERRIDE = 1 FEATURE_DEPMOD_ALIAS = 1 FEATURE_DEPMOD_SYMBOLS = 1 FEATURE_USE_LIBRESSL = 0 -FEATURE_USE_BEARSSL = 1 +FEATURE_USE_BEARSSL = 0 FEATURE_USE_OPENSSL = 0 FEATURE_TAR_TTY_SAFE = 1 FEATURE_TAR_NOFOLLOW = 1 @@ -246,10 +250,9 @@ FEATURE_IP_ROUTE_ADD_DEL = 1 FEATURE_IP_LINK_SET = 1 FEATURE_IP_ADDR_FLUSH = 1 - CPPFLAGS =\ -Ishared\ - -DPREFIX=\"$(PREFIX)\"\ + -DPREFIX=\"\$(PREFIX)\"\ -D_DEFAULT_SOURCE\ -D_GNU_SOURCE\ -D_NETBSD_SOURCE\ @@ -311,17 +314,17 @@ CPPFLAGS =\ -DFEATURE_IP_LINK_SET=$(FEATURE_IP_LINK_SET)\ -DFEATURE_IP_ADDR_FLUSH=$(FEATURE_IP_ADDR_FLUSH) $(CPPFLAGS_TLS) - -CFLAGS = -std=c99 -Wall -Wextra -pedantic -LDFLAGS = $(LDFLAGS_TLS) +CC = cc +CFLAGS = +LDFLAGS = LDLIBS_HISTEDIT_0 = LDLIBS_HISTEDIT_1 = LDLIBS_TLS_LIBRESSL_1 = -ltls -LDLIBS_TLS_BEARSSL_1 = -lbearssl +LDLIBS_TLS_BEARSSL_1 = externalRepos/BearSSL/build/libbearssl.a LDLIBS_TLS_OPENSSL_1 = -lssl -lcrypto LDLIBS_TLS = $(LDLIBS_TLS_LIBRESSL_$(FEATURE_USE_LIBRESSL)) $(LDLIBS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL)) $(LDLIBS_TLS_OPENSSL_$(FEATURE_USE_OPENSSL)) -CPPFLAGS_TLS_BEARSSL_1 = -LDFLAGS_TLS_BEARSSL_1 = +CPPFLAGS_TLS_BEARSSL_1 = -IexternalRepos/BearSSL/inc +LDFLAGS_TLS_BEARSSL_1 = -LexternalRepos/BearSSL/build CPPFLAGS_TLS = $(CPPFLAGS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL)) LDFLAGS_TLS = $(LDFLAGS_TLS_BEARSSL_$(FEATURE_USE_BEARSSL)) -LDLIBS = -lcrypt -lresolv $(LDLIBS_HISTEDIT_$(FEATURE_SH_HISTEDIT)) $(LDLIBS_TLS) +LDLIBS = -lcrypt -lresolv $(LDLIBS_HISTEDIT_$(FEATURE_SH_HISTEDIT)) diff --git a/scripts/mkman/main.go b/scripts/mkman/main.go @@ -10,7 +10,7 @@ import ( "time" ) -// Parse config.mk variables and values +// parse config.mk variables and values type Config map[string]string func parseConfigMk(path string) (Config, error) { @@ -71,7 +71,7 @@ func (cfg Config) isEnabled(key string) bool { return cfg[key] == "1" } -// Preprocessor condition stack for nested feature blocks +// preprocessor condition stack for nested feature blocks type ifFrame struct { active bool seen bool @@ -116,7 +116,7 @@ func (s *ifStack) top() *ifFrame { return &s.frames[len(s.frames)-1] } -// Parse and evaluate preprocessor feature conditions +// parse and evaluate preprocessor feature conditions func evalCondition(expr string, cfg Config) bool { expr = strings.TrimSpace(expr) if strings.HasPrefix(expr, "defined(") && strings.HasSuffix(expr, ")") { @@ -146,7 +146,7 @@ func evalCondition(expr string, cfg Config) bool { return cfg[expr] == "1" } -// Section inference from file path +// section inference from file path func inferSection(path string) int { clean := filepath.ToSlash(path) switch { @@ -159,15 +159,32 @@ func inferSection(path string) int { } } -// Main entry point and flags definition +// a Renderer turns a parsed Page into one output format on os.Stdout +type Renderer interface { + Render() error +} + +func newRenderer(format string, page *Page) (Renderer, error) { + switch strings.ToLower(format) { + case "", "mdoc": + return NewMdocRenderer(page, os.Stdout), nil + case "txt": + return NewTxtRenderer(page, os.Stdout), nil + default: + return nil, fmt.Errorf("unknown format %q (want mdoc or txt)", format) + } +} + +// main entry point and flags definition func main() { configPath := flag.String("config", "config.mk", "path to config.mk") sectionFlag := flag.Int("section", 0, "man section override (0 = infer from path)") dateFlag := flag.String("date", "", "date string for TH line (default: current month/year)") + formatFlag := flag.String("fmt", "mdoc", "output format: mdoc or txt") flag.Parse() if flag.NArg() < 1 { - fmt.Fprintf(os.Stderr, "usage: mkman [-config config.mk] [-section N] file.c\n") + fmt.Fprintf(os.Stderr, "usage: mkman [-config config.mk] [-section N] [-fmt mdoc|txt] file.c\n") os.Exit(1) } cfile := flag.Arg(0) @@ -199,7 +216,11 @@ func main() { os.Exit(0) } - r := NewMdocRenderer(page, os.Stdout) + r, err := newRenderer(*formatFlag, page) + if err != nil { + fmt.Fprintf(os.Stderr, "mkman: %v\n", err) + os.Exit(1) + } if err := r.Render(); err != nil { fmt.Fprintf(os.Stderr, "mkman: render: %v\n", err) os.Exit(1) diff --git a/scripts/mkman/mdoc.go b/scripts/mkman/mdoc.go @@ -16,27 +16,21 @@ func NewMdocRenderer(page *Page, w io.Writer) *MdocRenderer { } func (r *MdocRenderer) Render() error { - if err := r.page.validate(); err != nil { - return err - } + if err := r.page.validate(); err != nil { return err; } fmt.Fprintf(r.w, ".Dd %s\n", troffEscape(r.page.Date)) fmt.Fprintf(r.w, ".Dt %s %d\n", strings.ToUpper(r.page.Name), r.page.Section) fmt.Fprintf(r.w, ".Os %s\n", "aruu") r.renderName() - if len(r.page.Synopsis) != 0 { - r.renderSynopsis() - } - if len(r.page.Description) != 0 { - r.renderDescription() - } - if len(r.page.Options) != 0 { - r.renderOptions() - } + if len(r.page.Synopsis) != 0 { r.renderSynopsis(); } + if len(r.page.Description) != 0 { r.renderDescription(); } + if len(r.page.Options) != 0 { r.renderOptions(); } + for _, section := range r.page.Sections { r.renderSection(section.Title, section.Blocks) } + return nil } @@ -65,6 +59,11 @@ func (r *MdocRenderer) renderSynopsis() { i++ continue } + if item.Kind == SynRequiredGroup { + fmt.Fprintf(r.w, ".Brq %s\n", renderSynopsisPhrase(item.Children, false)) + i++ + continue + } phrase, next := consumeSynopsisPhrase(form.Items, i) fmt.Fprintln(r.w, renderSynopsisPhrase(phrase, true)) @@ -106,6 +105,8 @@ func renderSynopsisPhrase(items []SynopsisItem, topLevel bool) string { parts = append(parts, troffEscape(item.Text)) case SynOptional: parts = append(parts, renderMacro("Op", renderSynopsisPhrase(item.Children, false), topLevel && len(parts) == 0)) + case SynRequiredGroup: + parts = append(parts, renderMacro("Brq", renderSynopsisPhrase(item.Children, false), topLevel && len(parts) == 0)) } } return strings.Join(parts, " ") @@ -113,14 +114,12 @@ func renderSynopsisPhrase(items []SynopsisItem, topLevel bool) string { func renderMacro(name, body string, topLevel bool) string { if body == "" { - if topLevel { - return "." + name - } + if topLevel { return "." + name; } + return name } - if topLevel { - return "." + name + " " + body - } + if topLevel { return "." + name + " " + body; } + return name + " " + body } @@ -246,6 +245,4 @@ func trailingSpace(inline Inline) bool { } } -func isSpaceByte(b byte) bool { - return b == ' ' || b == '\t' || b == '\n' -} +func isSpaceByte(b byte) bool { return b == ' ' || b == '\t' || b == '\n'; } diff --git a/scripts/mkman/page.go b/scripts/mkman/page.go @@ -45,10 +45,12 @@ type XRef struct { } type Option struct { - Spec []SynopsisItem - Desc string - Body []Block - Key string + Spec []SynopsisItem + Desc string + Body []Block + Key string + Group string /* name shared by a mutually exclusive option set, empty if standalone */ + Required bool /* set by a trailing ! on the option spec */ } type SynopsisForm struct { @@ -64,6 +66,7 @@ const ( SynLiteral SynOptional SynPipe + SynRequiredGroup /* a {-a|-b|-c} mutually exclusive required group */ ) type SynopsisItem struct { diff --git a/scripts/mkman/parse.go b/scripts/mkman/parse.go @@ -10,6 +10,7 @@ import ( ) var xrefPattern = regexp.MustCompile(`^\s*([A-Za-z0-9][A-Za-z0-9+_.-]*)\((\d+[A-Za-z]*)\)\s*$`) +var groupPattern = regexp.MustCompile(`\{([A-Za-z0-9_-]+)\}`) func parseNameSummary(line string) (string, string, bool) { line = strings.TrimSpace(line) @@ -228,8 +229,8 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) return nil, nil } - // explicit 'synopsis' forms are authoritative. for simple pages we can produce - // a synopsis from the parsed option specs plus the 'arguments' + // explicit synopsis forms are authoritative. for simple pages we can produce + // a synopsis from the parsed option specs plus the arguments line for _, raw := range rawOptions { raw.Option.Body = parseBlocks(raw.Lines, "") addOption(page, optionIndex, raw.Option) @@ -283,19 +284,52 @@ func parseOption(line string) (Option, bool) { } desc := strings.TrimSpace(strings.Join(parts[i:], ":")) - spec := normalizeOptionSpec(strings.Join(specParts, ":")) + flag, typ, group, required := splitOptionSpec(strings.Join(specParts, ":")) + if flag == "" { + return Option{}, false + } + + rawSpec := flag + if typ != "" { + rawSpec += " " + typ + } + spec := normalizeOptionSpec(rawSpec) desc = stripRepeatedSpec(spec, desc) if spec == "" || desc == "" { return Option{}, false } return Option{ - Spec: parseSynopsis(spec, false).Items, - Desc: desc, - Key: synopsisKey(spec), + Spec: parseSynopsis(spec, false).Items, + Desc: desc, + Key: synopsisKey(spec) + "\x00" + group, + Group: group, + Required: required, }, true } +// 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) { + raw = strings.TrimSpace(raw) + if strings.HasSuffix(raw, "!") { + required = true + raw = raw[:len(raw)-1] + } + if m := groupPattern.FindStringSubmatchIndex(raw); m != nil { + group = raw[m[2]:m[3]] + raw = raw[:m[0]] + raw[m[1]:] + } + if idx := strings.Index(raw, ":"); idx >= 0 { + flag = raw[:idx] + typ = raw[idx+1:] + } else { + flag = raw + } + return flag, typ, group, required +} + func looksLikeOptionArg(s string) bool { if s == "" { return false @@ -703,23 +737,77 @@ func classifyInlineLiteral(s string) Inline { } func synthesizeSynopsis(options []Option, args string) SynopsisForm { - var items []SynopsisItem - for _, opt := range sortedOptions(options) { - items = append(items, SynopsisItem{ - Kind: SynOptional, - Children: cloneSynopsisItems(opt.Spec), + type unit struct { + sortKey string + items []SynopsisItem + } + + groups := make(map[string][]Option) + var groupOrder []string + var units []unit + + for _, opt := range options { + if opt.Group == "" { + if opt.Required { + units = append(units, unit{ + sortKey: optionSortKey(opt), + items: cloneSynopsisItems(opt.Spec), + }) + } else { + units = append(units, unit{ + sortKey: optionSortKey(opt), + items: []SynopsisItem{{ + Kind: SynOptional, + Children: cloneSynopsisItems(opt.Spec), + }}, + }) + } + continue + } + if _, seen := groups[opt.Group]; !seen { + groupOrder = append(groupOrder, opt.Group) + } + groups[opt.Group] = append(groups[opt.Group], opt) + } + + for _, name := range groupOrder { + members := groups[name] + required := false + for _, m := range members { + if m.Required { + required = true + break + } + } + + var children []SynopsisItem + for i, m := range members { + if i != 0 { + children = append(children, SynopsisItem{Kind: SynPipe, Text: "|"}) + } + children = append(children, cloneSynopsisItems(m.Spec)...) + } + + kind := SynOptional + if required { + kind = SynRequiredGroup + } + units = append(units, unit{ + sortKey: optionSortKey(members[0]), + items: []SynopsisItem{{Kind: kind, Children: children}}, }) } - items = append(items, parseSynopsis(args, false).Items...) - return SynopsisForm{Items: items} -} -func sortedOptions(options []Option) []Option { - out := append([]Option(nil), options...) - slices.SortFunc(out, func(a, b Option) int { - return strings.Compare(optionSortKey(a), optionSortKey(b)) + slices.SortFunc(units, func(a, b unit) int { + return strings.Compare(a.sortKey, b.sortKey) }) - return out + + var items []SynopsisItem + for _, u := range units { + items = append(items, u.items...) + } + items = append(items, parseSynopsis(args, false).Items...) + return SynopsisForm{Items: items} } func optionSortKey(opt Option) string { @@ -796,7 +884,7 @@ func tokenizeSynopsis(raw string) []string { for i := 0; i < len(raw); i++ { ch := raw[i] switch ch { - case '[', ']', '|': + case '[', ']', '{', '}', '|': flush() tokens = append(tokens, string(ch)) case ' ', '\t', '\n': @@ -815,12 +903,16 @@ func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) for i := start; i < len(tokens); i++ { switch tokens[i] { - case "]": + case "]", "}": return items, i case "[": children, end := parseSynopsisSeq(tokens, i+1, explicit, false) items = append(items, SynopsisItem{Kind: SynOptional, Children: children}) i = end + case "{": + children, end := parseSynopsisSeq(tokens, i+1, explicit, false) + items = append(items, SynopsisItem{Kind: SynRequiredGroup, Children: children}) + i = end case "|": items = append(items, SynopsisItem{Kind: SynPipe, Text: "|"}) default: @@ -845,8 +937,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 @@ -0,0 +1,221 @@ +package main + +import ( + "fmt" + "io" + "strings" +) + +// fixed-width ascii layout, matching the column widths a classic +// nroff -Tascii rendering of an mdoc page would produce +const ( + txtWidth = 78 + txtIndent = 7 + txtTagIndent = 15 + txtSubIndent = 4 +) + +type TxtRenderer struct { + page *Page + w io.Writer + wrote bool +} + +func NewTxtRenderer(page *Page, w io.Writer) *TxtRenderer { + return &TxtRenderer{page: page, w: w} +} + +func (r *TxtRenderer) Render() error { + if err := r.page.validate(); err != nil { + return err + } + + r.heading("NAME") + r.writeIndented(r.page.Name+" - "+renderInlinesTxt(parseInlines(r.page.Summary)), txtIndent) + + if len(r.page.Synopsis) != 0 { + r.renderSynopsis() + } + if len(r.page.Description) != 0 { + r.heading("DESCRIPTION") + for _, block := range r.page.Description { + r.renderBlock(block, txtIndent) + } + } + if len(r.page.Options) != 0 { + r.renderOptions() + } + for _, section := range r.page.Sections { + r.heading(section.Title) + for _, block := range section.Blocks { + r.renderBlock(block, txtIndent) + } + } + return nil +} + +// heading prints a flush-left section title, with a blank line above +// every one but the first +func (r *TxtRenderer) heading(title string) { + if r.wrote { + fmt.Fprintln(r.w) + } + fmt.Fprintln(r.w, title) + r.wrote = true +} + +func (r *TxtRenderer) renderSynopsis() { + r.heading("SYNOPSIS") + hang := len(r.page.Name) + 1 + + for _, form := range r.page.Synopsis { + body := renderSynopsisItemsTxt(form.Items) + + avail := txtWidth - txtIndent - hang + if avail < 10 { + avail = 10 + } + lines := wrapWords(body, avail) + if len(lines) == 0 { + lines = []string{""} + } + + fmt.Fprintln(r.w, strings.Repeat(" ", txtIndent)+strings.TrimSpace(r.page.Name+" "+lines[0])) + for _, l := range lines[1:] { + fmt.Fprintln(r.w, strings.Repeat(" ", txtIndent+hang)+l) + } + } +} + +func (r *TxtRenderer) renderOptions() { + r.heading("OPTIONS") + for i, opt := range r.page.Options { + if i != 0 { + fmt.Fprintln(r.w) + } + r.writeIndented(renderSynopsisItemsTxt(opt.Spec), txtIndent) + for _, block := range opt.Body { + r.renderBlock(block, txtTagIndent) + } + } +} + +func (r *TxtRenderer) renderBlock(block Block, indent int) { + switch block.Kind { + case BlockParagraph: + fmt.Fprintln(r.w) + r.writeIndented(renderInlinesTxt(block.Inlines), indent) + case BlockTaggedList: + for i, item := range block.Items { + if i != 0 { + fmt.Fprintln(r.w) + } + r.writeIndented(renderInlinesTxt(item.Label), indent) + if len(item.Body) != 0 { + fmt.Fprintln(r.w) + r.writeIndented(renderInlinesTxt(item.Body), indent+8) + } + } + case BlockSeeAlso: + var refs []string + for _, ref := range block.Refs { + refs = append(refs, ref.Name+"("+ref.Section+")") + } + fmt.Fprintln(r.w) + r.writeIndented(strings.Join(refs, ", "), indent) + case BlockSubsection: + fmt.Fprintln(r.w) + r.writeIndented(block.Title, indent) + for _, child := range block.Blocks { + r.renderBlock(child, indent+txtSubIndent) + } + } +} + +// 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 + if width < 10 { + width = 10 + } + for _, line := range wrapWords(text, width) { + fmt.Fprintln(r.w, strings.Repeat(" ", indent)+line) + } +} + +func wrapWords(text string, width int) []string { + text = strings.Join(strings.Fields(text), " ") + if text == "" { + return nil + } + if width < 1 { + width = 1 + } + + words := strings.Fields(text) + lines := []string{words[0]} + for _, word := range words[1:] { + last := lines[len(lines)-1] + if len(last)+1+len(word) <= width { + lines[len(lines)-1] = last + " " + word + } else { + lines = append(lines, word) + } + } + return lines +} + +// renderSynopsisItemsTxt mirrors renderSynopsisPhrase from mdoc.go but +// writes literal brackets and braces instead of mdoc macros +func renderSynopsisItemsTxt(items []SynopsisItem) string { + var parts []string + for _, item := range items { + switch item.Kind { + case SynFlag: + parts = append(parts, "-"+strings.TrimPrefix(item.Text, "-")) + case SynArg: + parts = append(parts, strings.Trim(item.Text, "<>")) + case SynCommand: + parts = append(parts, item.Text) + case SynPipe: + parts = append(parts, "|") + case SynLiteral: + parts = append(parts, item.Text) + case SynOptional: + parts = append(parts, "["+renderSynopsisItemsTxt(item.Children)+"]") + case SynRequiredGroup: + parts = append(parts, "{"+renderSynopsisItemsTxt(item.Children)+"}") + } + } + return strings.Join(parts, " ") +} + +func renderInlinesTxt(inlines []Inline) string { + var b strings.Builder + for _, inline := range inlines { + b.WriteString(renderInlineTxt(inline)) + } + return b.String() +} + +func renderInlineTxt(inline Inline) string { + switch inline.Kind { + case InlineText: + return inline.Text + case InlineNm: + return inline.Text + case InlineEmph: + return "_" + renderInlinesTxt(inline.Children) + "_" + case InlineLiteral: + return "`" + inline.Text + "'" + case InlinePath: + return inline.Text + case InlineXRef: + return inline.Text + "(" + inline.Section + ")" + case InlineFlag: + return "-" + inline.Text + default: + return "" + } +} diff --git a/shared/diskutil.h b/shared/diskutil.h @@ -0,0 +1,34 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef ARUU_DISKUTIL_H +#define ARUU_DISKUTIL_H + +#include <stdint.h> +#include <stddef.h> + +struct BlockDev { + int fd; + uint64_t size; /* size in bytes */ + size_t sec_size; /* sector size */ +}; + +struct BlockDevInfo { + char name[32]; + char type[16]; /* disk, part, loop */ + uint64_t size; + int major; + int minor; + char mountpoint[256]; + char fstype[32]; + struct BlockDevInfo *parts; + struct BlockDevInfo *next; +}; + +int blockdev_open(struct BlockDev *dev, const char *path, int writable); +int blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf, size_t sector_count); +int blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf, size_t sector_count); +void blockdev_close(struct BlockDev *dev); + +struct BlockDevInfo *blockdev_get_list(void); +void blockdev_free_list(struct BlockDevInfo *list); + +#endif diff --git a/shared/libutil/diskutil.c b/shared/libutil/diskutil.c @@ -0,0 +1,439 @@ +/* See LICENSE file for copyright and license details. */ +#include "../diskutil.h" +#include "../util.h" + +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> + +#if defined(__linux__) +#include <sys/ioctl.h> +#include <linux/fs.h> +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__Apple__) +#include <sys/ioctl.h> +#include <sys/disk.h> +#if defined(__OpenBSD__) || defined(__NetBSD__) +#include <sys/dkio.h> +#include <sys/disklabel.h> +#include <sys/sysctl.h> +#elif defined(__FreeBSD__) +#include <sys/disk.h> +#include <sys/sysctl.h> +#include <dirent.h> +#endif +#endif + +int +blockdev_open(struct BlockDev *dev, const char *path, int writable) +{ + struct stat st; + int fd, flags; + + flags = writable ? O_RDWR : O_RDONLY; + fd = open(path, flags); + if (fd < 0) + return -1; + + if (fstat(fd, &st) < 0) { + close(fd); + return -1; + } + + dev->fd = fd; + dev->size = st.st_size; + dev->sec_size = 512; + + if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) { +#if defined(__linux__) + uint64_t size_bytes = 0; + int sec_size = 0; + if (ioctl(fd, BLKGETSIZE64, &size_bytes) >= 0) + dev->size = size_bytes; + if (ioctl(fd, BLKSSZGET, &sec_size) >= 0) + dev->sec_size = sec_size; +#elif defined(__FreeBSD__) + off_t size_bytes = 0; + unsigned int sec_size = 0; + if (ioctl(fd, DIOCGMEDIASIZE, &size_bytes) >= 0) + dev->size = size_bytes; + if (ioctl(fd, DIOCGSECTORSIZE, &sec_size) >= 0) + dev->sec_size = sec_size; +#elif defined(__OpenBSD__) || defined(__NetBSD__) + struct disklabel dl; + if (ioctl(fd, DIOCGDINFO, &dl) >= 0) { + dev->size = (uint64_t)dl.d_secsize * DL_GETDSIZE(&dl); + dev->sec_size = dl.d_secsize; + } +#endif + } + + return 0; +} + +int +blockdev_read(struct BlockDev *dev, uint64_t sector, void *buf, size_t sector_count) +{ + off_t offset = (off_t)sector * dev->sec_size; + size_t size = sector_count * dev->sec_size; + ssize_t n; + + if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) + return -1; + + n = read(dev->fd, buf, size); + if (n < 0 || (size_t)n != size) + return -1; + + return 0; +} + +int +blockdev_write(struct BlockDev *dev, uint64_t sector, const void *buf, size_t sector_count) +{ + off_t offset = (off_t)sector * dev->sec_size; + size_t size = sector_count * dev->sec_size; + ssize_t n; + + if (lseek(dev->fd, offset, SEEK_SET) == (off_t)-1) + return -1; + + n = write(dev->fd, buf, size); + if (n < 0 || (size_t)n != size) + return -1; + + return 0; +} + +void +blockdev_close(struct BlockDev *dev) +{ + if (dev->fd >= 0) { + close(dev->fd); + dev->fd = -1; + } +} + +struct BlockDevInfo * +blockdev_get_list(void) +{ +#if defined(__linux__) + FILE *fp; + char line[256]; + struct BlockDevInfo *head = NULL, *tail = NULL; + unsigned int major, minor; + unsigned long long blocks; + char name[64]; + + fp = fopen("/proc/partitions", "r"); + if (!fp) + return NULL; + + while (fgets(line, sizeof(line), fp)) { + if (sscanf(line, " %u %u %llu %63s", &major, &minor, &blocks, name) != 4) + continue; + + struct BlockDevInfo *info = calloc(1, sizeof(*info)); + if (!info) + break; + + strlcpy(info->name, name, sizeof(info->name)); + info->size = blocks * 1024; + info->major = major; + info->minor = minor; + + /* check if this is a partition of an existing disk */ + struct BlockDevInfo *curr; + int is_part = 0; + for (curr = head; curr; curr = curr->next) { + size_t len = strlen(curr->name); + if (strncmp(name, curr->name, len) == 0) { + char c = name[len]; + if ((c >= '0' && c <= '9') || (c == 'p' && name[len+1] >= '0' && name[len+1] <= '9')) { + is_part = 1; + strlcpy(info->type, "part", sizeof(info->type)); + struct BlockDevInfo *p = curr->parts; + if (!p) { + curr->parts = info; + } else { + while (p->next) + p = p->next; + p->next = info; + } + break; + } + } + } + + if (!is_part) { + strlcpy(info->type, "disk", sizeof(info->type)); + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + } + fclose(fp); + + /* parse mounts to populate mountpoint and fstype */ + FILE *mfile = fopen("/proc/mounts", "r"); + if (mfile) { + char mline[512]; + char devpath[128], mnt[256], fs[64]; + while (fgets(mline, sizeof(mline), mfile)) { + if (sscanf(mline, "%127s %255s %63s", devpath, mnt, fs) == 3) { + char *devname = devpath; + if (strncmp(devpath, "/dev/", 5) == 0) + devname = devpath + 5; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mnt, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, fs, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mnt, sizeof(part->mountpoint)); + strlcpy(part->fstype, fs, sizeof(part->fstype)); + } + } + } + } + } + fclose(mfile); + } + + return head; + +#elif defined(__FreeBSD__) + char disks[1024]; + size_t len = sizeof(disks); + struct BlockDevInfo *head = NULL, *tail = NULL; + + if (sysctlbyname("kern.disks", disks, &len, NULL, 0) < 0) + return NULL; + + char *tok, *ptr = disks; + while ((tok = strsep(&ptr, " \t")) != NULL) { + if (!*tok) + continue; + + struct BlockDevInfo *info = calloc(1, sizeof(*info)); + if (!info) + break; + + strlcpy(info->name, tok, sizeof(info->name)); + strlcpy(info->type, "disk", sizeof(info->type)); + + char devpath[64]; + snprintf(devpath, sizeof(devpath), "/dev/%s", tok); + struct BlockDev dev; + if (blockdev_open(&dev, devpath, 0) == 0) { + info->size = dev.size; + blockdev_close(&dev); + } + + DIR *dir = opendir("/dev"); + if (dir) { + struct dirent *de; + size_t disk_len = strlen(tok); + while ((de = readdir(dir)) != NULL) { + if (strncmp(de->d_name, tok, disk_len) == 0) { + char c = de->d_name[disk_len]; + if (c == 's' || c == 'p') { + struct BlockDevInfo *part = calloc(1, sizeof(*part)); + if (part) { + strlcpy(part->name, de->d_name, sizeof(part->name)); + strlcpy(part->type, "part", sizeof(part->type)); + snprintf(devpath, sizeof(devpath), "/dev/%s", de->d_name); + if (blockdev_open(&dev, devpath, 0) == 0) { + part->size = dev.size; + blockdev_close(&dev); + } + struct BlockDevInfo *p = info->parts; + if (!p) { + info->parts = part; + } else { + while (p->next) + p = p->next; + p->next = part; + } + } + } + } + } + closedir(dir); + } + + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + + struct statfs *mntbuf; + int mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + for (int i = 0; i < mntsize; i++) { + char *devpath = mntbuf[i].f_mntfromname; + char *devname = devpath; + if (strncmp(devpath, "/dev/", 5) == 0) + devname = devpath + 5; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); + strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); + } + } + } + } + + return head; + +#elif defined(__OpenBSD__) + char disknames[1024]; + size_t len = sizeof(disknames); + int mib[2] = { CTL_HW, HW_DISKNAMES }; + struct BlockDevInfo *head = NULL, *tail = NULL; + + if (sysctl(mib, 2, disknames, &len, NULL, 0) < 0) + return NULL; + + char *tok, *ptr = disknames; + while ((tok = strsep(&ptr, ",")) != NULL) { + char *colon = strchr(tok, ':'); + if (colon) + *colon = '\0'; + if (!*tok) + continue; + + struct BlockDevInfo *info = calloc(1, sizeof(*info)); + if (!info) + break; + + strlcpy(info->name, tok, sizeof(info->name)); + strlcpy(info->type, "disk", sizeof(info->type)); + + char devpath[64]; + snprintf(devpath, sizeof(devpath), "/dev/r%sc", tok); + struct BlockDev dev; + if (blockdev_open(&dev, devpath, 0) == 0) { + info->size = dev.size; + blockdev_close(&dev); + } + + for (char c = 'a'; c <= 'p'; c++) { + if (c == 'c') + continue; + snprintf(devpath, sizeof(devpath), "/dev/r%s%c", tok, c); + if (blockdev_open(&dev, devpath, 0) == 0) { + struct BlockDevInfo *part = calloc(1, sizeof(*part)); + if (part) { + snprintf(part->name, sizeof(part->name), "%s%c", tok, c); + strlcpy(part->type, "part", sizeof(part->type)); + part->size = dev.size; + struct BlockDevInfo *p = info->parts; + if (!p) { + info->parts = part; + } else { + while (p->next) + p = p->next; + p->next = part; + } + } + blockdev_close(&dev); + } + } + + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + + struct statfs *mntbuf; + int mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + for (int i = 0; i < mntsize; i++) { + char *devpath = mntbuf[i].f_mntfromname; + char *devname = devpath; + if (strncmp(devpath, "/dev/", 5) == 0) + devname = devpath + 5; + struct BlockDevInfo *curr; + for (curr = head; curr; curr = curr->next) { + if (strcmp(curr->name, devname) == 0) { + strlcpy(curr->mountpoint, mntbuf[i].f_mntonname, sizeof(curr->mountpoint)); + strlcpy(curr->fstype, mntbuf[i].f_fstypename, sizeof(curr->fstype)); + } + struct BlockDevInfo *part; + for (part = curr->parts; part; part = part->next) { + if (strcmp(part->name, devname) == 0) { + strlcpy(part->mountpoint, mntbuf[i].f_mntonname, sizeof(part->mountpoint)); + strlcpy(part->fstype, mntbuf[i].f_fstypename, sizeof(part->fstype)); + } + } + } + } + + return head; + +#else + struct BlockDevInfo *head = NULL, *tail = NULL; + char devname[16]; + for (char c = 'a'; c <= 'z'; c++) { + snprintf(devname, sizeof(devname), "sd%c", c); + char devpath[32]; + snprintf(devpath, sizeof(devpath), "/dev/%s", devname); + struct BlockDev dev; + if (blockdev_open(&dev, devpath, 0) == 0) { + struct BlockDevInfo *info = calloc(1, sizeof(*info)); + if (info) { + strlcpy(info->name, devname, sizeof(info->name)); + strlcpy(info->type, "disk", sizeof(info->type)); + info->size = dev.size; + if (!head) { + head = info; + } else { + tail->next = info; + } + tail = info; + } + blockdev_close(&dev); + } + } + return head; +#endif +} + +void +blockdev_free_list(struct BlockDevInfo *list) +{ + struct BlockDevInfo *curr = list; + while (curr) { + struct BlockDevInfo *next = curr->next; + struct BlockDevInfo *part = curr->parts; + while (part) { + struct BlockDevInfo *next_part = part->next; + free(part); + part = next_part; + } + free(curr); + curr = next; + } +}