aruu

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

commit b52592bb4524cc67434b0323c96352f9fbc141a7
parent c9e91a9878726888ca9d41d267a2a2503015a6dc
Author: xplshn <anto@xplshn.com.ar>
Date:   Mon,  6 Jul 2026 12:10:30 -0300

Get rif of Make/Makefile.sh and a bunch of bullshit

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

Diffstat:
MMakefile | 923+++++++------------------------------------------------------------------------
DMakefile.sh | 537-------------------------------------------------------------------------------
MREADME | 59++++++++++++++++++++++++++++++++++++++++++-----------------
Mbuild.cfg | 33+++++++++++++++++++--------------
Acmd/dev/ninqu/exec.c | 294+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/expand.c | 355+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/fs.c | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/gate.c | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/kv.c | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/main.c | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/ninqu.h | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/parse.c | 650+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/query.c | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/registry.c | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/resolve.c | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/schedule.c | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/sexpr.c | 344+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ninqu/strlist.c | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aninqu.rules | 678+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dscripts/deps | 98-------------------------------------------------------------------------------
Ascripts/genbox.sh | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/genconfig.sh | 604++++++++++++++++++++++++++++++++++++-------------------------------------------
Dscripts/mkbox | 511-------------------------------------------------------------------------------
Mshared/libutil/tls.c | 16++++++++--------
Mshared/tls.h | 4++--
25 files changed, 4569 insertions(+), 2366 deletions(-)

diff --git a/Makefile b/Makefile @@ -1,848 +1,77 @@ --include scripts/mk/config.mk - -.SUFFIXES: .y .o .c -HDR =\ - shared/arg.h\ - shared/compat.h\ - shared/config.h\ - shared/crypt.h\ - shared/wexec.h\ - shared/fs.h\ - shared/md5.h\ - shared/queue.h\ - shared/sha1.h\ - shared/sha224.h\ - shared/sha256.h\ - shared/sha384.h\ - shared/sha512.h\ - shared/sha512-224.h\ - shared/sha512-256.h\ - shared/text.h\ - shared/utf.h\ - shared/util.h\ - shared/passwd.h\ - shared/paths.h\ - shared/reboot.h\ - shared/rtc.h\ - shared/proc.h\ - shared/tls.h - -LIBUTFOBJ =\ - shared/libutf/fgetrune.o\ - shared/libutf/fputrune.o\ - shared/libutf/isalnumrune.o\ - shared/libutf/isalpharune.o\ - shared/libutf/isblankrune.o\ - shared/libutf/iscntrlrune.o\ - shared/libutf/isdigitrune.o\ - shared/libutf/isgraphrune.o\ - shared/libutf/isprintrune.o\ - shared/libutf/ispunctrune.o\ - shared/libutf/isspacerune.o\ - shared/libutf/istitlerune.o\ - shared/libutf/isxdigitrune.o\ - shared/libutf/lowerrune.o\ - shared/libutf/rune.o\ - shared/libutf/runetype.o\ - shared/libutf/upperrune.o\ - shared/libutf/utf.o\ - shared/libutf/utftorunestr.o - -LIBUTILOBJ =\ - shared/libutil/concat.o\ - shared/libutil/cp.o\ - shared/libutil/crypt.o\ - shared/libutil/confirm.o\ - shared/libutil/diffutil.o\ - shared/libutil/wexec.o\ - shared/libutil/ealloc.o\ - shared/libutil/enmasse.o\ - shared/libutil/eprintf.o\ - shared/libutil/eregcomp.o\ - shared/libutil/estrtod.o\ - shared/libutil/fnck.o\ - shared/libutil/fshut.o\ - shared/libutil/getlines.o\ - shared/libutil/human.o\ - shared/libutil/linecmp.o\ - shared/libutil/md5.o\ - shared/libutil/memmem.o\ - shared/libutil/mkdirp.o\ - shared/libutil/mode.o\ - shared/libutil/parseoffset.o\ - shared/libutil/putword.o\ - shared/libutil/reallocarray.o\ - shared/libutil/recurse.o\ - shared/libutil/rm.o\ - shared/libutil/sha1.o\ - shared/libutil/sha224.o\ - shared/libutil/sha256.o\ - shared/libutil/sha384.o\ - shared/libutil/sha512.o\ - shared/libutil/sha512-224.o\ - shared/libutil/sha512-256.o\ - shared/libutil/strcasestr.o\ - shared/libutil/strlcat.o\ - shared/libutil/strlcpy.o\ - shared/libutil/strsep.o\ - shared/libutil/strnsubst.o\ - shared/libutil/strtonum.o\ - shared/libutil/writeall.o\ - shared/libutil/unescape.o\ - shared/libutil/agetcwd.o\ - shared/libutil/agetline.o\ - shared/libutil/apathmax.o\ - shared/libutil/estrtol.o\ - shared/libutil/estrtoul.o\ - shared/libutil/explicit_bzero.o\ - shared/libutil/passwd.o\ - shared/libutil/proc.o\ - shared/libutil/tty.o\ - shared/libutil/fconcat.o\ - shared/libutil/recurse_dir.o\ - shared/libutil/sig.o\ - shared/libutil/net.o\ - shared/libutil/sysinfo.o\ - shared/libutil/tls.o\ - shared/libutil/diskutil.o - -LIBREDLINEOBJ =\ - shared/libredline/redline.o - -LIB = shared/libredline/libredline.a shared/libutil/libutil.a shared/libutf/libutf.a - -POSIX_BIN_ALL =\ - cmd/posix/basename\ - cmd/posix/cal\ - cmd/posix/cat\ - cmd/posix/chgrp\ - cmd/posix/chmod\ - cmd/posix/chown\ - cmd/posix/cksum\ - cmd/posix/cmp\ - cmd/posix/comm\ - cmd/posix/cp\ - cmd/posix/cut\ - cmd/posix/date\ - cmd/posix/dd\ - cmd/posix/df\ - cmd/posix/diff\ - cmd/posix/patch\ - cmd/posix/dirname\ - cmd/posix/du\ - cmd/posix/echo\ - cmd/posix/ed\ - cmd/posix/env\ - cmd/posix/expand\ - cmd/posix/expr\ - cmd/posix/false\ - cmd/posix/find\ - cmd/posix/fold\ - cmd/posix/getconf\ - cmd/posix/grep\ - cmd/posix/head\ - cmd/posix/id\ - cmd/posix/join\ - cmd/posix/kill\ - cmd/posix/link\ - cmd/posix/ln\ - cmd/posix/logger\ - cmd/posix/logname\ - cmd/posix/ls\ - cmd/posix/mesg\ - cmd/posix/mkdir\ - cmd/posix/mkfifo\ - cmd/posix/mv\ - cmd/posix/nice\ - cmd/posix/nl\ - cmd/posix/nohup\ - cmd/posix/od\ - cmd/posix/paste\ - cmd/posix/pathchk\ - cmd/posix/printf\ - cmd/posix/ps\ - cmd/posix/pwd\ - cmd/posix/readlink\ - cmd/posix/renice\ - cmd/posix/rm\ - cmd/posix/rmdir\ - cmd/posix/sed\ - cmd/posix/sleep\ - cmd/posix/sort\ - cmd/posix/split\ - cmd/posix/tail\ - cmd/posix/tee\ - cmd/posix/test\ - cmd/posix/time\ - cmd/posix/touch\ - cmd/posix/tr\ - cmd/posix/true\ - cmd/posix/tsort\ - cmd/posix/tty\ - cmd/posix/uname\ - cmd/posix/unexpand\ - cmd/posix/uniq\ - cmd/posix/unlink\ - cmd/posix/uudecode\ - cmd/posix/uuencode\ - cmd/posix/wc\ - cmd/posix/who\ - cmd/posix/xargs\ - cmd/posix/awk/awk\ - cmd/posix/sh/sh\ - cmd/posix/pax\ - cmd/posix/make/make\ - cmd/posix/bc - -LINUX_BIN_ALL =\ - cmd/linux/blkdiscard\ - cmd/linux/chvt\ - cmd/linux/ctrlaltdel\ - cmd/linux/eject\ - cmd/linux/freeramdisk\ - cmd/linux/fsfreeze\ - cmd/linux/hwclock\ - cmd/linux/insmod\ - cmd/linux/lsmod\ - cmd/linux/lsusb\ - cmd/linux/modprobe\ - cmd/linux/depmod\ - cmd/linux/mkswap\ - cmd/linux/mount\ - cmd/linux/mountpoint\ - cmd/linux/pivot_root\ - cmd/linux/readahead\ - cmd/linux/rmmod\ - cmd/linux/swaplabel\ - cmd/linux/swapoff\ - cmd/linux/swapon\ - cmd/linux/switch_root\ - cmd/linux/sysctl\ - cmd/linux/tunctl\ - cmd/linux/umount\ - cmd/linux/unshare\ - cmd/linux/vtallow - -NET_BIN_ALL =\ - cmd/net/netcat\ - cmd/net/tftp\ - cmd/net/wget\ - cmd/net/ping\ - cmd/net/sdhcp\ - cmd/net/ifconfig\ - cmd/net/host\ - cmd/net/httpd\ - cmd/net/ip - -XSI_BIN_ALL =\ - cmd/xsi/mknod\ - cmd/xsi/passwd\ - cmd/xsi/su - -PSEUDO_BIN_ALL =\ - cmd/pseudo/chroot\ - cmd/pseudo/clear\ - cmd/pseudo/cols\ - cmd/pseudo/cron\ - cmd/pseudo/flock\ - cmd/pseudo/getty\ - cmd/pseudo/halt\ - cmd/pseudo/hostname\ - cmd/pseudo/killall5\ - cmd/pseudo/last\ - cmd/pseudo/lastlog\ - cmd/pseudo/login\ - cmd/pseudo/md5sum\ - cmd/pseudo/mktemp\ - cmd/pseudo/nologin\ - cmd/pseudo/pagesize\ - cmd/pseudo/printenv\ - cmd/pseudo/respawn\ - cmd/pseudo/rev\ - cmd/pseudo/seq\ - cmd/pseudo/setsid\ - cmd/pseudo/sha1sum\ - cmd/pseudo/sha224sum\ - cmd/pseudo/sha256sum\ - cmd/pseudo/sha384sum\ - cmd/pseudo/sha512sum\ - cmd/pseudo/sha512-224sum\ - cmd/pseudo/sha512-256sum\ - cmd/pseudo/sponge\ - cmd/pseudo/stat\ - cmd/pseudo/tar\ - cmd/pseudo/truncate\ - cmd/pseudo/watch\ - cmd/pseudo/which\ - cmd/pseudo/whoami\ - cmd/pseudo/xinstall\ - cmd/pseudo/yes\ - cmd/pseudo/base64\ - cmd/pseudo/mkpasswd\ - cmd/extra/b3sum\ - cmd/extra/blkid\ - cmd/extra/lsblk\ - cmd/extra/fdisk\ - cmd/extra/sync\ - cmd/extra/yap/yap\ - cmd/dev/ar/ar\ - cmd/dev/as/as\ - cmd/dev/ld/ld\ - cmd/dev/cc/cc\ - cmd/pseudo/dmesg\ - cmd/pseudo/fallocate\ - cmd/pseudo/free\ - cmd/pseudo/pidof\ - cmd/pseudo/pwdx\ - cmd/pseudo/uptime\ - cmd/pseudo/diff3 - -MAKEOBJ =\ - cmd/posix/make/defaults.o\ - cmd/posix/make/main.o\ - cmd/posix/make/parser.o\ - cmd/posix/make/posix.o\ - cmd/posix/make/rules.o - - - -BIN_basename_1 = cmd/posix/basename -BIN_cal_1 = cmd/posix/cal -BIN_cat_1 = cmd/posix/cat -BIN_chgrp_1 = cmd/posix/chgrp -BIN_chmod_1 = cmd/posix/chmod -BIN_chown_1 = cmd/posix/chown -BIN_cksum_1 = cmd/posix/cksum -BIN_cmp_1 = cmd/posix/cmp -BIN_comm_1 = cmd/posix/comm -BIN_cp_1 = cmd/posix/cp -BIN_cut_1 = cmd/posix/cut -BIN_date_1 = cmd/posix/date -BIN_dd_1 = cmd/posix/dd -BIN_df_1 = cmd/posix/df -BIN_diff_1 = cmd/posix/diff -BIN_patch_1 = cmd/posix/patch -BIN_dirname_1 = cmd/posix/dirname -BIN_du_1 = cmd/posix/du -BIN_echo_1 = cmd/posix/echo -BIN_ed_1 = cmd/posix/ed -BIN_env_1 = cmd/posix/env -BIN_expand_1 = cmd/posix/expand -BIN_expr_1 = cmd/posix/expr -BIN_false_1 = cmd/posix/false -BIN_find_1 = cmd/posix/find -BIN_fold_1 = cmd/posix/fold -BIN_getconf_1 = cmd/posix/getconf -BIN_grep_1 = cmd/posix/grep -BIN_head_1 = cmd/posix/head -BIN_id_1 = cmd/posix/id -BIN_join_1 = cmd/posix/join -BIN_kill_1 = cmd/posix/kill -BIN_link_1 = cmd/posix/link -BIN_ln_1 = cmd/posix/ln -BIN_logger_1 = cmd/posix/logger -BIN_logname_1 = cmd/posix/logname -BIN_ls_1 = cmd/posix/ls -BIN_mesg_1 = cmd/posix/mesg -BIN_mkdir_1 = cmd/posix/mkdir -BIN_mkfifo_1 = cmd/posix/mkfifo -BIN_mv_1 = cmd/posix/mv -BIN_nice_1 = cmd/posix/nice -BIN_nl_1 = cmd/posix/nl -BIN_nohup_1 = cmd/posix/nohup -BIN_od_1 = cmd/posix/od -BIN_paste_1 = cmd/posix/paste -BIN_pathchk_1 = cmd/posix/pathchk -BIN_printf_1 = cmd/posix/printf -BIN_ps_1 = cmd/posix/ps -BIN_pwd_1 = cmd/posix/pwd -BIN_readlink_1 = cmd/posix/readlink -BIN_renice_1 = cmd/posix/renice -BIN_rm_1 = cmd/posix/rm -BIN_rmdir_1 = cmd/posix/rmdir -BIN_sed_1 = cmd/posix/sed -BIN_sleep_1 = cmd/posix/sleep -BIN_sort_1 = cmd/posix/sort -BIN_split_1 = cmd/posix/split -BIN_tail_1 = cmd/posix/tail -BIN_tee_1 = cmd/posix/tee -BIN_test_1 = cmd/posix/test -BIN_time_1 = cmd/posix/time -BIN_touch_1 = cmd/posix/touch -BIN_tr_1 = cmd/posix/tr -BIN_true_1 = cmd/posix/true -BIN_tsort_1 = cmd/posix/tsort -BIN_tty_1 = cmd/posix/tty -BIN_uname_1 = cmd/posix/uname -BIN_unexpand_1 = cmd/posix/unexpand -BIN_uniq_1 = cmd/posix/uniq -BIN_unlink_1 = cmd/posix/unlink -BIN_uudecode_1 = cmd/posix/uudecode -BIN_uuencode_1 = cmd/posix/uuencode -BIN_wc_1 = cmd/posix/wc -BIN_who_1 = cmd/posix/who -BIN_xargs_1 = cmd/posix/xargs -BIN_awk_1 = cmd/posix/awk/awk -BIN_sh_1 = cmd/posix/sh/sh -BIN_pax_1 = cmd/posix/pax -BIN_make_1 = cmd/posix/make/make - -BIN_blkdiscard_1 = cmd/linux/blkdiscard -BIN_chvt_1 = cmd/linux/chvt -BIN_ctrlaltdel_1 = cmd/linux/ctrlaltdel -BIN_eject_1 = cmd/linux/eject -BIN_freeramdisk_1 = cmd/linux/freeramdisk -BIN_fsfreeze_1 = cmd/linux/fsfreeze -BIN_hwclock_1 = cmd/linux/hwclock -BIN_insmod_1 = cmd/linux/insmod -BIN_lsmod_1 = cmd/linux/lsmod -BIN_lsusb_1 = cmd/linux/lsusb -BIN_modprobe_1 = cmd/linux/modprobe -BIN_depmod_1 = cmd/linux/depmod -BIN_mkswap_1 = cmd/linux/mkswap -BIN_mount_1 = cmd/linux/mount -BIN_mountpoint_1 = cmd/linux/mountpoint -BIN_pivot_root_1 = cmd/linux/pivot_root -BIN_readahead_1 = cmd/linux/readahead -BIN_rmmod_1 = cmd/linux/rmmod -BIN_swaplabel_1 = cmd/linux/swaplabel -BIN_swapoff_1 = cmd/linux/swapoff -BIN_swapon_1 = cmd/linux/swapon -BIN_switch_root_1 = cmd/linux/switch_root -BIN_sysctl_1 = cmd/linux/sysctl -BIN_tunctl_1 = cmd/linux/tunctl -BIN_umount_1 = cmd/linux/umount -BIN_unshare_1 = cmd/linux/unshare -BIN_vtallow_1 = cmd/linux/vtallow - -BIN_netcat_1 = cmd/net/netcat -BIN_tftp_1 = cmd/net/tftp -BIN_wget_1 = cmd/net/wget -BIN_ping_1 = cmd/net/ping -BIN_sdhcp_1 = cmd/net/sdhcp -BIN_ifconfig_1 = cmd/net/ifconfig -BIN_host_1 = cmd/net/host -BIN_httpd_1 = cmd/net/httpd -BIN_ip_1 = cmd/net/ip - -BIN_mknod_1 = cmd/xsi/mknod -BIN_passwd_1 = cmd/xsi/passwd -BIN_su_1 = cmd/xsi/su - -BIN_chroot_1 = cmd/pseudo/chroot -BIN_clear_1 = cmd/pseudo/clear -BIN_cols_1 = cmd/pseudo/cols -BIN_cron_1 = cmd/pseudo/cron -BIN_flock_1 = cmd/pseudo/flock -BIN_getty_1 = cmd/pseudo/getty -BIN_halt_1 = cmd/pseudo/halt -BIN_hostname_1 = cmd/pseudo/hostname -BIN_killall5_1 = cmd/pseudo/killall5 -BIN_last_1 = cmd/pseudo/last -BIN_lastlog_1 = cmd/pseudo/lastlog -BIN_login_1 = cmd/pseudo/login -BIN_md5sum_1 = cmd/pseudo/md5sum -BIN_mktemp_1 = cmd/pseudo/mktemp -BIN_nologin_1 = cmd/pseudo/nologin -BIN_pagesize_1 = cmd/pseudo/pagesize -BIN_printenv_1 = cmd/pseudo/printenv -BIN_respawn_1 = cmd/pseudo/respawn -BIN_rev_1 = cmd/pseudo/rev -BIN_seq_1 = cmd/pseudo/seq -BIN_setsid_1 = cmd/pseudo/setsid -BIN_sha1sum_1 = cmd/pseudo/sha1sum -BIN_sha224sum_1 = cmd/pseudo/sha224sum -BIN_sha256sum_1 = cmd/pseudo/sha256sum -BIN_sha384sum_1 = cmd/pseudo/sha384sum -BIN_sha512sum_1 = cmd/pseudo/sha512sum -BIN_sha512_224sum_1 = cmd/pseudo/sha512-224sum -BIN_sha512_256sum_1 = cmd/pseudo/sha512-256sum -BIN_sponge_1 = cmd/pseudo/sponge -BIN_stat_1 = cmd/pseudo/stat -BIN_tar_1 = cmd/pseudo/tar -BIN_truncate_1 = cmd/pseudo/truncate -BIN_watch_1 = cmd/pseudo/watch -BIN_which_1 = cmd/pseudo/which -BIN_whoami_1 = cmd/pseudo/whoami -BIN_xinstall_1 = cmd/pseudo/xinstall -BIN_yes_1 = cmd/pseudo/yes -BIN_base64_1 = cmd/pseudo/base64 -BIN_mkpasswd_1 = cmd/pseudo/mkpasswd -BIN_bc_1 = cmd/posix/bc -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_sync_1 = cmd/extra/sync -BIN_yap_1 = cmd/extra/yap/yap -BIN_diff3_1 = cmd/pseudo/diff3 -BIN_ar_1 = cmd/dev/ar/ar -BIN_as_1 = cmd/dev/as/as -BIN_ld_1 = cmd/dev/ld/ld -BIN_cc_1 = cmd/dev/cc/cc -BIN_dmesg_1 = cmd/pseudo/dmesg -BIN_fallocate_1 = cmd/pseudo/fallocate -BIN_free_1 = cmd/pseudo/free -BIN_pidof_1 = cmd/pseudo/pidof -BIN_pwdx_1 = cmd/pseudo/pwdx -BIN_uptime_1 = cmd/pseudo/uptime - -POSIX_BIN = $(POSIX_BIN_CONFIG) - -LINUX_BIN = $(LINUX_BIN_CONFIG) - -NET_BIN = $(NET_BIN_CONFIG) - -XSI_BIN = $(XSI_BIN_CONFIG) - -PSEUDO_BIN = $(PSEUDO_BIN_CONFIG) $(EXTRA_BIN_CONFIG) $(DEV_BIN_CONFIG) - - -OBJ = $(LIBUTFOBJ) $(LIBUTILOBJ) $(MAKEOBJ) - -all: $(LIB) $(POSIX_BIN) $(LINUX_BIN) $(NET_BIN) $(XSI_BIN) $(PSEUDO_BIN) - --include deps.mk --include scripts/mk/rules.mk - -$(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL): $(LIB) - -$(OBJ) $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL): $(HDR) - -.o: - $(CC) $(LDFLAGS) -o $@ $< $(LIB) $(LDLIBS) - -.c.o: - $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $< - -.c: - $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< $(LIB) $(LDLIBS) - -cmd/posix/bc.c: cmd/posix/bc.y - YACC='$(YACC)' sh scripts/genconfig.sh bc - -cmd/posix/bc: cmd/posix/bc.c - $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ cmd/posix/bc.c $(LIB) $(LDLIBS) - -$(MAKEOBJ): cmd/posix/make/make.h - -cmd/posix/make/make: $(MAKEOBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(MAKEOBJ) $(LIB) $(LDLIBS) - -cmd/posix/diff: cmd/posix/diff.c $(LIB) - $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ cmd/posix/diff.c $(LIB) $(LDLIBS) -lm - -shared/libutf/libutf.a: $(LIBUTFOBJ) - $(AR) $(ARFLAGS) $@ $? - $(RANLIB) $@ - -shared/libredline/libredline.a: $(LIBREDLINEOBJ) - $(AR) $(ARFLAGS) $@ $? - $(RANLIB) $@ - -shared/libutil/libutil.a: $(LIBUTILOBJ) - $(AR) $(ARFLAGS) $@ $? - $(RANLIB) $@ - -cmd/posix/getconf: cmd/posix/getconf.h - -cmd/posix/getconf.h: - sh scripts/genconfig.sh getconf - -box: $(LIB) - CC='$(CC)' CPPFLAGS='$(CPPFLAGS)' CFLAGS='$(CFLAGS)' \ - LDFLAGS='$(LDFLAGS)' LDLIBS='$(LDLIBS)' OBJCOPY='$(OBJCOPY)' \ - scripts/mkbox - -.PHONY: man clean install regen help - -scripts/mkman/mkman: scripts/mkman/main.go scripts/mkman/page.go scripts/mkman/parse.go scripts/mkman/mdoc.go - cd scripts/mkman && go build -o mkman . - -man: scripts/mkman/mkman - find cmd -type f -name '*.c' | while read -r src; do \ - if [ -f "$$src" ] && grep -qE '!man|\?man' "$$src"; then \ - sub=$${src#cmd/}; \ - cat=$${sub%%/*}; \ - base=$${src##*/}; \ - base=$${base%.c}; \ - name=$${sub#*/}; \ - if [ "$${name}" != "$${base}.c" ]; then \ - name=$${name%%/*}; \ - else \ - name=$$base; \ - fi; \ - u_group=$$(echo "$$cat" | tr 'a-z' 'A-Z'); \ - u_tool=$$(echo "$$name" | tr 'a-z-' 'A-Z_'); \ - var_name="BUILD_$${u_group}_$${u_tool}"; \ - val=""; \ - if [ -f scripts/mk/config.kv ]; then \ - val=$$(grep "^$${var_name}=" scripts/mk/config.kv | cut -d= -f2 | tr -d '"'); \ - fi; \ - if [ "$$val" != "1" ]; then \ - continue; \ - fi; \ - case "$$cat" in \ - linux|net|xsi) sec=8 ;; \ - *) sec=1 ;; \ - esac; \ - mkdir -p "man/man$${sec}"; \ - scripts/mkman/mkman -fmt mdoc -config scripts/mk/config.kv -section "$${sec}" "$$src" > "man/man$${sec}/$$name.$${sec}"; \ - scripts/mkman/mkman -fmt txt -config scripts/mk/config.kv -section "$${sec}" "$$src" > "man/man$${sec}/$$name.$${sec}.txt"; \ - fi; \ - done - -regen: scripts/mk/config.mk cmd/posix/getconf.h cmd/posix/bc.c cmd/posix/awk/awkgram.tab.c cmd/posix/awk/proctab.c cmd/posix/sh/token.h cmd/posix/sh/syntax.c cmd/posix/sh/nodes.c cmd/posix/sh/builtins.c - -help: - @echo "Available targets:" - @echo " all - Build all enabled utilities" - @echo " clean - Clean build artifacts" - @echo " install - Install binaries and man pages" - @echo " box - Build the multicall binary (aruu-box)" - @echo " man - Generate manual pages" - @echo " regen - Regenerate build system files and config" - @echo " help - Show this help message" - -install: all man - @mkdir -p $(PREFIX)/bin $(MANPREFIX)/man1 $(MANPREFIX)/man8 - @find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do \ - printf " INSTALL %s/bin/%s\n" "$(PREFIX)" "$${bin##*/}"; \ - cp "$$bin" "$(PREFIX)/bin/$${bin##*/}"; \ - chmod 755 "$(PREFIX)/bin/$${bin##*/}"; \ - done - @find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do \ - sec=$${f%/*}; sec=$${sec##*/}; \ - cp "$$f" "$(MANPREFIX)/$${sec}/$${f##*/}"; \ - done - -clean: - @printf " CLEAN object files\n" - @find shared cmd -name "*.o" -exec rm -f {} + - @printf " CLEAN static libraries\n" - @rm -f $(LIB) - @printf " CLEAN compiled binaries\n" - @rm -f $(POSIX_BIN_ALL) $(LINUX_BIN_ALL) $(NET_BIN_ALL) $(XSI_BIN_ALL) $(PSEUDO_BIN_ALL) - @sh scripts/genconfig.sh clean - @printf " CLEAN build tools\n" - @rm -f scripts/mkman/mkman - @rm -f scripts/mk/config.kv - @rm -f scripts/mk/config.mk - @rm -f scripts/mk/rules.mk - - @printf " CLEAN dev artifacts\n" - @rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar shared/libaruuelf.so - @rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h - @printf " CLEAN misc\n" - @rm -rf aruu-box .box man/man1 man/man8 - @printf " CLEAN done\n" -AWKOBJ =\ - cmd/posix/awk/b.o\ - cmd/posix/awk/main.o\ - cmd/posix/awk/parse.o\ - cmd/posix/awk/proctab.o\ - cmd/posix/awk/tran.o\ - cmd/posix/awk/lib.o\ - cmd/posix/awk/run.o\ - cmd/posix/awk/lex.o\ - cmd/posix/awk/math.o\ - cmd/posix/awk/awkgram.tab.o - -SH_GENHDRS =\ - cmd/posix/sh/syntax.h\ - cmd/posix/sh/nodes.h\ - cmd/posix/sh/builtins.h\ - cmd/posix/sh/token.h - -SHOBJ =\ - cmd/posix/sh/alias.o\ - cmd/posix/sh/arith_yacc.o\ - cmd/posix/sh/arith_yylex.o\ - cmd/posix/sh/cd.o\ - cmd/posix/sh/echo.o\ - cmd/posix/sh/error.o\ - cmd/posix/sh/easter.o\ - cmd/posix/sh/eval.o\ - cmd/posix/sh/exec.o\ - cmd/posix/sh/expand.o\ - cmd/posix/sh/lineedit.o\ - cmd/posix/sh/input.o\ - cmd/posix/sh/jobs.o\ - cmd/posix/sh/kill.o\ - cmd/posix/sh/mail.o\ - cmd/posix/sh/main.o\ - cmd/posix/sh/memalloc.o\ - cmd/posix/sh/miscbltin.o\ - cmd/posix/sh/mystring.o\ - cmd/posix/sh/options.o\ - cmd/posix/sh/output.o\ - cmd/posix/sh/parser.o\ - cmd/posix/sh/printf.o\ - cmd/posix/sh/redir.o\ - cmd/posix/sh/show.o\ - cmd/posix/sh/test.o\ - cmd/posix/sh/trap.o\ - cmd/posix/sh/var.o\ - cmd/posix/sh/builtins.o\ - cmd/posix/sh/nodes.o\ - cmd/posix/sh/syntax.o - -YAPOBJ =\ - cmd/extra/yap/ansi.o\ - cmd/extra/yap/commands.o\ - cmd/extra/yap/display.o\ - cmd/extra/yap/getcomm.o\ - cmd/extra/yap/getline.o\ - cmd/extra/yap/help.o\ - cmd/extra/yap/keys.o\ - cmd/extra/yap/machine.o\ - cmd/extra/yap/main.o\ - cmd/extra/yap/options.o\ - cmd/extra/yap/output.o\ - cmd/extra/yap/pattern.o\ - cmd/extra/yap/process.o\ - cmd/extra/yap/prompt.o\ - cmd/extra/yap/term.o - -cmd/posix/awk/awkgram.tab.c: cmd/posix/awk/awkgram.y cmd/posix/awk/maketab.c - CC='$(CC)' CFLAGS='$(CFLAGS)' YACC='$(YACC)' sh scripts/genconfig.sh awk - -cmd/posix/awk/awkgram.tab.h: cmd/posix/awk/awkgram.tab.c ; -cmd/posix/awk/maketab: cmd/posix/awk/awkgram.tab.c ; -cmd/posix/awk/proctab.c: cmd/posix/awk/awkgram.tab.c ; - -$(AWKOBJ): cmd/posix/awk/awk.h cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proto.h - -cmd/posix/awk/awk: $(AWKOBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(AWKOBJ) $(LIB) $(LDLIBS) -lm - -cmd/posix/sh/builtins.c: cmd/posix/sh/mknodes.c cmd/posix/sh/mksyntax.c cmd/posix/sh/nodetypes cmd/posix/sh/nodes.c.pat cmd/posix/sh/mkbuiltins cmd/posix/sh/builtins.def cmd/posix/sh/shell.h cmd/posix/sh/mktokens - CC='$(CC)' CFLAGS='$(CFLAGS)' CPPFLAGS='$(CPPFLAGS)' sh scripts/genconfig.sh sh - -cmd/posix/sh/syntax.c: cmd/posix/sh/builtins.c ; -cmd/posix/sh/syntax.h: cmd/posix/sh/builtins.c ; -cmd/posix/sh/nodes.c: cmd/posix/sh/builtins.c ; -cmd/posix/sh/nodes.h: cmd/posix/sh/builtins.c ; -cmd/posix/sh/builtins.h: cmd/posix/sh/builtins.c ; -cmd/posix/sh/token.h: cmd/posix/sh/builtins.c ; -cmd/posix/sh/mknodes: cmd/posix/sh/builtins.c ; -cmd/posix/sh/mksyntax: cmd/posix/sh/builtins.c ; - -$(SHOBJ): $(SH_GENHDRS) - -cmd/posix/sh/sh: $(SHOBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(SHOBJ) $(LIB) $(LDLIBS) - -cmd/extra/yap/yap: $(YAPOBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(YAPOBJ) $(LIB) $(LDLIBS) -ltinfo - -cmd/extra/diff3/diff3: cmd/extra/diff3/diff3.o cmd/posix/diff/xmalloc.o $(LIB) - $(CC) $(LDFLAGS) -o $@ cmd/extra/diff3/diff3.o cmd/posix/diff/xmalloc.o $(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) - -LD_OBJ =\ - 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/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/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 - -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/as: $(AS_OBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(AS_OBJ) $(LIB) $(LDLIBS) - -cmd/dev/cc/driver.o: cmd/dev/cc/config.h - -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 =\ - cmd/dev/cc/attr.o\ - cmd/dev/cc/decl.o\ - cmd/dev/cc/eval.o\ - cmd/dev/cc/expr.o\ - cmd/dev/cc/init.o\ - cmd/dev/cc/cc1.o\ - cmd/dev/cc/map.o\ - cmd/dev/cc/pp.o\ - cmd/dev/cc/qbe.o\ - cmd/dev/cc/scan.o\ - cmd/dev/cc/scope.o\ - cmd/dev/cc/stmt.o\ - cmd/dev/cc/targ.o\ - cmd/dev/cc/token.o\ - cmd/dev/cc/tree.o\ - cmd/dev/cc/type.o\ - cmd/dev/cc/utf.o\ - cmd/dev/cc/util.o - -CPP_OBJ =\ - cmd/dev/cc/attr.o\ - cmd/dev/cc/decl.o\ - cmd/dev/cc/eval.o\ - cmd/dev/cc/expr.o\ - cmd/dev/cc/init.o\ - cmd/dev/cc/map.o\ - cmd/dev/cc/pp.o\ - cmd/dev/cc/qbe.o\ - cmd/dev/cc/scan.o\ - cmd/dev/cc/scope.o\ - cmd/dev/cc/stmt.o\ - cmd/dev/cc/targ.o\ - cmd/dev/cc/token.o\ - cmd/dev/cc/tree.o\ - cmd/dev/cc/type.o\ - cmd/dev/cc/utf.o\ - cmd/dev/cc/util.o - -cmd/dev/cc/cc1: $(CC1_OBJ) $(LIB) - $(CC) $(LDFLAGS) -o $@ $(CC1_OBJ) $(LIB) $(LDLIBS) - -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/configure - sh cmd/dev/configure - -cmd/dev/cc/config.h: cmd/dev/config.h ; -cmd/dev/version.h: cmd/dev/config.h ; - -$(AS_OBJ) $(LD_OBJ) $(CC1_OBJ) $(CPP_OBJ) cmd/dev/ar/ar.o cmd/dev/cc/cpp.o: cmd/dev/config.h - -scripts/mk/config.mk: build.cfg scripts/genconfig.sh - sh scripts/genconfig.sh - -scripts/mk/config.kv: scripts/mk/config.mk ; -scripts/mk/rules.mk: scripts/mk/config.mk ; - +CC ?= cc -static +CFLAGS ?= -std=c99 -Wall -Wextra -pedantic +CPPFLAGS ?= -Ishared -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L \ + -DFEATURE_NOFORK=0 -DFEATURE_NOEXEC=0 +# NOEXEC cannot be on the bootstrap compile, but it can +# be on when one compiles aruu-box with ninqu included + +NINQU_LIB_SRC =\ + shared/libutil/ealloc.c\ + shared/libutil/eprintf.c\ + shared/libutil/strlcpy.c\ + shared/libutil/strlcat.c\ + shared/libutil/strtonum.c\ + shared/libutil/fshut.c\ + shared/libutil/mkdirp.c\ + shared/libutil/recurse_dir.c + +NINQU_SRC =\ + cmd/dev/ninqu/main.c\ + cmd/dev/ninqu/strlist.c\ + cmd/dev/ninqu/kv.c\ + cmd/dev/ninqu/sexpr.c\ + cmd/dev/ninqu/gate.c\ + cmd/dev/ninqu/registry.c\ + cmd/dev/ninqu/fs.c\ + cmd/dev/ninqu/exec.c\ + cmd/dev/ninqu/parse.c\ + cmd/dev/ninqu/expand.c\ + cmd/dev/ninqu/schedule.c\ + cmd/dev/ninqu/query.c\ + cmd/dev/ninqu/resolve.c + +# map make's -j to ninqu's -j flag +NINQU ?= cmd/dev/ninqu/ninqu +JOBS ?= $(filter -j%,$(MAKEFLAGS)) + +# rebuilds config.set first so a build.cfg edit is picked up before +# ninqu compiles, ninqu also does this lazily on its own via +# (set-file), this just avoids the extra shell startup on every run +$(NINQU): $(NINQU_SRC) cmd/dev/ninqu/ninqu.h scripts/mk/config.set $(NINQU_LIB_SRC) + $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(NINQU_SRC) $(NINQU_LIB_SRC) + +# FORCE has no rule, thus making any pattern +# that depends on it be always outdated +.PHONY: FORCE +FORCE: + +%: $(NINQU) FORCE + $(NINQU) $(JOBS) $@ + +clean: $(NINQU) + $(NINQU) clean + rm -f $(NINQU) + +scripts/mk/config.set: build.cfg scripts/genconfig.sh + sh scripts/genconfig.sh config + +# stops the % pattern rule above from trying to rebuild these as if +# they were stale build targets Makefile: ; +ninqu.rules: ; +cmd/dev/ninqu/ninqu.h: ; +cmd/dev/ninqu/main.c: ; +cmd/dev/ninqu/strlist.c: ; +cmd/dev/ninqu/kv.c: ; +cmd/dev/ninqu/sexpr.c: ; +cmd/dev/ninqu/gate.c: ; +cmd/dev/ninqu/registry.c: ; +cmd/dev/ninqu/fs.c: ; +cmd/dev/ninqu/exec.c: ; +cmd/dev/ninqu/parse.c: ; +cmd/dev/ninqu/expand.c: ; +cmd/dev/ninqu/schedule.c: ; +cmd/dev/ninqu/query.c: ; +cmd/dev/ninqu/resolve.c: ; +build.cfg: ; +scripts/genconfig.sh: ; diff --git a/Makefile.sh b/Makefile.sh @@ -1,537 +0,0 @@ -#!/bin/sh -# drives the build without needing a working make to bootstrap -# -set -e - -# per-run work directory, cleaned up on exit -# -WORKDIR="${TMPDIR:-/tmp}/aruu.$$" -mkdir -p "$WORKDIR" -trap 'rm -rf "$WORKDIR"' EXIT INT TERM HUP - -JOBS=1 -LOAD=0 -TARGET=all - -while [ $# -gt 0 ]; do - case "$1" in - -j) shift; JOBS="${1:?-j requires a number}" ;; - -j*) JOBS="${1#-j}" ;; - -l) shift; LOAD="${1:?-l requires a number}" ;; - -l*) LOAD="${1#-l}" ;; - -*) printf 'unknown flag: %s\n' "$1" >&2; exit 1 ;; - *) TARGET="$1" ;; - esac - shift -done - -# timestamp comparison -# -mtime() { - stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0 -} -newer_than() { - local s t - [ -e "$2" ] || return 0 - s=$(mtime "$1"); t=$(mtime "$2") - [ "$s" -gt "$t" ] -} -any_newer_than() { - local target="$1"; shift - for src do - newer_than "$src" "$target" && return 0 - done - return 1 -} - -[ -f build.cfg ] || { printf 'build.cfg not found; see the repository README\n' >&2; exit 1; } - -# generate config files if missing or build.cfg is newer -if [ ! -f scripts/mk/config.kv ] || newer_than build.cfg scripts/mk/config.kv; then - sh scripts/genconfig.sh -fi - -# shellcheck disable=SC1091 -. ./build.cfg - -# load config.kv if it exists to override and provide detected TLS settings -if [ -f scripts/mk/config.kv ]; then - # shellcheck disable=SC1091 - . ./scripts/mk/config.kv -fi - -# cppflags derived from build.cfg; any feature_* added there is picked up automatically -_feature_flags="" -while IFS= read -r _line; do - _trimmed=$(printf '%s' "$_line" | tr -d ' \t') - case "$_trimmed" in - FEATURE_*=*) - _key=${_trimmed%%=*} - eval "_val=\$$_key" - _feature_flags="$_feature_flags -D${_key}=${_val}" - ;; - esac -done <<EOF -$(tr ';' '\n' < build.cfg) -EOF -unset _line _key _val _trimmed - -CPPFLAGS="-Ishared -DPREFIX=\\\"\$PREFIX\\\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64$_feature_flags $CPPFLAGS_TLS" -LDFLAGS="${LDFLAGS:-} $LDFLAGS_TLS" -TLS_LDLIBS="$LDLIBS_TLS" - -CC=${CC:-cc} -AR=${AR:-ar} -ARFLAGS=${ARFLAGS:-rc} -RANLIB=${RANLIB:-ranlib} -PREFIX=${PREFIX:-/usr/local} -MANPREFIX=${MANPREFIX:-$PREFIX/share/man} - -# shared headers, most objects depend on these -HDR=$(echo shared/*.h) -LIB="shared/libredline/libredline.a shared/libutil/libutil.a shared/libutf/libutf.a" - -# set by multi-file builders for generated headers, cleared after use -EXTRA_HDR= - -# parallel job queue -# objs_for must not run in a subshell, enqueue writes _qn/_queue in the current shell -# -_qn=0 -_queue="" -_objs="" -# wraps arg in single quotes, escaping embedded ones, for safe eval -shquote() { - printf "'" - printf '%s' "$1" | sed "s/'/'\\\\''/g" - printf "'" -} -enqueue() { - local desc="$1" cmd="$2" - _qn=$((_qn + 1)) - local s="$WORKDIR/j${_qn}.sh" - { - printf '#!/bin/sh\n' - printf 'printf "%%s\\n" %s\n' "$(shquote "$desc")" - printf 'eval %s\n' "$(shquote "$cmd")" - } > "$s" - _queue="$_queue $_qn" -} -# silently skipped on systems without /proc/loadavg -_wait_for_load() { - [ "$LOAD" -eq 0 ] && return 0 - local avg - while true; do - avg=$(awk '{printf "%d", int($1 + 0.5)}' /proc/loadavg 2>/dev/null) || return 0 - [ "$avg" -le "$LOAD" ] && return 0 - sleep 1 - done -} -drain() { - [ -z "$_queue" ] && return 0 - local n - _wait_for_load - if [ "$JOBS" -le 1 ]; then - for n in $_queue; do - sh "$WORKDIR/j${n}.sh" || { printf 'error: build step failed\n' >&2; exit 1; } - done - else - # xargs -P (POSIX 2024), -n 1 so each path becomes its own sh invocation - for n in $_queue; do - printf '%s\n' "$WORKDIR/j${n}.sh" - done | xargs -P "$JOBS" -n 1 sh || { printf 'error: build step failed\n' >&2; exit 1; } - fi - _queue="" -} - -# compile and link routines -# -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" -} -link_bin() { - local bin="$1" objs="" libs="" sep=0; shift - for a do - if [ "$a" = "--" ]; then sep=1 - elif [ "$sep" = 0 ]; then objs="$objs $a" - else libs="$libs $a" - fi - done - drain - # shellcheck disable=SC2086 - any_newer_than "$bin" $objs || return 0 - printf ' LD %s\n' "$bin" - # shellcheck disable=SC2086 - if [ "${bin##*/}" = "wget" ]; then - eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS $TLS_LDLIBS" - else - eval "$CC $LDFLAGS -o $bin $objs $libs $LDLIBS" - fi -} -# writes to _objs rather than stdout so the caller avoids a subshell that -# would discard enqueued jobs -objs_for() { - local dir="$1" skip=" $2 " flags="$3" src base - _objs="" - for src in "$dir"/*.c; do - [ -f "$src" ] || continue - base=${src##*/} - case "$skip" in *" $base "*) continue ;; esac - compile_c "$src" "${src%.c}.o" $flags - _objs="$_objs ${src%.c}.o" - done -} - -# static libraries -# both directories enqueued before the single drain so they compile in parallel -# -build_lib() { - local utf_objs util_objs redline_objs - objs_for shared/libutf "" "" - utf_objs="$_objs" - objs_for shared/libutil "" "" - util_objs="$_objs" - objs_for shared/libredline "" "" - redline_objs="$_objs" - drain - # shellcheck disable=SC2086 - any_newer_than shared/libutf/libutf.a $utf_objs && { - printf ' AR shared/libutf/libutf.a\n' - $AR $ARFLAGS shared/libutf/libutf.a $utf_objs - $RANLIB shared/libutf/libutf.a - } - # shellcheck disable=SC2086 - any_newer_than shared/libutil/libutil.a $util_objs && { - printf ' AR shared/libutil/libutil.a\n' - $AR $ARFLAGS shared/libutil/libutil.a $util_objs - $RANLIB shared/libutil/libutil.a - } - # shellcheck disable=SC2086 - any_newer_than shared/libredline/libredline.a $redline_objs && { - printf ' AR shared/libredline/libredline.a\n' - $AR $ARFLAGS shared/libredline/libredline.a $redline_objs - $RANLIB shared/libredline/libredline.a - } - return 0 -} - -# per-tool category builder -# -cfgvar() { - local cat="$1" base="$2" - printf 'BUILD_%s_%s' "$cat" "$base" | tr 'a-z-' 'A-Z_' -} - -# individual flag overrides group flag -cfg_enabled() { - local _var="$1" _v - while [ -n "$_var" ]; do - eval "_v=\${${_var}-UNSET}" - if [ "$_v" = "1" ]; then - return 0 - elif [ "$_v" = "0" ]; then - return 1 - fi - case "$_var" in - *_[!_]*) _var=$(printf '%s' "$_var" | sed 's/_[^_]*$//') ;; - *) break ;; - esac - done - return 1 -} - -build_simple_tools() { - local cat="$1" src base var - for src in cmd/"$cat"/*.c; do - [ -f "$src" ] || continue - base=${src##*/}; base=${base%.c} - var=$(cfgvar "$cat" "$base") - cfg_enabled "$var" || continue - local bin="cmd/$cat/$base" - # shellcheck disable=SC2086 - any_newer_than "$bin" "$src" $HDR $EXTRA_HDR $LIB || continue - if [ "$base" = "diff" ]; then - enqueue " CC $bin" "$CC $src $CPPFLAGS $CFLAGS $LDFLAGS -o $bin $LIB -lm $LDLIBS" - else - enqueue " CC $bin" "$CC $src $CPPFLAGS $CFLAGS $LDFLAGS -o $bin $LIB $LDLIBS" - fi - done - drain -} - -build_awk() { - cfg_enabled BUILD_POSIX_AWK || return 0 - local dir=cmd/posix/awk - CC="$CC" CFLAGS="$CFLAGS" YACC="$YACC" sh scripts/genconfig.sh awk - EXTRA_HDR="$dir/awk.h $dir/awkgram.tab.h $dir/proto.h" - objs_for "$dir" maketab.c "-I$dir" - EXTRA_HDR= - link_bin "$dir/awk" $_objs -- $LIB -lm -} - -build_sh() { - cfg_enabled BUILD_POSIX_SH || return 0 - local dir=cmd/posix/sh - CC="$CC" CFLAGS="$CFLAGS" CPPFLAGS="$CPPFLAGS" sh scripts/genconfig.sh sh - EXTRA_HDR="$dir/syntax.h $dir/nodes.h $dir/builtins.h $dir/token.h" - objs_for "$dir" "mknodes.c mksyntax.c" "-DSHELL -I$dir" - EXTRA_HDR= - link_bin "$dir/sh" $_objs -- $LIB -} - -build_make() { - cfg_enabled BUILD_POSIX_MAKE || return 0 - local dir=cmd/posix/make - EXTRA_HDR="$dir/make.h" - objs_for "$dir" "" "" - EXTRA_HDR= - link_bin "$dir/make" $_objs -- $LIB -} - -build_bc() { - cfg_enabled BUILD_POSIX_BC || return 0 - local src=cmd/posix/bc.c - YACC="$YACC" sh scripts/genconfig.sh bc - # shellcheck disable=SC2086 - any_newer_than cmd/posix/bc "$src" $HDR $EXTRA_HDR $LIB || return 0 - printf ' CC cmd/posix/bc\n' - eval "$CC $src $CPPFLAGS $CFLAGS $LDFLAGS -o cmd/posix/bc $LIB $LDLIBS" -} - -build_posix() { - cfg_enabled BUILD_POSIX_GETCONF && sh scripts/genconfig.sh getconf - build_simple_tools posix - build_awk - build_bc - build_sh - build_make -} - -# multi-file dev toolchain -# -build_ar() { - cfg_enabled BUILD_DEV_AR || return 0 - local dir=cmd/dev/ar - objs_for "$dir" tinyar.c "-I$dir" - link_bin "$dir/ar" $_objs -- $LIB -} - -build_as() { - cfg_enabled BUILD_DEV_AS || return 0 - local dir="cmd/dev/as" - local flags="-Icmd/dev/xcutil -I$dir -Ishared" - local objs="" - objs_for "cmd/dev/xcutil" "" "$flags" - objs="$objs $_objs" - objs_for "$dir" "" "$flags" - objs="$objs $_objs" - objs_for "$dir/arch/x64" "" "-Icmd/dev/xcutil -I$dir -I$dir/arch/x64 -Ishared" - objs="$objs $_objs" - link_bin "$dir/as" $objs -- $LIB -} - -build_ld() { - cfg_enabled BUILD_DEV_LD || return 0 - local dir="cmd/dev/ld" - local flags="-Icmd/dev/xcutil -I$dir" - local objs="" - objs_for "cmd/dev/xcutil" "" "$flags" - objs="$objs $_objs" - objs_for "$dir" "" "$flags" - objs="$objs $_objs" - link_bin "$dir/ld" $objs -- $LIB -} - -build_cc() { - cfg_enabled BUILD_DEV_CC || return 0 - local dir="cmd/dev/cc" - local cflags="-I$dir" - local common - - # compiled once, linked into both cc1 and cpp - objs_for "$dir" "driver.c cc1.c cpp.c" "$cflags" - common="$_objs" - drain - - compile_c "$dir/cc1.c" "$dir/cc1.o" $cflags - compile_c "$dir/cpp.c" "$dir/cpp.o" $cflags - compile_c "$dir/driver.c" "$dir/driver.o" $cflags - drain - - link_bin "$dir/cc1" "$dir/cc1.o" $common -- $LIB - link_bin "$dir/cpp" "$dir/cpp.o" $common -- $LIB - link_bin "$dir/cc" "$dir/driver.o" "$dir/util.o" -- $LIB -} - -build_dev() { - [ -f cmd/dev/configure ] && sh cmd/dev/configure - build_ar - build_as - build_ld - build_cc -} - -# manual page generation -# -man_section() { - case "$1" in - */linux/*|*/net/*|*/xsi/*) printf '8\n' ;; - *) printf '1\n' ;; - esac -} - -build_man_for() { - local var="$1" src="$2" name="$3" 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 - - sec=$(man_section "$src") - - mkdir -p "man/man${sec}" - out_mdoc="man/man${sec}/${name}.${sec}" - out_txt="man/man${sec}/${name}.${sec}.txt" - if any_newer_than "$out_mdoc" "$src" scripts/mk/config.kv scripts/mkman/mkman; then - printf ' MAN %s\n' "$out_mdoc" - scripts/mkman/mkman -fmt mdoc -config scripts/mk/config.kv -section "$sec" "$src" > "$out_mdoc" - fi - if any_newer_than "$out_txt" "$src" scripts/mk/config.kv scripts/mkman/mkman; then - printf ' MAN %s\n' "$out_txt" - scripts/mkman/mkman -fmt txt -config scripts/mk/config.kv -section "$sec" "$src" > "$out_txt" - fi -} - -build_man() { - local src cat base sub name var - 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 - find cmd -type f -name '*.c' | while read -r src; do - sub=${src#cmd/} - cat=${sub%%/*} - base=${src##*/} - base=${base%.c} - name=${sub#*/} - if [ "${name}" != "${base}.c" ]; then - name=${name%%/*} - else - name=$base - fi - var=$(cfgvar "$cat" "$name") - build_man_for "$var" "$src" "$name" - done -} - -# install and clean -# -do_install() { - local bin f sec - mkdir -p "$PREFIX/bin" "$MANPREFIX/man1" "$MANPREFIX/man8" - find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do - printf ' INSTALL %s/bin/%s\n' "$PREFIX" "${bin##*/}" - cp "$bin" "$PREFIX/bin/${bin##*/}" - chmod 755 "$PREFIX/bin/${bin##*/}" - done - find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do - sec=${f%/*}; sec=${sec##*/} - cp "$f" "$MANPREFIX/${sec}/${f##*/}" - done -} - -do_regen() { - # 1. regenerate config - sh scripts/genconfig.sh - - # 2. re-read the new config.kv - if [ -f scripts/mk/config.kv ]; then - # shellcheck disable=SC1091 - . scripts/mk/config.kv - fi - - # 3. clean and generate files using scripts/genconfig.sh - CC="$CC" CFLAGS="$CFLAGS" CPPFLAGS="$CPPFLAGS" YACC="$YACC" sh scripts/genconfig.sh clean - CC="$CC" CFLAGS="$CFLAGS" CPPFLAGS="$CPPFLAGS" YACC="$YACC" sh scripts/genconfig.sh all -} - -do_clean() { - printf ' CLEAN object files\n' - find shared cmd -name '*.o' -exec rm -f {} + - printf ' CLEAN static libraries\n' - find shared -name '*.a' -exec rm -f {} + - printf ' CLEAN compiled binaries\n' - find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} + - sh scripts/genconfig.sh clean - rm -f scripts/mk/config.mk scripts/mk/config.kv scripts/mk/rules.mk shared/libutil/nofork_list.h - printf ' CLEAN build tools\n' - rm -f scripts/mkman/mkman - printf ' CLEAN dev artifacts\n' - rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar - rm -f shared/libaruuelf.so - rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h - printf ' CLEAN misc\n' - rm -rf man/man1 man/man8 - rm -rf aruu-box .box - printf ' CLEAN done\n' -} - -case "$TARGET" in - all) - build_lib - build_posix - build_dev - build_simple_tools linux - build_simple_tools net - build_simple_tools xsi - build_simple_tools pseudo - build_simple_tools extra - ;; - lib) build_lib ;; - posix) build_lib; build_posix ;; - dev) build_lib; build_dev ;; - make) build_lib; build_make ;; - linux|net|xsi|pseudo|extra) - build_lib; build_simple_tools "$TARGET" ;; - regen) do_regen ;; - clean) do_clean ;; - man) build_man ;; - install) - build_lib - build_posix - build_dev - build_simple_tools linux - build_simple_tools net - build_simple_tools xsi - build_simple_tools pseudo - build_simple_tools extra - build_man - do_install - ;; - help) - printf 'usage: sh Makefile.sh [-jN] [-lN] [all|clean|install|man|lib|posix|linux|net|xsi|pseudo|extra|dev|make|regen|help]\n' - printf '\nTargets:\n' - printf ' all Build all enabled utilities\n' - printf ' clean Clean built objects and binaries\n' - printf ' install Install binaries and man pages\n' - printf ' man Generate man pages\n' - printf ' lib Build core libraries\n' - printf ' posix Build POSIX utilities\n' - printf ' linux Build Linux utilities\n' - printf ' net Build Network utilities\n' - printf ' xsi Build XSI utilities\n' - printf ' pseudo Build Pseudo utilities\n' - printf ' extra Build Extra utilities\n' - printf ' dev Build Dev toolchain\n' - printf ' make Build POSIX make\n' - printf ' regen Regenerate configuration and all generated source files\n' - printf ' help Show this help message\n' - ;; - *) - printf 'usage: sh Makefile.sh [-jN] [-lN] [all|clean|install|man|lib|posix|linux|net|xsi|pseudo|extra|dev|make|regen|help]\n' >&2 - exit 1 - ;; -esac diff --git a/README b/README @@ -9,7 +9,8 @@ on their toybox applet equivalent. The codebase has diverged a lot since the project started. And we have a myriad of utilities which were written specifically for ARUU. We also have greatly simplified ports of components from other systems -and projects, such as FreeBSD sh, minix yap (pager), onetrueawk, etc. +and projects, such as FreeBSD sh, minix yap (pager (thanks shrub)), +onetrueawk, etc. OVERVIEW ======== @@ -19,10 +20,11 @@ aruu builds two things: 1. individual tool binaries (default 'make all') 2. aruu-box: a multi-call binary containing every tool ('make box') -The multi-call binary is built by scripts/mkbox. It uses objcopy to -rename each tool's 'main' symbol, generates a C dispatch table, then -links everything into a single statically-dispatched binary. Invoke -tools by symlinking aruu-box to the tool name, or by running: +The multi-call binary is built by ninqu's box group (BOX_OBJ, BOX_DISPATCH, +and BOX in ninqu.rules). Each enabled tool gets objcopied so only its +renamed main stays global, scripts/genbox.sh turns the resulting object +paths into a C dispatch table, and everything links into one binary. +Invoke tools by symlinking aruu-box to the tool name, or by running: aruu-box <command> [args...] @@ -43,6 +45,23 @@ Optional: yacc only needed if rebuilding bc from bc.y +HOW THE BUILD WORKS +==================== + +make builds cmd/dev/ninqu/ninqu, then forwards whatever target you +gave it (make all, make box, make clean, ...) straight to that binary. + +ninqu reads ninqu.rules, which pulls in scripts/mk/config.set. That +file is generated by scripts/genconfig.sh, which reads build.cfg, +resolves every preset and per-tool override, and writes config.set +(read by ninqu), config.kv (shell-sourced by genbox.sh), and +scripts/mk/features.h (the resolved FEATURE_* set, pulled into every +compile with -include). + +To change what gets built, or see what a preset turns on or off, +edit or read build.cfg. That is the one file genconfig.sh expands +from, everything downstream of it is generated and safe to delete. + BUILDING ======== @@ -58,7 +77,8 @@ Both targets can be combined: make all box -Configuration is in config.mk. You can override compile flags via make +Configuration is in build.cfg. You can override compile flags via make +or with ninqu's -D flag (see HOW THE BUILD WORKS above). INSTALL ======= @@ -69,14 +89,18 @@ INSTALL SOURCE LAYOUT ============= - Makefile pdpmake-compatible build rules + Makefile builds cmd/dev/ninqu/ninqu, forwards to it + ninqu.rules all real build knowledge, read by ninqu + build.cfg presets and per-tool overrides scripts/ - mkbox builds aruu-box from compiled tool objects - getconf.sh generates cmd/posix/getconf.h at build time + genconfig.sh build.cfg -> config.set/config.kv/features.h + genbox.sh writes aruu-box's dispatch table + getconf.sh generates cmd/posix/getconf.h at build time + mkbox legacy, superseded by ninqu's box group shared/ - *.h project headers (util.h, arg.h, utf.h, ...) - libutil/ utility library (eprintf, ealloc, recurse, ...) - libutf/ UTF-8/rune library + *.h project headers (util.h, arg.h, utf.h, ...) + libutil/ utility library (eprintf, ealloc, recurse, ...) + libutf/ UTF-8/rune library cmd/ posix/ POSIX.1-2008 tools (sh, make, grep, sed, pax, ...) linux/ Linux-specific tools (mount, dmesg, insmod, ...) @@ -84,8 +108,9 @@ SOURCE LAYOUT pseudo/ widely-used non-POSIX tools (tar, stat, seq, ...) xsi/ XSI-extension tools (mknod, su, passwd) extra/ third-party-flavored extras (yap, b3sum, fdisk, ...) - dev/ small toolchain (as, cc, ld, ar); not built by - default, see PRESET_UTILS in build.cfg + dev/ small toolchain tooling (ninqu, in the future: as, cc, ld, ar) + + See PRESET_UTILS in build.cfg to understand, en/dis/able the build of a set TOOLS ===== @@ -125,9 +150,9 @@ extra: TODOs / PENDING RELEASE ======================= -init - situation/sctl rewrite -troff - neatroff -man - unsure +init - vendor cowmonk's +troff - neatroff? create cmd/9? +man - unsure, this is not a fun task vendor and publish my compiler toolchain (small binutils + cproc), even if incomplete - unsure LICENSE diff --git a/build.cfg b/build.cfg @@ -161,7 +161,7 @@ FEATURE_SH_HISTEDIT=1 # FEATURE_NOEXEC: when set to 1, wexec/wpopen/wsystem can execute registered # tool mains directly inside the forked child process (skipping execve) -# This is equivalent to Busybox noexec applet support. +# This is equivalent to Busybox noexec applet support # This applies to ALL commands contained within aruu-box, you may also # specify if some specific command is not an attack vector to also be nofork # via enabling FEATURE_NOFORK=1 and specifying those commands in NOFORK_LIST @@ -177,7 +177,7 @@ FEATURE_SH_HISTEDIT=1 # (like cat, echo, pwd, test) directly in the current process without spawning # a subprocess (noexec+nofork). This is equivalent to Busybox nofork applet support # -FEATURE_NOFORK=1 +#FEATURE_NOFORK=1 # # FEATURE_NOFORK_OVERRIDE: only meaningful when FEATURE_NOFORK=1 # when set to 1, ARUU_NOFORK=0 in the environment forces fork for nofork commands @@ -192,25 +192,30 @@ NOFORK_LIST="true false echo pwd test [ basename dirname cat clear yes" # BUILD_EXTRA_YAP=0 +if pkg-config --exists tinfo 2>/dev/null; then + BUILD_EXTRA_YAP=1 +fi # tls backend: set exactly one to 1 to enable tls # FEATURE_USE_BEARSSL=0 -FEATURE_USE_LIBRESSL=0 +FEATURE_USE_LIBTLS=0 FEATURE_USE_OPENSSL=0 -FEATURE_USE_SSL=0 +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 +if [ "$FEATURE_USE_SSL" = 1 ] && + [ "$FEATURE_USE_BEARSSL$FEATURE_USE_LIBTLS$FEATURE_USE_OPENSSL" = "000" ] +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_LIBTLS=1 + elif pkg-config --exists openssl 2>/dev/null; then + FEATURE_USE_OPENSSL=1 fi fi + +unset FEATURE_USE_SSL # auto-detect TLS/SSL flags based on selected backend CPPFLAGS_TLS="" LDFLAGS_TLS="" LDLIBS_TLS="" PKG_NAME="" if [ "$FEATURE_USE_BEARSSL" = 1 ]; then @@ -219,7 +224,7 @@ if [ "$FEATURE_USE_BEARSSL" = 1 ]; then elif pkg-config --exists bearssl 2>/dev/null; then PKG_NAME="bearssl" fi -elif [ "$FEATURE_USE_LIBRESSL" = 1 ]; then +elif [ "$FEATURE_USE_LIBTLS" = 1 ]; then if pkg-config --exists libtls 2>/dev/null; then PKG_NAME="libtls" else diff --git a/cmd/dev/ninqu/exec.c b/cmd/dev/ninqu/exec.c @@ -0,0 +1,294 @@ +#include "ninqu.h" + +#include <errno.h> +#include <libgen.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/wait.h> +#include <unistd.h> + +int jobs_n = 1; +int summary_mode; +int failed_any; + +/* fork, chdir, redirect, exec. the child _exit on error so the + * parent never sees a stale pid */ +pid_t +spawn_inst(struct Inst *inst, struct StrList *argv) +{ + pid_t pid = fork(); + if (pid < 0) + eprintf("fork:"); + if (pid != 0) + return pid; + + if (inst->workdir[0] && chdir(inst->workdir) != 0) + eprintf("chdir %s:", inst->workdir); + if (inst->redirect) { + FILE *f = fopen(inst->out, "w"); + if (!f) + eprintf("open %s:", inst->out); + if (dup2(fileno(f), STDOUT_FILENO) < 0) + _exit(127); + fclose(f); + } + child_execvp(sl_argv(argv)); +} + +/* fork a supervisor that chains each stage stdout into the next + * stdin. the parent waits on the supervisor, so the whole pipeline + * has one exit status */ +pid_t +spawn_pipe(struct Inst *inst) +{ + pid_t pid = fork(); + if (pid < 0) + eprintf("fork:"); + if (pid != 0) + return pid; + + if (inst->workdir[0] && chdir(inst->workdir) != 0) + eprintf("chdir %s:", inst->workdir); + + { + int k, prev_read = -1; + for (k = 0; k < inst->cmd.nstages; k++) { + int p[2] = {-1, -1}; + pid_t sp; + if (k < inst->cmd.nstages - 1) { + if (pipe(p) != 0) + _exit(127); + } + sp = fork(); + if (sp < 0) + _exit(127); + if (sp == 0) { + if (prev_read >= 0) { + if (dup2(prev_read, STDIN_FILENO) < 0) + _exit(127); + close(prev_read); + } + if (k < inst->cmd.nstages - 1) { + close(p[0]); + if (dup2(p[1], STDOUT_FILENO) < 0) + _exit(127); + close(p[1]); + } + child_execvp(sl_argv(inst->cmd.stages[k])); + } + if (prev_read >= 0) + close(prev_read); + if (k < inst->cmd.nstages - 1) { + close(p[1]); + prev_read = p[0]; + } + } + for (k = 0; k < inst->cmd.nstages; k++) + wait(NULL); + _exit(0); + } +} + +/* mkdir -p the directory an instance writes into, so a rule (out) + * can point at a path that does not exist yet */ +void +mk_out_dir(const char *out) +{ + char tmp[PATH_MAX]; + char *dir; + + if (!out || !out[0]) + return; + estrlcpy(tmp, out, sizeof tmp); + dir = dirname(tmp); + if (strcmp(dir, ".") == 0 || strcmp(dir, "/") == 0) + return; + mkdirp(dir, 0777, 0777); +} + +/* print the rule line and flush before the child runs, so the + * announcement appears before the child own output */ +void +announce_inst(struct Inst *inst) +{ + mk_out_dir(inst->out); + printf(" %-10s %s\n", rules[inst->rule_idx].name, inst->out[0] ? inst->out : "(phony)"); + fflush(stdout); +} + +/* run one instance synchronously. exits on failure since a missing + * producer is unrecoverable */ +void +run_inst_sync(int idx) +{ + struct Inst *inst = &insts[idx]; + pid_t pid; + int status; + + if (!inst_stale(inst)) + return; + announce_inst(inst); + pid = inst->cmd.is_pipe ? spawn_pipe(inst) : spawn_inst(inst, &inst->cmd.argv); + if (waitpid(pid, &status, 0) < 0) + eprintf("waitpid:"); + if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0)) + eprintf("manifest: producer failed (rule %s)\n", rules[inst->rule_idx].name); +} + +/* run a batch of independent instances concurrently, at most jobs_n + * at a time. all instances in the batch are at the same kahn level */ +void +run_batch(int *idxs, int n) +{ + int next = 0, running = 0; + pid_t *pids = emalloc((size_t)(n > 0 ? n : 1) * sizeof *pids); + int *slot = emalloc((size_t)(n > 0 ? n : 1) * sizeof *slot); + + while (next < n || running > 0) { + while (running < jobs_n && next < n) { + struct Inst *inst = &insts[idxs[next]]; + pid_t pid; + + if (!inst_stale(inst)) { + next++; + continue; + } + announce_inst(inst); + + pid = inst->cmd.is_pipe ? spawn_pipe(inst) : spawn_inst(inst, &inst->cmd.argv); + pids[running] = pid; + slot[running] = idxs[next]; + running++; + next++; + } + if (running > 0) { + int status; + pid_t done = wait(&status); + int i; + if (done < 0) + eprintf("wait:"); + for (i = 0; i < running; i++) { + if (pids[i] == done) { + if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0)) { + char *cmd = sl_join(&insts[slot[i]].cmd.argv); + weprintf("rule %s failed: %s\n", rules[insts[slot[i]].rule_idx].name, cmd); + free(cmd); + failed_any = 1; + } + pids[i] = pids[running - 1]; + slot[i] = slot[running - 1]; + running--; + break; + } + } + } + } + free(pids); + free(slot); +} + +/* run an instance and all its transitive deps in order, so a + * producer like LIBUTIL does not archive .o files that have not + * been compiled yet */ +void +run_inst_with_deps(int idx) +{ + struct Inst *inst = &insts[idx]; + int i; + + for (i = 0; i < inst->dep_rule_names.n; i++) { + struct Rule *dep = rule_find(inst->dep_rule_names.v[i]); + int k; + if (!dep) + continue; + for (k = 0; k < dep->n_inst; k++) + dep_push(inst, dep->inst_idx[k]); + } + for (i = 0; i < inst->n_dep; i++) + run_inst_with_deps(inst->dep_inst[i]); + run_inst_sync(idx); +} + +/* bootstrap: run the producer for path only if path does not exist. + * after that the normal dependency graph takes over */ +void +materialize_if_missing(const char *path) +{ + struct Rule *r; + + if (file_exists(path)) + return; + r = rule_find_output(path); + if (!r) + r = rule_find_produces(base_of(path)); + if (!r) + return; + expand_rule(r->name); + if (r->n_inst > 0) { + int k; + for (k = 0; k < r->n_inst; k++) + run_inst_with_deps(r->inst_idx[k]); + } +} + +/* run argv synchronously, return its stdout as a string. used by + * (set NAME (capture (exec ...))) at parse time */ +char * +capture_argv(struct StrList *argv) +{ + int fds[2]; + pid_t pid; + char *buf; + size_t cap, len; + int status; + + if (argv->n == 0) + eprintf("capture: empty argv\n"); + if (pipe(fds) != 0) + eprintf("capture: pipe:"); + + pid = fork(); + if (pid < 0) + eprintf("capture: fork:"); + if (pid == 0) { + close(fds[0]); + if (dup2(fds[1], STDOUT_FILENO) < 0) + _exit(127); + close(fds[1]); + child_execvp(sl_argv(argv)); + } + close(fds[1]); + + cap = 4096; + len = 0; + buf = emalloc(cap); + for (;;) { + ssize_t n; + if (len + 4096 > cap) { + cap *= 2; + buf = erealloc(buf, cap); + } + n = read(fds[0], buf + len, cap - len - 1); + if (n < 0) { + if (errno == EINTR) + continue; + eprintf("capture: read:"); + } + if (n == 0) + break; + len += (size_t)n; + } + buf[len] = '\0'; + close(fds[0]); + + while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) + buf[--len] = '\0'; + + if (waitpid(pid, &status, 0) < 0) + eprintf("capture: waitpid:"); + if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0)) + eprintf("capture: command failed\n"); + return buf; +} diff --git a/cmd/dev/ninqu/expand.c b/cmd/dev/ninqu/expand.c @@ -0,0 +1,355 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +void +dep_push(struct Inst *inst, int idx) +{ + int i; + for (i = 0; i < inst->n_dep; i++) + if (inst->dep_inst[i] == idx) + return; + if (inst->n_dep >= inst->cap_dep) { + inst->cap_dep = inst->cap_dep ? inst->cap_dep * 2 : 4; + inst->dep_inst = erealloc(inst->dep_inst, (size_t)inst->cap_dep * sizeof *inst->dep_inst); + } + inst->dep_inst[inst->n_dep++] = idx; +} + +void +resolve_deps(void) +{ + int i, j, k; + for (i = 0; i < ninsts; i++) { + struct Inst *inst = &insts[i]; + for (j = 0; j < inst->dep_rule_names.n; j++) { + struct Rule *dep = rule_find(inst->dep_rule_names.v[j]); + if (!dep) + continue; + for (k = 0; k < dep->n_inst; k++) + dep_push(inst, dep->inst_idx[k]); + } + } +} + +int +inst_stale(struct Inst *inst) +{ + int i; + if (inst->phony) + return 1; + if (!file_exists(inst->out)) + return 1; + for (i = 0; i < inst->in.n; i++) + if (mtime_of(inst->in.v[i]) > mtime_of(inst->out)) + return 1; + for (i = 0; i < inst->stale_extra.n; i++) + if (file_exists(inst->stale_extra.v[i]) + && mtime_of(inst->stale_extra.v[i]) > mtime_of(inst->out)) + return 1; + return 0; +} + +/* a pure $(NAME) splits on whitespace so $(CFLAGS) becomes many + * flags, while -I$(INCDIR) stays one token */ +static int +is_pure_ref(const char *tok) +{ + size_t len; + int depth; + const char *p; + + if (tok[0] != '$' || tok[1] != '(') + return 0; + len = strlen(tok); + if (tok[len - 1] != ')') + return 0; + depth = 1; + for (p = tok + 2; *p; p++) { + if (p[0] == '$' && p[1] == '(') { + depth++; + p++; + continue; + } + if (*p == ')') { + depth--; + if (depth == 0) + return (size_t)(p - tok) == len - 1; + } + } + return 0; +} + +static void +expand_cmd_token(struct StrList *out, const char *raw) +{ + char *exp = kv_expand(raw); + if (is_pure_ref(raw)) { + struct StrList pieces = {0}; + int j; + sl_split(&pieces, exp); + for (j = 0; j < pieces.n; j++) + sl_push(out, pieces.v[j]); + } else { + sl_push(out, exp); + } + free(exp); +} + +static void +build_cmd(struct Inst *inst, struct Rule *r) +{ + int i; + if (r->cmd.is_pipe) { + inst->cmd.is_pipe = 1; + inst->cmd.nstages = r->cmd.nstages; + inst->cmd.stages = emalloc((size_t)r->cmd.nstages * sizeof *inst->cmd.stages); + for (i = 0; i < r->cmd.nstages; i++) { + int j; + struct StrList *slot = emalloc(sizeof *slot); + memset(slot, 0, sizeof *slot); + for (j = 0; j < r->cmd.stages[i]->n; j++) + expand_cmd_token(slot, r->cmd.stages[i]->v[j]); + inst->cmd.stages[i] = slot; + } + for (i = 0; i < inst->cmd.nstages; i++) { + char *joined = sl_join(inst->cmd.stages[i]); + if (i > 0) + sl_push(&inst->cmd.argv, "|"); + sl_push(&inst->cmd.argv, joined); + free(joined); + } + } else { + for (i = 0; i < r->cmd.argv.n; i++) + expand_cmd_token(&inst->cmd.argv, r->cmd.argv.v[i]); + } +} + +/* @NAME resolves to a rule ref. glob:PREFIX goes to glob_expand. + * anything else is a path: if it does not exist, try to find a + * producer and run it first */ +static void +resolve_input_token(int inst_idx, const char *raw, int only_dep) +{ + char *exp = kv_expand(raw); + + if (exp[0] == '@') { + const char *rulename = exp + 1; + struct Rule *dep; + struct KvStore *saved = local_overlay; + struct Inst *inst; + int i; + + /* expand_rule may set/clear local_overlay for its own loop */ + local_overlay = NULL; + expand_rule(rulename); + local_overlay = saved; + + /* insts[] may have moved during expand_rule */ + inst = &insts[inst_idx]; + dep = rule_find(rulename); + if (!dep) + eprintf( + "manifest: '%s' references unknown rule '@%s'\n", rules[inst->rule_idx].name, rulename + ); + if (!sl_has(&inst->dep_rule_names, rulename)) + sl_push(&inst->dep_rule_names, rulename); + if (!only_dep) + for (i = 0; i < dep->n_inst; i++) + sl_push(&inst->in, insts[dep->inst_idx[i]].out); + } else if (strncmp(exp, "glob:", 5) == 0) { + struct StrList matches = {0}; + int i; + glob_expand(exp + 5, &matches); + for (i = 0; i < matches.n; i++) { + if (only_dep) + sl_push(&insts[inst_idx].stale_extra, matches.v[i]); + else + sl_push(&insts[inst_idx].in, matches.v[i]); + } + } else { + struct StrList pieces = {0}; + int i; + sl_split(&pieces, exp); + for (i = 0; i < pieces.n; i++) { + const char *path = pieces.v[i]; + if (!file_exists(path)) + materialize_if_missing(path); + if (only_dep) + sl_push(&insts[inst_idx].stale_extra, path); + else + sl_push(&insts[inst_idx].in, path); + } + } + free(exp); +} + +static void +setup_inst(struct Inst *inst, struct Rule *r) +{ + inst->phony = r->phony; + inst->redirect = r->redirect; + if (r->workdir[0]) { + char *w = kv_expand(r->workdir); + strlcpy(inst->workdir, w, sizeof inst->workdir); + free(w); + } +} + +/* resolve deps, expand (out), populate IN/OUT on the overlay, build + * the cmd. caller must have local_overlay set if needed */ +static void +finalize_inst(int idx, struct Rule *r, struct KvStore *ov) +{ + struct Inst *inst = &insts[idx]; + int k; + + for (k = 0; k < r->in.n; k++) + resolve_input_token(idx, r->in.v[k], 0); + for (k = 0; k < r->extra_deps.n; k++) + resolve_input_token(idx, r->extra_deps.v[k], 1); + + inst = &insts[idx]; /* may have moved */ + { + char *o = kv_expand(r->out); + strlcpy(inst->out, o, sizeof inst->out); + free(o); + } + kv_set_raw(ov, "IN", sl_join(&inst->in)); + kv_set_raw(ov, "OUT", inst->out); + build_cmd(inst, r); +} + +void +expand_rule(const char *name) +{ + struct Rule *r = rule_find(name); + int i; + + if (!r) + eprintf("manifest: unknown rule '%s'\n", name); + if (r->expanded) + return; + r->expanded = 1; + + /* a gate with $(...) is per-instance, a static gate is checked + * once and if false the rule produces zero instances */ + if (r->gate && !gate_has_dyn(r->gate) && !gate_eval(r->gate)) + return; + + if (r->require_file[0] && r->globs.n == 0) { + char *rf = kv_expand(r->require_file); + int ok = file_exists(rf); + free(rf); + if (!ok) + return; + } + + if (r->globs.n > 0) { + struct StrList matches = {0}; + int j; + int r_literal = rule_is_literal(r); + + /* run order-only @rule producers before globbing, so a codegen + * step that generates sources finishes before the glob runs. + * skipped in summary mode since -S must not execute */ + if (!summary_mode) { + for (j = 0; j < r->extra_deps.n; j++) { + char *tok = kv_expand(r->extra_deps.v[j]); + if (tok[0] == '@') { + struct Rule *dep = rule_find(tok + 1); + if (dep) { + expand_rule(dep->name); + if (dep->n_inst > 0) { + int k; + for (k = 0; k < dep->n_inst; k++) + run_inst_with_deps(dep->inst_idx[k]); + } + } + } + free(tok); + } + } + + glob_all(r, &matches); + + for (i = 0; i < matches.n; i++) { + const char *match = matches.v[i]; + const char *base = base_of(match); + char dir[1024], stem[512], basestem[512], ext[64], unused[64]; + char ident[512]; + struct KvStore ov; + int idx; + struct Inst *inst; + + if (sl_has(&r->skip, base)) + continue; + if (!r_literal && path_claimed_elsewhere(match, r)) + continue; + if (r->require_marker[0] && !file_contains(match, r->require_marker)) + continue; + + if (strrchr(match, '/')) { + size_t dl = (size_t)(strrchr(match, '/') - match); + if (dl >= sizeof dir) + dl = sizeof dir - 1; + memcpy(dir, match, dl); + dir[dl] = '\0'; + } else { + strlcpy(dir, ".", sizeof dir); + } + splitext(base, basestem, sizeof basestem, ext, sizeof ext); + splitext(match, stem, sizeof stem, unused, sizeof unused); + to_ident(basestem, ident, sizeof ident); + + memset(&ov, 0, sizeof ov); + kv_set_raw(&ov, "MATCH", match); + kv_set_raw(&ov, "DIR", dir); + kv_set_raw(&ov, "BASE", base); + kv_set_raw(&ov, "EXT", ext); + kv_set_raw(&ov, "STEM", stem); + kv_set_raw(&ov, "BASESTEM", basestem); + kv_set_raw(&ov, "IDENT", ident); + local_overlay = &ov; + + if (r->gate && gate_has_dyn(r->gate)) { + struct Gate *mg = gate_materialize(r->gate); + int ok = gate_eval(mg); + gate_free(mg); + if (!ok) { + local_overlay = NULL; + continue; + } + } + if (r->require_file[0]) { + char *rf = kv_expand(r->require_file); + int ok = file_exists(rf); + free(rf); + if (!ok) { + local_overlay = NULL; + continue; + } + } + + idx = inst_new((int)(r - rules)); + inst = &insts[idx]; + setup_inst(inst, r); + finalize_inst(idx, r, &ov); + local_overlay = NULL; + } + } else { + int idx = inst_new((int)(r - rules)); + struct Inst *inst = &insts[idx]; + struct KvStore ov; + + /* non-glob rules have no MATCH/DIR/BASE to expose, so the + * overlay only carries IN/OUT for build_cmd */ + setup_inst(inst, r); + memset(&ov, 0, sizeof ov); + local_overlay = &ov; + finalize_inst(idx, r, &ov); + local_overlay = NULL; + } +} diff --git a/cmd/dev/ninqu/fs.c b/cmd/dev/ninqu/fs.c @@ -0,0 +1,193 @@ +#include "ninqu.h" + +#include <ctype.h> +#include <fnmatch.h> +#include <glob.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +long +mtime_of(const char *path) +{ + struct stat st; + if (stat(path, &st) != 0) + return -1; + return (long)st.st_mtime; +} + +int +file_exists(const char *path) +{ + return mtime_of(path) >= 0; +} + +int +file_contains(const char *path, const char *needle) +{ + FILE *fp; + char buf[8192]; + size_t n, needlen = strlen(needle), taillen = 0; + char tail[256]; + int found = 0; + + if (!needle[0]) + return 1; + fp = fopen(path, "r"); + if (!fp) + return 0; + tail[0] = '\0'; + while (!found && (n = fread(buf, 1, sizeof buf - 1, fp)) > 0) { + char joined[8192 + 256]; + buf[n] = '\0'; + snprintf(joined, sizeof joined, "%s%s", tail, buf); + if (strstr(joined, needle)) + found = 1; + taillen = strlen(buf); + if (taillen > needlen) + taillen = needlen - 1; + snprintf(tail, sizeof tail, "%s", buf + strlen(buf) - taillen); + } + fclose(fp); + return found; +} + +/* recurse_dir has no userdata slot, so the pattern and output list + * travel through file-scope statics for the span of one call */ +static const char *rg_suffix; +static struct StrList *rg_out; + +static void +rg_visit(const char *path) +{ + struct stat st; + + if (lstat(path, &st) != 0) + return; + if (S_ISDIR(st.st_mode)) { + recurse_dir(path, rg_visit); + return; + } + if (S_ISREG(st.st_mode) && fnmatch(rg_suffix, base_of(path), 0) == 0) + sl_push(rg_out, path); +} + +static void +recurse_glob(const char *dir, const char *suffix, struct StrList *out) +{ + rg_suffix = suffix; + rg_out = out; + recurse_dir(dir, rg_visit); +} + +/* a double-star-slash pattern recurses from the dir before it, + * matching the suffix against each basename. anything else goes to + * glob(3) as-is */ +void +glob_expand(const char *pattern, struct StrList *out) +{ + const char *rec = strstr(pattern, "**/"); + if (rec) { + char prefix[1024], suffix[1024]; + size_t plen = (size_t)(rec - pattern); + if (plen >= sizeof prefix) + plen = sizeof prefix - 1; + memcpy(prefix, pattern, plen); + prefix[plen] = '\0'; + if (plen > 0 && prefix[plen - 1] == '/') + prefix[plen - 1] = '\0'; + strlcpy(suffix, rec + 3, sizeof suffix); + recurse_glob(prefix[0] ? prefix : ".", suffix, out); + } else { + glob_t g; + size_t i; + if (glob(pattern, 0, NULL, &g) == 0) + for (i = 0; i < g.gl_pathc; i++) + sl_push(out, g.gl_pathv[i]); + globfree(&g); + } +} + +void +glob_all(struct Rule *r, struct StrList *out) +{ + int i; + for (i = 0; i < r->globs.n; i++) { + char *pat = kv_expand(r->globs.v[i]); + glob_expand(pat, out); + free(pat); + } +} + +int +is_wildcard_pattern(const char *pattern) +{ + return strpbrk(pattern, "*?[") != NULL; +} + +/* true if every glob on r is a literal path. a rule built entirely + * from literals is the override side of path_claimed_elsewhere */ +int +rule_is_literal(struct Rule *r) +{ + int i; + if (r->globs.n == 0) + return 0; + for (i = 0; i < r->globs.n; i++) + if (is_wildcard_pattern(r->globs.v[i])) + return 0; + return 1; +} + +/* a broad wildcard rule steps aside for any file another rule names + * outright, so a per-file override needs no (skip) on the broad rule */ +int +path_claimed_elsewhere(const char *path, struct Rule *self) +{ + int i, j; + for (i = 0; i < nrules; i++) { + struct Rule *other = &rules[i]; + if (other == self || !rule_is_literal(other)) + continue; + for (j = 0; j < other->globs.n; j++) { + char *exp = kv_expand(other->globs.v[j]); + int hit = strcmp(exp, path) == 0; + free(exp); + if (hit) + return 1; + } + } + return 0; +} + +void +splitext(const char *base, char *stem, size_t stemsz, char *ext, size_t extsz) +{ + const char *dot = strrchr(base, '.'); + if (dot && dot != base) { + size_t sl = (size_t)(dot - base); + if (sl >= stemsz) + sl = stemsz - 1; + memcpy(stem, base, sl); + stem[sl] = '\0'; + strlcpy(ext, dot, extsz); + } else { + strlcpy(stem, base, stemsz); + ext[0] = '\0'; + } +} + +/* a basestem like sha512-224sum has a hyphen, but a config toggle + * cannot. normalize so a gate keying off BASESTEM matches the form + * genconfig writes + * FIXME: I do not like our current genconfig.sh + */ +void +to_ident(const char *s, char *out, size_t outsz) +{ + size_t i; + for (i = 0; s[i] && i + 1 < outsz; i++) + out[i] = (s[i] == '-' || s[i] == '.') ? '_' : s[i]; + out[i] = '\0'; +} diff --git a/cmd/dev/ninqu/gate.c b/cmd/dev/ninqu/gate.c @@ -0,0 +1,139 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct Gate * +gate_new(enum GKind kind) +{ + struct Gate *g = ecalloc(1, sizeof *g); + g->kind = kind; + return g; +} + +void +gate_free(struct Gate *g) +{ + int i; + if (!g) + return; + for (i = 0; i < g->nkids; i++) + gate_free(g->kids[i]); + free(g->kids); + free(g->var); + free(g); +} + +struct Gate * +gate_parse(struct SNode *expr) +{ + const char *h; + struct Gate **kids; + int i, n; + + if (!expr) + return gate_new(G_TRUE); + + if (expr->kind == S_ATOM) { + struct Gate *g = gate_new(G_VAR); + g->var = estrdup(expr->atom); + return g; + } + + h = s_head(expr); + if (!h) + eprintf("manifest: empty () in gate\n"); + + if (strcmp(h, "not") == 0) { + struct Gate *g; + if (expr->nkids != 2) + eprintf("manifest: (not X) takes one operand\n"); + g = gate_new(G_NOT); + g->kids = emalloc(sizeof *g->kids); + g->kids[0] = gate_parse(expr->kids[1]); + g->nkids = 1; + return g; + } + if (strcmp(h, "and") == 0 || strcmp(h, "or") == 0) { + struct Gate *g = gate_new(h[0] == 'a' ? G_AND : G_OR); + if (expr->nkids < 2) + eprintf("manifest: (%s ...) needs one operand\n", h); + n = expr->nkids - 1; + kids = emalloc((size_t)n * sizeof *kids); + for (i = 0; i < n; i++) + kids[i] = gate_parse(expr->kids[i + 1]); + g->kids = kids; + g->nkids = n; + return g; + } + eprintf("manifest: unknown gate operator '%s'\n", h); + return NULL; +} + +/* true if the gate contains any $(...) that needs per-instance + * expansion before it can be evaluated */ +int +gate_has_dyn(struct Gate *g) +{ + int i; + if (!g) + return 0; + if (g->kind == G_VAR) + return strstr(g->var, "$(") != NULL; + for (i = 0; i < g->nkids; i++) + if (gate_has_dyn(g->kids[i])) + return 1; + return 0; +} + +int +gate_eval(struct Gate *g) +{ + int i, v; + if (!g) + return 1; + switch (g->kind) { + case G_TRUE: + return 1; + case G_VAR: { + char *vraw = kv_get(g->var); + return vraw && *vraw && strcmp(vraw, "0") != 0; + } + case G_NOT: + return !gate_eval(g->kids[0]); + case G_AND: + v = 1; + for (i = 0; i < g->nkids; i++) + v = v && gate_eval(g->kids[i]); + return v; + case G_OR: + v = 0; + for (i = 0; i < g->nkids; i++) + v = v || gate_eval(g->kids[i]); + return v; + } + return 0; +} + +/* expand every $(...) so a gate like build_$(BASESTEM) resolves + * against the active overlay before evaluation */ +struct Gate * +gate_materialize(struct Gate *g) +{ + int i; + struct Gate *out; + + if (!g) + return NULL; + out = gate_new(g->kind); + if (g->var) + out->var = kv_expand(g->var); + if (g->nkids) { + out->kids = emalloc((size_t)g->nkids * sizeof *out->kids); + for (i = 0; i < g->nkids; i++) + out->kids[i] = gate_materialize(g->kids[i]); + out->nkids = g->nkids; + } + return out; +} diff --git a/cmd/dev/ninqu/kv.c b/cmd/dev/ninqu/kv.c @@ -0,0 +1,182 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct KvStore kv; +struct KvStore *local_overlay; +struct StrList kv_locked; +struct Map *maps; +int nmaps, mapscap; + +char * +kv_get_raw(struct KvStore *s, const char *key) +{ + int i; + for (i = 0; i < s->n; i++) + if (strcmp(s->v[i].key, key) == 0) + return s->v[i].val; + return NULL; +} + +void +kv_set_raw(struct KvStore *s, const char *key, const char *val) +{ + int i; + for (i = 0; i < s->n; i++) { + if (strcmp(s->v[i].key, key) == 0) { + free(s->v[i].val); + s->v[i].val = estrdup(val); + return; + } + } + GROW(s->v, s->n, s->cap, 16); + s->v[s->n].key = estrdup(key); + s->v[s->n].val = estrdup(val); + s->n++; +} + +/* overlay beats global beats environ, so a per-match $(BASESTEM) can + * shadow a (set BASESTEM ...) without clobbering it for other matches */ +char * +kv_get(const char *key) +{ + char *v; + if (local_overlay) { + v = kv_get_raw(local_overlay, key); + if (v) + return v; + } + v = kv_get_raw(&kv, key); + if (v) + return v; + return getenv(key); +} + +const char * +kv_get_or(const char *key, const char *def) +{ + char *v = kv_get(key); + return v ? v : def; +} + +void +kv_set(const char *key, const char *val) +{ + kv_set_raw(&kv, key, val); +} + +/* -D on the cli locks the name so a later (set) in the file cannot + * overwrite it */ +void +kv_set_manifest(const char *key, const char *val) +{ + if (sl_has(&kv_locked, key)) + return; + kv_set(key, val); +} + +void +kv_set_cli(const char *key, const char *val) +{ + kv_set(key, val); + sl_push(&kv_locked, key); +} + +struct Map * +map_find(const char *name) +{ + int i; + for (i = 0; i < nmaps; i++) + if (strcmp(maps[i].name, name) == 0) + return &maps[i]; + return NULL; +} + +struct Map * +map_new(const char *name) +{ + struct Map *m; + GROW(maps, nmaps, mapscap, 8); + m = &maps[nmaps++]; + memset(m, 0, sizeof *m); + strlcpy(m->name, name, sizeof m->name); + return m; +} + +/* $(NAME) and $(NAME:KEY). KEY is expanded first, the map value is + * re-expanded once so $(LDLIBS_TLS) inside a map entry resolves. the + * result is not recursively expanded, matching simply-expanded vars */ +char * +kv_expand(const char *s) +{ + size_t cap = strlen(s) * 2 + 64, len = 0; + char *out = emalloc(cap); + const char *p = s; + + while (*p) { + if (p[0] == '$' && p[1] == '(') { + const char *inner = p + 2; + const char *close = NULL; + char *val = NULL; + char *expanded_val = NULL; + + close = find_dollar_close(inner); + + if (close) { + char name[4096]; + size_t nl = (size_t)(close - inner); + char *colon; + + if (nl >= sizeof name) + nl = sizeof name - 1; + memcpy(name, inner, nl); + name[nl] = '\0'; + + colon = strchr(name, ':'); + if (colon) { + char mapname[128]; + char *keypart; + struct Map *m; + size_t mnl = (size_t)(colon - name); + + if (mnl >= sizeof mapname) + mnl = sizeof mapname - 1; + memcpy(mapname, name, mnl); + mapname[mnl] = '\0'; + m = map_find(mapname); + keypart = kv_expand(colon + 1); + if (m) { + char *raw = kv_get_raw(&m->entries, keypart); + if (raw) + expanded_val = kv_expand(raw); + } + free(keypart); + val = expanded_val; + } else { + val = kv_get(name); + } + + if (!val) + val = ""; + while (len + strlen(val) + 1 >= cap) { + cap *= 2; + out = erealloc(out, cap); + } + memcpy(out + len, val, strlen(val)); + len += strlen(val); + free(expanded_val); + p = close + 1; + continue; + } + } + if (len + 2 >= cap) { + cap *= 2; + out = erealloc(out, cap); + } + out[len++] = *p++; + } + out[len] = '\0'; + return out; +} diff --git a/cmd/dev/ninqu/main.c b/cmd/dev/ninqu/main.c @@ -0,0 +1,112 @@ +#include "ninqu.h" + +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +static void +usage(void) +{ + eprintf( + "usage: %s [-jN] [-f manifest] [-C dir] [-Dvar=val]... [-S] [-F] [target|meta.target ...]\n" + " %s query (features|groups|metas|rules|graph) [arg]\n", + argv0, + argv0 + ); +} + +int +main(int argc, char *argv[]) +{ + const char *manifest = "ninqu.rules"; + int features_mode = 0; + int query_mode = 0; + const char *query_sub = NULL; + const char *query_arg = NULL; + int i; + struct StrList wanted = {0}; + + /* detect `query` before ARGBEGIN so it is not parsed as a target */ + if (argc >= 2 && strcmp(argv[1], "query") == 0) { + query_mode = 1; + if (argc < 3) + usage(); + query_sub = argv[2]; + query_arg = (argc >= 4) ? argv[3] : NULL; + for (i = 3; i < argc; i++) { + if (argv[i][0] == '-' && argv[i][1] == 'f') + manifest = argv[i][2] ? argv[i] + 2 : argv[++i]; + else if (argv[i][0] == '-' && argv[i][1] == 'C') { + if (chdir(argv[i][2] ? argv[i] + 2 : argv[++i]) != 0) + eprintf("chdir:"); + } else if (argv[i][0] == '-' && argv[i][1] == 'D') { + char *spec = argv[i][2] ? argv[i] + 2 : argv[++i]; + char *eq = strchr(spec, '='); + if (!eq) + usage(); + *eq = '\0'; + kv_set_cli(spec, eq + 1); + } + } + } else { + ARGBEGIN + { + case 'j': + jobs_n = (int)estrtonum(EARGF(usage()), 1, INT_MAX); + break; + case 'f': + manifest = EARGF(usage()); + break; + case 'C': + if (chdir(EARGF(usage())) != 0) + eprintf("chdir:"); + break; + case 'D': { + char *spec = EARGF(usage()); + char *eq = strchr(spec, '='); + if (!eq) + usage(); + *eq = '\0'; + kv_set_cli(spec, eq + 1); + break; + } + case 'S': + summary_mode = 1; + break; + case 'F': + features_mode = 1; + break; + default: + usage(); + } + ARGEND + + for (i = 0; i < argc; i++) + sl_push(&wanted, argv[i]); + } + + load_file(manifest); + resolve_all_bareword_deps(); + + if (query_mode) { + do_query(query_sub, query_arg); + return 0; + } + if (features_mode) { + do_features(); + return 0; + } + + if (wanted.n == 0) + build_default_group(); + else + for (i = 0; i < wanted.n; i++) + resolve_wanted(wanted.v[i]); + + resolve_deps(); + schedule_and_run(); + + return failed_any ? 1 : 0; +} diff --git a/cmd/dev/ninqu/ninqu.h b/cmd/dev/ninqu/ninqu.h @@ -0,0 +1,256 @@ +#if !defined(_DEFAULT_SOURCE) +#define _DEFAULT_SOURCE +#endif +#if !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 200809L +#endif + +#include <sys/types.h> + +#include "arg.h" +#include "util.h" + +/* grow a struct-array when full. n/cap doubles each time */ +#define GROW(arr, n, cap, init) \ + do { \ + if ((n) >= (cap)) { \ + (cap) = (cap) ? (cap) * 2 : (init); \ + (arr) = erealloc((arr), (size_t)(cap) * sizeof *(arr)); \ + } \ + } while (0) + +struct StrList { + char **v; + int n; + int cap; +}; + +void sl_push(struct StrList *sl, const char *s); +int sl_has(struct StrList *sl, const char *s); +void sl_split(struct StrList *sl, const char *s); +char *sl_join(struct StrList *sl); +char **sl_argv(struct StrList *sl); +const char *base_of(const char *path); +void child_execvp(char **av) __attribute__((noreturn)); + +struct Kv { + char *key; + char *val; +}; + +struct KvStore { + struct Kv *v; + int n, cap; +}; + +struct Map { + char name[128]; + struct KvStore entries; +}; + +char *kv_get(const char *key); +const char *kv_get_or(const char *key, const char *def); +void kv_set(const char *key, const char *val); +void kv_set_manifest(const char *key, const char *val); +void kv_set_cli(const char *key, const char *val); +char *kv_expand(const char *s); +char *kv_get_raw(struct KvStore *s, const char *key); +void kv_set_raw(struct KvStore *s, const char *key, const char *val); +struct Map *map_find(const char *name); +struct Map *map_new(const char *name); + +extern struct KvStore kv; +extern struct KvStore *local_overlay; +extern struct StrList kv_locked; +extern struct Map *maps; +extern int nmaps, mapscap; + +enum SKind { S_ATOM, S_LIST }; + +struct SNode { + enum SKind kind; + char *atom; + struct SNode **kids; + int nkids; + int line; +}; + +struct SLex { + const char *src; + size_t pos; + int line; +}; + +struct SNode *snode_atom(const char *s, int line); +struct SNode *snode_list(int line); +void snode_push(struct SNode *list, struct SNode *kid); +void snode_free(struct SNode *n); +struct SNode *snode_clone(struct SNode *n); +struct SNode *snode_parse(struct SLex *lx); +int s_is_list(struct SNode *n); +const char *s_head(struct SNode *n); +char *subst_tmpl(const char *s, struct StrList *params, char **vals); +void snode_subst(struct SNode *n, struct StrList *params, char **vals); +void lex_swallow_dollar(struct SLex *lx, char *buf, size_t *blen, size_t bsz); +void lex_string(struct SLex *lx, char *buf, size_t bsz); +const char *find_dollar_close(const char *inner); + +/* gate: (not X) | (and X...) | (or X...) | bare var */ +enum GKind { G_TRUE, G_VAR, G_NOT, G_AND, G_OR }; + +struct Gate { + enum GKind kind; + char *var; + struct Gate **kids; + int nkids; +}; + +struct Gate *gate_new(enum GKind kind); +void gate_free(struct Gate *g); +struct Gate *gate_parse(struct SNode *expr); +int gate_has_dyn(struct Gate *g); +int gate_eval(struct Gate *g); +struct Gate *gate_materialize(struct Gate *g); + +struct Cmd { + struct StrList argv; + int is_pipe; + struct StrList **stages; + int nstages; +}; + +struct Rule { + char name[128]; + struct StrList globs; + struct StrList skip; + char require_marker[1024]; + char require_file[1024]; + struct StrList in; + struct StrList extra_deps; + char out[1024]; + struct Cmd cmd; + struct Gate *gate; + char workdir[1024]; + int phony; + int redirect; + char produces[128]; + char description[256]; + char group_name[128]; + char member_of[128]; + char member_alias[128]; + struct StrList features; + + int *inst_idx; + int n_inst, cap_inst; + int expanded; +}; + +struct Group { + char name[128]; + struct StrList refs; +}; + +struct Meta { + char name[128]; + struct StrList keys; + struct StrList vals; +}; + +struct Template { + char name[128]; + struct StrList params; + struct SNode *body; +}; + +struct Rule *rule_find(const char *name); +struct Rule *rule_find_output(const char *path); +struct Rule *rule_find_produces(const char *name); +struct Rule *rule_new(const char *name); +struct Group *group_find(const char *name); +struct Group *group_new(const char *name); +struct Meta *meta_find(const char *name); +struct Meta *meta_new(const char *name); +struct Template *template_find(const char *name); +struct Template *template_new(const char *name); + +extern struct Rule *rules; +extern int nrules, rulescap; +extern struct Group *groups; +extern int ngroups, groupscap; +extern struct Meta *metas; +extern int nmetas, metascap; +extern struct Template *templates; +extern int ntemplates, templatescap; + +struct Inst { + int rule_idx; + struct StrList in; + struct StrList stale_extra; + char out[1024]; + struct Cmd cmd; + char workdir[1024]; + int phony; + int redirect; + + struct StrList dep_rule_names; + int *dep_inst; + int n_dep, cap_dep; + int will_build; +}; + +int inst_new(int rule_idx); +int inst_stale(struct Inst *inst); +void dep_push(struct Inst *inst, int idx); +void resolve_deps(void); + +extern struct Inst *insts; +extern int ninsts, instscap; + +long mtime_of(const char *path); +int file_exists(const char *path); +int file_contains(const char *path, const char *needle); +void glob_expand(const char *pattern, struct StrList *out); +void glob_all(struct Rule *r, struct StrList *out); +int is_wildcard_pattern(const char *pattern); +int rule_is_literal(struct Rule *r); +int path_claimed_elsewhere(const char *path, struct Rule *self); +void splitext(const char *base, char *stem, size_t stemsz, char *ext, size_t extsz); +void to_ident(const char *s, char *out, size_t outsz); + +pid_t spawn_inst(struct Inst *inst, struct StrList *argv); +pid_t spawn_pipe(struct Inst *inst); +void mk_out_dir(const char *out); +void announce_inst(struct Inst *inst); +void run_inst_sync(int idx); +void run_batch(int *idxs, int n); +void run_inst_with_deps(int idx); +void materialize_if_missing(const char *path); +char *capture_argv(struct StrList *argv); + +extern int jobs_n; +extern int summary_mode; +extern int failed_any; + +void load_file(const char *path); +void load_manifest(struct SNode *root); +void dispatch_top_form(struct SNode *form); +void parse_exec_clause(struct SNode *clause, struct Cmd *cmd); +void parse_shell_clause(struct SNode *clause, struct Cmd *cmd); +void parse_pipe_clause(struct SNode *clause, struct Cmd *cmd); +void meta_apply(struct Meta *m); +const char *first_atom(struct SNode *node, const char *msg); +const char *sole_atom(struct SNode *node, const char *msg); + +extern struct StrList files_read; + +void expand_rule(const char *name); + +void schedule_and_run(void); + +void do_features(void); +void do_query(const char *sub, const char *arg); + +void include_ref(const char *name); +void build_default_group(void); +void resolve_wanted(const char *w); +void resolve_all_bareword_deps(void); diff --git a/cmd/dev/ninqu/parse.c b/cmd/dev/ninqu/parse.c @@ -0,0 +1,650 @@ +#include "ninqu.h" + +#include <ctype.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct StrList files_read; + +/* second child must be an atom, more children may follow */ +const char * +first_atom(struct SNode *node, const char *msg) +{ + if (node->nkids < 2 || node->kids[1]->kind != S_ATOM) + eprintf("manifest: %s\n", msg); + return node->kids[1]->atom; +} + +/* second child must be the only other child, and an atom */ +const char * +sole_atom(struct SNode *node, const char *msg) +{ + if (node->nkids != 2 || node->kids[1]->kind != S_ATOM) + eprintf("manifest: %s\n", msg); + return node->kids[1]->atom; +} + +/* a dep operand is a bare atom, a (rule NAME) stored as @NAME, or + * an (after X...) whose operands are order-only */ +static void +parse_dep_item(struct SNode *item, struct StrList *hard, struct StrList *ord, int allow_after) +{ + const char *h; + + if (item->kind == S_ATOM) { + sl_push(hard, item->atom); + return; + } + h = s_head(item); + if (!h) + eprintf("manifest: empty () in dep\n"); + if (strcmp(h, "rule") == 0) { + char buf[256]; + snprintf(buf, sizeof buf, "@%s", sole_atom(item, "(rule NAME) takes one name")); + sl_push(hard, buf); + return; + } + if (strcmp(h, "after") == 0) { + int i; + if (!allow_after) + eprintf("manifest: (after ...) not allowed here\n"); + for (i = 1; i < item->nkids; i++) + parse_dep_item(item->kids[i], ord, ord, 0); + return; + } + eprintf("manifest: unknown dep operand '%s'\n", h); +} + +static void +parse_dep_clause(struct SNode *clause, struct StrList *hard, struct StrList *ord) +{ + int i; + for (i = 1; i < clause->nkids; i++) + parse_dep_item(clause->kids[i], hard, ord, 1); +} + +void +parse_exec_clause(struct SNode *clause, struct Cmd *cmd) +{ + int i; + memset(cmd, 0, sizeof *cmd); + for (i = 1; i < clause->nkids; i++) { + if (clause->kids[i]->kind != S_ATOM) + eprintf("manifest: (exec ...) operands must be atoms\n"); + sl_push(&cmd->argv, clause->kids[i]->atom); + } + if (cmd->argv.n == 0) + eprintf("manifest: (exec ...) needs one operand\n"); +} + +/* desugar to (exec sh -c STR). sh is the posix shell, overridable + * by writing (exec ...) directly */ +void +parse_shell_clause(struct SNode *clause, struct Cmd *cmd) +{ + memset(cmd, 0, sizeof *cmd); + sl_push(&cmd->argv, "sh"); + sl_push(&cmd->argv, "-c"); + sl_push(&cmd->argv, sole_atom(clause, "(shell \"...\") takes one string")); +} + +static void +parse_pipe_stage(struct SNode *stage, struct StrList *argv) +{ + const char *h = s_head(stage); + int j; + + if (!h) + eprintf("manifest: (pipe ...) stage must be a form\n"); + if (strcmp(h, "exec") == 0) { + for (j = 1; j < stage->nkids; j++) { + if (stage->kids[j]->kind != S_ATOM) + eprintf("manifest: (exec ...) operands must be atoms\n"); + sl_push(argv, stage->kids[j]->atom); + } + } else if (strcmp(h, "shell") == 0) { + sl_push(argv, "sh"); + sl_push(argv, "-c"); + sl_push(argv, sole_atom(stage, "(shell \"...\") takes one string")); + } else { + eprintf("manifest: (pipe) stage must be exec or shell, got '%s'\n", h); + } + if (argv->n == 0) + eprintf("manifest: (pipe) stage cannot be empty\n"); +} + +void +parse_pipe_clause(struct SNode *clause, struct Cmd *cmd) +{ + int i, j; + memset(cmd, 0, sizeof *cmd); + cmd->is_pipe = 1; + for (i = 1; i < clause->nkids; i++) { + struct StrList argv = {0}; + struct StrList *slot; + + parse_pipe_stage(clause->kids[i], &argv); + + slot = emalloc(sizeof *slot); + memset(slot, 0, sizeof *slot); + for (j = 0; j < argv.n; j++) + sl_push(slot, argv.v[j]); + if (cmd->nstages == 0) + cmd->stages = emalloc(8 * sizeof *cmd->stages); + else if (cmd->nstages >= 8) + cmd->stages = erealloc(cmd->stages, (size_t)cmd->nstages * 2 * sizeof *cmd->stages); + cmd->stages[cmd->nstages++] = slot; + } + if (cmd->nstages < 2) + eprintf("manifest: (pipe ...) needs two stages\n"); + for (i = 0; i < cmd->nstages; i++) { + char *joined = sl_join(cmd->stages[i]); + if (i > 0) + sl_push(&cmd->argv, "|"); + sl_push(&cmd->argv, joined); + free(joined); + } +} + +static void apply_rule_clause(struct Rule *r, const char *name, struct SNode *clause); + +static void +process_rule_body(struct Rule *r, const char *name, struct SNode *form, int start) +{ + int i; + for (i = start; i < form->nkids; i++) + apply_rule_clause(r, name, form->kids[i]); +} + +/* (if EXPR clause...) splices its clauses in when EXPR is true. + * reuses the gate grammar so there is one condition language. + * a $(...) in the condition is rejected: splicing per glob match + * would mean deferring cmd/dep construction, which no rule needs. + * use (gate ...) on a separate rule for a per-instance condition */ +static void +apply_if_clause(struct Rule *r, const char *name, struct SNode *clause) +{ + struct Gate *cond; + + if (clause->nkids < 2) + eprintf("manifest: rule %s: (if EXPR clause...) needs a condition\n", name); + cond = gate_parse(clause->kids[1]); + if (gate_has_dyn(cond)) + eprintf( + "manifest: rule %s: (if ...) condition cannot reference $(...), " + "only (gate ...) on the whole rule supports a per-instance condition\n", + name + ); + if (gate_eval(cond)) + process_rule_body(r, name, clause, 2); + gate_free(cond); +} + +static void +apply_rule_clause(struct Rule *r, const char *name, struct SNode *clause) +{ + const char *h = s_head(clause); + if (!h) + eprintf("manifest: rule %s: empty () clause\n", name); + + if (strcmp(h, "if") == 0) { + apply_if_clause(r, name, clause); + } else if (strcmp(h, "glob") == 0) { + int j; + for (j = 1; j < clause->nkids; j++) { + if (clause->kids[j]->kind != S_ATOM) + eprintf("manifest: (glob ...) operands must be atoms\n"); + sl_push(&r->globs, clause->kids[j]->atom); + } + } else if (strcmp(h, "skip") == 0) { + int j; + for (j = 1; j < clause->nkids; j++) { + if (clause->kids[j]->kind != S_ATOM) + eprintf("manifest: (skip ...) operands must be atoms\n"); + sl_push(&r->skip, clause->kids[j]->atom); + } + } else if (strcmp(h, "mark") == 0) { + strlcpy( + r->require_marker, + sole_atom(clause, "(mark STR) takes one string"), + sizeof r->require_marker + ); + } else if (strcmp(h, "req") == 0) { + strlcpy( + r->require_file, sole_atom(clause, "(req PATH) takes one path"), sizeof r->require_file + ); + } else if (strcmp(h, "gate") == 0) { + if (clause->nkids != 2) + eprintf("manifest: (gate EXPR) takes one expression\n"); + r->gate = gate_parse(clause->kids[1]); + } else if (strcmp(h, "dep") == 0) { + parse_dep_clause(clause, &r->in, &r->extra_deps); + } else if (strcmp(h, "after") == 0) { + parse_dep_clause(clause, &r->extra_deps, &r->extra_deps); + } else if (strcmp(h, "out") == 0) { + strlcpy(r->out, sole_atom(clause, "(out TEMPLATE) takes one template"), sizeof r->out); + } else if (strcmp(h, "exec") == 0) { + parse_exec_clause(clause, &r->cmd); + } else if (strcmp(h, "shell") == 0) { + parse_shell_clause(clause, &r->cmd); + } else if (strcmp(h, "pipe") == 0) { + parse_pipe_clause(clause, &r->cmd); + } else if (strcmp(h, "dir") == 0) { + strlcpy(r->workdir, sole_atom(clause, "(dir PATH) takes one path"), sizeof r->workdir); + } else if (strcmp(h, "phony") == 0) { + r->phony = 1; + } else if (strcmp(h, "redirect") == 0) { + r->redirect = 1; + } else if (strcmp(h, "produces") == 0) { + strlcpy(r->produces, sole_atom(clause, "(produces NAME) takes one name"), sizeof r->produces); + } else if (strcmp(h, "description") == 0) { + strlcpy( + r->description, + sole_atom(clause, "(description STR) takes one string"), + sizeof r->description + ); + } else if (strcmp(h, "group") == 0) { + /* display-only: shows up in (query rules) output, no effect on + * resolution. (member ...) below is the enforcing one. the two + * are separate because several rules used (group ...) this way + * before namespacing existed */ + strlcpy(r->group_name, sole_atom(clause, "(group NAME) takes one name"), sizeof r->group_name); + } else if (strcmp(h, "member") == 0) { + /* (member GROUP [ALIAS]) hides the bare name from the command + * line. ALIAS defaults to the rule own name */ + if (clause->nkids < 2 || clause->nkids > 3 || clause->kids[1]->kind != S_ATOM) + eprintf("manifest: rule %s: (member GROUP [ALIAS]) needs a group name\n", name); + strlcpy(r->member_of, clause->kids[1]->atom, sizeof r->member_of); + if (clause->nkids == 3) { + if (clause->kids[2]->kind != S_ATOM) + eprintf("manifest: rule %s: (member GROUP ALIAS) alias must be an atom\n", name); + strlcpy(r->member_alias, clause->kids[2]->atom, sizeof r->member_alias); + } + } else if (strcmp(h, "feature") == 0) { + sl_push(&r->features, sole_atom(clause, "(feature NAME) takes one name")); + } else { + eprintf("manifest: rule %s: unknown clause '%s'\n", name, h); + } +} + +static void +parse_rule(struct SNode *form) +{ + struct Rule *r; + const char *name; + + name = first_atom(form, "(rule NAME ...) needs a name"); + r = rule_new(name); + process_rule_body(r, name, form, 2); +} + +static void +parse_group(struct SNode *form) +{ + struct Group *g; + int i; + const char *name; + + name = first_atom(form, "(group NAME ...) needs a name"); + g = group_new(name); + + for (i = 2; i < form->nkids; i++) { + struct SNode *ref = form->kids[i]; + const char *h; + + if (ref->kind == S_ATOM) { + sl_push(&g->refs, ref->atom); + continue; + } + h = s_head(ref); + if (!h) + eprintf("manifest: group %s: empty () ref\n", name); + if ((strcmp(h, "rule") == 0 || strcmp(h, "group") == 0) && ref->nkids == 2 + && ref->kids[1]->kind == S_ATOM) { + sl_push(&g->refs, ref->kids[1]->atom); + continue; + } + eprintf("manifest: group %s: unknown ref '%s'\n", name, h); + } +} + +/* stores K/V verbatim, unexpanded. expansion happens in meta_apply + * at target-resolution time, so a value picks up whatever its vars + * hold then, not what they held at load time */ +static void +parse_meta(struct SNode *form) +{ + struct Meta *m; + int i; + const char *name; + + name = first_atom(form, "(meta NAME ...) needs a name"); + m = meta_new(name); + + for (i = 2; i < form->nkids; i++) { + struct SNode *clause = form->kids[i]; + const char *h = s_head(clause); + if (!h || strcmp(h, "set") != 0) + eprintf("manifest: meta %s: only (set NAME VAL) clauses are allowed\n", name); + if (clause->nkids != 3 || clause->kids[1]->kind != S_ATOM || clause->kids[2]->kind != S_ATOM) + eprintf("manifest: meta %s: (set NAME VAL) needs a name and an atom value\n", name); + sl_push(&m->keys, clause->kids[1]->atom); + sl_push(&m->vals, clause->kids[2]->atom); + } +} + +void +meta_apply(struct Meta *m) +{ + int i; + for (i = 0; i < m->keys.n; i++) { + char *exp = kv_expand(m->vals.v[i]); + kv_set_manifest(m->keys.v[i], exp); + free(exp); + } +} + +static void +parse_set(struct SNode *form) +{ + char buf[8192]; + + first_atom(form, "(set NAME VAL) needs a name"); + if (form->nkids != 3) + eprintf("manifest: (set NAME VAL) takes one value\n"); + + if (form->kids[2]->kind == S_LIST) { + const char *h = s_head(form->kids[2]); + if (h && strcmp(h, "capture") == 0) { + struct SNode *cap = form->kids[2]; + struct Cmd cmd; + char *out; + + if (cap->nkids != 2) + eprintf("manifest: (capture (exec ...)) takes one form\n"); + h = s_head(cap->kids[1]); + if (!h) + eprintf("manifest: capture operand must be a form\n"); + if (strcmp(h, "exec") == 0) + parse_exec_clause(cap->kids[1], &cmd); + else if (strcmp(h, "shell") == 0) + parse_shell_clause(cap->kids[1], &cmd); + else + eprintf("manifest: capture operand must be exec or shell\n"); + out = capture_argv(&cmd.argv); + strlcpy(buf, out, sizeof buf); + free(out); + kv_set_manifest(form->kids[1]->atom, buf); + return; + } + eprintf("manifest: (set NAME VAL): value must be atom or (capture ...)\n"); + } + kv_set_manifest(form->kids[1]->atom, form->kids[2]->atom); +} + +/* (list) and (append) keep a space-joined string in the kv store. + * a $(NAME) alone in a command splits back into argv entries */ +static void +parse_list_or_append(struct SNode *form, int append) +{ + const char *name; + char buf[8192]; + char msg[64]; + size_t len = 0; + int i; + char *prev; + + snprintf(msg, sizeof msg, "(%s NAME tok...) needs a name", form->kids[0]->atom); + name = first_atom(form, msg); + buf[0] = '\0'; + + if (append) { + prev = kv_get(name); + if (prev) + len = strlcpy(buf, prev, sizeof buf); + } + for (i = 2; i < form->nkids; i++) { + struct SNode *tok = form->kids[i]; + char *exp; + if (tok->kind != S_ATOM) + eprintf("manifest: (%s NAME tok...): tokens must be atoms\n", form->kids[0]->atom); + if (len > 0 && len + 1 < sizeof buf) + buf[len++] = ' '; + exp = kv_expand(tok->atom); + len += strlcpy(buf + len, exp, sizeof buf - len); + free(exp); + } + kv_set_manifest(name, buf); +} + +static void +parse_map(struct SNode *form) +{ + struct Map *m; + int i; + const char *name; + + name = first_atom(form, "(map NAME (k v)...) needs a name"); + m = map_find(name); + if (!m) + m = map_new(name); + + for (i = 2; i < form->nkids; i++) { + struct SNode *pair = form->kids[i]; + if (!s_is_list(pair) || pair->nkids != 2 || pair->kids[0]->kind != S_ATOM + || pair->kids[1]->kind != S_ATOM) + eprintf("manifest: (map %s ...) entries must be (key value)\n", name); + kv_set_raw(&m->entries, pair->kids[0]->atom, pair->kids[1]->atom); + } +} + +static void +parse_import(struct SNode *form) +{ + char rp[PATH_MAX]; + const char *path; + + path = sole_atom(form, "(import PATH) takes one path"); + + if (realpath(path, rp) && sl_has(&files_read, rp)) + return; + + materialize_if_missing(path); + if (!file_exists(path)) + eprintf("manifest: (import %s): missing and no rule produces it\n", path); + load_file(path); +} + +static void +parse_set_file(struct SNode *form) +{ + const char *path; + FILE *fp; + char line[8192]; + char rp[PATH_MAX]; + + path = sole_atom(form, "(set-file PATH) takes one path"); + + materialize_if_missing(path); + if (!file_exists(path)) + eprintf("manifest: (set-file %s): missing and no rule produces it\n", path); + + fp = fopen(path, "r"); + if (!fp) + eprintf("manifest: (set-file %s):", path); + if (realpath(path, rp)) + sl_push(&files_read, rp); + + while (fgets(line, sizeof line, fp)) { + char *s = line, *eq, *end; + while (isspace((unsigned char)*s)) + s++; + if (*s == '\0' || *s == '#') + continue; + eq = strchr(s, '='); + if (!eq) + continue; + *eq = '\0'; + end = eq - 1; + while (end > s && isspace((unsigned char)*end)) + *end-- = '\0'; + eq++; + while (isspace((unsigned char)*eq)) + eq++; + end = eq + strlen(eq); + while (end > eq && (isspace((unsigned char)end[-1]) || end[-1] == '\n')) + *--end = '\0'; + kv_set_manifest(s, eq); + } + fclose(fp); +} + +/* (template NAME (PARAM...) FORM...): the body is cloned so it stays + * valid regardless of when or how many times (use ...) instantiates + * it */ +static void +parse_template(struct SNode *form) +{ + struct Template *t; + struct SNode *params; + const char *name; + int i; + + name = first_atom(form, "(template NAME (PARAM...) FORM...) needs a name"); + if (form->nkids < 3 || form->kids[2]->kind != S_LIST) + eprintf("manifest: template %s: needs a (PARAM...) list\n", name); + params = form->kids[2]; + + t = template_new(name); + for (i = 0; i < params->nkids; i++) { + if (params->kids[i]->kind != S_ATOM) + eprintf("manifest: template %s: param names must be atoms\n", name); + sl_push(&t->params, params->kids[i]->atom); + } + t->body = snode_list(form->line); + for (i = 3; i < form->nkids; i++) + snode_push(t->body, snode_clone(form->kids[i])); +} + +/* clone the template body, substitute each $(PARAM), then dispatch + * every substituted form as a normal top-level form */ +static void +parse_use(struct SNode *form) +{ + struct Template *t; + struct SNode *clone; + const char *name; + char **vals; + int i, nargs; + + name = first_atom(form, "(use NAME arg...) needs a name"); + t = template_find(name); + if (!t) + eprintf("manifest: (use %s ...): no such template\n", name); + + nargs = form->nkids - 2; + if (nargs != t->params.n) + eprintf("manifest: (use %s ...): takes %d argument(s), got %d\n", name, t->params.n, nargs); + + vals = emalloc((size_t)(nargs ? nargs : 1) * sizeof *vals); + for (i = 0; i < nargs; i++) { + if (form->kids[i + 2]->kind != S_ATOM) + eprintf("manifest: (use %s ...): arguments must be atoms\n", name); + vals[i] = form->kids[i + 2]->atom; + } + + clone = snode_clone(t->body); + snode_subst(clone, &t->params, vals); + for (i = 0; i < clone->nkids; i++) + dispatch_top_form(clone->kids[i]); + snode_free(clone); + free(vals); +} + +void +dispatch_top_form(struct SNode *form) +{ + const char *h = s_head(form); + if (!h) + eprintf("manifest: top-level form has no head\n"); + if (strcmp(h, "set") == 0) + parse_set(form); + else if (strcmp(h, "list") == 0) + parse_list_or_append(form, 0); + else if (strcmp(h, "append") == 0) + parse_list_or_append(form, 1); + else if (strcmp(h, "map") == 0) + parse_map(form); + else if (strcmp(h, "rule") == 0) + parse_rule(form); + else if (strcmp(h, "group") == 0) + parse_group(form); + else if (strcmp(h, "meta") == 0) + parse_meta(form); + else if (strcmp(h, "import") == 0) + parse_import(form); + else if (strcmp(h, "set-file") == 0) + parse_set_file(form); + else if (strcmp(h, "template") == 0) + parse_template(form); + else if (strcmp(h, "use") == 0) + parse_use(form); + else + eprintf("manifest: unknown top-level form '%s'\n", h); +} + +void +load_manifest(struct SNode *root) +{ + int i; + for (i = 0; i < root->nkids; i++) + dispatch_top_form(root->kids[i]); +} + +void +load_file(const char *path) +{ + FILE *fp; + char *buf; + size_t cap, len; + char rp[PATH_MAX]; + struct SLex lx; + struct SNode *root; + + if (realpath(path, rp)) { + if (sl_has(&files_read, rp)) + return; + sl_push(&files_read, rp); + } + + fp = fopen(path, "r"); + if (!fp) + eprintf("cannot open manifest %s:", path); + + cap = 65536; + len = 0; + buf = emalloc(cap); + for (;;) { + size_t n; + if (len + 65536 > cap) { + cap *= 2; + buf = erealloc(buf, cap); + } + n = fread(buf + len, 1, cap - len - 1, fp); + len += n; + if (n == 0) + break; + } + buf[len] = '\0'; + fclose(fp); + + lx.src = buf; + lx.pos = 0; + lx.line = 1; + root = snode_parse(&lx); + free(buf); + load_manifest(root); + snode_free(root); +} diff --git a/cmd/dev/ninqu/query.c b/cmd/dev/ninqu/query.c @@ -0,0 +1,203 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* walk every gate tree, collect the static var names and the rules + * each one gates. skips $(...) vars since those are per-instance */ +static void +collect_gate_vars(struct StrList *out, struct StrList *affects, struct StrList *rules_affected) +{ + int i; + for (i = 0; i < nrules; i++) { + struct Rule *r = &rules[i]; + struct Gate *g = r->gate; + struct StrList seen = {0}; + struct Gate **stack; + int sp = 0; + + if (!g) + continue; + stack = emalloc(64 * sizeof *stack); + stack[sp++] = g; + while (sp > 0) { + struct Gate *cur = stack[--sp]; + int k; + if (cur->kind == G_VAR) { + if (strstr(cur->var, "$(")) + continue; + if (!sl_has(&seen, cur->var)) { + sl_push(&seen, cur->var); + if (!sl_has(out, cur->var)) + sl_push(out, cur->var); + sl_push(affects, cur->var); + sl_push(rules_affected, r->name); + } + continue; + } + for (k = 0; k < cur->nkids; k++) + stack[sp++] = cur->kids[k]; + } + free(stack); + } +} + +/* (feature NAME) tags, separate from gate vars. a rule can carry + * more than one, so the pairing is flattened */ +static void +collect_named_features(struct StrList *out, struct StrList *owns, struct StrList *rules_tagged) +{ + int i, j; + for (i = 0; i < nrules; i++) { + struct Rule *r = &rules[i]; + for (j = 0; j < r->features.n; j++) { + const char *feat = r->features.v[j]; + if (!sl_has(out, feat)) + sl_push(out, feat); + sl_push(owns, feat); + sl_push(rules_tagged, r->name); + } + } +} + +void +do_features(void) +{ + struct StrList gatevars = {0}, affects = {0}, affected = {0}; + struct StrList featnames = {0}, feat_owns = {0}, feat_rules = {0}; + int i, j; + + printf("variables (override with -Dname=value):\n"); + for (i = 0; i < kv.n; i++) + printf( + " %s=%s%s\n", + kv.v[i].key, + kv.v[i].val, + sl_has(&kv_locked, kv.v[i].key) ? " [locked by -D]" : "" + ); + + collect_gate_vars(&gatevars, &affects, &affected); + printf("\nfeature gates (override with -Dname=0 or -Dname=1):\n"); + for (i = 0; i < gatevars.n; i++) { + printf(" %s=%s\n", gatevars.v[i], kv_get_or(gatevars.v[i], "")); + for (j = 0; j < affects.n; j++) + if (strcmp(affects.v[j], gatevars.v[i]) == 0) + printf(" gates rule: %s\n", affected.v[j]); + } + + collect_named_features(&featnames, &feat_owns, &feat_rules); + if (featnames.n > 0) { + printf("\nnamed features (declared with (feature NAME)):\n"); + for (i = 0; i < featnames.n; i++) { + printf(" %s\n", featnames.v[i]); + for (j = 0; j < feat_owns.n; j++) + if (strcmp(feat_owns.v[j], featnames.v[i]) == 0) + printf(" rule: %s\n", feat_rules.v[j]); + } + } + + printf("\ngroups:\n"); + for (i = 0; i < ngroups; i++) + printf(" %s\n", groups[i].name); + + printf("\nrules:\n"); + for (i = 0; i < nrules; i++) { + struct Rule *r = &rules[i]; + printf(" %s%s\n", r->name, r->globs.n > 0 ? " (pattern rule)" : ""); + if (r->description[0]) + printf(" # %s\n", r->description); + if (r->group_name[0]) + printf(" group: %s\n", r->group_name); + if (r->member_of[0]) + printf(" member: %s/%s\n", r->member_of, r->member_alias[0] ? r->member_alias : r->name); + for (j = 0; j < r->features.n; j++) + printf(" feature: %s\n", r->features.v[j]); + } +} + +void +do_query(const char *sub, const char *arg) +{ + int i, j; + + if (strcmp(sub, "features") == 0) { + do_features(); + return; + } + if (strcmp(sub, "groups") == 0) { + for (i = 0; i < ngroups; i++) { + printf("%s\n", groups[i].name); + for (j = 0; j < groups[i].refs.n; j++) + printf(" %s\n", groups[i].refs.v[j]); + } + return; + } + if (strcmp(sub, "metas") == 0) { + for (i = 0; i < nmetas; i++) { + printf("%s\n", metas[i].name); + for (j = 0; j < metas[i].keys.n; j++) + printf(" %s=%s\n", metas[i].keys.v[j], metas[i].vals.v[j]); + } + return; + } + if (strcmp(sub, "rules") == 0) { + for (i = 0; i < nrules; i++) { + printf("%s", rules[i].name); + if (rules[i].globs.n > 0) { + printf(" glob:"); + for (j = 0; j < rules[i].globs.n; j++) + printf(" %s", rules[i].globs.v[j]); + } + if (rules[i].produces[0]) + printf(" produces=%s", rules[i].produces); + if (rules[i].group_name[0]) + printf(" group=%s", rules[i].group_name); + if (rules[i].member_of[0]) + printf( + " member=%s/%s", + rules[i].member_of, + rules[i].member_alias[0] ? rules[i].member_alias : rules[i].name + ); + for (j = 0; j < rules[i].features.n; j++) + printf(" feature=%s", rules[i].features.v[j]); + if (rules[i].description[0]) + printf(" # %s", rules[i].description); + printf("\n"); + } + return; + } + if (strcmp(sub, "graph") == 0) { + printf("digraph ninqu {\n"); + if (arg) { + struct Group *g = group_find(arg); + if (!g) + eprintf("query graph: no such group '%s'\n", arg); + for (i = 0; i < g->refs.n; i++) { + struct Rule *r = rule_find(g->refs.v[i]); + if (!r) + continue; + for (j = 0; j < r->in.n; j++) + if (r->in.v[j][0] == '@') + printf(" \"%s\" -> \"%s\";\n", r->in.v[j] + 1, r->name); + for (j = 0; j < r->extra_deps.n; j++) + if (r->extra_deps.v[j][0] == '@') + printf(" \"%s\" -> \"%s\" [style=dashed];\n", r->extra_deps.v[j] + 1, r->name); + } + } else { + for (i = 0; i < nrules; i++) { + for (j = 0; j < rules[i].in.n; j++) + if (rules[i].in.v[j][0] == '@') + printf(" \"%s\" -> \"%s\";\n", rules[i].in.v[j] + 1, rules[i].name); + for (j = 0; j < rules[i].extra_deps.n; j++) + if (rules[i].extra_deps.v[j][0] == '@') + printf( + " \"%s\" -> \"%s\" [style=dashed];\n", rules[i].extra_deps.v[j] + 1, rules[i].name + ); + } + } + printf("}\n"); + return; + } + eprintf("query: unknown subcommand '%s' (try features, groups, metas, rules, graph)\n", sub); +} diff --git a/cmd/dev/ninqu/registry.c b/cmd/dev/ninqu/registry.c @@ -0,0 +1,167 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct Rule *rules; +int nrules, rulescap; +struct Group *groups; +int ngroups, groupscap; +struct Meta *metas; +int nmetas, metascap; +struct Template *templates; +int ntemplates, templatescap; +struct Inst *insts; +int ninsts, instscap; + +struct Rule * +rule_find(const char *name) +{ + int i; + for (i = 0; i < nrules; i++) + if (strcmp(rules[i].name, name) == 0) + return &rules[i]; + return NULL; +} + +/* match (out) against path, expanding $(...) as needed. used to + * find a producer for a file that does not exist yet */ +struct Rule * +rule_find_output(const char *path) +{ + int i; + for (i = 0; i < nrules; i++) { + if (!rules[i].out[0]) + continue; + if (strchr(rules[i].out, '$')) { + char *exp = kv_expand(rules[i].out); + int ok = strcmp(exp, path) == 0; + free(exp); + if (ok) + return &rules[i]; + } else if (strcmp(rules[i].out, path) == 0) { + return &rules[i]; + } + } + return NULL; +} + +struct Rule * +rule_find_produces(const char *name) +{ + int i; + for (i = 0; i < nrules; i++) + if (rules[i].produces[0] && strcmp(rules[i].produces, name) == 0) + return &rules[i]; + return NULL; +} + +struct Rule * +rule_new(const char *name) +{ + struct Rule *r; + if (rule_find(name)) + eprintf("manifest: duplicate rule '%s'\n", name); + if (group_find(name)) + eprintf("manifest: name '%s' already a group\n", name); + GROW(rules, nrules, rulescap, 16); + r = &rules[nrules++]; + memset(r, 0, sizeof *r); + strlcpy(r->name, name, sizeof r->name); + return r; +} + +struct Group * +group_find(const char *name) +{ + int i; + for (i = 0; i < ngroups; i++) + if (strcmp(groups[i].name, name) == 0) + return &groups[i]; + return NULL; +} + +struct Group * +group_new(const char *name) +{ + struct Group *g; + if (group_find(name)) + eprintf("manifest: duplicate group '%s'\n", name); + if (rule_find(name)) + eprintf("manifest: name '%s' already a rule\n", name); + GROW(groups, ngroups, groupscap, 16); + g = &groups[ngroups++]; + memset(g, 0, sizeof *g); + strlcpy(g->name, name, sizeof g->name); + return g; +} + +struct Meta * +meta_find(const char *name) +{ + int i; + for (i = 0; i < nmetas; i++) + if (strcmp(metas[i].name, name) == 0) + return &metas[i]; + return NULL; +} + +struct Meta * +meta_new(const char *name) +{ + struct Meta *m; + if (meta_find(name)) + eprintf("manifest: duplicate meta '%s'\n", name); + if (rule_find(name)) + eprintf("manifest: name '%s' already a rule\n", name); + if (group_find(name)) + eprintf("manifest: name '%s' already a group\n", name); + GROW(metas, nmetas, metascap, 8); + m = &metas[nmetas++]; + memset(m, 0, sizeof *m); + strlcpy(m->name, name, sizeof m->name); + return m; +} + +struct Template * +template_find(const char *name) +{ + int i; + for (i = 0; i < ntemplates; i++) + if (strcmp(templates[i].name, name) == 0) + return &templates[i]; + return NULL; +} + +struct Template * +template_new(const char *name) +{ + struct Template *t; + if (template_find(name)) + eprintf("manifest: duplicate template '%s'\n", name); + GROW(templates, ntemplates, templatescap, 8); + t = &templates[ntemplates++]; + memset(t, 0, sizeof *t); + strlcpy(t->name, name, sizeof t->name); + return t; +} + +int +inst_new(int rule_idx) +{ + struct Inst *in; + struct Rule *r = &rules[rule_idx]; + + GROW(insts, ninsts, instscap, 32); + in = &insts[ninsts]; + memset(in, 0, sizeof *in); + in->rule_idx = rule_idx; + + if (r->n_inst >= r->cap_inst) { + r->cap_inst = r->cap_inst ? r->cap_inst * 2 : 4; + r->inst_idx = erealloc(r->inst_idx, (size_t)r->cap_inst * sizeof *r->inst_idx); + } + r->inst_idx[r->n_inst++] = ninsts; + return ninsts++; +} diff --git a/cmd/dev/ninqu/resolve.c b/cmd/dev/ninqu/resolve.c @@ -0,0 +1,195 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* pull in every rule a group names, recursively */ +static struct StrList visited_groups; + +void +include_ref(const char *name) +{ + struct Group *g = group_find(name); + int i; + + if (g) { + if (sl_has(&visited_groups, name)) + return; + sl_push(&visited_groups, name); + for (i = 0; i < g->refs.n; i++) + include_ref(g->refs.v[i]); + return; + } + if (rule_find(name)) { + expand_rule(name); + return; + } + eprintf("manifest: '%s' is neither a known group nor a known rule\n", name); +} + +void +build_default_group(void) +{ + struct Group *def = group_find("default"); + int i; + if (!def) + eprintf("no group given, and manifest defines no (group default)\n"); + for (i = 0; i < def->refs.n; i++) + include_ref(def->refs.v[i]); +} + +/* match on ALIAS when the rule gave one, otherwise on the rule own + * bare name, so a member with no alias is still reachable under its + * existing name */ +static struct Rule * +rule_find_member(const char *group, const char *alias) +{ + int i; + for (i = 0; i < nrules; i++) { + struct Rule *r = &rules[i]; + if (!r->member_of[0] || strcmp(r->member_of, group) != 0) + continue; + if (r->member_alias[0]) { + if (strcmp(r->member_alias, alias) == 0) + return r; + } else if (strcmp(r->name, alias) == 0) { + return r; + } + } + return NULL; +} + +/* GROUP/ALIAS qualified addressing. leading segments before the + * last two are ignored, so "posix/bc" and "cmd/posix/bc" resolve + * the same rule. returns NULL when w has no '/', so callers can + * fall through to plain group/rule resolution. a qualified path + * that does not resolve is a hard error, not a silent fallthrough */ +static struct Rule * +resolve_member_path(const char *w) +{ + const char *last_slash; + const char *alias; + const char *group_start; + const char *p; + char group[128]; + size_t glen; + struct Rule *r; + + last_slash = strrchr(w, '/'); + if (!last_slash) + return NULL; + alias = last_slash + 1; + if (!*alias) + eprintf("manifest: '%s' ends in '/', expected GROUP/ALIAS\n", w); + + group_start = w; + for (p = w; p < last_slash; p++) + if (*p == '/') + group_start = p + 1; + glen = (size_t)(last_slash - group_start); + if (glen == 0 || glen >= sizeof group) + eprintf("manifest: '%s': bad GROUP/ALIAS path\n", w); + memcpy(group, group_start, glen); + group[glen] = '\0'; + + if (!group_find(group)) + eprintf("manifest: '%s': no such group '%s'\n", w, group); + r = rule_find_member(group, alias); + if (!r) + eprintf("manifest: '%s' names no member of group '%s'\n", alias, group); + return r; +} + +/* META.TARGET applies META overrides then resolves TARGET. + * META alone applies META then falls back to (group default). + * anything else is a plain group or rule name */ +void +resolve_wanted(const char *w) +{ + const char *dot = strchr(w, '.'); + struct Meta *m; + char meta_name[128]; + struct Rule *member; + + if (strchr(w, '/')) { + member = resolve_member_path(w); + expand_rule(member->name); + return; + } + + if (dot) { + size_t len = (size_t)(dot - w); + if (len >= sizeof meta_name) + eprintf("manifest: meta name too long in '%s'\n", w); + memcpy(meta_name, w, len); + meta_name[len] = '\0'; + m = meta_find(meta_name); + if (!m) + eprintf("manifest: '%s' names no known meta-target\n", meta_name); + meta_apply(m); + include_ref(dot + 1); + return; + } + + m = meta_find(w); + if (m) { + meta_apply(m); + build_default_group(); + return; + } + + /* a rule that declared (member ...) does not resolve by bare name + * from the command line, only through GROUP/ALIAS or transitively + * via its owning group ref list */ + { + struct Rule *br = rule_find(w); + if (br && br->member_of[0]) + eprintf( + "manifest: '%s' is a member of group '%s', not a top-level target; " + "use '%s/%s'\n", + w, + br->member_of, + br->member_of, + br->member_alias[0] ? br->member_alias : br->name + ); + } + + include_ref(w); +} + +/* a plain token in (dep) or (after) that names an existing rule + * means the same as (rule NAME). resolved once after the whole + * manifest loads, so a rule declared later can still be named + * earlier. a token with $, glob metachars, /, or . is left alone + * so this never shadows a real file dependency */ +static int +looks_like_path(const char *s) +{ + return strpbrk(s, "$*?/.") != NULL; +} + +static void +resolve_bareword_deps(struct StrList *sl) +{ + int i; + for (i = 0; i < sl->n; i++) { + char *tok = sl->v[i]; + char buf[256]; + if (tok[0] == '@' || looks_like_path(tok) || !rule_find(tok)) + continue; + snprintf(buf, sizeof buf, "@%s", tok); + free(sl->v[i]); + sl->v[i] = estrdup(buf); + } +} + +void +resolve_all_bareword_deps(void) +{ + int i; + for (i = 0; i < nrules; i++) { + resolve_bareword_deps(&rules[i].in); + resolve_bareword_deps(&rules[i].extra_deps); + } +} diff --git a/cmd/dev/ninqu/schedule.c b/cmd/dev/ninqu/schedule.c @@ -0,0 +1,93 @@ +#include "ninqu.h" + +#include <stdio.h> +#include <stdlib.h> + +/* kahn topo sort, one ready level at a time so each level + * runs in parallel. failures are reported but do not stop the + * batch, so one broken file does not block the rest */ +void +schedule_and_run(void) +{ + int *indeg = ecalloc((size_t)ninsts, sizeof *indeg); + int **dependents = emalloc((size_t)ninsts * sizeof *dependents); + int *ndep = ecalloc((size_t)ninsts, sizeof *ndep); + int *capdep = ecalloc((size_t)ninsts, sizeof *capdep); + int *level = emalloc((size_t)ninsts * sizeof *level); + int levn = 0, done_count = 0; + int i, j; + + for (i = 0; i < ninsts; i++) { + indeg[i] = insts[i].n_dep; + dependents[i] = NULL; + } + for (i = 0; i < ninsts; i++) { + for (j = 0; j < insts[i].n_dep; j++) { + int d = insts[i].dep_inst[j]; + if (ndep[d] >= capdep[d]) { + capdep[d] = capdep[d] ? capdep[d] * 2 : 4; + dependents[d] = erealloc(dependents[d], (size_t)capdep[d] * sizeof *dependents[d]); + } + dependents[d][ndep[d]++] = i; + } + } + for (i = 0; i < ninsts; i++) + if (indeg[i] == 0) + level[levn++] = i; + + while (levn > 0) { + int *next_level = emalloc((size_t)ninsts * sizeof *next_level); + int nextn = 0; + + if (summary_mode) { + for (i = 0; i < levn; i++) { + struct Inst *inst = &insts[level[i]]; + int will = inst_stale(inst); + int d; + for (d = 0; d < inst->n_dep && !will; d++) + if (insts[inst->dep_inst[d]].will_build) + will = 1; + inst->will_build = will; + printf( + "%-4s %-12s %s\n", + will ? "BUILD" : "OK", + rules[inst->rule_idx].name, + inst->out[0] ? inst->out : "(phony)" + ); + if (rules[inst->rule_idx].description[0]) + printf(" # %s\n", rules[inst->rule_idx].description); + if (will) { + char *cmd = sl_join(&inst->cmd.argv); + printf(" cmd: %s\n", cmd); + free(cmd); + } + } + } else { + run_batch(level, levn); + } + + done_count += levn; + for (i = 0; i < levn; i++) { + int u = level[i]; + for (j = 0; j < ndep[u]; j++) { + int v = dependents[u][j]; + if (--indeg[v] == 0) + next_level[nextn++] = v; + } + } + free(level); + level = next_level; + levn = nextn; + } + + if (done_count < ninsts) + eprintf("manifest: dependency cycle among %d instances\n", ninsts - done_count); + + free(level); + free(indeg); + for (i = 0; i < ninsts; i++) + free(dependents[i]); + free(dependents); + free(ndep); + free(capdep); +} diff --git a/cmd/dev/ninqu/sexpr.c b/cmd/dev/ninqu/sexpr.c @@ -0,0 +1,344 @@ +#include "ninqu.h" + +#include <ctype.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* track nesting so $(EXTRA_LIBS:$(BASESTEM)) does not stop at the + * inner close paren. shared by kv_expand and subst_tmpl */ +const char * +find_dollar_close(const char *inner) +{ + const char *scan = inner; + int depth = 1; + + while (*scan) { + if (scan[0] == '$' && scan[1] == '(') { + depth++; + scan += 2; + continue; + } + if (*scan == ')') { + if (--depth == 0) + return scan; + } + scan++; + } + return NULL; +} + +struct SNode * +snode_atom(const char *s, int line) +{ + struct SNode *n = ecalloc(1, sizeof *n); + n->kind = S_ATOM; + n->atom = estrdup(s); + n->line = line; + return n; +} + +struct SNode * +snode_list(int line) +{ + struct SNode *n = ecalloc(1, sizeof *n); + n->kind = S_LIST; + n->line = line; + return n; +} + +void +snode_push(struct SNode *list, struct SNode *kid) +{ + if (list->nkids == 0) { + list->kids = emalloc(8 * sizeof *list->kids); + } else { + int cap = 8; + while (cap < list->nkids) + cap *= 2; + if (list->nkids == cap) + list->kids = erealloc(list->kids, (size_t)cap * 2 * sizeof *list->kids); + } + list->kids[list->nkids++] = kid; +} + +void +snode_free(struct SNode *n) +{ + int i; + if (!n) + return; + if (n->kind == S_LIST) { + for (i = 0; i < n->nkids; i++) + snode_free(n->kids[i]); + free(n->kids); + } + free(n->atom); + free(n); +} + +/* deep copy. a template body is parsed from a file that gets freed + * once load_manifest returns, so the stored copy cannot point back + * into that tree */ +struct SNode * +snode_clone(struct SNode *n) +{ + struct SNode *out; + int i; + + if (!n) + return NULL; + if (n->kind == S_ATOM) + return snode_atom(n->atom, n->line); + out = snode_list(n->line); + for (i = 0; i < n->nkids; i++) + snode_push(out, snode_clone(n->kids[i])); + return out; +} + +/* replace each $(PARAM) with its argument text. any other $(...) is + * copied verbatim for the later kv_expand pass, so a template body + * can reference $(BASESTEM) the same way a hand-written rule does */ +char * +subst_tmpl(const char *s, struct StrList *params, char **vals) +{ + size_t cap = strlen(s) * 2 + 64, len = 0; + char *out = emalloc(cap); + const char *p = s; + + while (*p) { + if (p[0] == '$' && p[1] == '(') { + const char *inner = p + 2; + const char *close = find_dollar_close(inner); + + if (close) { + char name[256]; + size_t nl = (size_t)(close - inner); + size_t tokl; + int pi; + + if (nl >= sizeof name) + nl = sizeof name - 1; + memcpy(name, inner, nl); + name[nl] = '\0'; + + for (pi = 0; pi < params->n; pi++) + if (strcmp(params->v[pi], name) == 0) + break; + + tokl = (pi < params->n) ? strlen(vals[pi]) : (size_t)(close - p) + 1; + while (len + tokl + 1 >= cap) { + cap *= 2; + out = erealloc(out, cap); + } + memcpy(out + len, pi < params->n ? vals[pi] : p, tokl); + len += tokl; + p = close + 1; + continue; + } + } + if (len + 2 >= cap) { + cap *= 2; + out = erealloc(out, cap); + } + out[len++] = *p++; + } + out[len] = '\0'; + return out; +} + +void +snode_subst(struct SNode *n, struct StrList *params, char **vals) +{ + int i; + if (!n) + return; + if (n->kind == S_ATOM) { + char *out = subst_tmpl(n->atom, params, vals); + free(n->atom); + n->atom = out; + return; + } + for (i = 0; i < n->nkids; i++) + snode_subst(n->kids[i], params, vals); +} + +/* swallow a balanced $(...) inside a bare atom */ +void +lex_swallow_dollar(struct SLex *lx, char *buf, size_t *blen, size_t bsz) +{ + int depth = 1; + + if (*blen + 2 < bsz) { + buf[(*blen)++] = '$'; + buf[(*blen)++] = '('; + } + lx->pos += 2; + while (depth > 0) { + int e = lx->src[lx->pos]; + if (e == '\0') + eprintf("manifest: unterminated $(...) on line %d\n", lx->line); + if (e == '\n') + lx->line++; + if (e == '$' && lx->src[lx->pos + 1] == '(') { + depth++; + if (*blen + 2 < bsz) { + buf[(*blen)++] = e; + buf[(*blen)++] = lx->src[lx->pos + 1]; + } + lx->pos += 2; + continue; + } + if (*blen < bsz - 1) + buf[(*blen)++] = e; + if (e == ')') + depth--; + lx->pos++; + } +} + +/* \" \\ \n \t \r \$ are recognized. anything else keeps the backslash + * so shell escapes like \( survive */ +void +lex_string(struct SLex *lx, char *buf, size_t bsz) +{ + int line = lx->line; + size_t blen = 0; + + lx->pos++; + while (lx->src[lx->pos] && lx->src[lx->pos] != '"') { + int e = lx->src[lx->pos]; + + if (e == '\\' && lx->src[lx->pos + 1]) { + int esc = lx->src[lx->pos + 1]; + switch (esc) { + case 'n': + e = '\n'; + break; + case 't': + e = '\t'; + break; + case 'r': + e = '\r'; + break; + case '"': + case '\\': + case '$': + e = esc; + break; + default: + if (blen < bsz - 1) + buf[blen++] = '\\'; + e = esc; + break; + } + lx->pos += 2; + } else { + lx->pos++; + } + if (e == '\n') + lx->line++; + if (blen < bsz - 1) + buf[blen++] = (char)e; + } + if (lx->src[lx->pos] != '"') + eprintf("manifest: unterminated string on line %d\n", line); + lx->pos++; + buf[blen] = '\0'; +} + +struct SNode * +snode_parse(struct SLex *lx) +{ + char buf[8192]; + size_t blen; + int line; + struct SNode *root = snode_list(lx->line); + struct SNode **stack = emalloc(16 * sizeof *stack); + int sp = 0, scap = 16; + + stack[sp++] = root; + + for (;;) { + int c = lx->src[lx->pos]; + + if (c == '\0') + break; + if (c == '\n') { + lx->line++; + lx->pos++; + continue; + } + if (isspace((unsigned char)c)) { + lx->pos++; + continue; + } + if (c == ';') { + while (lx->src[lx->pos] && lx->src[lx->pos] != '\n') + lx->pos++; + continue; + } + if (c == '(') { + struct SNode *lst = snode_list(lx->line); + snode_push(stack[sp - 1], lst); + if (sp >= scap) { + scap *= 2; + stack = erealloc(stack, (size_t)scap * sizeof *stack); + } + stack[sp++] = lst; + lx->pos++; + continue; + } + if (c == ')') { + if (sp <= 1) + eprintf("manifest: stray ')' on line %d\n", lx->line); + sp--; + lx->pos++; + continue; + } + if (c == '"') { + line = lx->line; + lex_string(lx, buf, sizeof buf); + snode_push(stack[sp - 1], snode_atom(buf, line)); + continue; + } + + /* bare atom */ + line = lx->line; + blen = 0; + while (lx->src[lx->pos]) { + int d = lx->src[lx->pos]; + if (d == '(' || d == ')' || d == '"' || d == ';' || isspace((unsigned char)d)) + break; + if (d == '$' && lx->src[lx->pos + 1] == '(') { + lex_swallow_dollar(lx, buf, &blen, sizeof buf); + continue; + } + if (blen < sizeof buf - 1) + buf[blen++] = d; + lx->pos++; + } + buf[blen] = '\0'; + snode_push(stack[sp - 1], snode_atom(buf, line)); + } + + if (sp != 1) + eprintf("manifest: %d unclosed '(' at end of file\n", sp - 1); + + free(stack); + return root; +} + +int +s_is_list(struct SNode *n) +{ + return n && n->kind == S_LIST; +} + +const char * +s_head(struct SNode *n) +{ + if (!s_is_list(n) || n->nkids == 0 || n->kids[0]->kind != S_ATOM) + return NULL; + return n->kids[0]->atom; +} diff --git a/cmd/dev/ninqu/strlist.c b/cmd/dev/ninqu/strlist.c @@ -0,0 +1,103 @@ +#include "ninqu.h" + +#include <ctype.h> +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +void +sl_push(struct StrList *sl, const char *s) +{ + GROW(sl->v, sl->n, sl->cap, 8); + sl->v[sl->n++] = estrdup(s); +} + +int +sl_has(struct StrList *sl, const char *s) +{ + int i; + for (i = 0; i < sl->n; i++) + if (strcmp(sl->v[i], s) == 0) + return 1; + return 0; +} + +void +sl_split(struct StrList *sl, const char *s) +{ + const char *p = s; + + sl->n = 0; + while (*p) { + const char *start; + char buf[4096]; + size_t len; + + while (*p && isspace((unsigned char)*p)) + p++; + if (!*p) + break; + start = p; + while (*p && !isspace((unsigned char)*p)) + p++; + len = (size_t)(p - start); + if (len >= sizeof buf) + len = sizeof buf - 1; + memcpy(buf, start, len); + buf[len] = '\0'; + sl_push(sl, buf); + } +} + +char * +sl_join(struct StrList *sl) +{ + size_t cap = 64, len = 0; + char *out = emalloc(cap); + int i; + + out[0] = '\0'; + for (i = 0; i < sl->n; i++) { + size_t addlen = strlen(sl->v[i]) + 1; + while (len + addlen + 1 > cap) { + cap *= 2; + out = erealloc(out, cap); + } + if (i > 0) + out[len++] = ' '; + memcpy(out + len, sl->v[i], strlen(sl->v[i])); + len += strlen(sl->v[i]); + out[len] = '\0'; + } + return out; +} + +const char * +base_of(const char *path) +{ + const char *p = strrchr(path, '/'); + return p ? p + 1 : path; +} + +/* null-terminate the array so execvp stops scanning */ +char ** +sl_argv(struct StrList *sl) +{ + char **av = emalloc((size_t)(sl->n + 1) * sizeof *av); + int i; + for (i = 0; i < sl->n; i++) + av[i] = sl->v[i]; + av[sl->n] = NULL; + return av; +} + +/* noreturn so callers do not need to guard the dead path after the + * fork child calls this */ +void +child_execvp(char **av) +{ + execvp(av[0], av); + fprintf(stderr, "%s: exec %s: %s\n", argv0, av[0], strerror(errno)); + _exit(127); +} diff --git a/ninqu.rules b/ninqu.rules @@ -0,0 +1,678 @@ +; genconfig.sh config produces four files from build.cfg: +; config.set (read by ninqu), config.kv (sourced by genbox.sh), +; nofork_list.h (included by wexec.c), and features.h (-include'd +; into every compile). each gets its own rule so ninqu can find a +; producer for any of them +; +(rule CONFIG_SET + (out "scripts/mk/config.set") + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh config)) + +(rule NOFORK_LIST_H + (out "shared/libutil/nofork_list.h") + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh config)) + +(rule FEATURES_H + (out "scripts/mk/features.h") + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh config)) + +(set-file "scripts/mk/config.set") + +; static libraries: compile every .c in each lib dir then AR +; +(rule LIBUTF_OBJ + (glob "shared/libutf/*.c") + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Ishared/libutf $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule LIBUTF + (dep LIBUTF_OBJ) + (out "shared/libutf/libutf.a") + (description "utf-8 and rune handling, linked into every aruu tool") + (feature core-lib) + (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) + +(rule LIBUTIL_OBJ + (glob "shared/libutil/*.c") + (dep $(MATCH)) + (after NOFORK_LIST_H FEATURES_H) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS_LIBUTIL) -Ishared/libutil $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule LIBUTIL + (dep LIBUTIL_OBJ) + (out "shared/libutil/libutil.a") + (description "allocation, error reporting, and string helpers shared by every tool") + (feature core-lib) + (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) + +(rule LIBREDLINE_OBJ + (glob "shared/libredline/*.c") + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Ishared/libredline $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule LIBREDLINE + (dep LIBREDLINE_OBJ) + (out "shared/libredline/libredline.a") + (description "line editing used by sh and any other interactive tool") + (feature core-lib) + (exec $(AR) $(ARFLAGS) $(OUT) $(IN))) + +(group lib LIBUTF LIBUTIL LIBREDLINE) + +; perfile: every *.c directly inside one of these dirs becomes its +; own binary of the same name, individually gated by +; build_<category>_<ident> (lowercase, hyphens and dots turned to +; underscores, see the $(IDENT) comment above BOX_OBJ below for why) +; (skip) excludes files that belong to a multi-file tool below instead +; +(map EXTRA_LIBS + (diff "-lm") + (wget $(LDLIBS_TLS))) + +; Every .c file in a category builds into its own binary. PERFILE captures +; that shared rule. Only EXTRA_AFTER differs cuz POSIX waits for GETCONF_H +; the rest pass "". cmd/posix/bc.c overrides this with its own yacc-based +; rule, so no need for PERFILE to have that as a special case +; +(template PERFILE (NAME CATEGORY DESC EXTRA_AFTER) + (rule $(NAME) + (glob "cmd/$(CATEGORY)/*.c") + (gate build_$(CATEGORY)_$(IDENT)) + (dep $(MATCH)) + (after LIBUTIL LIBUTF $(EXTRA_AFTER)) + (out $(STEM)) + (description $(DESC)) + (feature perfile) + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(MATCH) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS) $(EXTRA_LIBS:$(BASESTEM))))) + +(use PERFILE POSIX_BIN posix "one POSIX2024 utility per source file under cmd/posix" GETCONF_H) +(use PERFILE LINUX_BIN linux "Linux-only utility, one source file per binary under cmd/linux" "") +(use PERFILE NET_BIN net "networking utility, one source file per binary under cmd/net" "") +(use PERFILE XSI_BIN xsi "XSI-specified utility, one source file per binary under cmd/xsi" "") +(use PERFILE PSEUDO_BIN pseudo "common but undefined utility, one source file per binary under cmd/pseudo" "") +(use PERFILE EXTRA_BIN extra "extra utility outside POSIX/XSI scope, one source file per binary under cmd/extra" "") + +(group posix lib POSIX_BIN POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE) +(group linux lib LINUX_BIN) +(group net lib NET_BIN) +(group xsi lib XSI_BIN) +(group pseudo lib PSEUDO_BIN) +(group extra lib EXTRA_BIN EXTRA_YAP) + +; codegen: generate sources consumed by the build rules below. Ungated +; generators always run; conditional ones use (req) so they only run +; when their inputs exist in this checkout +; +(rule GETCONF_H + (gate build_posix_getconf) + (out "cmd/posix/getconf.h") + (dep "scripts/getconf.sh") + (exec sh scripts/genconfig.sh getconf)) + +(rule POSIX_BC_C + (gate build_posix_bc) + (req "cmd/posix/bc.y") + (out "cmd/posix/bc.c") + (dep "cmd/posix/bc.y") + (exec sh scripts/genconfig.sh bc)) + +(rule POSIX_AWK_C + (gate build_posix_awk) + (out "cmd/posix/awk/awkgram.tab.c") + (dep "cmd/posix/awk/awkgram.y") + (exec sh scripts/genconfig.sh awk)) + +(rule POSIX_SH_C + (gate build_posix_sh) + (out "cmd/posix/sh/syntax.c") + (dep "cmd/posix/sh/mksyntax.c" "cmd/posix/sh/mknodes.c" "cmd/posix/sh/mkbuiltins" "cmd/posix/sh/mktokens") + (exec sh scripts/genconfig.sh sh)) + +(rule DEVCONF + (req "cmd/dev/configure") + (out "cmd/dev/config.h") + (dep "cmd/dev/configure") + (phony) + (exec sh cmd/dev/configure)) + +(group codegen GETCONF_H POSIX_BC_C POSIX_AWK_C POSIX_SH_C DEVCONF) + +; multi: one binary from all .c files in one or more dirs (minus skip). +; codegen must run first so generated sources are present before these +; globs collect them +; +(rule POSIX_BC_OBJ + (glob "cmd/posix/bc.c") + (gate build_posix_bc) + (dep $(MATCH)) + (after POSIX_BC_C) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_BC + (gate build_posix_bc) + (member posix bc) + (dep POSIX_BC_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/posix/bc") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS) -lm)) + +(rule POSIX_AWK_OBJ + (glob "cmd/posix/awk/*.c") + (gate build_posix_awk) + (skip "maketab.c") + (dep $(MATCH)) + (after POSIX_AWK_C) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_AWK + (gate build_posix_awk) + (member posix awk) + (dep POSIX_AWK_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/posix/awk/awk") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS) -lm)) + +(rule POSIX_SH_OBJ + (glob "cmd/posix/sh/*.c") + (gate build_posix_sh) + (skip "mknodes.c" "mksyntax.c") + (dep $(MATCH)) + (after POSIX_SH_C) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_SH + (gate build_posix_sh) + (member posix sh) + (dep POSIX_SH_OBJ) + (after LIBUTIL LIBUTF LIBREDLINE) + (out "cmd/posix/sh/sh") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a shared/libredline/libredline.a $(LDFLAGS) $(LDLIBS))) + +(rule POSIX_MAKE_OBJ + (glob "cmd/posix/make/*.c") + (gate build_posix_make) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_MAKE + (gate build_posix_make) + (member posix make) + (dep POSIX_MAKE_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/posix/make/make") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +(rule EXTRA_YAP_OBJ + (glob "cmd/extra/yap/*.c") + (gate build_extra_yap) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule EXTRA_YAP + (gate build_extra_yap) + (member extra yap) + (dep EXTRA_YAP_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/extra/yap/yap") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS) -ltinfo)) + +; (member GROUP ALIAS) gives a rule a qualified user-facing name +; (e.g. posix/bc) while keeping its internal name (POSIX_BC) for deps, +; gates, and other references +; + +; dev: the aruu toolchain. ar/as/ld are standalone and cc +; shares one object pool linked into three frontends +; +(rule AR_OBJ + (glob "cmd/dev/ar/*.c") + (gate build_dev_ar) + (skip "tinyar.c") + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/ar $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule AR + (gate build_dev_ar) + (dep AR_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/dev/ar/ar") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +(rule XCUTIL_OBJ + (glob "cmd/dev/xcutil/*.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule AS_OBJ + (glob "cmd/dev/as/*.c" "cmd/dev/as/arch/x64/*.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil -Icmd/dev/as -Icmd/dev/as/arch/x64 -Ishared $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule AS + (gate build_dev_cc) + (dep AS_OBJ) + (after XCUTIL_OBJ LIBUTIL LIBUTF) + (out "cmd/dev/as/as") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +(rule LD_OBJ + (glob "cmd/dev/ld/*.c") + (gate build_dev_ld) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/xcutil -Icmd/dev/ld $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule LD + (gate build_dev_ld) + (dep LD_OBJ) + (after XCUTIL_OBJ LIBUTIL LIBUTF) + (out "cmd/dev/ld/ld") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +; CCPOOL_OBJ globs the whole directory. The entry points below use +; literal globs, so the override mechanism excludes them automatically +(rule CCPOOL_OBJ + (glob "cmd/dev/cc/*.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule CC1_OBJ + (glob "cmd/dev/cc/cc1.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule CC1 + (gate build_dev_cc) + (dep CC1_OBJ CCPOOL_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/dev/cc/cc1") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +(rule CPP_OBJ + (glob "cmd/dev/cc/cpp.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule CPP + (gate build_dev_cc) + (dep CPP_OBJ CCPOOL_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/dev/cc/cpp") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +(rule CCDRV_OBJ + (glob "cmd/dev/cc/driver.c" "cmd/dev/cc/util.c") + (gate build_dev_cc) + (dep $(MATCH)) + (out "$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule CCDRV + (gate build_dev_cc) + (dep CCDRV_OBJ) + (after LIBUTIL LIBUTF) + (out "cmd/dev/cc/cc") + (exec $(CC) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a $(LDFLAGS) $(LDLIBS))) + +; ninqu itself lives at cmd/dev/ninqu/ninqu and is built by the +; Makefile directly, since it has to exist before this file can be +; parsed. a rule here producing the same path would just race that +; bootstrap compile, so only the box variant below belongs to ninqu +; +; Like BOX_OBJ: rename main and hide other globals so ninqu can link +; into aruu-box. It is still not reentrant, so it stays out of +; NOFORK_LIST +; +(rule NINQU_BOX_OBJ + (glob "cmd/dev/ninqu/*.c") + (gate build_dev_ninqu) + (dep $(MATCH)) + (after LIBUTIL LIBUTF LIBREDLINE NOFORK_LIST_H FEATURES_H GETCONF_H) + (out ".box/cmd/dev/$(BASESTEM).o") + (description "ninqu as a box builtin, main renamed for the box dispatch table") + (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH) && sym=`echo $(BASESTEM) | tr '.-' '__'`_main && $(OBJCOPY) --redefine-sym main=$sym $(OUT) && $(OBJCOPY) --keep-global-symbol=$sym $(OUT)") + (group box)) + +(group dev lib DEVCONF AR AS LD CC1 CPP CCDRV) + +; man pages: build mdoc and text pages from ?man-marked sources. +; +(rule MKMAN + (dir "scripts/mkman") + (dep "glob:scripts/mkman/*.go") + (out "scripts/mkman/mkman") + (exec go build -o mkman .)) + +(rule MAN_MDOC + (glob "cmd/**/*.c") + (mark "?man") + (dep (after MKMAN)) + (out "man/man$(SEC_OF:$(DIR))/$(BASESTEM).$(SEC_OF:$(DIR))") + (exec scripts/mkman/mkman -fmt mdoc -config scripts/mk/config.kv -src $(MATCH)) + (redirect)) + +(rule MAN_TXT + (glob "cmd/**/*.c") + (mark "?man") + (dep (after MKMAN)) + (out "man/man$(SEC_OF:$(DIR))/$(BASESTEM).$(SEC_OF:$(DIR)).txt") + (exec scripts/mkman/mkman -fmt txt -config scripts/mk/config.kv -src $(MATCH)) + (redirect)) + +(map SEC_OF + (cmd/posix 1) + (cmd/linux 8) + (cmd/net 8) + (cmd/xsi 1) + (cmd/pseudo 1) + (cmd/extra 1) + (cmd/dev 1)) + +(group man MAN_MDOC MAN_TXT) + +(rule CLEAN + (phony) + (shell " + printf ' CLEAN object files\n' + find shared cmd -name '*.o' -exec rm -f {} + + + printf ' CLEAN static libraries\n' + find shared -name '*.a' -exec rm -f {} + + + printf ' CLEAN compiled binaries\n' + find cmd -type f ! -name '*.*' -perm -100 -exec rm -f {} + + + sh scripts/genconfig.sh clean + rm -f scripts/mk/config.mk scripts/mk/config.kv scripts/mk/rules.mk shared/libutil/nofork_list.h + + printf ' CLEAN build tools\n' + rm -f scripts/mkman/mkman + + printf ' CLEAN dev artifacts\n' + rm -f cmd/dev/cc/cc1 cmd/dev/cc/cpp cmd/dev/as/as cmd/dev/ld/ld cmd/dev/ar/ar + rm -f shared/libaruuelf.so + rm -f cmd/dev/config.h cmd/dev/cc/config.h cmd/dev/version.h + + printf ' CLEAN misc\n' + rm -rf man/man1 man/man8 + rm -rf aruu-box .box + + printf ' CLEAN done\n' + ")) + +(group clean CLEAN) + +; install every built executable and generated man page +(rule INSTALL + (phony) + (after ALL_BINS MAN_MDOC MAN_TXT) + (shell " + mkdir -p \"$(PREFIX)/bin\" \"$(MANPREFIX)/man1\" \"$(MANPREFIX)/man8\" + + find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do + name=${bin##*/} + printf ' INSTALL %s/bin/%s\n' '$(PREFIX)' \"$name\" + cp \"$bin\" \"$(PREFIX)/bin/$name\" + chmod 755 \"$(PREFIX)/bin/$name\" + done + + find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do + sec=${f%/*}; sec=${sec##*/} + name=${f##*/} + cp \"$f\" \"$(MANPREFIX)/$sec/$name\" + done + ")) + +(group install INSTALL) + +; remove exactly what install would have copied +(rule REMOVE + (phony) + (shell " + find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do + name=${bin##*/} + printf ' REMOVE %s/bin/%s\n' '$(PREFIX)' \"$name\" + rm -f \"$(PREFIX)/bin/$name\" + done + + find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do + sec=${f%/*}; sec=${sec##*/} + name=${f##*/} + printf ' REMOVE %s/%s/%s\n' '$(MANPREFIX)' \"$sec\" \"$name\" + rm -f \"$(MANPREFIX)/$sec/$name\" + done + ")) + +(group remove REMOVE) +(group uninstall REMOVE) + +; box: the multi-call binary containing every enabled tool in a single executable +; with a dispatch table. This includes multi-file tools like POSIX_BC, POSIX_AWK, +; POSIX_SH, POSIX_MAKE, and EXTRA_YAP. A single-file tool has its main function +; renamed directly by BOX_OBJ. The multi-file tools use a partial link (ld -r) +; in their respective rules to combine their objects before renaming main, +; preventing helper symbols from colliding. This replaces scripts/mkbox +; +; Object files are stored under .box/ to mirror the cmd/ layout and prevent +; collisions with standalone objects. Since standalone and box objects use +; different symbol names, they cannot share a path +; +; Ninqu determines which tools enter the box using the gate on BOX_OBJ. +; BOX_DISPATCH reads the object paths passed on argv rather than consulting +; build.cfg or config.set directly +; + +; CATEGORY_OF maps a directory path to its category name, matching the toggles +; in build.cfg. Since BOX_OBJ globs multiple directories, its gate evaluates the +; category dynamically based on the match directory +; +; Gates evaluate $(IDENT) instead of $(BASESTEM) because toggle names must be +; valid shell variables. Genconfig.sh replaces hyphens and periods with +; underscores, and $(IDENT) applies the same normalization so they match +; +(map CATEGORY_OF + (cmd/posix posix) + (cmd/linux linux) + (cmd/net net) + (cmd/pseudo pseudo) + (cmd/xsi xsi) + (cmd/extra extra)) + +; Tool basestems match their C symbols using a shell transform (tr '.-' '__' +; and appending _main) in both the objcopy step and in genbox.sh. A static map +; is unnecessary because no current tools require custom overrides, and +; genbox.sh only receives paths via argv +; + +; The match directory determines the gate and output path, allowing one rule +; to handle six categories. The multi-file tool bc.c inside cmd/posix is +; automatically excluded via the literal-glob override mechanism +; +(rule BOX_OBJ + (glob "cmd/posix/*.c" "cmd/linux/*.c" "cmd/net/*.c" "cmd/pseudo/*.c" + "cmd/xsi/*.c" "cmd/extra/*.c") + (gate build_$(CATEGORY_OF:$(DIR))_$(IDENT)) + (dep $(MATCH)) + (after LIBUTIL LIBUTF LIBREDLINE NOFORK_LIST_H FEATURES_H GETCONF_H) + (out ".box/$(DIR)/$(BASESTEM).o") + (description "one object per enabled tool, main renamed for the box dispatch table") + (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH) && sym=`echo $(BASESTEM) | tr '.-' '__'`_main && $(OBJCOPY) --redefine-sym main=$sym $(OUT) && $(OBJCOPY) --keep-global-symbol=$sym $(OUT)") + (group box)) + +; Multi-file tools like POSIX_BC, POSIX_AWK, POSIX_SH, POSIX_MAKE, and +; EXTRA_YAP cannot use the single-file objcopy step because their global helper +; symbols would collide when linked into a single binary. Combining these +; objects first with a partial link (ld -r) resolves internal references, making +; it safe to isolate the renamed main function and hide remaining symbols +; +; Combined objects use the layout .box/cmd/<category>/<tool>.o so genbox.sh +; can parse them without structural modifications +; +(rule POSIX_BC_BOX_OBJ + (glob "cmd/posix/bc.c") + (gate build_posix_bc) + (dep $(MATCH)) + (after POSIX_BC_C) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_BC_BOX + (gate build_posix_bc) + (dep POSIX_BC_BOX_OBJ) + (out ".box/cmd/posix/bc.o") + (description "bc's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=bc_main $(OUT) && $(OBJCOPY) --keep-global-symbol=bc_main $(OUT)") + (group box)) + +(rule POSIX_AWK_BOX_OBJ + (glob "cmd/posix/awk/*.c") + (gate build_posix_awk) + (skip "maketab.c") + (dep $(MATCH)) + (after POSIX_AWK_C) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_AWK_BOX + (gate build_posix_awk) + (dep POSIX_AWK_BOX_OBJ) + (out ".box/cmd/posix/awk.o") + (description "awk's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=awk_main $(OUT) && $(OBJCOPY) --keep-global-symbol=awk_main $(OUT)") + (group box)) + +(rule POSIX_SH_BOX_OBJ + (glob "cmd/posix/sh/*.c") + (gate build_posix_sh) + (skip "mknodes.c" "mksyntax.c") + (dep $(MATCH)) + (after POSIX_SH_C) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_SH_BOX + (gate build_posix_sh) + (dep POSIX_SH_BOX_OBJ) + (out ".box/cmd/posix/sh.o") + (description "sh's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=sh_main $(OUT) && $(OBJCOPY) --keep-global-symbol=sh_main $(OUT)") + (group box)) + +(rule POSIX_MAKE_BOX_OBJ + (glob "cmd/posix/make/*.c") + (gate build_posix_make) + (dep $(MATCH)) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule POSIX_MAKE_BOX + (gate build_posix_make) + (dep POSIX_MAKE_BOX_OBJ) + (out ".box/cmd/posix/make.o") + (description "make's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=make_main $(OUT) && $(OBJCOPY) --keep-global-symbol=make_main $(OUT)") + (group box)) + +(rule EXTRA_YAP_BOX_OBJ + (glob "cmd/extra/yap/*.c") + (gate build_extra_yap) + (dep $(MATCH)) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + +(rule EXTRA_YAP_BOX + (gate build_extra_yap) + (dep EXTRA_YAP_BOX_OBJ) + (out ".box/cmd/extra/yap.o") + (description "yap's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=yap_main $(OUT) && $(OBJCOPY) --keep-global-symbol=yap_main $(OUT)") + (group box)) + +; Genbox.sh relies on arguments passed by ninqu, where each argument matches +; an output from BOX_OBJ or a custom box rule. The script derives categories +; and tool names directly from these paths and outputs the dispatch code +; +(rule BOX_DISPATCH + (dep BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX_OBJ) + (out ".box/aruu-box.c") + (description "dispatch table and main() for aruu-box, generated from the enabled tool list") + (exec scripts/genbox.sh $(IN)) + (redirect) + (group box)) + +; Libm is linked unconditionally because bc requires it, and unused library +; references are safe. Modern toolchains omit unreferenced archive components. +; Yap requires terminfo, which is an optional system dependency. Linking it +; unconditionally breaks builds on systems without ncurses-dev when yap is +; disabled. Genconfig.sh exports BOX_EXTRA_LIBS as "-ltinfo" or an empty string +; based on whether yap is enabled +; +(rule BOX + (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX_OBJ) + (after LIBUTIL LIBUTF LIBREDLINE) + (out "aruu-box") + (description "single multi-call binary, one dispatch table for every enabled tool") +; (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a shared/libredline/libredline.a $(LDFLAGS) $(LDLIBS) -lm $(BOX_EXTRA_LIBS)") + (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) shared/libutil/libutil.a shared/libutf/libutf.a shared/libredline/libredline.a $(LDFLAGS) $(LDLIBS) $(BOX_EXTRA_LIBS)") + (group box)) + +(group box BOX) + +; ------------------------------------------------------------------- +; top level. (group all) contains every build target except clean +; and box. box is separate because it produces a different binary +; with different .o files, and mixing it with standalone builds +; would cause confusion. clean is never in all because it removes +; what all builds +; ------------------------------------------------------------------- + +(rule ALL_BINS + (phony) + (after LIBUTIL LIBUTF LIBREDLINE + POSIX_BIN LINUX_BIN NET_BIN XSI_BIN + PSEUDO_BIN EXTRA_BIN + POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE EXTRA_YAP + AR AS LD CC1 CPP CCDRV) + (exec true)) + +(group all ALL_BINS) + +(group default all) + +; ------------------------------------------------------------------- +; meta-targets: apply an override, then build a normal target under +; it. invoke as `ninqu META.TARGET` (`ninqu debug.posix`) or bare +; `ninqu META` to apply the override and build (group default). the +; $(CFLAGS) inside each value is expanded against whatever CFLAGS +; already holds (the config.set default, or a -DCFLAGS=... override) +; at the moment the meta is applied, so these only append, they +; never have to repeat -std=c99 -Wall -Wextra -pedantic themselves +; ------------------------------------------------------------------- + +(meta debug + (set CFLAGS "$(CFLAGS) -g -O0")) + +(meta release + (set CFLAGS "$(CFLAGS) -O2 -DNDEBUG")) diff --git a/scripts/deps b/scripts/deps @@ -1,98 +0,0 @@ -#!/bin/sh -# https://srcdump.net/shrub/shrubtools/tree/main/item/deps.html -# -# emit makefile dependencies for a list of C sources using the compiler's .d output. having a bunch of -# autogenerated .d files and -include's is flaky and ugly, and might not work on all make -# implementations. this way you can generate the deps once and ship the makefile. -# it takes a list of files from stdin and prints to stdout. you might also want to append -# you CFLAGS/CPPFLAGS if that will change the deps. -# -# example: -# find . -type f -name '*.c' | CPPFLAGS='-Iinclude' deps >> Makefile -# -set -eu - -cc=${CC:-cc} -cppflags=${CPPFLAGS:-} -cflags=${CFLAGS:-} -tmpbase=${TMPDIR:-/tmp} - -cleanup() { - rm -rf "$tmpdir" -} - -usage() { - printf 'usage: %s [file.c ...]\n' "${0##*/}" >&2 - printf ' %s < file-list\n' "${0##*/}" >&2 - exit 2 -} - -list() { - if [ "$#" -gt 0 ]; then - for src do - case $src in - *.c) printf '%s\n' "$src" ;; - *) printf '%s: not a .c file: %s\n' "${0##*/}" "$src" >&2; exit 2 ;; - esac - done - return - fi - - while IFS= read -r src; do - [ -n "$src" ] || continue - case $src in - *.c) printf '%s\n' "$src" ;; - *) printf '%s: not a .c file: %s\n' "${0##*/}" "$src" >&2; exit 2 ;; - esac - done -} - -if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then - usage -fi - -tmpdir=$(mktemp -d "$tmpbase/deps.XXXXXX") -trap cleanup EXIT HUP INT TERM - -count=0 -srcs=$tmpdir/sources -list "$@" > "$srcs" - -if [ ! -s "$srcs" ]; then - printf '%s: no .c files provided\n' "${0##*/}" >&2 - exit 1 -fi - -printf '\n' -printf '#AUTOGENERATED\n' - -while IFS= read -r src; do - dep=$tmpdir/$count.d - obj=${src%.c}.o - "$cc" $cppflags $cflags -MMD -MF "$dep" -MT "$obj" -E -o /dev/null "$src" - #flatten the block with one target: dep line per prereq - awk ' - BEGIN { - rule = "" - } - { - line = $0 - sub(/\\$/, "", line) - rule = rule line " " - if ($0 !~ /\\$/) { - sub(/^[[:space:]]*/, "", rule) - split(rule, parts, ":") - target = parts[1] - deps = substr(rule, length(target) + 2) - n = split(deps, items, /[[:space:]]+/) - for (i = 1; i <= n; ++i) { - if (items[i] == "") - continue - print target ": " items[i] - } - rule = "" - } - } - ' "$dep" - count=$((count + 1)) -done < "$srcs" diff --git a/scripts/genbox.sh b/scripts/genbox.sh @@ -0,0 +1,186 @@ +#!/bin/sh +# genbox.sh - generate the aruu-box dispatch table +# +# does one thing: given a list of object file paths on argv, each one +# of BOX_OBJ's own outputs (".box/cmd/<category>/<tool>.o"), emit the C +# source for aruu-box's dispatch table and main() on stdout +# +set -e + +[ $# -gt 0 ] || { + printf "genbox: no object paths given\n" >&2 + exit 1 +} + +# derive category, tool basestem, and C symbol from one BOX_OBJ output +# path. the symbol transform (tr '.-' '__', append _main) must match +# BOX_OBJ's own objcopy step exactly, see the CATEGORY_OF/symbol +# comment in ninqu.rules for why this is a shell transform and not a +# map +path_category() { + rest=${1#.box/cmd/} + printf "%s\n" "${rest%%/*}" +} + +path_tool() { + rest=${1##*/} + printf "%s\n" "${rest%.o}" +} + +path_symbol() { + tool=$(path_tool "$1") + printf "%s\n" "$(echo "$tool" | tr '.-' '__')_main" +} + +cat << 'HEAD' +/* this file is autogenerated by genbox.sh. do not edit */ + +#include "wexec.h" +#include "util.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +HEAD + +# extern decls, in the order ninqu passed the objects in (BOX_OBJ's +# own glob order, one category at a time) +for obj in "$@"; do + sym=$(path_symbol "$obj") + echo "int ${sym}(int, char **);" +done + +cat << 'MID' + +struct Cmd { + const char *name; + int (*fn)(int, char **); + const char *category; +}; + +static struct Cmd cmds[] = { +MID + +categories=$( + for obj in "$@"; do + path_category "$obj" + done | sort -u +) + +for category in $categories; do + for obj in "$@"; do + [ "$(path_category "$obj")" = "$category" ] || continue + tool=$(path_tool "$obj") + sym=$(path_symbol "$obj") + printf '\t{ "%s", %s, "%s" },\n' "$tool" "$sym" "$category" + if [ "$tool" = "test" ]; then + printf '\t{ "[", %s, "%s" },\n' "$sym" "$category" + fi + if [ "$tool" = "xinstall" ]; then + printf '\t{ "install", %s, "%s" },\n' "$sym" "$category" + fi + done +done + +cat << 'TAIL' + { NULL, NULL, NULL } +}; + +static void +usage(void) +{ + struct Cmd *c; + const char *last; + int col; + + last = NULL; + col = 0; + fprintf(stderr, "usage: %s [-i path] [command [args...]]\n", argv0); + for (c = cmds; c->name; c++) { + if (!last || strcmp(c->category, last) != 0) { + if (last) + fprintf(stderr, "\n\n"); + last = c->category; + fprintf(stderr, "%s:\n", last); + col = 0; + } + if (col == 0) { + fprintf(stderr, "\t%s", c->name); + col = 8 + strlen(c->name); + } else if (col + 2 + strlen(c->name) >= 78) { + fprintf(stderr, ",\n\t%s", c->name); + col = 8 + strlen(c->name); + } else { + fprintf(stderr, ", %s", c->name); + col += 2 + strlen(c->name); + } + } + if (last) + fputc('\n', stderr); + exit(1); +} + +static void +x_install(const char *path) +{ + struct Cmd *c; + char buf[4096]; + int r; + + for (c = cmds; c->name; c++) { + r = snprintf(buf, sizeof buf, "%s/%s", path, c->name); + if (r < 0 || r >= (int)sizeof buf) + eprintf("install: '%s/%s': path too long\n", path, c->name); + remove(buf); + if (symlink("aruu-box", buf) < 0) + eprintf("install: symlink '%s':", buf); + } +} + +int +main(int argc, char *argv[]) +{ + struct Cmd *c; + char *s; + + argv0 = argv[0]; + + for (c = cmds; c->name; c++) + wexec_register(c->name, c->fn); + + s = strrchr(argv[0], '/'); + if (s) + s++; + else + s = argv[0]; + + if (strcmp(s, "aruu-box") == 0) { + if (argc < 2) + usage(); + argc--; + argv++; + if (strcmp(argv[0], "-i") == 0) { + if (argc < 2) + eprintf("usage: aruu-box -i path\n"); + x_install(argv[1]); + return 0; + } + s = strrchr(argv[0], '/'); + if (s) + s++; + else + s = argv[0]; + } + for (c = cmds; c->name; c++) { + if (strcmp(c->name, s) == 0) { + argv0 = (char *)c->name; + argv[0] = (char *)c->name; + return c->fn(argc, argv); + } + } + enprintf(127, "%s: not found\n", s); + return 1; +} +TAIL diff --git a/scripts/genconfig.sh b/scripts/genconfig.sh @@ -1,11 +1,36 @@ #!/bin/sh -# genconfig.sh - generate config.mk and config.kv from build.cfg - +# genconfig.sh generates build configuration from build.cfg +# +# outputs four files: +# +# scripts/mk/config.set ninqu reads this via (set-file). flat +# KEY=VAL, unquoted. per-tool BUILD_CATEGORY_TOOL +# toggles get a lowercase alias here, since +# (gate ...) in ninqu.rules only ever checks +# the lowercase form +# +# scripts/mk/config.kv shell-quoted KEY="VAL" format. sourced by +# read via the -config flag by scripts/mkman. +# nothing in the ninqu build itself sources +# this file: genbox.sh takes its input on argv +# only, see the BOX section of ninqu.rules +# +# shared/libutil/nofork_list.h +# wexec.c includes this at compile time. +# generated from NOFORK_LIST in build.cfg +# +# scripts/mk/features.h every resolved FEATURE_* as a #define +# CPPFLAGS pulls this in with -include +# +# the codegen subcommands (getconf, bc, awk, sh) are also here so +# ninqu.rules can call (exec sh scripts/genconfig.sh <step>) for +# each one. they check mtimes internally and only regenerate when +# their input changed +# set -e target=${1:-config} -# load build.cfg if [ -f build.cfg ]; then . ./build.cfg else @@ -13,196 +38,275 @@ else exit 1 fi -# helper to check if source is newer than target newer_than() { - [ -e "$2" ] || return 0 - local s t - s=$(stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0) - t=$(stat -c '%Y' "$2" 2>/dev/null || stat -f '%m' "$2" 2>/dev/null || echo 0) - [ "$s" -gt "$t" ] + [ -e "$2" ] || return 0 + local s t + s=$(stat -c '%Y' "$1" 2>/dev/null || stat -f '%m' "$1" 2>/dev/null || echo 0) + t=$(stat -c '%Y' "$2" 2>/dev/null || stat -f '%m' "$2" 2>/dev/null || echo 0) + [ "$s" -gt "$t" ] } gen_getconf() { - if newer_than scripts/getconf.sh cmd/posix/getconf.h; then - printf " GEN cmd/posix/getconf.h\n" - scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; } - fi + if newer_than scripts/getconf.sh cmd/posix/getconf.h; then + printf " GEN cmd/posix/getconf.h\n" + scripts/getconf.sh > cmd/posix/getconf.h || { rm -f cmd/posix/getconf.h; exit 1; } + fi } gen_bc() { - if newer_than cmd/posix/bc.y cmd/posix/bc.c; then - printf " GEN cmd/posix/bc.c\n" - CC=${CC:-cc} - YACC=${YACC:-} - if [ -z "$YACC" ]; then - if command -v yacc >/dev/null 2>&1; then - YACC="yacc" - elif command -v bison >/dev/null 2>&1; then - YACC="bison -y" - else - YACC="yacc" - fi - fi - if [ "$YACC" = "bison -y" ]; then - bison -o cmd/posix/bc.c cmd/posix/bc.y - else - $YACC -o cmd/posix/bc.c cmd/posix/bc.y - fi - fi + if newer_than cmd/posix/bc.y cmd/posix/bc.c; then + printf " GEN cmd/posix/bc.c\n" + CC=${CC:-cc} + YACC=${YACC:-} + if [ -z "$YACC" ]; then + if command -v yacc >/dev/null 2>&1; then + YACC="yacc" + elif command -v bison >/dev/null 2>&1; then + YACC="bison -y" + else + YACC="yacc" + fi + fi + if [ "$YACC" = "bison -y" ]; then + bison -o cmd/posix/bc.c cmd/posix/bc.y + else + $YACC -o cmd/posix/bc.c cmd/posix/bc.y + fi + fi } gen_awk() { - local dir="cmd/posix/awk" - CC=${CC:-cc} - YACC=${YACC:-} - if [ -z "$YACC" ]; then - if command -v yacc >/dev/null 2>&1; then - YACC="yacc" - elif command -v bison >/dev/null 2>&1; then - YACC="bison -y" - else - YACC="yacc" - fi - fi - - if newer_than "$dir/awkgram.y" "$dir/awkgram.tab.c" || newer_than "$dir/awkgram.y" "$dir/awkgram.tab.h"; then - printf " YACC $dir/awkgram.tab.c\n" - if [ "$YACC" = "bison -y" ]; then - bison -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" - else - $YACC -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" - if [ ! -f "$dir/awkgram.tab.h" ]; then - if [ -f y.tab.h ]; then - mv y.tab.h "$dir/awkgram.tab.h" - elif [ -f "$dir/y.tab.h" ]; then - mv "$dir/y.tab.h" "$dir/awkgram.tab.h" + local dir="cmd/posix/awk" + CC=${CC:-cc} + YACC=${YACC:-} + if [ -z "$YACC" ]; then + if command -v yacc >/dev/null 2>&1; then + YACC="yacc" + elif command -v bison >/dev/null 2>&1; then + YACC="bison -y" + else + YACC="yacc" + fi + fi + + if newer_than "$dir/awkgram.y" "$dir/awkgram.tab.c" || newer_than "$dir/awkgram.y" "$dir/awkgram.tab.h"; then + printf " YACC $dir/awkgram.tab.c\n" + if [ "$YACC" = "bison -y" ]; then + bison -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" + else + $YACC -d -o "$dir/awkgram.tab.c" "$dir/awkgram.y" + if [ ! -f "$dir/awkgram.tab.h" ]; then + if [ -f y.tab.h ]; then + mv y.tab.h "$dir/awkgram.tab.h" + elif [ -f "$dir/y.tab.h" ]; then + mv "$dir/y.tab.h" "$dir/awkgram.tab.h" + fi + fi + fi + fi + + if newer_than "$dir/maketab.c" "$dir/maketab" || newer_than "$dir/awkgram.tab.h" "$dir/maketab"; then + printf " CC $dir/maketab\n" + $CC -o "$dir/maketab" "$dir/maketab.c" + fi + + if newer_than "$dir/maketab" "$dir/proctab.c" || newer_than "$dir/awkgram.tab.h" "$dir/proctab.c"; then + printf " GEN $dir/proctab.c\n" + "$dir/maketab" "$dir/awkgram.tab.h" > "$dir/proctab.c" fi - fi - fi - fi - - if newer_than "$dir/maketab.c" "$dir/maketab" || newer_than "$dir/awkgram.tab.h" "$dir/maketab"; then - printf " CC $dir/maketab\n" - $CC -o "$dir/maketab" "$dir/maketab.c" - fi - - if newer_than "$dir/maketab" "$dir/proctab.c" || newer_than "$dir/awkgram.tab.h" "$dir/proctab.c"; then - printf " GEN $dir/proctab.c\n" - "$dir/maketab" "$dir/awkgram.tab.h" > "$dir/proctab.c" - fi } gen_sh() { - local dir="cmd/posix/sh" - CC=${CC:-cc} - - if newer_than "$dir/mknodes.c" "$dir/mknodes"; then - printf " CC $dir/mknodes\n" - $CC -o "$dir/mknodes" "$dir/mknodes.c" - fi - - if newer_than "$dir/mksyntax.c" "$dir/mksyntax"; then - printf " CC $dir/mksyntax\n" - $CC -Ishared -I"$dir" -o "$dir/mksyntax" "$dir/mksyntax.c" - fi - - if newer_than "$dir/mktokens" "$dir/token.h"; then - printf " GEN $dir/token.h\n" - (cd "$dir" && sh mktokens) - fi - - if newer_than "$dir/mksyntax" "$dir/syntax.c" || newer_than "$dir/mksyntax" "$dir/syntax.h"; then - printf " GEN $dir/syntax.c\n" - (cd "$dir" && ./mksyntax) - fi - - if newer_than "$dir/mknodes" "$dir/nodes.c" || newer_than "$dir/nodetypes" "$dir/nodes.c" || newer_than "$dir/nodes.c.pat" "$dir/nodes.c"; then - printf " GEN $dir/nodes.c\n" - (cd "$dir" && ./mknodes nodetypes nodes.c.pat) - fi - - if newer_than "$dir/mkbuiltins" "$dir/builtins.c" || newer_than "$dir/builtins.def" "$dir/builtins.c" || newer_than "$dir/shell.h" "$dir/builtins.c" || [ ! -f "$dir/builtins.c" ]; then - printf " GEN $dir/builtins.c\n" - (cd "$dir" && sh mkbuiltins .) - fi + local dir="cmd/posix/sh" + CC=${CC:-cc} + + if newer_than "$dir/mknodes.c" "$dir/mknodes"; then + printf " CC $dir/mknodes\n" + $CC -o "$dir/mknodes" "$dir/mknodes.c" + fi + + if newer_than "$dir/mksyntax.c" "$dir/mksyntax"; then + printf " CC $dir/mksyntax\n" + $CC -Ishared -I"$dir" -o "$dir/mksyntax" "$dir/mksyntax.c" + fi + + if newer_than "$dir/mktokens" "$dir/token.h"; then + printf " GEN $dir/token.h\n" + (cd "$dir" && sh mktokens) + fi + + if newer_than "$dir/mksyntax" "$dir/syntax.c" || newer_than "$dir/mksyntax" "$dir/syntax.h"; then + printf " GEN $dir/syntax.c\n" + (cd "$dir" && ./mksyntax) + fi + + if newer_than "$dir/mknodes" "$dir/nodes.c" || newer_than "$dir/nodetypes" "$dir/nodes.c" || newer_than "$dir/nodes.c.pat" "$dir/nodes.c"; then + printf " GEN $dir/nodes.c\n" + (cd "$dir" && ./mknodes nodetypes nodes.c.pat) + fi + + if newer_than "$dir/mkbuiltins" "$dir/builtins.c" || newer_than "$dir/builtins.def" "$dir/builtins.c" || newer_than "$dir/shell.h" "$dir/builtins.c" || [ ! -f "$dir/builtins.c" ]; then + printf " GEN $dir/builtins.c\n" + (cd "$dir" && sh mkbuiltins .) + fi } clean() { - printf " CLEAN generated files\n" - rm -f cmd/posix/getconf.h - rm -f cmd/posix/bc.c cmd/posix/bc.h - rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c cmd/posix/awk/maketab - rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax cmd/posix/sh/token.h 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 - rm -f scripts/mk/config.mk scripts/mk/config.kv scripts/mk/rules.mk shared/libutil/nofork_list.h + printf " CLEAN generated files\n" + rm -f cmd/posix/getconf.h + rm -f cmd/posix/bc.c cmd/posix/bc.h + rm -f cmd/posix/awk/awkgram.tab.c cmd/posix/awk/awkgram.tab.h cmd/posix/awk/proctab.c cmd/posix/awk/maketab + rm -f cmd/posix/sh/mknodes cmd/posix/sh/mksyntax cmd/posix/sh/token.h 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 + rm -f scripts/mk/config.set scripts/mk/config.kv scripts/mk/features.h shared/libutil/nofork_list.h } -# dynamic tool discovery function -list_tools() { - local catg="$1" dirs="" files="" d f b - [ -d "cmd/$catg" ] || return 0 - # find all subdirectories - for d in "cmd/$catg"/*; do - if [ -d "$d" ]; then - dirs="$dirs ${d##*/}" - fi - done - # find all .c and .y files - for f in "cmd/$catg"/*.c "cmd/$catg"/*.y; do - [ -f "$f" ] || continue - b=${f##*/} - b=${b%.c} - b=${b%.y} - case "$b" in - # exclude intermediate files or helper generators - maketab|mknodes|mksyntax|y.tab|*gram.tab) continue ;; - esac - files="$files $b" +# config: generate config.set, config.kv, nofork_list.h +# +# config.set is what ninqu reads. config.kv is what mkbox and +# genbox.sh source. both contain the same data in different formats: +# config.kv is shell-quoted (KEY="VAL"), config.set is unquoted +# (KEY=VAL) since ninqu's (set-file) takes the rest of the line +# verbatim + +config() { + mkdir -p scripts/mk + + kv_file="scripts/mk/config.kv" + set_file="scripts/mk/config.set" + + : > "${kv_file}" + : > "${set_file}" + + emit() { + local k="$1" v="$2" + echo "${k}=\"${v}\"" >> "${kv_file}" + echo "${k}=${v}" >> "${set_file}" + } + + emit VERSION "${VERSION}" + emit PREFIX "${PREFIX}" + emit MANPREFIX "${MANPREFIX:-/usr/local/share/man}" + emit RANLIB "${RANLIB:-ranlib}" + emit AR "${AR:-ar}" + emit ARFLAGS "${ARFLAGS:-rc}" + emit CC "${CC:-cc}" + emit CFLAGS "${CFLAGS:--std=c99 -Wall -Wextra -pedantic}" + emit LDFLAGS "${LDFLAGS:-} ${LDFLAGS_TLS:-}" + emit LDLIBS "${LDLIBS:-} ${LDLIBS_TLS:-}" + emit OBJCOPY "${OBJCOPY:-objcopy}" + emit LD "${LD:-ld}" + + emit CPPFLAGS_TLS "${CPPFLAGS_TLS:-}" + emit LDFLAGS_TLS "${LDFLAGS_TLS:-}" + emit LDLIBS_TLS "${LDLIBS_TLS:-}" + + # these seven are only consulted per-tool below (build_CATEGORY_TOOL, + # build_CATEGORY_$(BASESTEM)), the bare category toggle has no gate + # anywhere in ninqu.rules, (group CATEGORY ...) already does that + # job. config.kv still gets the uppercase copy since genbox.sh + # and mkbox source it directly + for g in BUILD_POSIX BUILD_XSI BUILD_NET BUILD_PSEUDO BUILD_EXTRA BUILD_LINUX BUILD_DEV; do + eval "val=\${$g:-0}" + echo "${g}=\"${val}\"" >> "${kv_file}" done - # output sorted unique list of tool names - # shellcheck disable=SC2086 - printf '%s %s\n' $dirs $files | tr ' ' '\n' | sort -u | grep -v '^$' -} + # per-tool toggles: scan cmd/<category>/ for tools. a tool is + # either a .c/.y file directly in the category dir (perfile) + # or a subdirectory (multi-file tool). emit BUILD_<CATEGORY>_<TOOL> + # plus lowercase alias for each + for category in posix xsi net pseudo extra linux dev; do + [ -d "cmd/$category" ] || continue + u_category=$(echo "$category" | tr '[:lower:]' '[:upper:]') + + tools="" + for d in "cmd/$category"/*; do + [ -d "$d" ] && tools="$tools ${d##*/}" + done + for f in "cmd/$category"/*.c "cmd/$category"/*.y; do + [ -f "$f" ] || continue + b=${f##*/} + b=${b%.c} + b=${b%.y} + case "$b" in + maketab|mknodes|mksyntax|y.tab|*gram.tab) continue ;; + esac + tools="$tools $b" + done -write_subtarget() { - group="$1" - tool="$2" - u_group=$(echo "$group" | tr '[:lower:]' '[:upper:]') - u_tool=$(echo "$tool" | tr 'a-z-' 'A-Z_') - var_name="BUILD_${u_group}_${u_tool}" + tools=$(echo "$tools" | tr ' ' '\n' | sort -u | grep -v '^$' || true) - eval "has_override=\${$var_name+yes}" - eval "val=\${$var_name:-}" + for b in $tools; do + u_tool=$(echo "$b" | tr 'a-z-' 'A-Z_') + var_name="BUILD_${u_category}_${u_tool}" - eval "group_val=\$BUILD_${u_group}" + #if [ "$category" = "dev" ] && [ "$u_tool" = "AS" ]; then + # var_name="BUILD_DEV_CC" + #fi - if [ "$has_override" = "yes" ]; then - echo "${var_name} = ${val}" >> "${mk_file}" - echo "${var_name}=\"${val}\"" >> "${kv_file}" - else - echo "${var_name} = \$(BUILD_${u_group})" >> "${mk_file}" - echo "${var_name}=\"${group_val}\"" >> "${kv_file}" - fi -} + eval "has_override=\${$var_name+yes}" + if [ "$has_override" = "yes" ]; then + eval "val=\${$var_name}" + else + eval "val=\$BUILD_${u_category}" + fi -gen_dir_rules() { - local dir="$1" flags="$2" extra_files="$3" f obj files uniq_files - [ -d "$dir" ] || return 0 - files="" - for f in "$dir"/*.c; do - if [ -f "$f" ]; then - files="$files $f" - fi + echo "${var_name}=\"${val}\"" >> "${kv_file}" + lk=$(echo "$var_name" | tr '[:upper:]' '[:lower:]') + echo "${lk}=${val}" >> "${set_file}" + done done - for f in ${extra_files}; do - files="$files $f" + + # box's own link line has no per-tool composition the way a + # standalone PERFILE binary's EXTRA_LIBS map does (box links + # every enabled tool's object into one binary in one shot), so + # a tool that needs a library nothing else in the box needs + # (yap needs terminfo) can only get it by ninqu.rules reading + # a value genconfig.sh already resolved, same as every other + # build_* toggle. this is still data, not policy: which + # library to add for which tool is decided here, not what to + # do with that decision + box_extra_libs="" + [ "${yap_val:-0}" != "0" ] && box_extra_libs="-ltinfo" + emit BOX_EXTRA_LIBS "${box_extra_libs}" + + features=$(set | grep '^FEATURE_[A-Za-z0-9_]*=' | cut -d= -f1 | sort) + for f in $features; do + eval "val=\$$f" + emit "$f" "$val" done - uniq_files=$(echo "$files" | tr ' ' '\n' | sort -u | grep -v '^$') - for f in $uniq_files; do - obj="${f%.c}.o" - echo "${obj}: ${f}" >> "${rules_file}" - echo " \$(CC) \$(CPPFLAGS) ${flags} \$(CFLAGS) -o \$@ -c ${f}" >> "${rules_file}" + + # every resolved FEATURE_* becomes a #define in one generated + # header. config.h's own #ifndef guards still apply to anything + # not here (there is nothing not here), and any file gets the + # real values just by being compiled with -include, whether or + # not it bothers to #include "config.h" itself. + features_h="scripts/mk/features.h" + { + echo "/* autogenerated by genconfig.sh, do not edit */" + for f in $features; do + eval "fval=\$$f" + echo "#define ${f} ${fval}" + done + } > "${features_h}" + + cppflags_common="-DPREFIX=\"${PREFIX}\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64 -include ${features_h} ${CPPFLAGS_TLS:-}" + cppflags_set="-Ishared ${cppflags_common}" + echo "CPPFLAGS=\"${cppflags_set}\"" >> "${kv_file}" + echo "CPPFLAGS=${cppflags_set}" >> "${set_file}" + + # shared/tls.h would conflict with the system's tls.h + # if we passed -Ishared to build libutil + echo "CPPFLAGS_LIBUTIL=\"${cppflags_common}\"" >> "${kv_file}" + echo "CPPFLAGS_LIBUTIL=${cppflags_common}" >> "${set_file}" + + nofork_h="shared/libutil/nofork_list.h" + echo "/* autogenerated by genconfig.sh */" > "${nofork_h}" + echo "static const char *nofork_list[] = {" >> "${nofork_h}" + for app in ${NOFORK_LIST}; do + echo " \"${app}\"," >> "${nofork_h}" done + echo " NULL" >> "${nofork_h}" + echo "};" >> "${nofork_h}" } case "$target" in @@ -210,181 +314,17 @@ case "$target" in bc) gen_bc ;; awk) gen_awk ;; sh) gen_sh ;; - clean) clean ;; all) gen_getconf gen_bc gen_awk gen_sh ;; - config) - mkdir -p scripts/mk - - mk_file="scripts/mk/config.mk" - kv_file="scripts/mk/config.kv" - - # clear existing files - : > "${mk_file}" - : > "${kv_file}" - - # write version prefix manprefix - echo "VERSION = ${VERSION}" >> "${mk_file}" - echo "VERSION=\"${VERSION}\"" >> "${kv_file}" - - echo "PREFIX = ${PREFIX}" >> "${mk_file}" - echo "PREFIX=\"${PREFIX}\"" >> "${kv_file}" - - # default manprefix to prefix/share/man if empty - man_pref="${MANPREFIX:-/usr/local/share/man}" - echo "MANPREFIX = ${man_pref}" >> "${mk_file}" - echo "MANPREFIX=\"${man_pref}\"" >> "${kv_file}" - - # toolchain defaults - echo "RANLIB = ${RANLIB:-ranlib}" >> "${mk_file}" - echo "RANLIB=\"${RANLIB:-ranlib}\"" >> "${kv_file}" - - echo "AR = ${AR:-ar}" >> "${mk_file}" - echo "AR=\"${AR:-ar}\"" >> "${kv_file}" - - echo "ARFLAGS = ${ARFLAGS:-rc}" >> "${mk_file}" - echo "ARFLAGS=\"${ARFLAGS:-rc}\"" >> "${kv_file}" - - # build toggles - echo "" >> "${mk_file}" - echo "# build toggles" >> "${mk_file}" - for g in BUILD_POSIX BUILD_XSI BUILD_NET BUILD_PSEUDO BUILD_EXTRA BUILD_LINUX BUILD_DEV; do - eval "val=\${$g:-0}" - echo "$g = $val" >> "${mk_file}" - echo "$g=\"$val\"" >> "${kv_file}" - done - - # write subtargets for each category dynamically - for catg in posix xsi net pseudo extra linux dev; do - echo "" >> "${mk_file}" - echo "# ${catg} subtargets" >> "${mk_file}" - tools=$(list_tools "$catg") - for t in $tools; do - write_subtarget "$catg" "$t" - done - - # build the enabled list using lowercase tools - enabled="" - for t in $tools; do - u_group=$(echo "$catg" | tr '[:lower:]' '[:upper:]') - u_tool=$(echo "$t" | tr 'a-z-' 'A-Z_') - - # special cases for dev tools mapping to different variables - if [ "$catg" = "dev" ] && [ "$u_tool" = "AS" ]; then - var_name="BUILD_DEV_CC" - else - var_name="BUILD_${u_group}_${u_tool}" - fi - - eval "has_override=\${$var_name+yes}" - eval "val=\${$var_name:-}" - if [ "$has_override" != "yes" ]; then - if [ "$catg" = "dev" ] && [ "$u_tool" = "AS" ]; then - eval "val=\$BUILD_DEV" - else - eval "val=\$BUILD_${u_group}" - fi - fi - - if [ "$val" = "1" ]; then - # map to the correct path - case "$catg/$t" in - posix/awk) path="cmd/posix/awk/awk" ;; - posix/sh) path="cmd/posix/sh/sh" ;; - posix/make) path="cmd/posix/make/make" ;; - extra/yap) path="cmd/extra/yap/yap" ;; - dev/ar) path="cmd/dev/ar/ar" ;; - dev/as) path="cmd/dev/as/as" ;; - dev/ld) path="cmd/dev/ld/ld" ;; - dev/cc) path="cmd/dev/cc/cc" ;; - *) path="cmd/$catg/$t" ;; - esac - enabled="$enabled $path" - fi - done - u_catg=$(echo "$catg" | tr '[:lower:]' '[:upper:]') - # write the list of enabled binaries - echo "${u_catg}_BIN_CONFIG =${enabled}" >> "${mk_file}" - done - - # write feature flags - echo "" >> "${mk_file}" - echo "# feature flags" >> "${mk_file}" - features=$(set | grep '^FEATURE_[A-Za-z0-9_]*=' | cut -d= -f1 | sort) - for f in $features; do - eval "val=\$$f" - echo "$f = $val" >> "${mk_file}" - echo "$f=\"$val\"" >> "${kv_file}" - done - - # write TLS variables to config files - echo "" >> "${mk_file}" - echo "CPPFLAGS_TLS = ${CPPFLAGS_TLS}" >> "${mk_file}" - echo "CPPFLAGS_TLS=\"${CPPFLAGS_TLS}\"" >> "${kv_file}" - - echo "LDFLAGS_TLS = ${LDFLAGS_TLS}" >> "${mk_file}" - echo "LDFLAGS_TLS=\"${LDFLAGS_TLS}\"" >> "${kv_file}" - - echo "LDLIBS_TLS = ${LDLIBS_TLS}" >> "${mk_file}" - echo "LDLIBS_TLS=\"${LDLIBS_TLS}\"" >> "${kv_file}" - - # write CPPFLAGS with all feature macros - echo "" >> "${mk_file}" - echo "CPPFLAGS =\\" >> "${mk_file}" - echo " -Ishared\\" >> "${mk_file}" - echo " -DPREFIX=\\\"\\\$(PREFIX)\\\"\\" >> "${mk_file}" - echo " -D_DEFAULT_SOURCE\\" >> "${mk_file}" - echo " -D_GNU_SOURCE\\" >> "${mk_file}" - echo " -D_NETBSD_SOURCE\\" >> "${mk_file}" - echo " -D_BSD_SOURCE\\" >> "${mk_file}" - echo " -D_XOPEN_SOURCE=700\\" >> "${mk_file}" - echo " -D_FILE_OFFSET_BITS=64\\" >> "${mk_file}" - for f in $features; do - if [ "$f" = "FEATURE_USE_SSL" ]; then - continue - fi - echo " -D$f=\$($f)\\" >> "${mk_file}" - done - echo " \$(CPPFLAGS_TLS)" >> "${mk_file}" - - # write toolchain configuration - echo "" >> "${mk_file}" - echo "CC = ${CC:-cc}" >> "${mk_file}" - echo "CFLAGS = ${CFLAGS:-}" >> "${mk_file}" - echo "LDFLAGS = ${LDFLAGS:-} \$(LDFLAGS_TLS)" >> "${mk_file}" - echo "LDLIBS = ${LDLIBS:-} \$(LDLIBS_TLS)" >> "${mk_file}" - - # write compilation rules for subdirectories that need special flags or nested structures - rules_file="scripts/mk/rules.mk" - echo "# autogenerated compilation rules" > "${rules_file}" - - echo "" >> "${rules_file}" - gen_dir_rules "cmd/posix/awk" "-Icmd/posix/awk" "cmd/posix/awk/awkgram.tab.c cmd/posix/awk/proctab.c" - gen_dir_rules "cmd/posix/sh" "-DSHELL -Icmd/posix/sh" "cmd/posix/sh/syntax.c cmd/posix/sh/nodes.c cmd/posix/sh/builtins.c" - gen_dir_rules "cmd/extra/yap" "" "" - gen_dir_rules "cmd/dev/ar" "-Icmd/dev/ar" "" - gen_dir_rules "cmd/dev/xcutil" "-Icmd/dev/xcutil" "" - gen_dir_rules "cmd/dev/ld" "-Icmd/dev/xcutil -Icmd/dev/ld" "" - gen_dir_rules "cmd/dev/as" "-Icmd/dev/xcutil -Icmd/dev/as" "" - gen_dir_rules "cmd/dev/as/arch/x64" "-Icmd/dev/xcutil -Icmd/dev/as -Icmd/dev/as/arch/x64" "" - gen_dir_rules "cmd/dev/cc" "-Icmd/dev/cc" "" - - # generate nofork_list.h - nofork_h="shared/libutil/nofork_list.h" - echo "/* autogenerated by genconfig.sh */" > "${nofork_h}" - echo "static const char *nofork_list[] = {" >> "${nofork_h}" - for app in ${NOFORK_LIST}; do - echo " \"${app}\"," >> "${nofork_h}" - done - echo " NULL" >> "${nofork_h}" - echo "};" >> "${nofork_h}" - ;; + config) config ;; + clean) clean ;; *) - printf "unknown target: %s\n" "$target" >&2 + printf "genconfig: unknown target: %s\n" "$target" >&2 + printf "usage: %s (config|getconf|bc|awk|sh|all|clean)\n" "$0" >&2 exit 1 ;; esac diff --git a/scripts/mkbox b/scripts/mkbox @@ -1,511 +0,0 @@ -#!/bin/sh -# mkbox - build aruu-box, the aruu multi-call binary -# -# expects CC CPPFLAGS CFLAGS LDFLAGS LDLIBS OBJCOPY YACC from the environment -# defaults match config.kv but can be overridden -# -# run from the source root (the Makefile does this automatically) - -set -e - -ROOT=$(CDPATH= cd "$(dirname "$0")/.." && pwd) - -# load key-value config if it exists -if [ -f "${ROOT}/scripts/mk/config.kv" ]; then - . "${ROOT}/scripts/mk/config.kv" -fi - -: "${CC:=cc}" -: "${CFLAGS:=-std=c99 -Wall -Wextra -pedantic}" -: "${LDFLAGS:=}" -: "${LDLIBS:=-lcrypt -lresolv}" -: "${OBJCOPY:=objcopy}" -: "${YACC:=yacc}" - -# build feature flag string from loaded config.kv variables -_feature_flags="" -for _f in $(set | grep '^FEATURE_[A-Za-z0-9_]*=' | cut -d= -f1 | sort); do - eval "_v=\$$_f" - _feature_flags="$_feature_flags -D${_f}=${_v}" -done -unset _f _v - -CPPFLAGS="-Ishared -DPREFIX=\\\"${PREFIX:-/usr/local}\\\" -D_DEFAULT_SOURCE -D_GNU_SOURCE -D_NETBSD_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64${_feature_flags} ${CPPFLAGS_TLS:-}" - -# -lm must be included if diff or awk is built -if [ "${BUILD_POSIX_DIFF:-0}" = "1" ] || [ "${BUILD_POSIX_AWK:-0}" = "1" ]; then - case "$LDLIBS" in - *-lm*) ;; - *) LDLIBS="${LDLIBS} -lm" ;; - esac -fi -# -ltinfo must be included if yap is built -if [ "${BUILD_EXTRA_YAP:-0}" = "1" ]; then - case "$LDLIBS" in - *-ltinfo*) ;; - *) LDLIBS="${LDLIBS} -ltinfo" ;; - esac -fi - -BDIR="${ROOT}/.box" -BOX="${ROOT}/aruu-box" -LIBREDLINE="${ROOT}/shared/libredline/libredline.a" -LIBUTIL="${ROOT}/shared/libutil/libutil.a" -LIBUTF="${ROOT}/shared/libutf/libutf.a" - -die() { - printf 'mkbox: %s\n' "$*" >&2 - exit 1 -} - -# Clean up build directory on exit or signal termination -trap 'rm -rf "${BDIR}"' EXIT INT QUIT TERM - -[ -f "${LIBREDLINE}" ] || die "libredline.a not found; run 'make' first" -[ -f "${LIBUTIL}" ] || die "libutil.a not found; run 'make' first" -[ -f "${LIBUTF}" ] || die "libutf.a not found; run 'make' first" - -[ -f "${ROOT}/cmd/posix/getconf.h" ] || { - printf 'mkbox: generating getconf.h\n' - "${ROOT}/scripts/getconf.sh" > "${ROOT}/cmd/posix/getconf.h" || - die "scripts/getconf.sh failed" -} - -rm -rf "${BDIR}" -mkdir -p "${BDIR}" - -OBJS="" -DECL_F="${BDIR}/decls.inc" -: > "${DECL_F}" -for _c in posix linux net pseudo xsi extra; do - : > "${BDIR}/entries_${_c}.inc" -done -unset _c - -alias_entry() { - printf '\t{ "%s", %s_main, "%s" },\n' "$1" "$2" "$3" \ - >> "${BDIR}/entries_${3}.inc" -} - -compile_tool() { - src="$1" - name="$2" - fn="$3" - catg="$4" - extra="${5:-}" - out="${BDIR}/${fn}.o" - symf="${BDIR}/${fn}.syms" - - printf 'mkbox: cc %s\n' "${name}" - eval "${CC} ${CPPFLAGS} ${extra} ${CFLAGS} -c \"\$src\" -o \"\$out\"" || - die "compile failed: ${src}" - printf 'main %s_main\n' "${fn}" > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${out}" || - die "objcopy failed: ${name}" - ${OBJCOPY} --keep-global-symbol="${fn}_main" "${out}" || - die "objcopy localize failed: ${name}" - rm -f "${symf}" - OBJS="${OBJS} ${out}" - printf 'int %s_main(int, char **);\n' "${fn}" >> "${DECL_F}" - printf '\t{ "%s", %s_main, "%s" },\n' "${name}" "${fn}" "${catg}" \ - >> "${BDIR}/entries_${catg}.inc" -} - -compile_make() { - mdir="${ROOT}/cmd/posix/make" - symf="${BDIR}/make.syms" - printf 'mkbox: cc make (multi)\n' - make_objs="" - for s in defaults parser posix rules; do - out="${BDIR}/make_${s}.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/\$s.c\" -o \"\$out\"" || - die "compile failed: make/${s}.c" - make_objs="${make_objs} ${out}" - done - out_main="${BDIR}/make_main.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -I\"\$mdir\" -c \"\$mdir/main.c\" -o \"\${out_main}\"" || - die "compile failed: make/main.c" - make_objs="${make_objs} ${out_main}" - - # Combined incremental link to resolve internal symbols cleanly - combined="${BDIR}/make_combined.o" - ${LD:-ld} -r -o "${combined}" ${make_objs} || - die "ld -r failed: make" - - printf 'main make_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: make" - ${OBJCOPY} --keep-global-symbol=make_main "${combined}" || - die "objcopy localize failed: make" - rm -f "${symf}" ${make_objs} - - OBJS="${OBJS} ${combined}" - printf 'int make_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "make", make_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" -} - - -compile_yap() { - ydir="${ROOT}/cmd/extra/yap" - symf="${BDIR}/yap.syms" - yap_objs="" - - [ -d "${ydir}" ] || return 0 - printf 'mkbox: cc yap (multi)\n' - for src in "${ydir}"/*.c; do - [ -f "${src}" ] || continue - s=${src##*/} - s=${s%.c} - out="${BDIR}/yap_${s}.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -c \"\$src\" -o \"\$out\"" || - die "compile failed: yap/${s}.c" - yap_objs="${yap_objs} ${out}" - done - - combined="${BDIR}/yap_combined.o" - ${LD:-ld} -r -o "${combined}" ${yap_objs} || - die "ld -r failed: yap" - - printf 'main yap_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: yap" - ${OBJCOPY} --keep-global-symbol=yap_main "${combined}" || - die "objcopy localize failed: yap" - rm -f "${symf}" ${yap_objs} - - OBJS="${OBJS} ${combined}" - printf 'int yap_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "yap", yap_main, "extra" },\n' >> "${BDIR}/entries_extra.inc" -} - -compile_bc() { - bdir="${ROOT}/cmd/posix" - symf="${BDIR}/bc.syms" - - printf 'mkbox: yacc bc/bc.y\n' - ${YACC} -o "${bdir}/bc.c" "${bdir}/bc.y" || - die "yacc failed: bc/bc.y" - - out="${BDIR}/bc.o" - eval "${CC} ${CPPFLAGS} ${CFLAGS} -c \"${bdir}/bc.c\" -o \"${out}\"" || - die "compile failed: bc/bc.c" - - printf 'main bc_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${out}" || - die "objcopy failed: bc" - ${OBJCOPY} --keep-global-symbol=bc_main "${out}" || - die "objcopy localize failed: bc" - rm -f "${symf}" "${bdir}/bc.c" - - OBJS="${OBJS} ${out}" - printf 'int bc_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "bc", bc_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" -} - -compile_awk() { - adir="${ROOT}/cmd/posix/awk" - symf="${BDIR}/awk.syms" - awk_objs="" - - printf 'mkbox: yacc awk/awkgram.y\n' - ${YACC} -d -o "${adir}/awkgram.tab.c" "${adir}/awkgram.y" || - die "yacc failed: awk/awkgram.y" - - # maketab is a host code-generator, only needs CFLAGS, no CPPFLAGS - printf 'mkbox: cc awk/maketab\n' - ${CC} ${CFLAGS} -o "${BDIR}/awk_maketab" "${adir}/maketab.c" || - die "compile failed: awk/maketab.c" - - printf 'mkbox: gen awk/proctab.c\n' - "${BDIR}/awk_maketab" "${adir}/awkgram.tab.h" > "${adir}/proctab.c" || - die "maketab failed" - - for s in b main parse proctab tran lib run lex math; do - out="${BDIR}/awk_${s}.o" - eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/${s}.c\" -o \"\$out\"" || - die "compile failed: awk/${s}.c" - awk_objs="${awk_objs} ${out}" - done - out="${BDIR}/awk_awkgram.tab.o" - eval "${CC} ${CPPFLAGS} -I\"\$adir\" ${CFLAGS} -c \"\$adir/awkgram.tab.c\" -o \"\$out\"" || - die "compile failed: awk/awkgram.tab.c" - awk_objs="${awk_objs} ${out}" - - combined="${BDIR}/awk_combined.o" - ${LD:-ld} -r -o "${combined}" ${awk_objs} || - die "ld -r failed: awk" - - printf 'main awk_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: awk" - ${OBJCOPY} --keep-global-symbol=awk_main "${combined}" || - die "objcopy localize failed: awk" - rm -f "${symf}" ${awk_objs} - - OBJS="${OBJS} ${combined}" - printf 'int awk_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "awk", awk_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" -} - -compile_sh() { - sdir="${ROOT}/cmd/posix/sh" - symf="${BDIR}/sh.syms" - sh_objs="" - - # mknodes and mksyntax are host code-generators, not part of the shell - printf 'mkbox: cc sh/mknodes\n' - ${CC} ${CFLAGS} -o "${BDIR}/sh_mknodes" "${sdir}/mknodes.c" || - die "compile failed: sh/mknodes.c" - - printf 'mkbox: cc sh/mksyntax\n' - ${CC} ${CPPFLAGS} -I"${sdir}" ${CFLAGS} -o "${BDIR}/sh_mksyntax" "${sdir}/mksyntax.c" || - die "compile failed: sh/mksyntax.c" - - printf 'mkbox: gen sh/nodes.{c,h}\n' - (cd "${sdir}" && "${BDIR}/sh_mknodes" nodetypes nodes.c.pat) || - die "mknodes failed" - - printf 'mkbox: gen sh/syntax.{c,h}\n' - (cd "${sdir}" && "${BDIR}/sh_mksyntax") || - die "mksyntax failed" - - printf 'mkbox: gen sh/builtins.{c,h}\n' - (cd "${sdir}" && sh mkbuiltins .) || - die "mkbuiltins failed" - - printf 'mkbox: gen sh/token.h\n' - (cd "${sdir}" && sh mktokens) || - die "mktokens failed" - - for s in alias arith_yacc arith_yylex cd easter echo error eval exec \ - expand lineedit input jobs kill mail main memalloc \ - miscbltin mystring options output parser printf redir \ - show test trap var builtins nodes syntax; do - out="${BDIR}/sh_${s}.o" - eval "${CC} ${CPPFLAGS} -DSHELL -I\"\$sdir\" ${CFLAGS} -c \"\$sdir/${s}.c\" -o \"\$out\"" || - die "compile failed: sh/${s}.c" - sh_objs="${sh_objs} ${out}" - done - - combined="${BDIR}/sh_combined.o" - ${LD:-ld} -r -o "${combined}" ${sh_objs} || - die "ld -r failed: sh" - - printf 'main sh_main\n' > "${symf}" - ${OBJCOPY} --redefine-syms="${symf}" "${combined}" || - die "objcopy failed: sh" - ${OBJCOPY} --keep-global-symbol=sh_main "${combined}" || - die "objcopy localize failed: sh" - rm -f "${symf}" ${sh_objs} - - OBJS="${OBJS} ${combined}" - printf 'int sh_main(int, char **);\n' >> "${DECL_F}" - printf '\t{ "sh", sh_main, "posix" },\n' >> "${BDIR}/entries_posix.inc" -} - -process_dir() { - dir="$1" - catg="$2" - extra="${3:-}" - for src in "${dir}"/*.c; do - [ -f "${src}" ] || continue - name=${src##*/} - name=${name%.c} - - # bc.c is generated by compile_bc() (see below); it lands in - # this same directory but must not be picked up here too, or - # bc_main ends up defined twice and the final link fails - [ "${catg}" = "posix" ] && [ "${name}" = "bc" ] && continue - - u_catg=$(printf '%s' "${catg}" | tr '[:lower:]' '[:upper:]') - u_name=$(printf '%s' "${name}" | tr '[:lower:].-' '[:upper:]__') - var_name="BUILD_${u_catg}_${u_name}" - eval "val=\${$var_name:-0}" - [ "$val" = "1" ] || continue - - fn=$(printf '%s' "${name}" | tr '.-' '__') - compile_tool "${src}" "${name}" "${fn}" "${catg}" "${extra}" - if [ "${name}" = "test" ]; then - alias_entry "[" "test" "${catg}" - fi - if [ "${name}" = "xinstall" ]; then - alias_entry "install" "xinstall" "${catg}" - fi - done -} - -process_dir "${ROOT}/cmd/posix" "posix" -[ "${BUILD_POSIX_AWK:-0}" = "1" ] && compile_awk -[ "${BUILD_POSIX_BC:-0}" = "1" ] && compile_bc -[ "${BUILD_POSIX_SH:-0}" = "1" ] && compile_sh -[ "${BUILD_POSIX_MAKE:-0}" = "1" ] && compile_make -process_dir "${ROOT}/cmd/linux" "linux" -process_dir "${ROOT}/cmd/net" "net" -process_dir "${ROOT}/cmd/pseudo" "pseudo" -process_dir "${ROOT}/cmd/xsi" "xsi" -process_dir "${ROOT}/cmd/extra" "extra" -[ "${BUILD_EXTRA_YAP:-0}" = "1" ] && compile_yap - -DISP="${BDIR}/aruu-box.c" -printf 'mkbox: generating dispatch\n' - -escaped_license=$(tr -d '\r' < "${ROOT}/LICENSE" | sed 's/\\/\\\\/g; s/"/\\"/g; s/^/\"/; s/$/\\n\"/') - -cat > "${DISP}" << DISPATCH_HEAD -/* this software is released into the public domain, or - registered under the isc license, see ./license for details - 2026 xplshn anto@xplshn.com.ar */ - -/* routes argv0 to the appropriate tool main */ -#include "wexec.h" -#include "util.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> - -static const char license[] = -${escaped_license} -; - -extern char *argv0; - -DISPATCH_HEAD - -cat "${DECL_F}" >> "${DISP}" - -cat >> "${DISP}" << 'DISPATCH_STRUCT' - -struct Cmd { - const char *name; - int (*fn)(int, char **); - const char *cat; -}; - -static struct Cmd cmds[] = { -DISPATCH_STRUCT - -# sort each category alphabetically by tool name at build time; -# entries have the form: \t{ "name", fn_main, "cat" }, -# splitting on " makes field 2 the tool name -for _c in posix linux net pseudo xsi extra; do - sort -t'"' -k2,2 "${BDIR}/entries_${_c}.inc" -done >> "${DISP}" -unset _c - -cat >> "${DISP}" << 'DISPATCH_TAIL' - { NULL, NULL, NULL } -}; - -static void -usage(void) -{ - struct Cmd *c; - const char *last; - int col; - - last = NULL; - col = 0; - fprintf(stderr, "usage: %s [-i path] [--license | -l] [command [args...]]\n", argv0); - for (c = cmds; c->name; c++) { - if (!last || strcmp(c->cat, last) != 0) { - if (last) - fprintf(stderr, "\n\n"); - last = c->cat; - fprintf(stderr, "%s:\n", last); - col = 0; - } - if (col == 0) { - fprintf(stderr, "\t%s", c->name); - col = 8 + strlen(c->name); - } else if (col + 2 + strlen(c->name) >= 78) { - fprintf(stderr, ",\n\t%s", c->name); - col = 8 + strlen(c->name); - } else { - fprintf(stderr, ", %s", c->name); - col += 2 + strlen(c->name); - } - } - if (last) - fputc('\n', stderr); - exit(1); -} - -static void -x_install(const char *path) -{ - struct Cmd *c; - char buf[4096]; - int r; - - for (c = cmds; c->name; c++) { - r = snprintf(buf, sizeof buf, "%s/%s", path, c->name); - if (r < 0 || r >= (int)sizeof buf) - eprintf("install: '%s/%s': path too long\n", path, c->name); - remove(buf); - if (symlink("aruu-box", buf) < 0) - eprintf("install: symlink '%s':", buf); - } -} - -int -main(int argc, char *argv[]) -{ - struct Cmd *c; - char *s; - - argv0 = argv[0]; - - for (c = cmds; c->name; c++) - wexec_register(c->name, c->fn); - - s = strrchr(argv[0], '/'); - if (s) - s++; - else - s = argv[0]; - - if (strcmp(s, "aruu-box") == 0) { - if (argc < 2) - usage(); - if (strcmp(argv[1], "--license") == 0 || strcmp(argv[1], "-l") == 0) { - printf("%s", license); - return 0; - } - argc--; - argv++; - if (strcmp(argv[0], "-i") == 0) { - if (argc < 2) - eprintf("usage: aruu-box -i path\n"); - x_install(argv[1]); - return 0; - } - s = strrchr(argv[0], '/'); - if (s) - s++; - else - s = argv[0]; - } - for (c = cmds; c->name; c++) { - if (strcmp(c->name, s) == 0) { - argv0 = (char *)c->name; - argv[0] = (char *)c->name; - return c->fn(argc, argv); - } - } - enprintf(127, "%s: not found\n", s); - return 1; -} -DISPATCH_TAIL - -printf 'mkbox: cc dispatch\n' -eval "${CC} ${CPPFLAGS} ${CFLAGS} -c \"\$DISP\" -o \"\${BDIR}/aruu-box.o\"" || - die "compile failed: dispatch" -OBJS="${OBJS} ${BDIR}/aruu-box.o" - -printf 'mkbox: ld aruu-box\n' -eval "${CC} ${LDFLAGS} -o \"\$BOX\" \$OBJS \"\$LIBREDLINE\" \"\$LIBUTIL\" \"\$LIBUTF\" \${LDLIBS}" || - die "link failed" - -printf 'mkbox: done => %s\n' "${BOX}" diff --git a/shared/libutil/tls.c b/shared/libutil/tls.c @@ -10,7 +10,7 @@ #include <string.h> #include <unistd.h> -#if FEATURE_USE_LIBRESSL +#if FEATURE_USE_LIBTLS #include <tls.h> struct TlsSocket { @@ -298,12 +298,12 @@ tls_connect(int fd, const char *host, int check_cert, int is_tls) if (!is_tls) return s; -#if !FEATURE_USE_LIBRESSL && !FEATURE_USE_BEARSSL && !FEATURE_USE_OPENSSL + + /* not every backend below uses these */ (void)host; (void)check_cert; -#endif -#if FEATURE_USE_LIBRESSL +#if FEATURE_USE_LIBTLS { struct tls_config *cfg; @@ -369,7 +369,7 @@ tls_connect(int fd, const char *host, int check_cert, int is_tls) } #else weprintf( - "TLS not supported, compile with FEATURE_USE_LIBRESSL or " + "TLS not supported, compile with FEATURE_USE_LIBTLS or " "FEATURE_USE_BEARSSL\n" ); free(s); @@ -390,7 +390,7 @@ tls_read(struct TlsSocket *s, void *buf, size_t len) return r; } } -#if FEATURE_USE_LIBRESSL +#if FEATURE_USE_LIBTLS for (;;) { ssize_t r = tls_read(s->ctx, buf, len); if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) @@ -415,7 +415,7 @@ tls_write(struct TlsSocket *s, const void *buf, size_t len) return r; } } -#if FEATURE_USE_LIBRESSL +#if FEATURE_USE_LIBTLS for (;;) { ssize_t r = tls_write(s->ctx, buf, len); if (r == TLS_WANT_POLLIN || r == TLS_WANT_POLLOUT) @@ -440,7 +440,7 @@ void tls_close(struct TlsSocket *s, int close_fd) { if (s->is_tls) { -#if FEATURE_USE_LIBRESSL +#if FEATURE_USE_LIBTLS tls_close(s->ctx); tls_free(s->ctx); #elif FEATURE_USE_BEARSSL diff --git a/shared/tls.h b/shared/tls.h @@ -6,12 +6,12 @@ struct TlsSocket; -/* tls_connect takes an already connected socket fd and upgrades it to tls +/* tlssock_connect takes an already connected socket fd and upgrades it to tls if check_cert is 0 certificate validation is bypassed returns a new tls socket or null on error */ struct TlsSocket *tls_connect(int fd, const char *host, int check_cert, int is_tls); -/* standard read and write wrapping either libressl bearssl or plain fallback */ +/* standard read and write wrapping either libtls, bearssl or plain fallback */ ssize_t tls_read(struct TlsSocket *s, void *buf, size_t len); ssize_t tls_write(struct TlsSocket *s, const void *buf, size_t len);