aruu

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

commit ea1ff22cec6490b8ca2eea56dc38999b73735735
parent d4eae9b32c04fcf4144427666730e37dfe718672
Author: xplshn <anto@xplshn.com.ar>
Date:   Wed,  4 Nov 2026 00:11:57 -0300

Cleanup

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

Diffstat:
MGNUmakefile | 25++++++++++++++-----------
MMakefile | 33++++++++++++++++++++++-----------
ATODO | 1+
Mbuild.cfg | 71+++++++++++++++++++++++++++++++++++++++++++++++------------------------
Acmd/dev/ar/ar.c | 608+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch.h | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch/x64/asm_code.c | 3012+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch/x64/backend.c | 36++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch/x64/inst.h | 679+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch/x64/parse_x64.c | 2018+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/arch/x64/reloc_x64.c | 263+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/as.c | 291++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/as_util.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/as_util.h | 15+++++++++++++++
Acmd/dev/as/asm_code.h | 28++++++++++++++++++++++++++++
Acmd/dev/as/emit_elf.c | 729+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/emit_macho.c | 561+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/format.h | 25+++++++++++++++++++++++++
Acmd/dev/as/ir_asm.c | 301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/ir_asm.h | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/parse_asm.c | 1566+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/as/parse_asm.h | 236+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/build.sh | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/LICENSE | 14++++++++++++++
Acmd/dev/cc/arg.h | 19+++++++++++++++++++
Acmd/dev/cc/attr.c | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/cc.h | 507+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/cc1.c | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/cpp.c | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/decl.c | 1503+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/driver.c | 661+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/eval.c | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/expr.c | 1827+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/include/float.h | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/include/stdalign.h | 15+++++++++++++++
Acmd/dev/cc/include/stdarg.h | 14++++++++++++++
Acmd/dev/cc/include/stdatomic.h | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/include/stdbool.h | 11+++++++++++
Acmd/dev/cc/include/stddef.h | 42++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/include/stdnoreturn.h | 7+++++++
Acmd/dev/cc/init.c | 324+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/map.c | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/ops.h | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/pp.c | 1290+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/qbe.c | 2306+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/scan.c | 530+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/scope.c | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/stmt.c | 328+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/targ.c | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/token.c | 191+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/tokens.h | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/tree.c | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/type.c | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/utf.c | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/utf.h | 3+++
Acmd/dev/cc/util.c | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/cc/util.h | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/configure | 339+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/arch.c | 27+++++++++++++++++++++++++++
Acmd/dev/ld/arch/aarch64/reloc_aarch64.c | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/arch/arm/reloc_arm.c | 42++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/arch/riscv64/reloc_riscv64.c | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/arch/x64/reloc_x64.c | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/arch/x86/reloc_x86.c | 37+++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/ld.c | 1301+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/ld.h | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acmd/dev/ld/ld_arch.h | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcmd/dev/ninqu/expand.c | 15++++++---------
Mcmd/dev/ninqu/ninja.c | 105++++++++++++++++++++++++++++---------------------------------------------------
Mcmd/extra/blkid.c | 5+++--
Mcmd/extra/dc.c | 24++++++++++--------------
Mcmd/extra/install.c | 2+-
Mcmd/extra/pgrep.c | 6+++---
Mcmd/extra/sync.c | 11++++++++---
Mcmd/extra/yap/in_all.h | 2++
Mcmd/extra/yap/main.c | 4+++-
Mcmd/linux/ctrlaltdel.c | 5+++++
Mcmd/linux/depmod.c | 2--
Mcmd/linux/hwclock.c | 5+++++
Mcmd/linux/insmod.c | 5+++++
Mcmd/linux/modprobe.c | 46+++++++++++++++++++---------------------------
Mcmd/linux/mount.c | 5+++++
Mcmd/linux/pivot_root.c | 5+++++
Mcmd/linux/readahead.c | 8++++++++
Mcmd/linux/rmmod.c | 9+++++++--
Mcmd/linux/switch_root.c | 11++++++++++-
Mcmd/linux/unshare.c | 4++++
Mcmd/net/host.c | 1+
Mcmd/net/httpd.c | 5+++++
Mcmd/net/ifconfig.c | 197+++++++++++++++++++------------------------------------------------------------
Mcmd/net/ip.c | 94+++++++++++++++++++++++++------------------------------------------------------
Mcmd/net/ping.c | 6++++++
Mcmd/net/sdhcp.c | 14++++++++++++--
Mcmd/net/wget.c | 8+++++++-
Mcmd/posix/awk/main.c | 5+++++
Mcmd/posix/awk/run.c | 33+++++++++++++--------------------
Mcmd/posix/bc.y | 89+++++++++++++++++++++++++++++++------------------------------------------------
Mcmd/posix/cal.c | 8++++----
Mcmd/posix/cat.c | 11++++++-----
Mcmd/posix/df.c | 54++++++++++++++++++++++++++++--------------------------
Mcmd/posix/diff.c | 13++++++-------
Mcmd/posix/ed.c | 2--
Mcmd/posix/env.c | 5+++++
Mcmd/posix/find.c | 9+++++++--
Mcmd/posix/grep.c | 71++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/posix/id.c | 5+++++
Mcmd/posix/ln.c | 24+++++++++++++-----------
Mcmd/posix/logger.c | 5+++++
Mcmd/posix/ls.c | 9++++++---
Mcmd/posix/nl.c | 1-
Mcmd/posix/od.c | 22+++-------------------
Mcmd/posix/patch.c | 5+++++
Mcmd/posix/pax.c | 21+++++++--------------
Mcmd/posix/readlink.c | 5+++++
Mcmd/posix/sed.c | 13+++++++++----
Mcmd/posix/sh/error.h | 3+++
Mcmd/posix/sh/expand.c | 10+++++++++-
Mcmd/posix/sh/input.c | 8++++++++
Mcmd/posix/sh/jobs.c | 8++++++++
Mcmd/posix/sh/miscbltin.c | 10+++++++++-
Mcmd/posix/sh/output.c | 8++++++++
Mcmd/posix/sh/parser.c | 8++++++++
Mcmd/posix/sh/sh_cdefs.h | 9+++++++++
Mcmd/posix/sh/test.c | 8++++++++
Mcmd/posix/sort.c | 6------
Mcmd/posix/tail.c | 6------
Mcmd/posix/test.c | 5+++++
Mcmd/posix/touch.c | 8++++++++
Mcmd/pseudo/chroot.c | 13+++++++++++++
Mcmd/pseudo/cron.c | 20++++++++++++++++++++
Mcmd/pseudo/dmesg.c | 5+----
Mcmd/pseudo/free.c | 3+--
Mcmd/pseudo/getty.c | 10++++++++++
Mcmd/pseudo/halt.c | 15+++++++++++++++
Mcmd/pseudo/hostname.c | 10++++++++++
Dcmd/pseudo/install.c | 214-------------------------------------------------------------------------------
Mcmd/pseudo/killall5.c | 1+
Mcmd/pseudo/seq.c | 1-
Mcmd/pseudo/sponge.c | 22+++++++++++++++++-----
Mcmd/pseudo/stat.c | 28+++++++++++-----------------
Mcmd/pseudo/tar.c | 21++++++++++++++++-----
Mcmd/pseudo/uptime.c | 4+---
Mcmd/pseudo/watch.c | 14++++++++------
Mcmd/xsi/login.c | 4++++
Mcmd/xsi/mknod.c | 6++++++
Mcmd/xsi/mkpasswd.c | 7+++++++
Mcmd/xsi/passwd.c | 7+++++++
Mcmd/xsi/su.c | 4++++
Mninqu.rules | 196+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Mscripts/genbox.sh | 32+++++++++++++++++++++-----------
Mscripts/genconfig.sh | 314++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Mscripts/mkman/main.go | 240++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mscripts/mkman/mdoc.go | 32++++++++++++++++++++++----------
Ascripts/mkman/mkman_test.go | 379+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/mkman/page.go | 23+++++++++++++++++++++++
Mscripts/mkman/parse.go | 474++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------
Mscripts/mkman/txt.go | 6+++---
Ashared/filesystem.h | 22++++++++++++++++++++++
Mshared/libredline/redline.c | 7+++++++
Mshared/libtcutil/tcutil.h | 2+-
Mshared/libutil/cp.c | 5+++++
Ashared/libutil/filesystem_linux.c | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libutil/filesystem_other.c | 31+++++++++++++++++++++++++++++++
Mshared/libutil/mode.c | 5+++++
Mshared/libutil/net.c | 588+++----------------------------------------------------------------------------
Ashared/libutil/net_linux.c | 663+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libutil/net_other.c | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/libutil/passwd.c | 38++++++++++++++++++++++++++++++--------
Mshared/libutil/sysinfo.c | 145++++---------------------------------------------------------------------------
Ashared/libutil/sysinfo_linux.c | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ashared/libutil/sysinfo_other.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Mshared/libutil/tls.c | 444+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mshared/libutil/wexec.c | 42++++++++++++++++++++++++++++++++++++++++++
Ashared/net.h | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mshared/paths.h | 6++++++
Ashared/sysinfo.h | 24++++++++++++++++++++++++
Mshared/tls.h | 9+++++++++
Mshared/util.h | 65++---------------------------------------------------------------
Mshared/wexec.h | 1+
179 files changed, 28514 insertions(+), 2160 deletions(-)

diff --git a/GNUmakefile b/GNUmakefile @@ -3,7 +3,7 @@ CFLAGS ?= -std=c99 -Wall -Wextra -pedantic BACKEND ?= auto -CPPFLAGS ?= -Ishared -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L \ +CPPFLAGS ?= -Ishared -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 @@ -40,10 +40,9 @@ NINQU_SRC =\ 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) +# rebuild the config first so a build.cfg edit lands before ninqu +# compiles. ninqu does this lazily too, this saves a shell startup +$(NINQU): $(NINQU_SRC) cmd/dev/ninqu/ninqu.h scripts/mk/config.set scripts/mk/features.h shared/libutil/nofork_list.h $(NINQU_LIB_SRC) $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(NINQU_SRC) $(NINQU_LIB_SRC) # FORCE has no rule, thus making any pattern @@ -62,13 +61,17 @@ clean: $(NINQU) rm -f $(NINQU) build.ninja scripts/mk/config.set: build.cfg scripts/genconfig.sh - sh scripts/genconfig.sh config + sh scripts/genconfig.sh config-set -# stops the % pattern rule above from trying to rebuild these as if -# they were stale build targets: GNU make's own implicit "remake my -# makefiles" check runs the pattern rule against this file's own -# name too, otherwise (and, since a POSIX Makefile can sit right next -# to this one, against that name as well) +scripts/mk/features.h: build.cfg scripts/genconfig.sh + sh scripts/genconfig.sh features-h + +shared/libutil/nofork_list.h: build.cfg scripts/genconfig.sh + sh scripts/genconfig.sh nofork-list-h + +# keep the % pattern rule from rebuilding these as stale targets. make +# remakes its own makefiles by running the rule on this file name, and +# on Makefile when one sits next to it GNUmakefile: ; Makefile: ; ninqu.rules: ; diff --git a/Makefile b/Makefile @@ -1,9 +1,15 @@ CC = cc -static CFLAGS = -std=c99 -Wall -Wextra -pedantic +# ninqu has to exist before any ninqu.rules build (box, dev, ...) can +# start, so it compiles with BOOTSTRAP_CC. plain $(CC) could resolve to +# an installed aruu cc that cant yet build the tool it is needed for. +# defaults to $(CC), override it alone to pick a bootstrap compiler +BOOTSTRAP_CC ?= $(CC) + BACKEND ?= auto -CPPFLAGS ?= -Ishared -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L \ +CPPFLAGS ?= -Ishared -D_POSIX_C_SOURCE=200809L \ -DFEATURE_NOFORK=0 -DFEATURE_NOEXEC=0 NINQU_LIB_SRC =\ @@ -35,24 +41,29 @@ NINQU_SRC =\ cmd/dev/ninqu/ninja.c NINQU ?= cmd/dev/ninqu/ninqu -# no $(filter -j%,$(MAKEFLAGS)) equivalent here (GNUmakefile's own -# trick): pass ninqu's own parallelism directly, "make JOBS=-j8 box" +# no $(filter -j%,$(MAKEFLAGS)) trick here, pass the parallelism +# directly: make JOBS=-j8 box JOBS ?= -# every real goal ninqu.rules exposes, listed once instead of -# GNUmakefile's own "%: FORCE" catch-all. a new top-level group needs -# a matching name added here too +# every goal ninqu.rules exposes, since there is no %: FORCE catch-all +# here. a new top-level group needs a name added too .PHONY: all default clean box dev man install install-base uninstall \ - remove fmt fmt-all lib posix linux net xsi pseudo extra codegen + remove fmt fmt-all lib posix linux net xsi pseudo extra codegen test -$(NINQU): $(NINQU_SRC) cmd/dev/ninqu/ninqu.h scripts/mk/config.set $(NINQU_LIB_SRC) - $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(NINQU_SRC) $(NINQU_LIB_SRC) +$(NINQU): $(NINQU_SRC) cmd/dev/ninqu/ninqu.h scripts/mk/config.set scripts/mk/features.h shared/libutil/nofork_list.h $(NINQU_LIB_SRC) + $(BOOTSTRAP_CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(NINQU_SRC) $(NINQU_LIB_SRC) scripts/mk/config.set: build.cfg scripts/genconfig.sh - sh scripts/genconfig.sh config + sh scripts/genconfig.sh config-set + +scripts/mk/features.h: build.cfg scripts/genconfig.sh + sh scripts/genconfig.sh features-h + +shared/libutil/nofork_list.h: build.cfg scripts/genconfig.sh + sh scripts/genconfig.sh nofork-list-h all default box dev man install install-base uninstall remove \ -fmt fmt-all lib posix linux net xsi pseudo extra codegen: $(NINQU) + fmt fmt-all lib posix linux net xsi pseudo extra codegen test: $(NINQU) $(NINQU) $(JOBS) $@ clean: $(NINQU) diff --git a/TODO b/TODO @@ -0,0 +1 @@ +mkfs.vfat, mkfs.ext4, fsck diff --git a/build.cfg b/build.cfg @@ -6,15 +6,15 @@ PRESET_UTILS="posix xsi net pseudo extra linux dev" # installation paths VERSION=2026-08-09T03-56-UTC-03 -PREFIX=/usr/local -MANPREFIX=/usr/local/share/man +PREFIX= +MANPREFIX=/share/man # toolchain -CC=cc +CC=${CC:-cc} CFLAGS="-std=c99 -Wall -Wextra -pedantic" -LDFLAGS="" +LDFLAGS=${LDFLAGS:-} LDLIBS="" -AR=ar +AR=${AR:-ar} ARFLAGS="rc" RANLIB=ranlib @@ -77,8 +77,8 @@ common) FEATURE_SORT_BIG=0; FEATURE_SORT_STABLE=1 FEATURE_OD_ENDIAN=0; FEATURE_SH_EASTER=1; FEATURE_SH_HISTEDIT=0; - FEATURE_SH_LOCAL=1 FEATURE_SH_LET=1; - FEATURE_SH_ULIMIT=1 FEATURE_SH_SETVAR=0; + FEATURE_SH_LOCAL=1; FEATURE_SH_LET=1; + FEATURE_SH_ULIMIT=1; FEATURE_SH_SETVAR=0; FEATURE_CAL_EXT=1 FEATURE_LS_COLOR=1 FEATURE_DIFF3_MERGE=0; FEATURE_DIFF3_EDSCRIPT=1 @@ -117,9 +117,9 @@ all) FEATURE_SORT_BIG=1; FEATURE_SORT_STABLE=1 FEATURE_OD_ENDIAN=1; FEATURE_SH_EASTER=1; FEATURE_SH_HISTEDIT=1 - FEATURE_SH_LOCAL=1 FEATURE_NOEXEC=0; + FEATURE_SH_LOCAL=1; FEATURE_NOEXEC=0; FEATURE_NOFORK=0; FEATURE_SH_LET=1; - FEATURE_SH_ULIMIT=1 FEATURE_SH_SETVAR=1; + FEATURE_SH_ULIMIT=1; FEATURE_SH_SETVAR=1; FEATURE_SH_WORDEXP=1 FEATURE_CAL_EXT=1 FEATURE_LS_COLOR=1 @@ -174,6 +174,36 @@ unset _p # BUILD_DEV_AS=1 # enable a tool whose group isnt in PRESET_UTILS FEATURE_SH_HISTEDIT=1 +# non-POSIX library interfaces used by the default command set +FEATURE_DIFF_EXT=1 +FEATURE_PATCH_EXT=1 +FEATURE_PAX_EXT=1 +FEATURE_YAP_EXT=1 +FEATURE_CASEFOLD=1 +FEATURE_MKNOD=1 +FEATURE_FILE_MODE_EXT=1 +FEATURE_NET_IOCTL=1 +FEATURE_PASSWD_EXT=1 +FEATURE_SYSINFO_EXT=1 +FEATURE_BC_ASCII=1 +FEATURE_AWK_RANDOM=1 +FEATURE_SH_LONGJMP=1 +FEATURE_SH_EXT=1 +FEATURE_ENV_PUTENV=1 +FEATURE_ID_GROUPLIST=1 +FEATURE_LOGGER_SYSLOG=1 +FEATURE_CRON_DAEMON=1 +FEATURE_GTTY_VHANGUP=1 +FEATURE_HOSTNAME_SET=1 +FEATURE_SED_ASCII=1 +FEATURE_TOUCH_EXT=1 +FEATURE_LINUX_SYSCALL=1 +FEATURE_LINUX_TIME=1 +FEATURE_LINUX_MOUNT=1 +FEATURE_LINUX_READAHEAD=1 +FEATURE_SWITCH_ROOT_EXT=1 +FEATURE_CHROOT=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 @@ -206,33 +236,32 @@ FEATURE_SH_HISTEDIT=1 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 +if [ "${BUILD_EXTRA_YAP+x}" != x ]; then + BUILD_EXTRA_YAP=0 + if pkg-config --exists tinfo 2>/dev/null; then + BUILD_EXTRA_YAP=1 + fi fi # tls backend: set exactly one to 1 to enable tls # -FEATURE_USE_BEARSSL=0 +FEATURE_USE_BEARSSL=${FEATURE_USE_BEARSSL:-0} FEATURE_USE_LIBTLS=0 -FEATURE_USE_OPENSSL=0 FEATURE_USE_SSL=1 # if [ "$FEATURE_USE_SSL" = 1 ] && - [ "$FEATURE_USE_BEARSSL$FEATURE_USE_LIBTLS$FEATURE_USE_OPENSSL" = "000" ] + [ "$FEATURE_USE_BEARSSL$FEATURE_USE_LIBTLS" = "00" ] 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="" +CPPFLAGS_TLS=${CPPFLAGS_TLS:-} LDFLAGS_TLS="" LDLIBS_TLS=${LDLIBS_TLS:-} PKG_NAME="" if [ "$FEATURE_USE_BEARSSL" = 1 ]; then if pkg-config --exists libbearssl 2>/dev/null; then PKG_NAME="libbearssl" @@ -245,12 +274,6 @@ elif [ "$FEATURE_USE_LIBTLS" = 1 ]; then else LDLIBS_TLS="-ltls" fi -elif [ "$FEATURE_USE_OPENSSL" = 1 ]; then - if pkg-config --exists openssl 2>/dev/null; then - PKG_NAME="openssl" - else - LDLIBS_TLS="-lssl -lcrypto" - fi fi if [ -n "$PKG_NAME" ]; then CPPFLAGS_TLS="$(pkg-config --cflags "$PKG_NAME")" diff --git a/cmd/dev/ar/ar.c b/cmd/dev/ar/ar.c @@ -0,0 +1,608 @@ +/* see LICENSE file for copyright and license details */ +#include "util.h" + +#include <ctype.h> +#include <elf.h> +#include <errno.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define ARMAG "!<arch>\n" +#define SARMAG 8 +#define ARFMAG "`\n" + +struct ArHdr { + char ar_name[16]; + char ar_date[12]; + char ar_uid[6]; + char ar_gid[6]; + char ar_mode[8]; + char ar_size[10]; + char ar_fmag[2]; +}; + +struct Member { + char *path; + char *name; + unsigned char *data; + size_t size; + size_t long_name_offset; + int use_long_name; + uint32_t offset; +}; + +struct ArchiveSym { + int member_index; + char *name; +}; + +static const char * +base_name(const char *path) +{ + const char *name; + + name = path + strlen(path); + while (name > path && name[-1] != '/' && name[-1] != '\\') + --name; + return name; +} + +static unsigned char * +read_file(const char *path, size_t *size) +{ + FILE *fp; + long len; + unsigned char *data; + + fp = fopen(path, "rb"); + if (!fp) + eprintf("fopen %s:", path); + if (fseek(fp, 0, SEEK_END) != 0) + eprintf("fseek %s:", path); + len = ftell(fp); + if (len < 0) + eprintf("ftell %s:", path); + if (fseek(fp, 0, SEEK_SET) != 0) + eprintf("fseek %s:", path); + + data = emalloc((size_t)len); + if (len && fread(data, 1, (size_t)len, fp) != (size_t)len) + eprintf("fread %s:", path); + fclose(fp); + *size = (size_t)len; + return data; +} + +static void +write_all(FILE *fp, const void *data, size_t size, const char *path) +{ + if (size && fwrite(data, 1, size, fp) != size) + eprintf("fwrite %s:", path); +} + +static void +put_field(char *dst, size_t dst_size, const char *str) +{ + size_t len; + + len = strlen(str); + if (len > dst_size) + eprintf("archive header field is too large\n"); + memset(dst, ' ', dst_size); + memcpy(dst, str, len); +} + +static void +put_decimal_field(char *dst, size_t dst_size, unsigned long long value) +{ + char buf[32]; + int len; + + len = snprintf(buf, sizeof(buf), "%llu", value); + if (len < 0 || (size_t)len > dst_size) + eprintf("archive header number is too large\n"); + memset(dst, ' ', dst_size); + memcpy(dst, buf, (size_t)len); +} + +static void +write_ar_header(FILE *fp, const char *archive, const char *name, size_t size) +{ + struct ArHdr hdr; + + put_field(hdr.ar_name, sizeof(hdr.ar_name), name); + put_decimal_field(hdr.ar_date, sizeof(hdr.ar_date), 0); + put_decimal_field(hdr.ar_uid, sizeof(hdr.ar_uid), 0); + put_decimal_field(hdr.ar_gid, sizeof(hdr.ar_gid), 0); + put_field(hdr.ar_mode, sizeof(hdr.ar_mode), "100644"); + put_decimal_field(hdr.ar_size, sizeof(hdr.ar_size), (unsigned long long)size); + memcpy(hdr.ar_fmag, ARFMAG, sizeof(hdr.ar_fmag)); + write_all(fp, &hdr, sizeof(hdr), archive); +} + +static void +write_be32(FILE *fp, const char *archive, uint32_t value) +{ + unsigned char buf[4]; + + buf[0] = (unsigned char)(value >> 24); + buf[1] = (unsigned char)(value >> 16); + buf[2] = (unsigned char)(value >> 8); + buf[3] = (unsigned char)value; + write_all(fp, buf, sizeof(buf), archive); +} + +static int +range_ok(uint64_t off, uint64_t len, size_t total) +{ + if (off > (uint64_t)SIZE_MAX || len > (uint64_t)SIZE_MAX) + return 0; + return (size_t)off <= total && (size_t)len <= total - (size_t)off; +} + +static int +is_exported_symbol(const Elf64_Sym *sym) +{ + unsigned bind; + unsigned type; + + bind = ELF64_ST_BIND(sym->st_info); + type = ELF64_ST_TYPE(sym->st_info); + if (sym->st_shndx == SHN_UNDEF) + return 0; + if (bind != STB_GLOBAL && bind != STB_WEAK) + return 0; + if (type == STT_SECTION || type == STT_FILE) + return 0; + return 1; +} + +static void +append_archive_sym( + struct ArchiveSym **symbols, + int *nb_symbols, + int *cap_symbols, + int member_index, + const char *name, + size_t *name_bytes +) +{ + struct ArchiveSym *sym; + + if (*nb_symbols == *cap_symbols) { + *cap_symbols = *cap_symbols ? *cap_symbols * 2 : 64; + *symbols = erealloc(*symbols, (size_t)*cap_symbols * sizeof(**symbols)); + } + sym = &(*symbols)[(*nb_symbols)++]; + sym->member_index = member_index; + sym->name = estrdup(name); + *name_bytes += strlen(name) + 1; +} + +static void +collect_symbols( + const struct Member *member, + int member_index, + struct ArchiveSym **symbols, + int *nb_symbols, + int *cap_symbols, + size_t *name_bytes +) +{ + const Elf64_Ehdr *ehdr; + const Elf64_Shdr *sections; + int i; + + if (member->size < sizeof(*ehdr) || memcmp(member->data, ELFMAG, SELFMAG) != 0) + eprintf("archive input is not an ELF object\n"); + + ehdr = (const Elf64_Ehdr *)member->data; + if (ehdr->e_ident[EI_CLASS] != ELFCLASS64) + eprintf("archive input is not an ELF64 object\n"); + if (ehdr->e_type != ET_REL) + eprintf("archive input is not a relocatable ELF object\n"); + if (ehdr->e_shentsize != sizeof(Elf64_Shdr)) + eprintf("unsupported ELF section header size\n"); + if (!range_ok(ehdr->e_shoff, (uint64_t)ehdr->e_shnum * ehdr->e_shentsize, member->size)) + eprintf("invalid ELF section table\n"); + + sections = (const Elf64_Shdr *)(member->data + ehdr->e_shoff); + for (i = 0; i < ehdr->e_shnum; ++i) { + const Elf64_Shdr *symsec = &sections[i]; + const Elf64_Shdr *strsec; + const unsigned char *symtab; + const char *strtab; + size_t strtab_size, nsym, j; + + if (symsec->sh_type != SHT_SYMTAB) + continue; + if (symsec->sh_entsize && symsec->sh_entsize != sizeof(Elf64_Sym)) + eprintf("unsupported ELF symbol size\n"); + if (symsec->sh_link >= ehdr->e_shnum) + eprintf("invalid ELF symbol string table\n"); + if (!range_ok(symsec->sh_offset, symsec->sh_size, member->size)) + eprintf("invalid ELF symbol table\n"); + + strsec = &sections[symsec->sh_link]; + if (!range_ok(strsec->sh_offset, strsec->sh_size, member->size)) + eprintf("invalid ELF string table\n"); + symtab = member->data + symsec->sh_offset; + strtab = (const char *)member->data + strsec->sh_offset; + strtab_size = (size_t)strsec->sh_size; + nsym = (size_t)(symsec->sh_size / sizeof(Elf64_Sym)); + + for (j = 1; j < nsym; ++j) { + const Elf64_Sym *sym = (const Elf64_Sym *)(symtab + j * sizeof(Elf64_Sym)); + const char *name; + + if (!is_exported_symbol(sym)) + continue; + if (sym->st_name >= strtab_size) + eprintf("invalid ELF symbol name\n"); + name = strtab + sym->st_name; + if (!*name) + continue; + append_archive_sym(symbols, nb_symbols, cap_symbols, member_index, name, name_bytes); + } + } +} + +static void +append_member(struct Member **members, int *nb_members, int *cap_members, const char *path) +{ + struct Member *member; + const char *name; + size_t name_len; + + name = base_name(path); + name_len = strlen(name); + if (!name_len) + eprintf("empty archive member name\n"); + if (*nb_members == *cap_members) { + *cap_members = *cap_members ? *cap_members * 2 : 16; + *members = erealloc(*members, (size_t)*cap_members * sizeof(**members)); + } + member = &(*members)[(*nb_members)++]; + member->path = estrdup(path); + member->name = estrdup(name); + member->data = read_file(path, &member->size); + member->long_name_offset = 0; + member->use_long_name = name_len > 15; + member->offset = 0; +} + +static char * +member_header_name(const struct Member *member) +{ + size_t len; + char *ar_name; + char buf[32]; + int n; + + len = strlen(member->name); + if (member->use_long_name) { + n = snprintf(buf, sizeof(buf), "/%zu", member->long_name_offset); + if (n < 0 || (size_t)n >= sizeof(buf) || n > 16) + eprintf("long archive member offset is too large\n"); + return estrdup(buf); + } + if (len > 15) + eprintf("archive member name is too long for ar\n"); + ar_name = emalloc(len + 2); + memcpy(ar_name, member->name, len); + ar_name[len] = '/'; + ar_name[len + 1] = '\0'; + return ar_name; +} + +static int +create_archive(const char *archive, int argc, char **argv, int verbose) +{ + struct Member *members = NULL; + struct ArchiveSym *symbols = NULL; + int nb_members = 0, cap_members = 0; + int nb_symbols = 0, cap_symbols = 0; + size_t symbol_name_bytes = 0; + size_t long_name_bytes = 0; + size_t symbol_table_size, offset; + FILE *fp; + int i; + + for (i = 0; i < argc; ++i) { + append_member(&members, &nb_members, &cap_members, argv[i]); + collect_symbols( + &members[nb_members - 1], + nb_members - 1, + &symbols, + &nb_symbols, + &cap_symbols, + &symbol_name_bytes + ); + if (verbose) + printf("a - %s\n", argv[i]); + } + + for (i = 0; i < nb_members; ++i) { + if (members[i].use_long_name) { + members[i].long_name_offset = long_name_bytes; + long_name_bytes += strlen(members[i].name) + 2; + } + } + + symbol_table_size = 4 + (size_t)nb_symbols * 4 + symbol_name_bytes; + offset = SARMAG + sizeof(struct ArHdr) + symbol_table_size + (symbol_table_size & 1); + if (long_name_bytes) + offset += sizeof(struct ArHdr) + long_name_bytes + (long_name_bytes & 1); + for (i = 0; i < nb_members; ++i) { + if (offset > UINT32_MAX) + eprintf( + "archive is too large for a 32-bit symbol " + "index\n" + ); + members[i].offset = (uint32_t)offset; + offset += sizeof(struct ArHdr) + members[i].size + (members[i].size & 1); + } + + fp = fopen(archive, "wb"); + if (!fp) + eprintf("fopen %s:", archive); + write_all(fp, ARMAG, SARMAG, archive); + write_ar_header(fp, archive, "/", symbol_table_size); + write_be32(fp, archive, (uint32_t)nb_symbols); + for (i = 0; i < nb_symbols; ++i) + write_be32(fp, archive, members[symbols[i].member_index].offset); + for (i = 0; i < nb_symbols; ++i) + write_all(fp, symbols[i].name, strlen(symbols[i].name) + 1, archive); + if (symbol_table_size & 1) + write_all(fp, "\n", 1, archive); + if (long_name_bytes) { + write_ar_header(fp, archive, "// ", long_name_bytes); + for (i = 0; i < nb_members; ++i) { + if (members[i].use_long_name) { + write_all(fp, members[i].name, strlen(members[i].name), archive); + write_all(fp, "/\n", 2, archive); + } + } + if (long_name_bytes & 1) + write_all(fp, "\n", 1, archive); + } + + for (i = 0; i < nb_members; ++i) { + char *ar_name = member_header_name(&members[i]); + write_ar_header(fp, archive, ar_name, members[i].size); + write_all(fp, members[i].data, members[i].size, archive); + if (members[i].size & 1) + write_all(fp, "\n", 1, archive); + free(ar_name); + } + if (fclose(fp) != 0) + eprintf("fclose %s:", archive); + + for (i = 0; i < nb_symbols; ++i) + free(symbols[i].name); + for (i = 0; i < nb_members; ++i) { + free(members[i].path); + free(members[i].name); + free(members[i].data); + } + free(symbols); + free(members); + return 0; +} + +static unsigned long long +parse_decimal_field(const char *field, size_t size) +{ + char buf[32]; + char *end; + size_t len; + + len = size; + if (len >= sizeof(buf)) + eprintf("archive header field is too large\n"); + memcpy(buf, field, len); + buf[len] = '\0'; + errno = 0; + while (len && buf[len - 1] == ' ') + buf[--len] = '\0'; + end = buf; + while (*end == ' ') + ++end; + if (!*end) + return 0; + return strtoull(end, NULL, 10); +} + +static char * +parse_member_name(const struct ArHdr *hdr) +{ + char name[17]; + size_t len; + + memcpy(name, hdr->ar_name, sizeof(hdr->ar_name)); + name[sizeof(hdr->ar_name)] = '\0'; + len = strlen(name); + while (len && name[len - 1] == ' ') + name[--len] = '\0'; + if (len > 1 && name[len - 1] == '/' && !(len == 2 && name[0] == '/' && name[1] == '/')) + name[--len] = '\0'; + return estrndup(name, len); +} + +static char * +resolve_long_name(const char *longnames, size_t longnames_size, const char *name) +{ + unsigned long off; + char *end; + const char *p; + const char *q; + + if (!longnames || name[0] != '/' || !isdigit((unsigned char)name[1])) + return NULL; + errno = 0; + off = strtoul(name + 1, &end, 10); + if (errno || *end || off >= longnames_size) + return NULL; + p = longnames + off; + q = p; + while ((size_t)(q - longnames) < longnames_size && *q != '\n') + ++q; + if (q > p && q[-1] == '/') + --q; + return estrndup(p, (size_t)(q - p)); +} + +static unsigned char * +read_archive_member(FILE *fp, const char *archive, size_t size) +{ + unsigned char *data; + + data = emalloc(size); + if (size && fread(data, 1, size, fp) != size) + eprintf("fread member %s:", archive); + if (size & 1) { + if (fgetc(fp) == EOF) + eprintf("fgetc padding %s:", archive); + } + return data; +} + +static int +table_or_extract_archive(const char *archive, int table, int extract, int verbose) +{ + FILE *fp; + char magic[SARMAG]; + char *longnames = NULL; + size_t longnames_size = 0; + + fp = fopen(archive, "rb"); + if (!fp) + eprintf("fopen %s:", archive); + if (fread(magic, 1, sizeof(magic), fp) != sizeof(magic) || memcmp(magic, ARMAG, SARMAG) != 0) + eprintf("not an ar archive\n"); + + for (;;) { + struct ArHdr hdr; + char *raw_name; + char *resolved_name; + char *name; + unsigned long long parsed_size; + size_t size; + unsigned char *data; + size_t nread; + + nread = fread(&hdr, 1, sizeof(hdr), fp); + if (nread == 0) + break; + if (nread != sizeof(hdr) || memcmp(hdr.ar_fmag, ARFMAG, 2) != 0) + eprintf("invalid ar archive\n"); + parsed_size = parse_decimal_field(hdr.ar_size, sizeof(hdr.ar_size)); + if (parsed_size > SIZE_MAX) + eprintf("archive member is too large\n"); + size = (size_t)parsed_size; + raw_name = parse_member_name(&hdr); + data = read_archive_member(fp, archive, size); + + if (!strcmp(raw_name, "// ")) { + free(longnames); + longnames = (char *)data; + longnames_size = size; + free(raw_name); + continue; + } + if (!strcmp(raw_name, "/") || !strcmp(raw_name, "/SYM64/")) { + free(data); + free(raw_name); + continue; + } + + resolved_name = resolve_long_name(longnames, longnames_size, raw_name); + name = resolved_name ? resolved_name : raw_name; + if (table || verbose) + printf("%s%s\n", extract ? "x - " : "", name); + if (extract) { + FILE *out = fopen(name, "wb"); + if (!out) + eprintf("fopen %s:", name); + write_all(out, data, size, name); + if (fclose(out) != 0) + eprintf("fclose %s:", name); + } + free(resolved_name); + free(raw_name); + free(data); + } + free(longnames); + fclose(fp); + return 0; +} + +static void +usage(void) +{ + fprintf(stderr, "usage: %s [crstvx] archive [files]\n", argv0); + exit(1); +} + +int +main(int argc, char **argv) +{ + const char *ops; + int i; + int extract = 0; + int table = 0; + int verbose = 0; + int ret = 0; + + argv0 = argv[0]; + if (argc < 3) + usage(); + + ops = argv[1]; + if (*ops == '-') + ++ops; + if (!*ops) + usage(); + + for (i = 0; ops[i]; ++i) { + switch (ops[i]) { + case 'c': + case 'r': + case 's': + case 'q': + break; + case 't': + table = 1; + break; + case 'x': + extract = 1; + break; + case 'v': + verbose = 1; + break; + case 'h': + case 'a': + case 'b': + case 'd': + case 'i': + case 'o': + case 'p': + case 'N': + default: + usage(); + } + } + + if (table || extract) { + ret = table_or_extract_archive(argv[2], table, extract, verbose); + } else { + ret = create_archive(argv[2], argc - 3, argv + 3, verbose); + } + + if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) + ret = 1; + + return ret; +} diff --git a/cmd/dev/as/arch.h b/cmd/dev/as/arch.h @@ -0,0 +1,89 @@ +/* arch dispatch: selects the target architecture backend at compile time + * a new target adds its inst.h below and its arch directory under arch/ + * core code includes this header instead of reaching into arch/ directly */ + +#ifndef AS_ARCH_H +#define AS_ARCH_H + +#include "../config.h" + +/* arch-specific type definitions: struct inst, struct operand, enum opcode + * each inst.h may include ir_asm.h for UNRES_ARCH_BASE to define + * arch-specific unresolved kinds */ +#if TC_TARGET_ARCH == TC_ARCH_X64 +#include "arch/x64/inst.h" +#elif TC_TARGET_ARCH == TC_ARCH_AARCH64 +#include "arch/aarch64/inst.h" +#elif TC_TARGET_ARCH == TC_ARCH_RISCV64 +#include "arch/riscv64/inst.h" +#else +#error "unsupported architecture" +#endif + +#include "asm_code.h" /* struct code */ + +/* code buffer macros. call through the arch backend function table */ + +#ifndef MAKE_CODE +#define MAKE_CODE(inst, code, ...) \ + do { \ + unsigned char buf[] = {__VA_ARGS__}; \ + arch.make_code(inst, code, buf, sizeof(buf)); \ + } while (0) +#endif + +#define IM8(x) (x) +#define IM16(x) (x), ((x) >> 8) +#define IM32(x) (x), ((x) >> 8), ((x) >> 16), ((x) >> 24) +#define IM64(x) \ + (x), ((x) >> 8), ((x) >> 16), ((x) >> 24), ((x) >> 32), ((x) >> 40), ((x) >> 48), ((x) >> 56) + +struct ParseInfo; +struct ParseInstTable; +struct SectionInfo; +struct Table; +struct Vector; + +/* per-arch hooks called from arch-neutral core code. each arch backend + * implements these and exports a single arch struct */ +struct arch_backend { + /* mnemonic string table, null-terminated. indexed by raw opcode */ + const char *const *raw_op_table; + /* instruction shape table, indexed by raw opcode */ + const struct ParseInstTable *parse_inst_table; + + /* scan for instruction prefix keywords (lock, rep, etc). returns + * the prefix flag bit or 0 if no prefix found. advances info->p + * past the keyword and trailing whitespace when a prefix matches */ + unsigned char (*scan_prefix)(struct ParseInfo *info); + + /* parse one operand from the input stream. returns a bitmask of + * matched operand-shape flags or 0 on failure */ + unsigned int (*parse_operand)( + struct ParseInfo *info, unsigned int opr_flag, struct Operand *operand + ); + + /* encode a parsed instruction into binary. fills code->buf and code->len */ + void (*assemble_inst)(struct Inst *inst, struct ParseInfo *info, struct Code *code); + + /* low-level code buffer filler used by MAKE_CODE macro */ + void (*make_code)(struct Inst *inst, struct Code *code, unsigned char *buf, int len); + + /* resolve arch-specific relocations for an IR_CODE node. core calls + * this for every code IR during the resolution pass. sets + * size_upgraded if a branch was promoted to long form and the + * fixpoint needs another iteration */ + void (*resolve_code_reloc)( + struct IR *ir, + struct SectionInfo *section, + uint64_t address, + uint64_t start_address, + struct Table *label_table, + struct Vector *unresolved, + int *size_upgraded + ); +}; + +extern const struct arch_backend arch; + +#endif /* AS_ARCH_H */ diff --git a/cmd/dev/as/arch/x64/asm_code.c b/cmd/dev/as/arch/x64/asm_code.c @@ -0,0 +1,3012 @@ +#include "../../../config.h" + +#include "arch.h" + +#include <assert.h> +#include <stdlib.h> /* exit */ +#include <string.h> /* memcpy */ + +#include "inst.h" +#include "parse_asm.h" +#include "tcutil.h" + +#ifndef PUT_CODE +#define PUT_CODE(p, ...) \ + do { \ + unsigned char buf[] = {__VA_ARGS__}; \ + memcpy(p, buf, sizeof(buf)); \ + } while (0) +#endif + +static unsigned char * +put_code_filtered(unsigned char *p, const short *buf, size_t count) +{ + for (size_t i = 0; i < count; ++i) { + short c = *buf++; + if (c >= 0) + *p++ = c; + } + return p; +} + +void +make_code(struct Inst *inst, struct Code *code, unsigned char *buf, int len) +{ + assert(code->len + len <= (int)sizeof(code->buf)); + code->inst = inst; + memcpy(code->buf + code->len, buf, len); + code->len += len; +} + +static inline char +opr_regno(const struct Reg *reg) +{ + return reg->no | (reg->x << 3); +} + +static inline int +opr_reg8(const struct Reg *reg) +{ + assert(reg->size == REG8); + return opr_regno(reg) < 4; +} + +static inline int +assemble_error(struct ParseInfo *info, const char *message) +{ + parse_error(info, message); + return 0; +} + +static unsigned char * +put_rex0(unsigned char *p, enum RegSize size, int sno, int dno, unsigned char opcode) +{ + if (size == REG16) + *p++ = 0x66; + if (sno >= 8 || dno >= 8 || size == REG64) + *p++ = 0x40 | ((dno & 8) >> 3) | ((sno & 8) >> 1) | (size != REG64 ? 0 : 8); + *p++ = opcode; + return p; +} + +#define MAKE_REX0(size, sno, dno, opcode) \ + (size) == REG16 ? 0x66 : -1, \ + ((sno) >= 8 || (dno) >= 8 || ((size) == REG8 && ((sno) >= 4 || (dno) >= 4)) \ + || (size) == REG64) \ + ? (0x40 | (((dno) & 8) >> 3) | (((sno) & 8) >> 1) | ((size) != REG64 ? 0 : 8)) \ + : -1, \ + opcode + +static unsigned char * +put_rex1(unsigned char *p, enum RegSize size, int rex_prefix, int dno, unsigned char opcode) +{ + p = put_rex0(p, size, 0, dno, opcode); + *p++ = rex_prefix | (dno & 7); + return p; +} + +static unsigned char * +put_rex2(unsigned char *p, enum RegSize size, int sno, int dno, unsigned char opcode) +{ + p = put_rex0(p, size, sno, dno, opcode); + *p++ = 0xc0 | ((sno & 7) << 3) | (dno & 7); + return p; +} + +#define MAKE_REX_INDIRECT(size, reg, indirect_reg, opcode, op2, offset) \ + MAKE_REX0(size, reg, indirect_reg, (size) == REG8 ? opcode : (unsigned char)((opcode) + 1)), \ + (((offset) == 0 && indirect_reg != RBP - RAX) ? op2 \ + : is_im8(offset) ? 0x40 \ + : 0x80) \ + | (indirect_reg & 7) | ((reg & 7) << 3), \ + indirect_reg == RSP - RAX ? 0x24 : -1 + +#define MAKE_OFFSET(offset, no) \ + ((offset) == 0 && no) ? -1 : (offset) & 0xff, \ + ((offset) == 0 && no) || is_im8(offset) ? -1 : ((offset) >> 8) & 0xff, \ + ((offset) == 0 && no) || is_im8(offset) ? -1 : ((offset) >> 16) & 0xff, \ + ((offset) == 0 && no) || is_im8(offset) ? -1 : ((offset) >> 24) & 0xff + +#define MAKE_IM(size, value) \ + (value) & 0xff, size < REG16 ? -1 : ((value) >> 8) & 0xff, \ + size < REG32 ? -1 : ((value) >> 16) & 0xff, size < REG32 ? -1 : ((value) >> 24) & 0xff, \ + size < REG64 ? -1 : ((value) >> 32) & 0xff, size < REG64 ? -1 : ((value) >> 40) & 0xff, \ + size < REG64 ? -1 : ((value) >> 48) & 0xff, size < REG64 ? -1 : ((value) >> 56) & 0xff + +static unsigned char * +asm_noop(struct Inst *inst, struct Code *code) +{ + UNUSED(inst); + unsigned char *p = code->buf; + return p; +} + +static unsigned char * +asm_mov_rr(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + enum RegSize size = inst->opr[0].reg.size; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x88 : 0x89 + ); + return p; +} + +static unsigned char * +asm_mov_imr(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + enum RegSize size = inst->opr[1].reg.size; + if (size == REG64 && is_im32(inst->opr[0].immediate)) { + int d = inst->opr[1].reg.no; + int pre = !inst->opr[1].reg.x ? 0x48 : 0x49; + MAKE_CODE(inst, code, pre, 0xc7, 0xc0 | d, IM32(inst->opr[0].immediate)); + return code->buf; + } + + short buf[] = { + MAKE_REX0( + size, 0, opr_regno(&inst->opr[1].reg), 0xb0 | (size == REG8 ? 0 : 8) | inst->opr[1].reg.no + ), + MAKE_IM(size, inst->opr[0].immediate), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_mov_ir(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect.reg.no != RIP) { + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) { + long offset = inst->opr[0].indirect.offset.expr->fixnum; + enum RegSize size = inst->opr[1].reg.size; + int sno = opr_regno(&inst->opr[0].indirect.reg); + int dno = opr_regno(&inst->opr[1].reg); + int ofszero = offset == 0 && ((sno & 7) != RBP - RAX); + short buf[] = { + size == REG16 ? 0x66 : -1, + (size == REG64 || sno >= 8 || dno >= 8) + ? 0x40 | (size == REG64 ? 0x08 : 0) | ((dno & 8) >> 1) | ((sno & 8) >> 3) + : -1, + 0x8a | (size == REG8 ? 0 : 0x01), + ((dno & 7) << 3) | (sno & 7) + | (ofszero ? 0 + : is_im8(offset) ? 0x40 + : 0x80), + (sno & 7) == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + + if (ofszero) { + /* nothing */ + } else if (is_im8(offset)) { + *p++ = offset; + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + } else { + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM) { + int pre = !inst->opr[1].reg.x ? 0x48 : 0x4c; + int d = inst->opr[1].reg.no; + MAKE_CODE(inst, code, pre, 0x8b, 0x05 | (d << 3), IM32(0)); + return code->buf; + } + } + return NULL; +} + +/* reg -> (mem), rex prefix + modrm + sib + disp: shared shape behind + * mov, xchg, xadd, and cmpxchg storing a register into memory. only + * the opcode bytes differ between them, xadd/cmpxchg add a 0f escape + * byte ahead of theirs */ +static unsigned char * +assemble_reg_to_mem( + struct Inst *inst, struct Code *code, int escape, unsigned char op8, unsigned char opw +) +{ + if (inst->opr[1].indirect.offset.expr->kind != EX_FIXNUM || inst->opr[1].indirect.reg.no == RIP) + return NULL; + + long offset = inst->opr[1].indirect.offset.expr->fixnum; + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].indirect.reg); + int ofszero = offset == 0 && ((dno & 7) != RBP - RAX); + short buf[] = { + size == REG16 ? 0x66 : -1, + (size == REG64 || sno >= 8 || dno >= 8) + ? 0x40 | (size == REG64 ? 0x08 : 0) | ((sno & 8) >> 1) | ((dno & 8) >> 3) + : -1, + escape ? 0x0f : -1, + size == REG8 ? op8 : opw, + ((sno & 7) << 3) | (dno & 7) + | (ofszero ? 0 + : is_im8(offset) ? 0x40 + : 0x80), + (dno & 7) == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + + if (ofszero) { + /* nothing */ + } else if (is_im8(offset)) { + *p++ = offset; + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; +} + +static unsigned char * +asm_mov_ri(struct Inst *inst, struct Code *code) +{ + return assemble_reg_to_mem(inst, code, 0, 0x88, 0x89); +} + +static unsigned char * +asm_mov_iir(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect_with_index.offset->kind == EX_FIXNUM) { + long offset = inst->opr[0].indirect_with_index.offset->fixnum; + assert(is_im32(offset)); + short offset_bit = offset == 0 ? 0x04 : is_im8(offset) ? 0x44 : 0x84; + enum RegSize size = inst->opr[1].reg.size; + assert(inst->opr[0].indirect_with_index.base_reg.no != RIP); + int bno = opr_regno(&inst->opr[0].indirect_with_index.base_reg); + int ino = opr_regno(&inst->opr[0].indirect_with_index.index_reg); + int dno = opr_regno(&inst->opr[1].reg); + struct Expr *scale_expr = inst->opr[0].indirect_with_index.scale; + char scale_bit = 0; + if (scale_expr != NULL) { + int s = scale_expr->fixnum; + if (s <= 0 || s > 8 || !IS_POWER_OF_2(s)) + return NULL; + scale_bit = most_significant_bit(s); + } + short x = ((bno & 8) >> 3) | ((ino & 8) >> 2) | ((dno & 8) >> 1); + short prefix = size == REG16 ? 0x66 : size == REG64 || x != 0 ? 0x48 | x : -1; + short buf[] = { + prefix, + size == REG8 ? 0x8a : 0x8b, + ((dno & 7) << 3) | offset_bit, + (scale_bit << 6) | ((ino & 7) << 3) | (bno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + + if (offset != 0) { + if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + } + return p; + } + return NULL; +} + +static unsigned char * +assemble_direct_mov(struct Inst *inst, struct Code *code, int load) +{ + struct Reg *reg = load ? &inst->opr[1].reg : &inst->opr[0].reg; + enum RegSize size = reg->size; + int dno = opr_regno(reg); + unsigned char opcode = load ? 0x8b : 0x89; + unsigned char *p = code->buf; + + switch (size) { + case REG8: + opcode = load ? 0x8a : 0x88; + break; + case REG16: + case REG32: + case REG64: + break; + default: + return NULL; + } + + if (size == REG16) + *p++ = 0x66; + if (size == REG64 || dno >= 8) + *p++ = 0x40 | (size == REG64 ? 0x08 : 0x00) | ((dno & 8) >> 1); + *p++ = opcode; + *p++ = (dno & 7) << 3 | 0x04; + *p++ = 0x25; + PUT_CODE(p, IM32(0)); + p += 4; + return p; +} + +static unsigned char * +asm_mov_dr(struct Inst *inst, struct Code *code) +{ + return assemble_direct_mov(inst, code, 1); +} + +static unsigned char * +asm_mov_rd(struct Inst *inst, struct Code *code) +{ + return assemble_direct_mov(inst, code, 0); +} + +static unsigned char * +asm_mov_sr(struct Inst *inst, struct Code *code) +{ + enum RegSize dsize = inst->opr[1].reg.size; + if (inst->opr[0].segment.reg != FS || (dsize != REG32 && dsize != REG64)) + return NULL; + + struct Expr *offset = inst->opr[0].segment.offset.expr; + int tpoff = inst->opr[0].segment.offset.flag & LF_TPOFF; + if (offset != NULL && offset->kind != EX_FIXNUM && !tpoff) + return NULL; + + /* tpoff's value is a link-time tls-layout quantity the assembler + cannot compute, 0 here is a placeholder patched in by the + relocation x64_resolve_code_reloc registers below */ + uint64_t value = (offset != NULL && offset->kind == EX_FIXNUM) ? offset->fixnum : 0; + unsigned char dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + 0x64, + dsize == REG64 ? 0x48 : -1, + 0x8b, + (short)(((dno & 7) << 3) | 0x04), + 0x25, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + PUT_CODE(p, IM32(value)); + p += 4; + return p; +} + +static unsigned char * +asm_movbwlq_imi(struct Inst *inst, struct Code *code) +{ + long offset = inst->opr[1].indirect.offset.expr->fixnum; + unsigned char sno = 0; + unsigned char dno = opr_regno(&inst->opr[1].indirect.reg); + unsigned char op = (offset == 0 && (dno & 7) != RBP - RAX) ? 0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + short buf[] = { + inst->op == MOVW_IMI ? 0x66 : -1, + (inst->op == MOVQ_IMI || dno >= 8) + ? 0x40 | (inst->op == MOVQ_IMI ? 0x08 : 0) | ((dno & 8) >> 3) | ((sno & 8) >> 1) + : -1, + 0xc6 | (inst->op == MOVB_IMI ? 0 : 1), + op | (dno & 7) | ((sno & 7) << 3), + (dno & 7) == RSP - RAX ? 0x24 : -1, + }; + + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset == 0 && (dno & 7) != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else if (is_im32(offset)) { + PUT_CODE(p, IM32(offset)); + p += 4; + } + + long value = inst->opr[0].immediate; + switch (inst->op) { + case MOVB_IMI: + *p++ = IM8(value); + break; + case MOVW_IMI: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case MOVL_IMI: + case MOVQ_IMI: + PUT_CODE(p, IM32(value)); + p += 4; + break; + default: + assert(0); + break; + } + return p; +} + +static unsigned char * +asm_movbwlq_imd(struct Inst *inst, struct Code *code) +{ + assert(inst->opr[1].direct.expr->kind == EX_FIXNUM); + int64_t dst = inst->opr[1].direct.expr->fixnum; + assert(is_im32(dst)); + + short buf[] = { + inst->op == MOVW_IMD ? 0x66 : -1, + inst->op == MOVQ_IMD ? 0x48 : -1, + 0xc6 | (inst->op == MOVB_IMD ? 0 : 1), + 0x04, + 0x25, + }; + + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + PUT_CODE(p, IM32(dst)); + p += 4; + + long value = inst->opr[0].immediate; + switch (inst->op) { + case MOVB_IMD: + *p++ = IM8(value); + break; + case MOVW_IMD: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case MOVL_IMD: + case MOVQ_IMD: + PUT_CODE(p, IM32(value)); + p += 4; + break; + default: + assert(0); + break; + } + return p; +} + +static unsigned char * +asm_movszx_rr(struct Inst *inst, struct Code *code) +{ + int s = inst->opr[0].reg.no; + int d = inst->opr[1].reg.no; + unsigned char op = inst->op == MOVZX ? 0xb6 : 0xbe; + unsigned char *p = code->buf; + switch (inst->opr[0].reg.size) { + case REG8: + switch (inst->opr[1].reg.size) { + case REG16: + if (opr_reg8(&inst->opr[0].reg) && !inst->opr[1].reg.x) { + MAKE_CODE(inst, code, 0x66, 0x0f, op, 0xc0 + s + d * 8); + } else { + int pre = ((inst->opr[0].reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, 0x66, pre, 0x0f, op, 0xc0 + s + d * 8); + } + return p; + case REG32: + if (opr_reg8(&inst->opr[0].reg) && !inst->opr[1].reg.x) { + MAKE_CODE(inst, code, 0x0f, op, 0xc0 + s + d * 8); + } else { + int pre = ((inst->opr[0].reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, pre, 0x0f, op, 0xc0 + s + d * 8); + } + return p; + case REG64: { + int pre = ((inst->opr[0].reg.x & 1) == 0 ? 0x48 : 0x49) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, pre, 0x0f, op, 0xc0 + s + d * 8); + return p; + } + default: + break; + } + break; + case REG16: + switch (inst->opr[1].reg.size) { + case REG32: + if (!inst->opr[0].reg.x && !inst->opr[1].reg.x) { + MAKE_CODE(inst, code, 0x0f, op | 1, 0xc0 + s + d * 8); + } else { + int pre = (!inst->opr[0].reg.x ? 0x40 : 0x41) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, pre, 0x0f, op | 1, 0xc0 + s + d * 8); + } + return p; + case REG64: { + int pre = (!inst->opr[0].reg.x ? 0x48 : 0x49) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, pre, 0x0f, op | 1, 0xc0 + s + d * 8); + return p; + } + default: + break; + } + break; + case REG32: + /* "MOVZX %32bit, %64bit" doesnt exist! */ + if (inst->opr[1].reg.size == REG64 && inst->op == MOVSX) { + int pre = (!inst->opr[0].reg.x ? 0x48 : 0x49) + (!inst->opr[1].reg.x ? 0 : 4); + MAKE_CODE(inst, code, pre, 0x63, 0xc0 + s + d * 8); + return p; + } + break; + default: + break; + } + return NULL; +} + +static unsigned char * +asm_movsds_xx(struct Inst *inst, struct Code *code, int single) +{ + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + prefix, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x10, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_movsd_xx(struct Inst *inst, struct Code *code) +{ + return asm_movsds_xx(inst, code, 0); +} +static unsigned char * +asm_movss_xx(struct Inst *inst, struct Code *code) +{ + return asm_movsds_xx(inst, code, 1); +} + +static unsigned char * +asm_movsds_ix(struct Inst *inst, struct Code *code, int single) +{ + long offset; + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char dno = inst->opr[1].regxmm - XMM0; + int d = dno & 7; + unsigned char *p = code->buf; + + if (inst->opr[0].indirect.reg.no != RIP) { + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM + || !(offset = inst->opr[0].indirect.offset.expr->fixnum, is_im32(offset))) + return NULL; + { + unsigned char sno = opr_regno(&inst->opr[0].indirect.reg); + int s = sno & 7; + unsigned char op = (offset == 0 && s != RBP - RAX) ? (unsigned char)0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + + short buf[] = { + prefix, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x10, + op | s | (d << 3), + s == RSP - RAX ? 0x24 : -1, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + + if (offset == 0 && s != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { /* is_im32(offset) */ + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + } + + /* rip-relative with a symbolic offset: emit a placeholder disp32, + the same convention asm_lea_ir uses, resolved to a pc32 + relocation by the ir pass */ + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) + return NULL; + { + short buf[] = { + prefix, + dno >= 8 ? (unsigned char)0x44 : -1, + 0x0f, + 0x10, + 0x05 | (d << 3), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + PUT_CODE(p, IM32(0)); + p += 4; + return p; + } +} +static unsigned char * +asm_movsd_ix(struct Inst *inst, struct Code *code) +{ + return asm_movsds_ix(inst, code, 0); +} +static unsigned char * +asm_movss_ix(struct Inst *inst, struct Code *code) +{ + return asm_movsds_ix(inst, code, 1); +} + +static unsigned char * +asm_movsds_xi(struct Inst *inst, struct Code *code, int single) +{ + long offset; + if (inst->opr[1].indirect.offset.expr->kind == EX_FIXNUM + && (offset = inst->opr[1].indirect.offset.expr->fixnum, is_im32(offset))) { + if (inst->opr[1].indirect.reg.no != RIP) { + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = opr_regno(&inst->opr[1].indirect.reg); + int d = dno & 7; + int s = sno & 7; + unsigned char op = (offset == 0 && d != RBP - RAX) ? (unsigned char)0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + + short buf[] = { + prefix, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((dno & 8) >> 3) | ((sno & 8) >> 1) : -1, + 0x0f, + 0x11, + op | d | (s << 3), + d == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + + if (offset == 0 && d != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { /* is_im32(offset) */ + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + } + return NULL; +} +static unsigned char * +asm_movsd_xi(struct Inst *inst, struct Code *code) +{ + return asm_movsds_xi(inst, code, 0); +} +static unsigned char * +asm_movss_xi(struct Inst *inst, struct Code *code) +{ + return asm_movsds_xi(inst, code, 1); +} + +static unsigned char * +assemble_bop_sd(struct Inst *inst, struct Code *code, int single, unsigned char op) +{ + unsigned char *p = code->buf; + unsigned char prefix = single ? 0xf3 : 0xf2; + if (inst->opr[0].type == REG_XMM && inst->opr[1].type == REG_XMM) { + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + prefix, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + op, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + } + + return p; +} + +static unsigned char * +asm_addsd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 0, 0x58); +} +static unsigned char * +asm_addss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 1, 0x58); +} + +static unsigned char * +asm_subsd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 0, 0x5c); +} +static unsigned char * +asm_subss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 1, 0x5c); +} + +static unsigned char * +asm_mulsd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 0, 0x59); +} +static unsigned char * +asm_mulss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 1, 0x59); +} + +static unsigned char * +asm_divsd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 0, 0x5e); +} +static unsigned char * +asm_divss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_bop_sd(inst, code, 1, 0x5e); +} + +static unsigned char * +assemble_xorpd_xx(struct Inst *inst, struct Code *code, int single) +{ + unsigned char *p = code->buf; + assert(inst->opr[0].type == REG_XMM); + assert(inst->opr[1].type == REG_XMM); + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + single ? -1 : 0x66, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x57, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_xorpd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_xorpd_xx(inst, code, 0); +} +static unsigned char * +asm_xorps_xx(struct Inst *inst, struct Code *code) +{ + return assemble_xorpd_xx(inst, code, 1); +} + +static unsigned char * +assemble_xorpd_ix(struct Inst *inst, struct Code *code, int single) +{ + long offset; + unsigned char dno = inst->opr[1].regxmm - XMM0; + int d = dno & 7; + unsigned char *p = code->buf; + + if (inst->opr[0].indirect.reg.no != RIP) { + unsigned char sno; + int s; + unsigned char op; + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM + || !(offset = inst->opr[0].indirect.offset.expr->fixnum, is_im32(offset))) + return NULL; + sno = opr_regno(&inst->opr[0].indirect.reg); + s = sno & 7; + op = (offset == 0 && s != RBP - RAX) ? (unsigned char)0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + { + short buf[] = { + single ? -1 : 0x66, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x57, + op | s | (d << 3), + s == RSP - RAX ? 0x24 : -1, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + } + if (offset == 0 && s != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { /* is_im32(offset) */ + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + + /* rip-relative with a symbolic offset, same convention as + asm_movsds_ix: placeholder disp32, resolved by the ir pass */ + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) + return NULL; + { + short buf[] = { + single ? -1 : 0x66, + dno >= 8 ? (unsigned char)0x44 : -1, + 0x0f, + 0x57, + 0x05 | (d << 3), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + PUT_CODE(p, IM32(0)); + p += 4; + return p; + } +} +static unsigned char * +asm_xorpd_ix(struct Inst *inst, struct Code *code) +{ + return assemble_xorpd_ix(inst, code, 0); +} +static unsigned char * +asm_xorps_ix(struct Inst *inst, struct Code *code) +{ + return assemble_xorpd_ix(inst, code, 1); +} + +static unsigned char * +assemble_ucomisd(struct Inst *inst, struct Code *code, unsigned char opc, int single) +{ + unsigned char *p = code->buf; + assert(inst->opr[0].type == REG_XMM); + assert(inst->opr[1].type == REG_XMM); + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + single ? -1 : 0x66, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + opc, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_comisd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd(inst, code, 0x2f, 0); +} +static unsigned char * +asm_comiss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd(inst, code, 0x2f, 1); +} +static unsigned char * +asm_ucomisd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd(inst, code, 0x2e, 0); +} +static unsigned char * +asm_ucomiss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd(inst, code, 0x2e, 1); +} + +/* comisd/ucomisd reg, (mem): same shape as assemble_xorpd_ix with the + * opcode byte as a parameter instead of fixed at 0x57. qbe emits it to + * compare a register against a float literal in a rip-relative + * constant pool */ +static unsigned char * +assemble_ucomisd_ix(struct Inst *inst, struct Code *code, unsigned char opc, int single) +{ + long offset; + unsigned char dno = inst->opr[1].regxmm - XMM0; + int d = dno & 7; + unsigned char *p = code->buf; + + if (inst->opr[0].indirect.reg.no != RIP) { + unsigned char sno; + int s; + unsigned char op; + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM + || !(offset = inst->opr[0].indirect.offset.expr->fixnum, is_im32(offset))) + return NULL; + sno = opr_regno(&inst->opr[0].indirect.reg); + s = sno & 7; + op = (offset == 0 && s != RBP - RAX) ? (unsigned char)0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + { + short buf[] = { + single ? -1 : 0x66, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + opc, + op | s | (d << 3), + s == RSP - RAX ? 0x24 : -1, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + } + if (offset == 0 && s != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + + /* rip-relative with a symbolic offset, same convention as + asm_movsds_ix/assemble_xorpd_ix: placeholder disp32, resolved by + the ir pass */ + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) + return NULL; + { + short buf[] = { + single ? -1 : 0x66, + dno >= 8 ? (unsigned char)0x44 : -1, + 0x0f, + opc, + 0x05 | (d << 3), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + PUT_CODE(p, IM32(0)); + p += 4; + return p; + } +} +static unsigned char * +asm_comisd_ix(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd_ix(inst, code, 0x2f, 0); +} +static unsigned char * +asm_comiss_ix(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd_ix(inst, code, 0x2f, 1); +} +static unsigned char * +asm_ucomisd_ix(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd_ix(inst, code, 0x2e, 0); +} +static unsigned char * +asm_ucomiss_ix(struct Inst *inst, struct Code *code) +{ + return assemble_ucomisd_ix(inst, code, 0x2e, 1); +} + +static unsigned char * +assemble_cvtsi2sd(struct Inst *inst, struct Code *code, int single) +{ + unsigned char *p = code->buf; + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char sno = opr_regno(&inst->opr[0].reg); + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + prefix, + sno >= 8 || dno >= 8 || inst->opr[0].reg.size == REG64 + ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) + | (inst->opr[0].reg.size == REG64 ? 8 : 0) + : -1, + 0x0f, + 0x2a, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_cvtsi2sd_rx(struct Inst *inst, struct Code *code) +{ + return assemble_cvtsi2sd(inst, code, 0); +} +static unsigned char * +asm_cvtsi2ss_rx(struct Inst *inst, struct Code *code) +{ + return assemble_cvtsi2sd(inst, code, 1); +} + +static unsigned char * +assemble_cvttsd2si(struct Inst *inst, struct Code *code, int single) +{ + unsigned char *p = code->buf; + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + prefix, + sno >= 8 || dno >= 8 || inst->opr[1].reg.size == REG64 + ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) + | (inst->opr[1].reg.size == REG64 ? 8 : 0) + : -1, + 0x0f, + 0x2c, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_cvttsd2si_xr(struct Inst *inst, struct Code *code) +{ + return assemble_cvttsd2si(inst, code, 0); +} +static unsigned char * +asm_cvttss2si_xr(struct Inst *inst, struct Code *code) +{ + return assemble_cvttsd2si(inst, code, 1); +} + +static unsigned char * +assemble_cvtsd2ss(struct Inst *inst, struct Code *code, int single) +{ + unsigned char *p = code->buf; + unsigned char prefix = single ? 0xf3 : 0xf2; + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + prefix, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x5a, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} +static unsigned char * +asm_cvtsd2ss_xx(struct Inst *inst, struct Code *code) +{ + return assemble_cvtsd2ss(inst, code, 0); +} +static unsigned char * +asm_cvtss2sd_xx(struct Inst *inst, struct Code *code) +{ + return assemble_cvtsd2ss(inst, code, 1); +} + +static unsigned char * +asm_sqrtsd_xx(struct Inst *inst, struct Code *code) +{ + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + 0xf2, + sno >= 8 || dno >= 8 ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) : -1, + 0x0f, + 0x51, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* movq %gp64, %xmm: bitwise move, the gp register's 64 bits become + * the xmm register's low 64 bits (high 64 zeroed). qbe emits this to + * spill a double through a gp register and to build the sign-bit mask + * operand xorpd needs for float negation */ +static unsigned char * +asm_movq_gpxmm(struct Inst *inst, struct Code *code) +{ + unsigned char sno = opr_regno(&inst->opr[0].reg); + unsigned char dno = inst->opr[1].regxmm - XMM0; + short buf[] = { + 0x66, + (unsigned char)0x48 | ((sno & 8) >> 3) | ((dno & 8) >> 1), + 0x0f, + 0x6e, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* mirror of asm_movq_gpxmm: the xmm register's low 64 bits become the + * gp register's value */ +static unsigned char * +asm_movq_xmmgp(struct Inst *inst, struct Code *code) +{ + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + 0x66, + (unsigned char)0x48 | ((dno & 8) >> 3) | ((sno & 8) >> 1), + 0x0f, + 0x7e, + (unsigned char)0xc0 | ((sno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_movq_ixmm(struct Inst *inst, struct Code *code) +{ + struct Expr *offset_expr; + struct Expr *scale_expr = NULL; + long offset; + int bno; + int ino = 0; + int dno; + int d; + int mod; + int scale_bit = 0; + int scale; + int indexed = 0; + short buf[7]; + unsigned char *p; + + dno = inst->opr[1].regxmm - XMM0; + d = dno & 7; + if (inst->opr[0].type == INDIRECT) { + bno = opr_regno(&inst->opr[0].indirect.reg); + offset_expr = inst->opr[0].indirect.offset.expr; + } else if (inst->opr[0].type == INDIRECT_WITH_INDEX) { + bno = opr_regno(&inst->opr[0].indirect_with_index.base_reg); + ino = opr_regno(&inst->opr[0].indirect_with_index.index_reg); + offset_expr = inst->opr[0].indirect_with_index.offset; + scale_expr = inst->opr[0].indirect_with_index.scale; + indexed = 1; + } else { + return NULL; + } + if (bno == RIP || offset_expr->kind != EX_FIXNUM + || !(offset = offset_expr->fixnum, is_im32(offset))) + return NULL; + if (scale_expr != NULL) { + if (scale_expr->kind != EX_FIXNUM) + return NULL; + scale = scale_expr->fixnum; + if (scale <= 0 || scale > 8 || !IS_POWER_OF_2(scale)) + return NULL; + scale_bit = most_significant_bit(scale); + } + + mod = offset == 0 && (bno & 7) != RBP - RAX ? 0x00 : is_im8(offset) ? 0x40 : 0x80; + buf[0] = 0xf3; + buf[1] = bno >= 8 || ino >= 8 || dno >= 8 + ? 0x40 | ((bno & 8) >> 3) | ((ino & 8) >> 2) | ((dno & 8) >> 1) + : -1; + buf[2] = 0x0f; + buf[3] = 0x7e; + buf[4] = mod | (d << 3) | (indexed ? 0x04 : bno & 7); + buf[5] = indexed ? (scale_bit << 6) | ((ino & 7) << 3) | (bno & 7) + : (bno & 7) == RSP - RAX ? 0x24 + : -1; + buf[6] = -1; + + p = put_code_filtered(code->buf, buf, ARRAY_SIZE(buf)); + if (offset == 0 && (bno & 7) != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; +} + +/* mirror of asm_movq_ixmm: movq %xmm, (mem), same 0f 7e opcode + * asm_movq_xmmgp uses, addressing a memory operand instead of a gp + * register */ +static unsigned char * +asm_movq_xmmi(struct Inst *inst, struct Code *code) +{ + long offset; + + if (inst->opr[1].indirect.reg.no == RIP) + return NULL; + if (inst->opr[1].indirect.offset.expr->kind != EX_FIXNUM + || !(offset = inst->opr[1].indirect.offset.expr->fixnum, is_im32(offset))) + return NULL; + { + unsigned char sno = inst->opr[0].regxmm - XMM0; + unsigned char dno = opr_regno(&inst->opr[1].indirect.reg); + int d = dno & 7; + int s = sno & 7; + unsigned char op = (offset == 0 && d != RBP - RAX) ? (unsigned char)0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + short buf[] = { + 0x66, + (unsigned char)0x48 | ((dno & 8) >> 3) | ((sno & 8) >> 1), + 0x0f, + 0x7e, + op | d | (s << 3), + d == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset == 0 && d != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } +} + +static unsigned char * +asm_endbr64(struct Inst *inst, struct Code *code) +{ + UNUSED(inst); + static const short buf[] = { + 0xf3, + 0x0f, + 0x1e, + 0xfa, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static long +signed_immediate(long value, enum RegSize size) +{ + switch (size) { + case REG8: + return (int8_t)value; + case REG16: + return (int16_t)value; + case REG32: + return (int32_t)value; + case REG64: + return (int64_t)value; + } + assert(!"Must not reached"); + return value; +} + +static unsigned char * +asm_lea_ir(struct Inst *inst, struct Code *code) +{ + assert(inst->opr[0].indirect.offset.expr != NULL); + unsigned char *p = code->buf; + if (inst->opr[0].indirect.reg.no != RIP) { + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) { + long offset = inst->opr[0].indirect.offset.expr->fixnum; + enum RegSize size = inst->opr[1].reg.size; + short buf[] = { + MAKE_REX_INDIRECT( + size, + opr_regno(&inst->opr[1].reg), + opr_regno(&inst->opr[0].indirect.reg), + 0x8c, + 0x00, + offset + ), + MAKE_OFFSET(offset, inst->opr[0].indirect.reg.no != RBP - RAX), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + } else { + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM) { + int pre = !inst->opr[1].reg.x ? 0x48 : 0x4c; + int d = inst->opr[1].reg.no; + MAKE_CODE(inst, code, pre, 0x8d, 0x05 | (d << 3), IM32(0)); + return p; + } + } + return NULL; +} + +static unsigned char * +asm_lea_iir(struct Inst *inst, struct Code *code) +{ + struct Expr *offset_expr = inst->opr[0].indirect_with_index.offset; + struct Expr *scale_expr = inst->opr[0].indirect_with_index.scale; + if ((offset_expr == NULL || offset_expr->kind == EX_FIXNUM) + && (scale_expr == NULL || scale_expr->kind == EX_FIXNUM)) { + long offset = offset_expr != NULL ? offset_expr->fixnum : 0; + long scale = scale_expr != NULL ? scale_expr->fixnum : 1; + if (is_im32(offset) && 1 <= scale && scale <= 8 && IS_POWER_OF_2(scale)) { + int breg = opr_regno(&inst->opr[0].indirect_with_index.base_reg); + int ireg = opr_regno(&inst->opr[0].indirect_with_index.index_reg); + int dreg = opr_regno(&inst->opr[1].reg); + int noofs = offset == 0 && breg != RBP - RAX; + int pow = most_significant_bit(scale); + short buf[] = { + 0x48 | ((breg & 8) >> 3) | ((ireg & 8) >> 2) | ((dreg & 8) >> 1), + 0x8d, + (noofs ? 0x00 + : is_im8(offset) ? 0x40 + : 0x80) + | ((dreg & 7) << 3) | 0x04, + (breg & 7) | ((ireg & 7) << 3) | (pow << 6), + breg == RSP - RAX ? 0x24 : -1, + }; + + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (noofs) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else if (is_im32(offset)) { + PUT_CODE(p, IM32(offset)); + p += 4; + } + return p; + } + } + return NULL; +} + +static unsigned char * +asm_add_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x00 : 0x01 + ); + return p; +} + +static unsigned char * +asm_add_imr(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + if (is_im32(value)) { + enum RegSize size = inst->opr[1].reg.size; + int im8 = is_im8(value) || size == REG8; + int d = opr_regno(&inst->opr[1].reg); + unsigned char *p = code->buf; + if (d == RAX - RAX && (size == REG8 || !im8)) + p = put_rex0(p, size, 0, d, im8 ? 0x04 : 0x05); + else + p = put_rex1(p, size, 0xc0, d, size == REG8 ? 0x80 : im8 ? 0x83 : 0x81); + + if (im8) { + *p++ = IM8(value); + } else { + switch (size) { + case REG8: + *p++ = IM8(value); + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + } + return p; + } + return NULL; +} + +static unsigned char * +asm_add_ir(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect.reg.no != RIP) { + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM) { + long offset = inst->opr[0].indirect.offset.expr->fixnum; + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX_INDIRECT( + size, + opr_regno(&inst->opr[1].reg), + opr_regno(&inst->opr[0].indirect.reg), + 0x02, + 0x00, + offset + ), + MAKE_OFFSET(offset, inst->opr[0].indirect.reg.no != RBP - RAX), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + } else { + /* sym(%rip)/sym@gottpoff(%rip): symbolic rip-relative operand, + * disp32 patched later once the target address (or got slot) is + * known, same shape as asm_mov_ir's rip branch */ + if (inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM) { + int pre = !inst->opr[1].reg.x ? 0x48 : 0x4c; + int d = inst->opr[1].reg.no; + MAKE_CODE(inst, code, pre, 0x03, 0x05 | (d << 3), IM32(0)); + return code->buf; + } + } + return NULL; +} + +static unsigned char * +asm_add_iir(struct Inst *inst, struct Code *code) +{ + assert( + inst->opr[0].indirect_with_index.offset->kind == EX_FIXNUM + && inst->opr[0].indirect_with_index.offset->fixnum == 0 + ); /* TODO */ + unsigned char scale = 0; + struct Expr *scale_expr = inst->opr[0].indirect_with_index.scale; + if (scale_expr != NULL) { + assert(scale_expr->kind == EX_FIXNUM); + int s = scale_expr->fixnum; + if (s <= 0 || s > 8 || !IS_POWER_OF_2(s)) + return NULL; + scale = most_significant_bit(s); + } + + unsigned char bno = inst->opr[0].indirect_with_index.base_reg.no; + unsigned char ino = inst->opr[0].indirect_with_index.index_reg.no; + unsigned char dno = inst->opr[1].reg.no; + short buf[] = { + (unsigned char)0x48 | (inst->opr[0].indirect_with_index.base_reg.x) + | (inst->opr[0].indirect_with_index.index_reg.x << 1) | (inst->opr[1].reg.x << 2), + 0x03, + 0x04 | (dno << 3), + bno | (ino << 3) | (scale << 6), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_addq_imi(struct Inst *inst, struct Code *code) +{ + if (inst->opr[1].indirect.offset.expr->kind == EX_FIXNUM) { + long value = inst->opr[0].immediate; + if (is_im32(value)) { + long offset = inst->opr[1].indirect.offset.expr->fixnum; + unsigned char sno = 0; + unsigned char dno = opr_regno(&inst->opr[1].indirect.reg); + unsigned char op = (offset == 0 && (dno & 7) != RBP - RAX) ? 0x00 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + short buf[] = { + (unsigned char)0x48 | ((dno & 8) >> 3) | ((sno & 8) >> 1), + (is_im8(value) ? 0x83 : 0x81), + op | (dno & 7) | ((sno & 7) << 3), + (dno & 7) == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset == 0 && (dno & 7) != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else if (is_im32(offset)) { + PUT_CODE(p, IM32(offset)); + p += 4; + } + + if (is_im8(value)) { + *p++ = IM8(value); + } else { + PUT_CODE(p, IM32(value)); + p += 4; + } + return p; + } + } + return NULL; +} + +static unsigned char * +asm_sub_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x28 : 0x29 + ); + return p; +} + +static unsigned char * +asm_sub_imr(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + if (is_im32(value)) { + enum RegSize size = inst->opr[1].reg.size; + int im8 = is_im8(value) || size == REG8; + int d = opr_regno(&inst->opr[1].reg); + unsigned char *p = code->buf; + if (d == RAX - RAX && (size == REG8 || !im8)) + p = put_rex0(p, size, 0, d, im8 ? 0x2c : 0x2d); + else + p = put_rex1(p, size, 0xe8, d, size == REG8 ? 0x80 : im8 ? 0x83 : 0x81); + + if (im8) { + *p++ = IM8(value); + } else { + switch (size) { + case REG8: + *p++ = IM8(value); + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + } + return p; + } + return NULL; +} + +static unsigned char * +asm_sub_ir(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect.offset.expr->kind == EX_FIXNUM && inst->opr[0].indirect.reg.no != RIP) { + long offset = inst->opr[0].indirect.offset.expr->fixnum; + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX_INDIRECT( + size, + opr_regno(&inst->opr[1].reg), + opr_regno(&inst->opr[0].indirect.reg), + 0x2a, + 0x00, + offset + ), + MAKE_OFFSET(offset, inst->opr[0].indirect.reg.no != RBP - RAX), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + return NULL; +} + +static unsigned char * +asm_sub_iir(struct Inst *inst, struct Code *code) +{ + assert( + inst->opr[0].indirect_with_index.offset->kind == EX_FIXNUM + && inst->opr[0].indirect_with_index.offset->fixnum == 0 + ); /* TODO */ + unsigned char scale = 0; + struct Expr *scale_expr = inst->opr[0].indirect_with_index.scale; + if (scale_expr != NULL) { + assert(scale_expr->kind == EX_FIXNUM); + int s = scale_expr->fixnum; + if (s <= 0 || s > 8 || !IS_POWER_OF_2(s)) + return NULL; + scale = most_significant_bit(s); + } + + unsigned char bno = inst->opr[0].indirect_with_index.base_reg.no; + unsigned char ino = inst->opr[0].indirect_with_index.index_reg.no; + unsigned char dno = inst->opr[1].reg.no; + short buf[] = { + (unsigned char)0x48 | (inst->opr[0].indirect_with_index.base_reg.x) + | (inst->opr[0].indirect_with_index.index_reg.x << 1) | (inst->opr[1].reg.x << 2), + 0x2b, + 0x04 | (dno << 3), + bno | (ino << 3) | (scale << 6), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_subq_imi(struct Inst *inst, struct Code *code) +{ + if (inst->opr[1].indirect.offset.expr->kind == EX_FIXNUM) { + long value = inst->opr[0].immediate; + if (is_im32(value)) { + long offset = inst->opr[1].indirect.offset.expr->fixnum; + unsigned char sno = 0; + unsigned char dno = opr_regno(&inst->opr[1].indirect.reg); + unsigned char op = (offset == 0 && (dno & 7) != RBP - RAX) ? 0x28 + : is_im8(offset) ? (unsigned char)0x40 + : (unsigned char)0x80; + short buf[] = { + (unsigned char)0x48 | ((dno & 8) >> 3) | ((sno & 8) >> 1), + (is_im8(value) ? 0x83 : 0x81), + op | (dno & 7) | ((sno & 7) << 3), + (dno & 7) == RSP - RAX ? 0x24 : -1, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset == 0 && (dno & 7) != RBP - RAX) { + ; + } else if (is_im8(offset)) { + *p++ = IM8(offset); + } else if (is_im32(offset)) { + PUT_CODE(p, IM32(offset)); + p += 4; + } + + if (is_im8(value)) { + *p++ = IM8(value); + } else { + PUT_CODE(p, IM32(value)); + p += 4; + } + return p; + } + } + return NULL; +} + +static unsigned char * +asm_mul_r(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(size, 0, opr_regno(&inst->opr[0].reg), 0xf6 | (size == REG8 ? 0 : 1)), + 0xe0 | inst->opr[0].reg.no, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_div_r(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(size, 0, opr_regno(&inst->opr[0].reg), 0xf6 | (size == REG8 ? 0 : 1)), + 0xf0 | inst->opr[0].reg.no, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_idiv_r(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(size, 0, opr_regno(&inst->opr[0].reg), 0xf6 | (size == REG8 ? 0 : 1)), + 0xf8 | inst->opr[0].reg.no, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_neg_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + p = put_rex1(p, inst->opr[0].reg.size, 0xd8, opr_regno(&inst->opr[0].reg), 0xf7); + return p; +} + +static unsigned char * +asm_not_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + p = put_rex1(p, inst->opr[0].reg.size, 0xd0, opr_regno(&inst->opr[0].reg), 0xf7); + return p; +} + +static unsigned char * +asm_inc_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + struct Reg *reg = &inst->opr[0].reg; + p = put_rex1(p, reg->size, 0xc0, opr_regno(reg), reg->size == REG8 ? 0xfe : 0xff); + return p; +} + +static unsigned char * +asm_incbwlq_i(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect.reg.no != RIP) { + enum RegSize size = inst->op + (REG8 - INCB); + long offset = inst->opr[0].indirect.offset.expr->fixnum; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX_INDIRECT(size, 0, opr_regno(&inst->opr[0].indirect.reg), 0xfe, 0x00, offset), + MAKE_OFFSET(offset, inst->opr[0].indirect.reg.no != RBP - RAX), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + return NULL; +} + +static unsigned char * +asm_dec_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + struct Reg *reg = &inst->opr[0].reg; + p = put_rex1(p, reg->size, 0xc8, opr_regno(reg), reg->size == REG8 ? 0xfe : 0xff); + return p; +} + +static unsigned char * +asm_decbwlq_i(struct Inst *inst, struct Code *code) +{ + if (inst->opr[0].indirect.reg.no != RIP) { + enum RegSize size = inst->op + (REG8 - DECB); + long offset = inst->opr[0].indirect.offset.expr->fixnum; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX_INDIRECT(size, 1, opr_regno(&inst->opr[0].indirect.reg), 0xfe, 0x08, offset), + MAKE_OFFSET(offset, inst->opr[0].indirect.reg.no != RBP - RAX), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + return NULL; +} + +static unsigned char * +asm_and_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x20 : 0x21 + ); + return p; +} + +static unsigned char * +asm_and_imr(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + if (is_im8(value) && (size != REG8 || opr_regno(&inst->opr[1].reg) != AL - AL)) { + p = put_rex1(p, size, 0xe0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x83); + *p++ = IM8(value); + return p; + } else if (size <= REG32 || is_im32(value)) { + if (opr_regno(&inst->opr[1].reg) == RAX - RAX) { + p = put_rex0(p, size, 0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x24 : 0x25); + } else { + p = put_rex1(p, size, 0xe0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x81); + } + + switch (size) { + case REG8: + PUT_CODE(p, IM8(value)); + p += 1; + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + return p; + } + return NULL; +} + +static unsigned char * +asm_or_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x08 : 0x09 + ); + return p; +} + +static unsigned char * +asm_or_imr(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + if (is_im8(value) && (size != REG8 || opr_regno(&inst->opr[1].reg) != AL - AL)) { + p = put_rex1(p, size, 0xc8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x83); + *p++ = IM8(value); + return p; + } else if (size <= REG32 || is_im32(value)) { + if (opr_regno(&inst->opr[1].reg) == RAX - RAX) { + p = put_rex0(p, size, 0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x0c : 0x0d); + } else { + p = put_rex1(p, size, 0xc8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x81); + } + switch (size) { + case REG8: + PUT_CODE(p, IM8(value)); + p += 1; + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + return p; + } + return NULL; +} + +static unsigned char * +asm_xor_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x30 : 0x31 + ); + return p; +} + +static unsigned char * +asm_xor_imr(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + if (is_im8(value) && (size != REG8 || opr_regno(&inst->opr[1].reg) != AL - AL)) { + p = put_rex1(p, size, 0xf0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x83); + *p++ = IM8(value); + return p; + } else if (size <= REG32 || is_im32(value)) { + if (opr_regno(&inst->opr[1].reg) == RAX - RAX) { + p = put_rex0(p, size, 0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x34 : 0x35); + } else { + p = put_rex1(p, size, 0xf0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0x80 : 0x81); + } + switch (size) { + case REG8: + PUT_CODE(p, IM8(value)); + p += 1; + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + return p; + } + return NULL; +} + +static unsigned char * +asm_shl_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex1(p, size, 0xe0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd2 : 0xd3); + return p; +} + +static unsigned char * +asm_shl_imr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + uint64_t shift = inst->opr[0].immediate; + if (shift >= 256) + return NULL; + if (shift == 1) { + p = put_rex1(p, size, 0xe0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd0 : 0xd1); + } else { + p = put_rex1(p, size, 0xe0, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xc0 : 0xc1); + *p++ = IM8(shift); + } + return p; +} + +static unsigned char * +asm_shr_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex1(p, size, 0xe8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd2 : 0xd3); + return p; +} + +static unsigned char * +asm_shr_imr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + uint64_t shift = inst->opr[0].immediate; + if (shift >= 256) + return NULL; + if (shift == 1) { + p = put_rex1(p, size, 0xe8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd0 : 0xd1); + } else { + p = put_rex1(p, size, 0xe8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xc0 : 0xc1); + *p++ = IM8(shift); + } + return p; +} + +static unsigned char * +asm_sar_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + p = put_rex1(p, size, 0xf8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd2 : 0xd3); + return p; +} + +static unsigned char * +asm_sar_imr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + unsigned char *p = code->buf; + uint64_t shift = inst->opr[0].immediate; + if (shift >= 256) + return NULL; + if (shift == 1) { + p = put_rex1(p, size, 0xf8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xd0 : 0xd1); + } else { + p = put_rex1(p, size, 0xf8, opr_regno(&inst->opr[1].reg), size == REG8 ? 0xc0 : 0xc1); + *p++ = IM8(shift); + } + return p; +} + +static unsigned char * +asm_cmp_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x38 : 0x39 + ); + return p; +} + +static unsigned char * +asm_cmp_imr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + long value = signed_immediate(inst->opr[0].immediate, size); + if (is_im32(value) || size <= REG32) { + int im8 = is_im8(value); + int d = opr_regno(&inst->opr[1].reg); + unsigned char *p = code->buf; + if (d == RAX - RAX && (size == REG8 || !im8)) + p = put_rex0(p, size, 0, d, size == REG8 ? 0x3c : 0x3d); + else + p = put_rex1(p, size, 0xf8, d, 0x80 | (size == REG8 ? 0 : im8 ? 3 : 1)); + + if (im8) { + *p++ = IM8(value); + } else { + switch (size) { + case REG8: + *p++ = IM8(value); + break; + case REG16: + PUT_CODE(p, IM16(value)); + p += 2; + break; + case REG32: + case REG64: + PUT_CODE(p, IM32(value)); + p += 4; + break; + } + } + return p; + } + return NULL; +} + +static unsigned char * +asm_test_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x84 : 0x85 + ); + return p; +} + +static unsigned char * +asm_cwtl(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x98); + return code->buf; +} + +static unsigned char * +asm_cltd(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x99); + return code->buf; +} + +static unsigned char * +asm_cqto(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x48, 0x99); + return code->buf; +} + +static unsigned char * +asm_bsr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, dno, sno, 0x0f), + 0xbd, + 0xc0 | (inst->opr[1].reg.no << 3) | inst->opr[0].reg.no, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_tzcnt(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char prefix = 0xf3; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + (size) == REG16 ? 0x66 : -1, + prefix, + sno >= 8 || dno >= 8 || size == REG64 + ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) | (size != REG64 ? 0 : 8) + : -1, + 0x0f, + inst->op == LZCNT ? 0xbd : 0xbc, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_popcnt(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char prefix = 0xf3; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + (size) == REG16 ? 0x66 : -1, + prefix, + sno >= 8 || dno >= 8 || size == REG64 + ? (unsigned char)0x40 | ((sno & 8) >> 3) | ((dno & 8) >> 1) | (size != REG64 ? 0 : 8) + : -1, + 0x0f, + 0xb8, + (unsigned char)0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_set_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(REG8, 0, opr_regno(&inst->opr[0].reg), 0x0f), + 0x90 | (inst->op - SETO), + 0xc0 | inst->opr[0].reg.no, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_push_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(REG32, 0, opr_regno(&inst->opr[0].reg), 0x50 | inst->opr[0].reg.no), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_push_im(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + long value = inst->opr[0].immediate; + if (is_im8(value)) { + *p++ = 0x6a; + *p++ = IM8(value); + return p; + } else if (is_im32(value)) { + *p++ = 0x68; + PUT_CODE(p, IM32(value)); + p += 4; + return p; + } + return NULL; +} + +static unsigned char * +asm_pop_r(struct Inst *inst, struct Code *code) +{ + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(REG32, 0, opr_regno(&inst->opr[0].reg), 0x58 | inst->opr[0].reg.no), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_jmp_d(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0xeb, IM8(0)); /* short jmp in default */ + return code->buf; +} + +static unsigned char * +asm_jmp_der(struct Inst *inst, struct Code *code) +{ + int s = inst->opr[0].reg.no; + short buf[] = { + inst->opr[0].reg.x ? 0x41 : -1, + 0xff, + 0xe0 | s, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +static unsigned char * +asm_jmp_dei(struct Inst *inst, struct Code *code) +{ + struct Expr *offset_expr = inst->opr[0].indirect.offset.expr; + if ((offset_expr == NULL || offset_expr->kind == EX_FIXNUM)) { + long offset = offset_expr != NULL ? offset_expr->fixnum : 0; + if (is_im32(offset)) { + short offset_bit = offset == 0 ? 0x20 : is_im8(offset) ? 0x60 : 0xa0; + short b = inst->opr[0].indirect.reg.no; + short buf[] = { + inst->opr[0].indirect.reg.x ? 0x41 : -1, + 0xff, + offset_bit | b, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset != 0) { + if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + } + return p; + } + } + return NULL; +} + +static unsigned char * +asm_jmp_deii(struct Inst *inst, struct Code *code) +{ + struct Expr *offset_expr = inst->opr[0].indirect_with_index.offset; + struct Expr *scale_expr = inst->opr[0].indirect_with_index.scale; + if ((offset_expr == NULL || offset_expr->kind == EX_FIXNUM) + && (scale_expr == NULL || scale_expr->kind == EX_FIXNUM)) { + long offset = offset_expr != NULL ? offset_expr->fixnum : 0; + long scale = scale_expr != NULL ? scale_expr->fixnum : 1; + if (is_im32(offset) && 1 <= scale && scale <= 8 && IS_POWER_OF_2(scale)) { + short b = inst->opr[0].indirect_with_index.base_reg.no; + short scale_bit = most_significant_bit(scale); + short i = inst->opr[0].indirect_with_index.index_reg.no; + short prefix = inst->opr[0].indirect_with_index.base_reg.x + | (inst->opr[0].indirect_with_index.index_reg.x << 1); + short offset_bit = offset == 0 && b != RBP - RAX ? 0x20 : is_im8(offset) ? 0x60 : 0xa0; + short buf[] = { + prefix != 0 ? 0x40 | prefix : -1, + 0xff, + offset_bit | 0x04, + (scale_bit << 6) | (i << 3) | b, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (offset != 0 || b == RBP - RAX) { + if (is_im8(offset)) { + *p++ = IM8(offset); + } else { + PUT_CODE(p, IM32(offset)); + p += 4; + } + } + return p; + } + } + return NULL; +} + +static unsigned char * +asm_jxx_d(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x70 + (inst->op - JO), IM8(0)); /* short jmp in default */ + return code->buf; +} + +static unsigned char * +asm_call_d(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0xe8, IM32(0)); + return code->buf; +} + +static unsigned char * +asm_call_der(struct Inst *inst, struct Code *code) +{ + int s = inst->opr[0].reg.no; + if (!inst->opr[0].reg.x) { + MAKE_CODE(inst, code, 0xff, 0xd0 + s); + } else { + MAKE_CODE(inst, code, 0x41, 0xff, 0xd0 + s); + } + return code->buf; +} + +static unsigned char * +asm_ret(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0xc3); + return code->buf; +} + +static unsigned char * +asm_int_im(struct Inst *inst, struct Code *code) +{ + long value = inst->opr[0].immediate; + MAKE_CODE(inst, code, 0xcd, IM8(value)); + return code->buf; +} + +static unsigned char * +asm_syscall(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x0f, 0x05); + return code->buf; +} + +/*// //////////////////////////////////////////// */ +/* new instruction encoders */ + +/* no-operand fixed-encoding instructions */ +static unsigned char * +asm_simple(struct Inst *inst, struct Code *code) +{ + switch (inst->op) { + case NOP: + MAKE_CODE(inst, code, 0x90); + return code->buf; + case PUSHFQ: + MAKE_CODE(inst, code, 0x9c); + return code->buf; + case POPFQ: + MAKE_CODE(inst, code, 0x9d); + return code->buf; + case PUSHF: + MAKE_CODE(inst, code, 0x66, 0x9c); + return code->buf; + case POPF: + MAKE_CODE(inst, code, 0x66, 0x9d); + return code->buf; + case CPUID: + MAKE_CODE(inst, code, 0x0f, 0xa2); + return code->buf; + case RDTSC: + MAKE_CODE(inst, code, 0x0f, 0x31); + return code->buf; + case UD2: + MAKE_CODE(inst, code, 0x0f, 0x0b); + return code->buf; + case PAUSE: + MAKE_CODE(inst, code, 0xf3, 0x90); + return code->buf; + case HLT: + MAKE_CODE(inst, code, 0xf4); + return code->buf; + case CMC: + MAKE_CODE(inst, code, 0xf5); + return code->buf; + case CLC: + MAKE_CODE(inst, code, 0xf8); + return code->buf; + case STC: + MAKE_CODE(inst, code, 0xf9); + return code->buf; + case CLI: + MAKE_CODE(inst, code, 0xfa); + return code->buf; + case STI: + MAKE_CODE(inst, code, 0xfb); + return code->buf; + case CLD: + MAKE_CODE(inst, code, 0xfc); + return code->buf; + case STD: + MAKE_CODE(inst, code, 0xfd); + return code->buf; + case CLTS: + MAKE_CODE(inst, code, 0x0f, 0x06); + return code->buf; + case WBINVD: + MAKE_CODE(inst, code, 0x0f, 0x09); + return code->buf; + case MFENCE: + MAKE_CODE(inst, code, 0x0f, 0xae, 0xf0); + return code->buf; + case LFENCE: + MAKE_CODE(inst, code, 0x0f, 0xae, 0xe8); + return code->buf; + case SFENCE: + MAKE_CODE(inst, code, 0x0f, 0xae, 0xf8); + return code->buf; + default: + return NULL; + } +} + +/* one-operand imul: f7 /5 */ +static unsigned char * +asm_imul_r(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + short buf[] = { + MAKE_REX0(size, 0, opr_regno(&inst->opr[0].reg), 0xf6 | (size == REG8 ? 0 : 1)), + 0xe8 | inst->opr[0].reg.no, + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* two-operand imul: 0f af /r, where reg is the destination (unlike + * mov/add, where it is the source). MAKE_REX0 wants the reg-field + * operand in the middle argument, so dno goes first, as in asm_bsf + * below */ +static unsigned char * +asm_imul_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, dno, sno, 0x0f), + 0xaf, + 0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* imul $imm, %reg: 6b/69 /r ib/id (reg used as both src and dst) */ +static unsigned char * +asm_imul_irr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[1].reg.size; + int dno = opr_regno(&inst->opr[1].reg); + long value = inst->opr[0].immediate; + int im8 = is_im8(value); + short buf[] = { + MAKE_REX0(size, dno, dno, im8 ? 0x6b : 0x69), + 0xc0 | ((dno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + if (im8) { + *p++ = IM8(value); + } else { + PUT_CODE(p, IM32(value)); + p += 4; + } + return p; +} + +static unsigned char * +asm_leave(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0xc9); + return code->buf; +} + +static unsigned char * +asm_enter(struct Inst *inst, struct Code *code) +{ + long size = inst->opr[0].immediate; + long depth = inst->opr[1].immediate; + MAKE_CODE(inst, code, 0xc8, IM16(size), IM8(depth)); + return code->buf; +} + +/* xchg: 86/87 /r */ +static unsigned char * +asm_xchg_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + unsigned char *p = code->buf; + p = put_rex2( + p, + size, + opr_regno(&inst->opr[0].reg), + opr_regno(&inst->opr[1].reg), + size == REG8 ? 0x86 : 0x87 + ); + return p; +} + +/* xchg reg, (mem): a memory operand always locks implicitly, needed + * for the atomic runtime's __atomic_exchange_N */ +static unsigned char * +asm_xchg_ri(struct Inst *inst, struct Code *code) +{ + return assemble_reg_to_mem(inst, code, 0, 0x86, 0x87); +} + +/* bsf: 0f bc /r */ +static unsigned char * +asm_bsf(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, dno, sno, 0x0f), + 0xbc, + 0xc0 | ((dno & 7) << 3) | (sno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* bswap: 0f c8+r (32/64 only) */ +static unsigned char * +asm_bswap(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int dno = opr_regno(&inst->opr[0].reg); + if (size != REG32 && size != REG64) + return NULL; + short buf[] = { + MAKE_REX0(size, 0, dno, 0x0f), + 0xc8 | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* xadd: 0f c0(8bit)/c1(16+32+64) /r */ +static unsigned char * +asm_xadd_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, sno, dno, 0x0f), + size == REG8 ? 0xc0 : 0xc1, + 0xc0 | ((sno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* cmpxchg: 0f b0(8bit)/b1(16+32+64) /r */ +static unsigned char * +asm_cmpxchg_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, sno, dno, 0x0f), + size == REG8 ? 0xb0 : 0xb1, + 0xc0 | ((sno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* xadd/cmpxchg reg, (mem): 0f escape byte ahead of the real (r/m,r) + * opcode pair, otherwise identical in shape to mov_ri. needed for the + * atomic runtime's __atomic_fetch_add_N/__atomic_compare_exchange_N, + * xadd also for __atomic_fetch_sub_N (negate then xadd) */ +static unsigned char * +asm_xadd_ri(struct Inst *inst, struct Code *code) +{ + return assemble_reg_to_mem(inst, code, 1, 0xc0, 0xc1); +} + +static unsigned char * +asm_cmpxchg_ri(struct Inst *inst, struct Code *code) +{ + return assemble_reg_to_mem(inst, code, 1, 0xb0, 0xb1); +} + +/* bt family: register form 0f [a3|ab|b3|bb] /r, + * immediate form 0f ba /[4|5|6|7] ib */ +static unsigned char * +asm_bt_family(struct Inst *inst, struct Code *code) +{ + int rr_opcodes[] = { + [BT_RR - BT_RR] = 0xa3, + [BTS_RR - BT_RR] = 0xab, + [BTR_RR - BT_RR] = 0xb3, + [BTC_RR - BT_RR] = 0xbb + }; + int imm_digits[] = { + [BT_RR - BT_RR] = 4, [BTS_RR - BT_RR] = 5, [BTR_RR - BT_RR] = 6, [BTC_RR - BT_RR] = 7 + }; + int idx = inst->op - BT_RR; + + if (inst->opr[0].type == IMMEDIATE) { + enum RegSize size = inst->opr[1].reg.size; + int dno = opr_regno(&inst->opr[1].reg); + long value = inst->opr[0].immediate; + short buf[] = { + MAKE_REX0(size, imm_digits[idx], dno, 0x0f), + 0xba, + 0xc0 | (imm_digits[idx] << 3) | (dno & 7), + value & 0xff, + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; + } + + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, sno, dno, 0x0f), + rr_opcodes[idx], + 0xc0 | ((sno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* cmovcc: 0f 40+cc /r */ +static unsigned char * +asm_cmov_rr(struct Inst *inst, struct Code *code) +{ + enum RegSize size = inst->opr[0].reg.size; + int sno = opr_regno(&inst->opr[0].reg); + int dno = opr_regno(&inst->opr[1].reg); + short buf[] = { + MAKE_REX0(size, sno, dno, 0x0f), + 0x40 + (inst->op - CMOVO), + 0xc0 | ((sno & 7) << 3) | (dno & 7), + }; + unsigned char *p = code->buf; + p = put_code_filtered(p, buf, ARRAY_SIZE(buf)); + return p; +} + +/* string operations: fixed encoding by size */ +static unsigned char * +asm_string(struct Inst *inst, struct Code *code) +{ + /* base opcodes: movs=0xa4, stos=0xaa, lods=0xac, scas=0xae, cmps=0xa6 + * the byte form has opcode x, word/dword/qword form has opcode X+1 + * the table below stores the byte-form opcode for each group */ + static const unsigned char base[] = { + [MOVSB - MOVSB] = 0xa4, + [STOSB - MOVSB] = 0xaa, + [LODSB - MOVSB] = 0xac, + [SCASB - MOVSB] = 0xae, + [CMPSB - MOVSB] = 0xa6, + }; + int group_idx = (inst->op - MOVSB) / 4; + int size_idx = (inst->op - MOVSB) % 4; /* 0=byte, 1=word, 2=long, 3=quad */ + + if (group_idx > 4) + return NULL; + + unsigned char opcode = base[group_idx * 4]; + + switch (size_idx) { + case 0: /* byte */ + MAKE_CODE(inst, code, opcode); + break; + case 1: /* word */ + MAKE_CODE(inst, code, 0x66, opcode + 1); + break; + case 2: /* long */ + MAKE_CODE(inst, code, opcode + 1); + break; + case 3: /* quad */ + MAKE_CODE(inst, code, 0x48, opcode + 1); + break; + } + return code->buf; +} + +/* gas intel-syntax conversion aliases */ +static unsigned char * +asm_cbw(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x66, 0x98); + return code->buf; +} + +static unsigned char * +asm_cdqe(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x48, 0x98); + return code->buf; +} + +static unsigned char * +asm_cwd(struct Inst *inst, struct Code *code) +{ + MAKE_CODE(inst, code, 0x66, 0x99); + return code->buf; +} + +/*// //////////////////////////////////////////// */ + +typedef unsigned char *(*AsmInstFunc)(struct Inst *inst, struct Code *code); + +static const AsmInstFunc table[] = { + [NOOP] = asm_noop, + [MOV_RR] = asm_mov_rr, + [MOV_IMR] = asm_mov_imr, + [MOV_IR] = asm_mov_ir, + [MOV_RI] = asm_mov_ri, + [MOV_IIR] = asm_mov_iir, + [MOV_DR] = asm_mov_dr, + [MOV_RD] = asm_mov_rd, + [MOV_SR] = asm_mov_sr, + [MOVB_IMI] = asm_movbwlq_imi, + [MOVW_IMI] = asm_movbwlq_imi, + [MOVL_IMI] = asm_movbwlq_imi, + [MOVQ_IMI] = asm_movbwlq_imi, + [MOVB_IMD] = asm_movbwlq_imd, + [MOVW_IMD] = asm_movbwlq_imd, + [MOVL_IMD] = asm_movbwlq_imd, + [MOVQ_IMD] = asm_movbwlq_imd, + [MOVSX] = asm_movszx_rr, + [MOVZX] = asm_movszx_rr, + [LEA_IR] = asm_lea_ir, + [LEA_IIR] = asm_lea_iir, + [ADD_RR] = asm_add_rr, + [ADD_IMR] = asm_add_imr, + [ADD_IR] = asm_add_ir, + [ADD_IIR] = asm_add_iir, + [ADDQ] = asm_addq_imi, + [SUB_RR] = asm_sub_rr, + [SUB_IMR] = asm_sub_imr, + [SUB_IR] = asm_sub_ir, + [SUB_IIR] = asm_sub_iir, + [SUBQ] = asm_subq_imi, + [MUL] = asm_mul_r, + [DIV] = asm_div_r, + [IDIV] = asm_idiv_r, + [NEG] = asm_neg_r, + [NOT] = asm_not_r, + [INC] = asm_inc_r, + [INCB] = asm_incbwlq_i, + [INCW] = asm_incbwlq_i, + [INCL] = asm_incbwlq_i, + [INCQ] = asm_incbwlq_i, + [DEC] = asm_dec_r, + [DECB] = asm_decbwlq_i, + [DECW] = asm_decbwlq_i, + [DECL] = asm_decbwlq_i, + [DECQ] = asm_decbwlq_i, + [AND_RR] = asm_and_rr, + [AND_IMR] = asm_and_imr, + [OR_RR] = asm_or_rr, + [OR_IMR] = asm_or_imr, + [XOR_RR] = asm_xor_rr, + [XOR_IMR] = asm_xor_imr, + [SHL_RR] = asm_shl_rr, + [SHL_IMR] = asm_shl_imr, + [SHR_RR] = asm_shr_rr, + [SHR_IMR] = asm_shr_imr, + [SAR_RR] = asm_sar_rr, + [SAR_IMR] = asm_sar_imr, + [CMP_RR] = asm_cmp_rr, + [CMP_IMR] = asm_cmp_imr, + [TEST] = asm_test_rr, + [CWTL] = asm_cwtl, + [CLTD] = asm_cltd, + [CQTO] = asm_cqto, + [BSR] = asm_bsr, + [LZCNT] = asm_tzcnt, + [TZCNT] = asm_tzcnt, + [POPCNT] = asm_popcnt, + [SETO] = asm_set_r, + [SETNO] = asm_set_r, + [SETB] = asm_set_r, + [SETAE] = asm_set_r, + [SETE] = asm_set_r, + [SETNE] = asm_set_r, + [SETBE] = asm_set_r, + [SETA] = asm_set_r, + [SETS] = asm_set_r, + [SETNS] = asm_set_r, + [SETP] = asm_set_r, + [SETNP] = asm_set_r, + [SETL] = asm_set_r, + [SETGE] = asm_set_r, + [SETLE] = asm_set_r, + [SETG] = asm_set_r, + [JMP_D] = asm_jmp_d, + [JMP_DER] = asm_jmp_der, + [JMP_DEI] = asm_jmp_dei, + [JMP_DEII] = asm_jmp_deii, + [JO] = asm_jxx_d, + [JNO] = asm_jxx_d, + [JB] = asm_jxx_d, + [JAE] = asm_jxx_d, + [JE] = asm_jxx_d, + [JNE] = asm_jxx_d, + [JBE] = asm_jxx_d, + [JA] = asm_jxx_d, + [JS] = asm_jxx_d, + [JNS] = asm_jxx_d, + [JP] = asm_jxx_d, + [JNP] = asm_jxx_d, + [JL] = asm_jxx_d, + [JGE] = asm_jxx_d, + [JLE] = asm_jxx_d, + [JG] = asm_jxx_d, + [CALL_D] = asm_call_d, + [CALL_DER] = asm_call_der, + [RET] = asm_ret, + [PUSH_R] = asm_push_r, + [PUSH_IM] = asm_push_im, + [POP] = asm_pop_r, + [INT] = asm_int_im, + [SYSCALL] = asm_syscall, + + [MOVSD_XX] = asm_movsd_xx, + [MOVSD_IX] = asm_movsd_ix, + [MOVSD_XI] = asm_movsd_xi, + [MOVSS_XX] = asm_movss_xx, + [MOVSS_IX] = asm_movss_ix, + [MOVSS_XI] = asm_movss_xi, + [ADDSD] = asm_addsd_xx, + [ADDSS] = asm_addss_xx, + [SUBSD] = asm_subsd_xx, + [SUBSS] = asm_subss_xx, + [MULSD] = asm_mulsd_xx, + [MULSS] = asm_mulss_xx, + [DIVSD] = asm_divsd_xx, + [DIVSS] = asm_divss_xx, + [XORPD] = asm_xorpd_xx, + [XORPD_IX] = asm_xorpd_ix, + [XORPS] = asm_xorps_xx, + [XORPS_IX] = asm_xorps_ix, + [COMISD] = asm_comisd_xx, + [COMISD_IX] = asm_comisd_ix, + [UCOMISD] = asm_ucomisd_xx, + [UCOMISD_IX] = asm_ucomisd_ix, + [COMISS] = asm_comiss_xx, + [COMISS_IX] = asm_comiss_ix, + [UCOMISS] = asm_ucomiss_xx, + [UCOMISS_IX] = asm_ucomiss_ix, + [CVTSI2SD] = asm_cvtsi2sd_rx, + [CVTSI2SS] = asm_cvtsi2ss_rx, + [CVTTSD2SI] = asm_cvttsd2si_xr, + [CVTTSS2SI] = asm_cvttss2si_xr, + [CVTSD2SS] = asm_cvtsd2ss_xx, + [CVTSS2SD] = asm_cvtss2sd_xx, + [SQRTSD] = asm_sqrtsd_xx, + [MOVQ_GP_XMM] = asm_movq_gpxmm, + [MOVQ_XMM_GP] = asm_movq_xmmgp, + [MOVQ_MEM_XMM] = asm_movq_ixmm, + [MOVQ_XMM_MEM] = asm_movq_xmmi, + [ENDBR64] = asm_endbr64, + + /* no-operand instructions */ + [NOP] = asm_simple, + [PUSHFQ] = asm_simple, + [POPFQ] = asm_simple, + [PUSHF] = asm_simple, + [POPF] = asm_simple, + [CPUID] = asm_simple, + [RDTSC] = asm_simple, + [UD2] = asm_simple, + [PAUSE] = asm_simple, + [HLT] = asm_simple, + [CMC] = asm_simple, + [CLC] = asm_simple, + [STC] = asm_simple, + [CLI] = asm_simple, + [STI] = asm_simple, + [CLD] = asm_simple, + [STD] = asm_simple, + [CLTS] = asm_simple, + [WBINVD] = asm_simple, + [MFENCE] = asm_simple, + [LFENCE] = asm_simple, + [SFENCE] = asm_simple, + + /* register instructions */ + [IMUL] = asm_imul_r, + [IMUL_RR] = asm_imul_rr, + [IMUL_IRR] = asm_imul_irr, + [LEAVE] = asm_leave, + [ENTER] = asm_enter, + [XCHG_RR] = asm_xchg_rr, + [XCHG_RI] = asm_xchg_ri, + [BSF] = asm_bsf, + [BSWAP] = asm_bswap, + [XADD_RR] = asm_xadd_rr, + [XADD_RI] = asm_xadd_ri, + [CMPXCHG_RR] = asm_cmpxchg_rr, + [CMPXCHG_RI] = asm_cmpxchg_ri, + + /* bit test */ + [BT_RR] = asm_bt_family, + [BTS_RR] = asm_bt_family, + [BTR_RR] = asm_bt_family, + [BTC_RR] = asm_bt_family, + + /* conditional move */ + [CMOVO] = asm_cmov_rr, + [CMOVNO] = asm_cmov_rr, + [CMOVB] = asm_cmov_rr, + [CMOVAE] = asm_cmov_rr, + [CMOVE] = asm_cmov_rr, + [CMOVNE] = asm_cmov_rr, + [CMOVBE] = asm_cmov_rr, + [CMOVA] = asm_cmov_rr, + [CMOVS] = asm_cmov_rr, + [CMOVNS] = asm_cmov_rr, + [CMOVP] = asm_cmov_rr, + [CMOVNP] = asm_cmov_rr, + [CMOVL] = asm_cmov_rr, + [CMOVGE] = asm_cmov_rr, + [CMOVLE] = asm_cmov_rr, + [CMOVG] = asm_cmov_rr, + + /* string operations */ + [MOVSB] = asm_string, + [MOVSW] = asm_string, + [MOVSL] = asm_string, + [MOVSQ] = asm_string, + [STOSB] = asm_string, + [STOSW] = asm_string, + [STOSL] = asm_string, + [STOSQ] = asm_string, + [LODSB] = asm_string, + [LODSW] = asm_string, + [LODSL] = asm_string, + [LODSQ] = asm_string, + [SCASB] = asm_string, + [SCASW] = asm_string, + [SCASL] = asm_string, + [SCASQ] = asm_string, + [CMPSB] = asm_string, + [CMPSW] = asm_string, + [CMPSL] = asm_string, + [CMPSQ] = asm_string, + + /* gas conversion aliases */ + [CBW] = asm_cbw, + [CDQE] = asm_cdqe, + [CWD] = asm_cwd, +}; + +void +assemble_inst(struct Inst *inst, struct ParseInfo *info, struct Code *code) +{ + code->flag = 0; + code->len = 0; + + unsigned char prefix = 0; + switch (inst->prefix) { + case 0: + break; + case PREFIX_LOCK: + prefix = 0xf0; + break; + case PREFIX_REP: + prefix = 0xf3; + break; + case PREFIX_REPNE: + prefix = 0xf2; + break; + default: + assemble_error(info, "invalid instruction prefix combination"); + return; + } + + const AsmInstFunc *func = NULL; + if (inst->op < (enum Opcode)ARRAY_SIZE(table)) { + func = &table[inst->op]; + + if (func != NULL) { + unsigned char *p = (*func)(inst, code); + if (p != NULL) { + if (p == code->buf) + p = code->buf + code->len; + if (p > code->buf) { + if (prefix != 0) { + size_t len = p - code->buf; + assert(len + 1 <= sizeof(code->buf)); + memmove(code->buf + 1, code->buf, len); + code->buf[0] = prefix; + p = code->buf + 1 + len; + } + code->inst = inst; + code->len = p - code->buf; + assert((size_t)code->len <= sizeof(code->buf)); + } + return; + } + } + } + + assemble_error(info, "Illegal operand"); +} diff --git a/cmd/dev/as/arch/x64/backend.c b/cmd/dev/as/arch/x64/backend.c @@ -0,0 +1,36 @@ +/* x64 arch backend: ties together tables, parser, encoder, and resolver */ + +#include "../../../config.h" +#include "arch.h" + +/* raw_op_table, parse_inst_table, parse_operand */ +#include "inst.h" +#include "parse_asm.h" + +/* table and function declarations from x64 backend sources */ +extern const char *kRawOpTable[]; +extern const struct ParseInstTable kParseInstTable[]; +extern unsigned int +parse_operand(struct ParseInfo *info, unsigned int opr_flag, struct Operand *operand); +extern void assemble_inst(struct Inst *inst, struct ParseInfo *info, struct Code *code); +extern void make_code(struct Inst *inst, struct Code *code, unsigned char *buf, int len); +extern unsigned char x64_scan_prefix(struct ParseInfo *info); +extern void x64_resolve_code_reloc( + struct IR *ir, + struct SectionInfo *section, + uint64_t address, + uint64_t start_address, + struct Table *label_table, + struct Vector *unresolved, + int *size_upgraded +); + +const struct arch_backend arch = { + .raw_op_table = kRawOpTable, + .parse_inst_table = kParseInstTable, + .scan_prefix = x64_scan_prefix, + .parse_operand = parse_operand, + .assemble_inst = assemble_inst, + .make_code = make_code, + .resolve_code_reloc = x64_resolve_code_reloc, +}; diff --git a/cmd/dev/as/arch/x64/inst.h b/cmd/dev/as/arch/x64/inst.h @@ -0,0 +1,679 @@ +/* x64 instruction set definitions */ + +#ifndef AS_ARCH_X64_INST_H +#define AS_ARCH_X64_INST_H + +#include "ir_asm.h" /* UNRES_ARCH_BASE */ + +#include <stdint.h> /* int64_t */ + +struct Expr; +struct Name; + +/* x64-specific unresolved relocation kinds */ +enum X64UnresolvedKind { + UNRES_X64_ABS32S = UNRES_ARCH_BASE, + UNRES_X64_ABS32, + UNRES_X64_GOT_LOAD, + UNRES_X64_TPOFF32, + UNRES_X64_GOTTPOFF, +}; + +/* instruction prefix flags */ +#define PREFIX_LOCK (1 << 0) +#define PREFIX_REP (1 << 1) +#define PREFIX_REPNE (1 << 2) + +enum Opcode { + NOOP, + MOV_RR, + MOV_IMR, + MOV_IR, + MOV_RI, + MOV_IIR, + MOV_RII, + MOV_DR, + MOV_RD, + MOV_SR, + MOVB_IMI, + MOVW_IMI, + MOVL_IMI, + MOVQ_IMI, + MOVB_IMD, + MOVW_IMD, + MOVL_IMD, + MOVQ_IMD, + MOVSX, + MOVZX, + /* sized extend forms. the gas mnemonics (movzbl, movswl, movslq, ...) + * fix the source size in the mnemonic itself, which the encoder needs + * when the source is a memory operand (a memory operand carries no + * size). each form below names the source width and signedness so a + * single encoder covers register and memory sources uniformly */ + MOVZX_B, + MOVZX_W, /* zero-extend byte / word source */ + MOVSX_B, + MOVSX_W, + MOVSX_LQ, /* sign-extend byte / word / long(source) source */ + LEA_IR, + LEA_IIR, + + ADD_RR, + ADD_IMR, + ADD_IR, + ADD_IIR, + ADDQ, + SUB_RR, + SUB_IMR, + SUB_IR, + SUB_IIR, + SUBQ, + MUL, + IMUL, + DIV, + IDIV, + NEG, + NOT, + INC, + INCB, + INCW, + INCL, + INCQ, + DEC, + DECB, + DECW, + DECL, + DECQ, + AND_RR, + AND_IMR, + OR_RR, + OR_IMR, + XOR_RR, + XOR_IMR, + SHL_RR, + SHL_IMR, + SHR_RR, + SHR_IMR, + SAR_RR, + SAR_IMR, + CMP_RR, + CMP_IMR, + TEST, + XCHG_RR, + XCHG_RI, + CWTL, + CLTD, + CQTO, + BSR, + LZCNT, + TZCNT, + POPCNT, + + SETO, + SETNO, + SETB, + SETAE, + SETE, + SETNE, + SETBE, + SETA, + SETS, + SETNS, + SETP, + SETNP, + SETL, + SETGE, + SETLE, + SETG, + + JMP_D, + JMP_DER, + JMP_DEI, + JMP_DEII, + JO, + JNO, + JB, + JAE, + JE, + JNE, + JBE, + JA, + JS, + JNS, + JP, + JNP, + JL, + JGE, + JLE, + JG, + CALL_D, + CALL_DER, + RET, + LEAVE, + PUSH_R, + PUSH_IM, + POP, + + INT, + SYSCALL, + + MOVSD_XX, + MOVSD_IX, + MOVSD_XI, + ADDSD, + SUBSD, + MULSD, + DIVSD, + XORPD, + XORPD_IX, + COMISD, + COMISD_IX, + UCOMISD, + UCOMISD_IX, + CVTSI2SD, + CVTTSD2SI, + SQRTSD, + MOVQ_GP_XMM, + MOVQ_XMM_GP, + MOVQ_MEM_XMM, + MOVQ_XMM_MEM, + + MOVSS_XX, + MOVSS_IX, + MOVSS_XI, + ADDSS, + SUBSS, + MULSS, + DIVSS, + XORPS, + XORPS_IX, + COMISS, + COMISS_IX, + UCOMISS, + UCOMISS_IX, + CVTSI2SS, + CVTTSS2SI, + CVTSD2SS, + CVTSS2SD, + + ENDBR64, + + /* no-operand instructions */ + NOP, + PUSHFQ, + POPFQ, + PUSHF, + POPF, + CPUID, + RDTSC, + UD2, + PAUSE, + HLT, + CMC, + CLC, + STC, + CLI, + STI, + CLD, + STD, + CLTS, + WBINVD, + MFENCE, + LFENCE, + SFENCE, + + /* register instructions */ + IMUL_RR, + IMUL_IRR, + BSF, + BSWAP, + XADD_RR, + XADD_RI, + CMPXCHG_RR, + CMPXCHG_RI, + + /* bit test family */ + BT_RR, + BTS_RR, + BTR_RR, + BTC_RR, + + /* conditional move */ + CMOVO, + CMOVNO, + CMOVB, + CMOVAE, + CMOVE, + CMOVNE, + CMOVBE, + CMOVA, + CMOVS, + CMOVNS, + CMOVP, + CMOVNP, + CMOVL, + CMOVGE, + CMOVLE, + CMOVG, + + /* string operations */ + MOVSB, + MOVSW, + MOVSL, + MOVSQ, + STOSB, + STOSW, + STOSL, + STOSQ, + LODSB, + LODSW, + LODSL, + LODSQ, + SCASB, + SCASW, + SCASL, + SCASQ, + CMPSB, + CMPSW, + CMPSL, + CMPSQ, + + /* gas intel-syntax conversion aliases */ + CBW, + CDQE, + CWD, + + /* misc */ + ENTER, + + /* sse packed single-precision float (no prefix) */ + ADDPS, + MULPS, + SUBPS, + MINPS, + MAXPS, + DIVPS, + SQRTPS, + RCPPS, + RSQRTPS, + ANDPS, + ORPS, + XORNPS, + ANDNPS, + CMPPS, + MOVAPS_RR, + MOVAPS_RM, + MOVAPS_MR, + MOVUPS_RR, + MOVUPS_RM, + MOVUPS_MR, + HADDPS, + HSUBPS, + ADDSUBPS, + + /* sse2 packed double-precision float (66 prefix) */ + ADDPD, + MULPD, + SUBPD, + MINPD, + MAXPD, + DIVPD, + SQRTPD, + ANDPD, + ORPD, + XORPD2, + ANDNPD, + CMPPD, + MOVAPD_RR, + MOVAPD_RM, + MOVAPD_MR, + MOVUPD_RR, + MOVUPD_RM, + MOVUPD_MR, + HADDPD, + HSUBPD, + ADDSUBPD, + + /* sse2 packed integer (66 prefix) */ + PADDB, + PADDW, + PADDD, + PADDQ, + PSUBB, + PSUBW, + PSUBD, + PSUBQ, + PMULLW, + PMULHW, + PAND, + POR, + PXOR, + PANDN, + PCMPEQB, + PCMPEQW, + PCMPEQD, + PCMPGTB, + PCMPGTW, + PCMPGTD, + PSLLW_R, + PSLLW_I, + PSRLW_R, + PSRLW_I, + PSRAW_R, + PSRAW_I, + PSLLD_R, + PSLLD_I, + PSRLD_R, + PSRLD_I, + PSRAD_R, + PSRAD_I, + PSLLQ_R, + PSLLQ_I, + PSRLQ_R, + PSRLQ_I, + PMAXUB, + PMINUB, + PMAXSW, + PMINSW, + PSHUFD, + PUNPCKLBW, + PUNPCKLWD, + PUNPCKLDQ, + PUNPCKLQDQ, + PUNPCKHBW, + PUNPCKHWD, + PUNPCKHDQ, + PUNPCKHQDQ, + PACKUSWB, + PACKSSWB, + PACKSSDW, + MOVDQA_RR, + MOVDQA_RM, + MOVDQA_MR, + MOVDQU_RR, + MOVDQU_RM, + MOVDQU_MR, + PEXTRW, + PINSRW, + PMOVMSKB, + + /* avx packed single (vex, pp=00) */ + VADDPS, + VMULPS, + VSUBPS, + VMINPS, + VMAXPS, + VDIVPS, + VSQRTPS, + VANDPS, + VORPS, + VXORPS, + VMOVAPS, + VMOVUPS, + + /* avx packed double (vex, pp=01) */ + VADDPD, + VMULPD, + VSUBPD, + VMINPD, + VMAXPD, + VDIVPD, + VSQRTPD, + VANDPD, + VORPD, + VXORPD, + VMOVAPD, + VMOVUPD, + + /* avx packed integer (vex, pp=01) */ + VPADDB, + VPADDW, + VPADDD, + VPADDQ, + VPSUBB, + VPSUBW, + VPSUBD, + VPSUBQ, + VPAND, + VPOR, + VPXOR, + VPANDN, + VPCMPEQB, + VPCMPEQW, + VPCMPEQD, + VPSLLW_I, + VPSRLW_I, + VPSRAW_I, + VPSLLD_I, + VPSRLD_I, + VPSRAD_I, + VPSLLQ_I, + VPSRLQ_I, + VPSHUFD, + VMOVDQA, + VMOVDQU, + VPMAXUB, + VPMINUB, + VPMAXSW, + VPMINSW, + VPEXTRW, + VPINSRW, + VPMOVMSKB, + + /* avx misc */ + VZEROUPPER, + VZEROALL, + VBLENDPS, + VBLENDPD, + VBROADCASTSS, + VBROADCASTSD, + VBROADCASTF128, +}; + +enum RegType { + NOREG = -1, + + /* 8bit */ + AL, + CL, + DL, + BL, + /* 8bit (high) */ + AH, + CH, + DH, + BH, + + /* 8bit */ + R8B, + R9B, + R10B, + R11B, + R12B, + R13B, + R14B, + R15B, + + /* 8bit: corresponds to AH~ in lower 4bit to handle easily */ + SPL = R15B + 1 + 4, + BPL, + SIL, + DIL, + + /* 16bit */ + AX, + CX, + DX, + BX, + SP, + BP, + SI, + DI, + R8W, + R9W, + R10W, + R11W, + R12W, + R13W, + R14W, + R15W, + + /* 32bit */ + EAX, + ECX, + EDX, + EBX, + ESP, + EBP, + ESI, + EDI, + R8D, + R9D, + R10D, + R11D, + R12D, + R13D, + R14D, + R15D, + + /* 64bit */ + RAX, + RCX, + RDX, + RBX, + RSP, + RBP, + RSI, + RDI, + R8, + R9, + R10, + R11, + R12, + R13, + R14, + R15, + RIP, + + /* segment register */ + CS, + DS, + ES, + FS, + GS, + SS, +}; + +enum RegXmmType { + NOREGXMM = -1, + XMM0, + XMM1, + XMM2, + XMM3, + XMM4, + XMM5, + XMM6, + XMM7, + XMM8, + XMM9, + XMM10, + XMM11, + XMM12, + XMM13, + XMM14, + XMM15, +}; + +/* ymm registers share the same numbering as xmm, distinguished by + * a separate type so the encoder knows the vector length */ +enum RegYmmType { + NOREGYMM = -1, + YMM0, + YMM1, + YMM2, + YMM3, + YMM4, + YMM5, + YMM6, + YMM7, + YMM8, + YMM9, + YMM10, + YMM11, + YMM12, + YMM13, + YMM14, + YMM15, +}; + +enum RegSize { + REG8, + REG16, + REG32, + REG64, +}; + +struct Reg { + char size; /* regsize */ + char no; /* 0~7, or RIP */ + char x; /* 0 or 1, (or 2 if size == REG8, SPL~DIL) */ +}; + +enum OperandType { + NOOPERAND, + REG, /* %rax */ + INDIRECT, /* ofs(%rax) */ + INDIRECT_WITH_INDEX, /* ofs(%rax, %rcx, 4) */ + IMMEDIATE, /* $1234 */ + DIRECT, /* foobar */ + DEREF_REG, /* *%rax */ + DEREF_INDIRECT, /* *ofs(%rax) */ + DEREF_INDIRECT_WITH_INDEX, /* *(%rax, %rcx, 4) */ + REG_XMM, + REG_YMM, + SEGMENT_OFFSET, +}; + +#define LF_GOTPCREL (1 << 0) +#define LF_TPOFF (1 << 1) /* sym@tpoff, local-exec tls offset */ +#define LF_GOTTPOFF (1 << 2) /* sym@gottpoff, initial-exec tls got slot */ + +struct ExprWithFlag { + struct Expr *expr; + int flag; +}; + +struct Operand { + enum OperandType type; + union { + struct Reg reg; + int64_t immediate; + struct { + struct Expr *expr; + } direct; + struct { + struct ExprWithFlag offset; + struct Reg reg; + } indirect; + struct { + struct Expr *offset; + struct Expr *scale; + struct Reg base_reg; + struct Reg index_reg; + } indirect_with_index; + enum RegXmmType regxmm; + enum RegYmmType regymm; + struct { + enum RegType reg; + struct ExprWithFlag offset; + } segment; + }; +}; + +struct Inst { + enum Opcode op; + unsigned char prefix; /* PREFIX_LOCK, PREFIX_REP, etc */ + struct Operand opr[3]; /* src, dst, dst2 (for 3-operand vex) */ +}; + +#endif /* AS_ARCH_X64_INST_H */ diff --git a/cmd/dev/as/arch/x64/parse_x64.c b/cmd/dev/as/arch/x64/parse_x64.c @@ -0,0 +1,2018 @@ +#include "../../../config.h" + +#include "arch.h" +#include "parse_asm.h" + +#include <assert.h> +#include <ctype.h> +#include <stddef.h> +#include <string.h> +#include <strings.h> + +#include "inst.h" +#include "tcutil.h" + +enum RawOpcode { + R_NOOP, + R_MOV, + R_MOVB, + R_MOVW, + R_MOVL, + R_MOVQ, + R_MOVSX, + R_MOVZX, + R_LEA, + + R_ADD, + R_ADDQ, + R_SUB, + R_SUBQ, + R_MUL, + R_DIV, + R_IDIV, + R_NEG, + R_NOT, + R_INC, + R_INCB, + R_INCW, + R_INCL, + R_INCQ, + R_DEC, + R_DECB, + R_DECW, + R_DECL, + R_DECQ, + R_AND, + R_OR, + R_XOR, + R_SHL, + R_SHR, + R_SAR, + R_CMP, + R_TEST, + R_CWTL, + R_CLTD, + R_CQTO, + R_BSR, + R_LZCNT, + R_TZCNT, + R_POPCNT, + + R_SETO, + R_SETNO, + R_SETB, + R_SETAE, + R_SETE, + R_SETNE, + R_SETBE, + R_SETA, + R_SETS, + R_SETNS, + R_SETP, + R_SETNP, + R_SETL, + R_SETGE, + R_SETLE, + R_SETG, + + R_JMP, + R_JO, + R_JNO, + R_JB, + R_JAE, + R_JE, + R_JNE, + R_JBE, + R_JA, + R_JS, + R_JNS, + R_JP, + R_JNP, + R_JL, + R_JGE, + R_JLE, + R_JG, + R_CALL, + R_RET, + R_PUSH, + R_POP, + + R_INT, + R_SYSCALL, + + R_MOVSD, + R_ADDSD, + R_SUBSD, + R_MULSD, + R_DIVSD, + R_XORPD, + R_COMISD, + R_UCOMISD, + R_CVTSI2SD, + R_CVTTSD2SI, + R_SQRTSD, + + R_MOVSS, + R_ADDSS, + R_SUBSS, + R_MULSS, + R_DIVSS, + R_XORPS, + R_COMISS, + R_UCOMISS, + R_CVTSI2SS, + R_CVTTSS2SI, + R_CVTSD2SS, + R_CVTSS2SD, + + R_ENDBR64, + + /* no-operand instructions */ + R_NOP, + R_PUSHFQ, + R_POPFQ, + R_PUSHF, + R_POPF, + R_CPUID, + R_RDTSC, + R_UD2, + R_PAUSE, + R_HLT, + R_CMC, + R_CLC, + R_STC, + R_CLI, + R_STI, + R_CLD, + R_STD, + R_CLTS, + R_WBINVD, + R_MFENCE, + R_LFENCE, + R_SFENCE, + + /* register instructions */ + R_IMUL, + R_BSF, + R_BSWAP, + R_XADD, + R_CMPXCHG, + R_LEAVE, + R_ENTER, + R_XCHG, + + /* bit test */ + R_BT, + R_BTS, + R_BTR, + R_BTC, + + /* conditional move */ + R_CMOVO, + R_CMOVNO, + R_CMOVB, + R_CMOVAE, + R_CMOVE, + R_CMOVNE, + R_CMOVBE, + R_CMOVA, + R_CMOVS, + R_CMOVNS, + R_CMOVP, + R_CMOVNP, + R_CMOVL, + R_CMOVGE, + R_CMOVLE, + R_CMOVG, + + /* string operations */ + R_MOVSB, + R_MOVSW, + R_MOVSL, + R_MOVSQ, + R_STOSB, + R_STOSW, + R_STOSL, + R_STOSQ, + R_LODSB, + R_LODSW, + R_LODSL, + R_LODSQ, + R_SCASB, + R_SCASW, + R_SCASL, + R_SCASQ, + R_CMPSB, + R_CMPSW, + R_CMPSL, + R_CMPSQ, + + /* gas conversion aliases */ + R_CBW, + R_CDQE, + R_CWD, + + /* condition code aliases accepted by gas */ + R_JC, + R_JNAE, + R_JNB, + R_JZ, + R_JNZ, + R_JNA, + R_JNBE, + R_JNGE, + R_JNL, + R_JNG, + R_JNLE, + R_JPE, + R_JPO, + R_CMOVZ, + R_CMOVNZ, + + /* gas-style explicit size suffixes that qbe's amd64_sysv backend + * emits, which this table otherwise only has for mov/inc/dec. + * appended instead of inserted next to their unsuffixed siblings, + * because kRawOpTable's array position is the enum value (see + * find_raw_opcode's i + 1 return) and an insertion would shift every + * later opcode */ + R_MOVSLQ, + R_MOVSBW, + R_MOVSBL, + R_MOVSBQ, + R_MOVSWL, + R_MOVSWQ, + R_MOVZBW, + R_MOVZBL, + R_MOVZBQ, + R_MOVZWL, + R_MOVZWQ, + R_LEAQ, + R_ADDL, + R_SUBL, + R_IDIVL, + R_ANDL, + R_ANDQ, + R_ORL, + R_ORQ, + R_SHLL, + R_SHLQ, + R_SHRL, + R_SHRQ, + R_SARL, + R_SARQ, + R_CMPL, + R_CMPQ, + R_CALLQ, + R_PUSHQ, + R_POPQ, + R_CVTTSD2SIL, + R_CVTTSD2SIQ, + R_CVTTSS2SIL, + R_CVTTSS2SIQ, + R_XCHGL, + R_XCHGQ, + R_SETZ, + R_SETNZ, + R_XORL, + R_XORQ, + R_NEGL, + R_NEGQ, +}; + +const char *kRawOpTable[] = { + "mov", + "movb", + "movw", + "movl", + "movq", + "movsx", + "movzx", + "lea", + + "add", + "addq", + "sub", + "subq", + "mul", + "div", + "idiv", + "neg", + "not", + "inc", + "incb", + "incw", + "incl", + "incq", + "dec", + "decb", + "decw", + "decl", + "decq", + "and", + "or", + "xor", + "shl", + "shr", + "sar", + "cmp", + "test", + "cwtl", + "cltd", + "cqto", + "bsr", + "lzcnt", + "tzcnt", + "popcnt", + + "seto", + "setno", + "setb", + "setae", + "sete", + "setne", + "setbe", + "seta", + "sets", + "setns", + "setp", + "setnp", + "setl", + "setge", + "setle", + "setg", + + "jmp", + "jo", + "jno", + "jb", + "jae", + "je", + "jne", + "jbe", + "ja", + "js", + "jns", + "jp", + "jnp", + "jl", + "jge", + "jle", + "jg", + "call", + "ret", + "push", + "pop", + + "int", + "syscall", + + "movsd", + "addsd", + "subsd", + "mulsd", + "divsd", + "xorpd", + "comisd", + "ucomisd", + "cvtsi2sd", + "cvttsd2si", + "sqrtsd", + + "movss", + "addss", + "subss", + "mulss", + "divss", + "xorps", + "comiss", + "ucomiss", + "cvtsi2ss", + "cvttss2si", + "cvtsd2ss", + "cvtss2sd", + + "endbr64", + + /* no-operand */ + "nop", + "pushfq", + "popfq", + "pushf", + "popf", + "cpuid", + "rdtsc", + "ud2", + "pause", + "hlt", + "cmc", + "clc", + "stc", + "cli", + "sti", + "cld", + "std", + "clts", + "wbinvd", + "mfence", + "lfence", + "sfence", + + /* register instructions */ + "imul", + "bsf", + "bswap", + "xadd", + "cmpxchg", + "leave", + "enter", + "xchg", + + /* bit test */ + "bt", + "bts", + "btr", + "btc", + + /* conditional move */ + "cmovo", + "cmovno", + "cmovb", + "cmovae", + "cmove", + "cmovne", + "cmovbe", + "cmova", + "cmovs", + "cmovns", + "cmovp", + "cmovnp", + "cmovl", + "cmovge", + "cmovle", + "cmovg", + + /* string operations */ + "movsb", + "movsw", + "movsl", + "movsq", + "stosb", + "stosw", + "stosl", + "stosq", + "lodsb", + "lodsw", + "lodsl", + "lodsq", + "scasb", + "scasw", + "scasl", + "scasq", + "cmpsb", + "cmpsw", + "cmpsl", + "cmpsq", + + /* gas conversion aliases */ + "cbw", + "cdqe", + "cwd", + + /* condition code aliases */ + "jc", + "jnae", + "jnb", + "jz", + "jnz", + "jna", + "jnbe", + "jnge", + "jnl", + "jng", + "jnle", + "jpe", + "jpo", + "cmovz", + "cmovnz", + + /* must stay in the same order as the R_* additions appended to + * enum RawOpcode above, this array's position doubles as that + * enum's value */ + "movslq", + "movsbw", + "movsbl", + "movsbq", + "movswl", + "movswq", + "movzbw", + "movzbl", + "movzbq", + "movzwl", + "movzwq", + "leaq", + "addl", + "subl", + "idivl", + "andl", + "andq", + "orl", + "orq", + "shll", + "shlq", + "shrl", + "shrq", + "sarl", + "sarq", + "cmpl", + "cmpq", + "callq", + "pushq", + "popq", + "cvttsd2sil", + "cvttsd2siq", + "cvttss2sil", + "cvttss2siq", + "xchgl", + "xchgq", + "setz", + "setnz", + "xorl", + "xorq", + "negl", + "negq", + NULL, +}; + +static const struct { + const char *name; + enum RegType reg; +} kRegisters[] = { + /* 8bit */ + {"al", AL}, + {"cl", CL}, + {"dl", DL}, + {"bl", BL}, + {"ah", AH}, + {"ch", CH}, + {"dh", DH}, + {"bh", BH}, + {"r8b", R8B}, + {"r9b", R9B}, + {"r10b", R10B}, + {"r11b", R11B}, + {"r12b", R12B}, + {"r13b", R13B}, + {"r14b", R14B}, + {"r15b", R15B}, + {"spl", SPL}, + {"bpl", BPL}, + {"sil", SIL}, + {"dil", DIL}, + + /* 16bit */ + {"ax", AX}, + {"cx", CX}, + {"dx", DX}, + {"bx", BX}, + {"sp", SP}, + {"bp", BP}, + {"si", SI}, + {"di", DI}, + {"r8w", R8W}, + {"r9w", R9W}, + {"r10w", R10W}, + {"r11w", R11W}, + {"r12w", R12W}, + {"r13w", R13W}, + {"r14w", R14W}, + {"r15w", R15W}, + + /* 32bit */ + {"eax", EAX}, + {"ecx", ECX}, + {"edx", EDX}, + {"ebx", EBX}, + {"esp", ESP}, + {"ebp", EBP}, + {"esi", ESI}, + {"edi", EDI}, + {"r8d", R8D}, + {"r9d", R9D}, + {"r10d", R10D}, + {"r11d", R11D}, + {"r12d", R12D}, + {"r13d", R13D}, + {"r14d", R14D}, + {"r15d", R15D}, + + /* 64bit */ + {"rax", RAX}, + {"rcx", RCX}, + {"rdx", RDX}, + {"rbx", RBX}, + {"rsp", RSP}, + {"rbp", RBP}, + {"rsi", RSI}, + {"rdi", RDI}, + {"r8", R8}, + {"r9", R9}, + {"r10", R10}, + {"r11", R11}, + {"r12", R12}, + {"r13", R13}, + {"r14", R14}, + {"r15", R15}, + {"rip", RIP}, + + /* segment register */ + {"cs", CS}, + {"ds", DS}, + {"es", ES}, + {"fs", FS}, + {"gs", GS}, + {"ss", SS}, +}; + +static const char kXmmRegisters[][6] = { + "xmm0", + "xmm1", + "xmm2", + "xmm3", + "xmm4", + "xmm5", + "xmm6", + "xmm7", + "xmm8", + "xmm9", + "xmm10", + "xmm11", + "xmm12", + "xmm13", + "xmm14", + "xmm15", +}; + +static inline int +is_reg8(enum RegType reg) +{ + return reg >= AL && reg <= DIL; +} + +static inline int +is_reg16(enum RegType reg) +{ + return reg >= AX && reg <= R15W; +} + +static inline int +is_reg32(enum RegType reg) +{ + return reg >= EAX && reg <= R15D; +} + +static inline int +is_reg64(enum RegType reg) +{ + return reg >= RAX && reg <= R15; +} + +static inline int +is_segment(enum RegType reg) +{ + return reg >= CS && reg <= SS; +} + +#define R8 (1 << 0) +#define R16 (1 << 1) +#define R32 (1 << 2) +#define R64 (1 << 3) +#define R8CL (1 << 4) +#define IMM (1 << 5) +#define EXP (1 << 6) +#define IND (1 << 7) +#define IIND (1 << 8) +#define DER (1 << 9) /* deref reg64 */ +#define DEI (1 << 10) /* deref indirect */ +#define DEII (1 << 11) /* deref indirect with index */ +#define XMM (1 << 12) +#define SEG (1 << 13) +#define YMM (1 << 14) + +/* scan for x86 instruction prefix keywords */ +unsigned char +x64_scan_prefix(struct ParseInfo *info) +{ + static const struct { + const char *name; + unsigned char flag; + } prefixes[] = { + {"lock", PREFIX_LOCK}, + {"rep", PREFIX_REP}, + {"repe", PREFIX_REP}, + {"repz", PREFIX_REP}, + {"repne", PREFIX_REPNE}, + {"repnz", PREFIX_REPNE}, + }; + const char *p = info->p; + const char *start = p; + while (isalnum(*p) || *p == '.') + ++p; + size_t n = p - start; + if (n > 0 && (*p == '\0' || isspace(*p))) { + for (int i = 0; i < (int)ARRAY_SIZE(prefixes); ++i) { + if (n == strlen(prefixes[i].name) && strncasecmp(start, prefixes[i].name, n) == 0) { + info->p = skip_whitespaces(p); + return prefixes[i].flag; + } + } + } + return 0; +} + +static enum RegType +find_register(const char **pp) +{ + const char *p = *pp; + for (int i = 0; i < (int)ARRAY_SIZE(kRegisters); ++i) { + const char *name = kRegisters[i].name; + size_t n = strlen(name); + if (strncasecmp(p, name, n) == 0 && !is_label_chr(p[n])) { + *pp = p + n; + return kRegisters[i].reg; + } + } + return NOREG; +} + +static enum RegXmmType +find_xmm_register(const char **pp) +{ + const char *p = *pp; + const char *q; + for (q = p; isalnum(*q); ++q) + ; + size_t l = q - p; + + for (int i = 0; i < (int)ARRAY_SIZE(kXmmRegisters); ++i) { + const char *name = kXmmRegisters[i]; + size_t n = strlen(name); + if (l == n && strncasecmp(p, name, n) == 0) { + *pp = p + n; + return i + XMM0; + } + } + return NOREGXMM; +} + +static unsigned int +parse_direct_register(struct ParseInfo *info, struct Operand *operand) +{ + { + enum RegXmmType regxmm = find_xmm_register(&info->p); + if (regxmm != NOREGXMM) { + operand->type = REG_XMM; + operand->regxmm = regxmm; + return XMM; + } + } + + enum RegType reg = find_register(&info->p); + if (is_segment(reg)) { + struct Expr *offset = NULL; + int flag = 0; + if (*info->p == ':') { + ++info->p; + offset = parse_expr(info); + if (strncasecmp(info->p, "@tpoff", 6) == 0 && !is_label_chr(info->p[6])) { + info->p += 6; + flag = LF_TPOFF; + } + } + operand->type = SEGMENT_OFFSET; + operand->segment.reg = reg; + operand->segment.offset.expr = offset; + operand->segment.offset.flag = flag; + return SEG; + } + + enum RegSize size; + int no; + if (is_reg8(reg)) { + size = REG8; + no = reg - AL; + } else if (is_reg16(reg)) { + size = REG16; + no = reg - AX; + } else if (is_reg32(reg)) { + size = REG32; + no = reg - EAX; + } else if (is_reg64(reg)) { + size = REG64; + no = reg - RAX; + } else { + parse_error(info, "illegal register"); + return 0; + } + + operand->type = REG; + operand->reg.size = size; + operand->reg.no = no & 7; + operand->reg.x = no >> 3; + return (R8 << (size - REG8)) | (reg == CL ? R8CL : 0); +} + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +static int +parse_label_postfix(struct ParseInfo *info) +{ + static struct { + const char *name; + int flag; + } const kPostfixes[] = { + {"@gotpcrel", LF_GOTPCREL}, + }; + const char *p = info->p; + for (size_t i = 0; i < ARRAY_SIZE(kPostfixes); ++i) { + const char *name = kPostfixes[i].name; + size_t n = strlen(name); + if (strncasecmp(p, name, n) == 0 && !is_label_chr(p[n])) { + info->p = p + n; + return kPostfixes[i].flag; + } + } + return 0; +} +#endif + +static struct ExprWithFlag +parse_expr_with_flag(struct ParseInfo *info) +{ + /* expr = label + nn */ +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + /* expr@page */ + /* expr@pageoff */ + /* expr@gotpage */ + /* expr@gotpageoff */ + struct Expr *expr = parse_expr(info); + int flag = parse_label_postfix(info); +#else + int flag = 0; + struct Expr *expr = parse_expr(info); +#endif + return (struct ExprWithFlag){expr, flag}; +} + +static unsigned int +parse_indirect_register( + struct ParseInfo *info, struct ExprWithFlag *offset, struct Operand *operand +) +{ + enum RegType index_reg = NOREG; + struct Expr *scale = NULL; + /* already read "(%" */ + enum RegType base_reg = find_register(&info->p); + + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if (*info->p != '%' || (++info->p, index_reg = find_register(&info->p), !is_reg64(index_reg))) + parse_error(info, "register expected"); + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + scale = parse_expr(info); + if (scale->kind != EX_FIXNUM) + parse_error(info, "constant value expected"); + info->p = skip_whitespaces(info->p); + } + } + if (*info->p != ')') + parse_error(info, "`)' expected"); + else + ++info->p; + + if (!(is_reg64(base_reg) || (base_reg == RIP && index_reg == NOREG))) + parse_error(info, "register expected"); + + if (index_reg == NOREG) { + char no = base_reg - RAX; + operand->type = INDIRECT; + operand->indirect.reg.size = REG64; + operand->indirect.reg.no = base_reg != RIP ? no & 7 : RIP; + operand->indirect.reg.x = (no & 8) >> 3; + operand->indirect.offset = *offset; + return IND; + } else { + if (!is_reg64(index_reg)) + parse_error(info, "register expected"); + + operand->type = INDIRECT_WITH_INDEX; + operand->indirect_with_index.offset = offset->expr; + operand->indirect_with_index.scale = scale; + char base_no = base_reg - RAX; + operand->indirect_with_index.base_reg.size = REG64; + operand->indirect_with_index.base_reg.no = base_no & 7; + operand->indirect_with_index.base_reg.x = (base_no & 8) >> 3; + char index_no = index_reg - RAX; + operand->indirect_with_index.index_reg.size = REG64; + operand->indirect_with_index.index_reg.no = index_no & 7; + operand->indirect_with_index.index_reg.x = (index_no & 8) >> 3; + return IIND; + } +} + +static enum RegType +parse_deref_register(struct ParseInfo *info, struct Operand *operand) +{ + enum RegType reg = find_register(&info->p); + if (!is_reg64(reg)) + parse_error(info, "illegal register"); + + char no = reg - RAX; + operand->type = DEREF_REG; + operand->reg.size = REG64; + operand->reg.no = no & 7; + operand->reg.x = (no & 8) >> 3; + return 1; +} + +static unsigned int +parse_deref_indirect(struct ParseInfo *info, struct Operand *operand) +{ + struct Expr *offset = parse_expr(info); + info->p = skip_whitespaces(info->p); + if (*info->p != '(') { + parse_error(info, "direct number not implemented"); + return 0; + } + if (info->p[1] != '%') { + parse_error(info, "register expected"); + return 0; + } + info->p += 2; + + enum RegType index_reg = NOREG; + struct Expr *scale = NULL; + /* already read "(%" */ + enum RegType base_reg = find_register(&info->p); + + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if (*info->p != '%' || (++info->p, index_reg = find_register(&info->p), !is_reg64(index_reg))) + parse_error(info, "register expected"); + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + scale = parse_expr(info); + if (scale->kind != EX_FIXNUM) + parse_error(info, "constant value expected"); + info->p = skip_whitespaces(info->p); + } + } + if (*info->p != ')') + parse_error(info, "`)' expected"); + else + ++info->p; + + if (!is_reg64(base_reg) || (index_reg != NOREG && !is_reg64(index_reg))) + parse_error(info, "register expected"); + + if (index_reg == NOREG) { + operand->type = DEREF_INDIRECT; + operand->indirect.offset.expr = offset; + operand->indirect.offset.flag = 0; + char reg_no = base_reg - RAX; + operand->indirect.reg.size = REG64; + operand->indirect.reg.no = reg_no & 7; + operand->indirect.reg.x = (reg_no & 8) >> 3; + return DEI; + } else { + operand->type = DEREF_INDIRECT_WITH_INDEX; + operand->indirect_with_index.offset = offset; + operand->indirect_with_index.scale = scale; + char base_no = base_reg - RAX; + operand->indirect_with_index.base_reg.size = REG64; + operand->indirect_with_index.base_reg.no = base_no & 7; + operand->indirect_with_index.base_reg.x = (base_no & 8) >> 3; + operand->indirect_with_index.index_reg.size = REG64; + char index_no = index_reg - RAX; + operand->indirect_with_index.index_reg.size = REG64; + operand->indirect_with_index.index_reg.no = index_no & 7; + operand->indirect_with_index.index_reg.x = (index_no & 8) >> 3; + return DEII; + } +} + +unsigned int +parse_operand(struct ParseInfo *info, unsigned int opr_flag, struct Operand *operand) +{ + const char *p = info->p; + if (opr_flag & (R8 | R16 | R32 | R64 | R8CL | XMM)) { + if (*p == '%') { + info->p = p + 1; + return parse_direct_register(info, operand) & opr_flag; + } + } + + if (opr_flag & (DER | DEI)) { + if (*p == '*') { + if (opr_flag & DER) { + if (p[1] == '%') { + info->p = p + 2; + if (parse_deref_register(info, operand)) + return DER; + } + } + if (opr_flag & DEI) { + info->p = p + 1; + return parse_deref_indirect(info, operand); + } + } + } + + if (opr_flag & IMM) { + if (*p == '$') { + info->p = p + 1; + if (!immediate(&info->p, &operand->immediate)) + parse_error(info, "syntax error"); + operand->type = IMMEDIATE; + return IMM; + } + } + + struct ExprWithFlag expr_with_flag = parse_expr_with_flag(info); + if (*info->p == '@') { + /* relocation suffix (@plt, @got, @gotpcrel, @gottpoff, ...): this + * toolchain is static-only, so a direct call/jump target needs + * nothing beyond the bare symbol. @gottpoff is the exception: an + * initial-exec tls load through (%rip) is still a got lookup in a + * static binary, so it is kept as a flag */ + if (strncasecmp(info->p, "@gottpoff", 9) == 0 && !is_label_chr(info->p[9])) { + expr_with_flag.flag |= LF_GOTTPOFF; + info->p += 9; + } else { + const char *q = info->p + 1; + while (isalpha((unsigned char)*q) || isdigit((unsigned char)*q)) + ++q; + info->p = q; + } + } + info->p = skip_whitespaces(info->p); + if (*info->p != '(') { + if (expr_with_flag.expr != NULL) { + if (expr_with_flag.expr->kind == EX_LABEL || expr_with_flag.expr->kind == EX_FIXNUM + || expr_with_flag.expr->kind == EX_ADD || expr_with_flag.expr->kind == EX_SUB) { + operand->type = DIRECT; + operand->direct.expr = expr_with_flag.expr; + return EXP; + } + parse_error(info, "direct number not implemented"); + } + } else { + if (info->p[1] == '%') { + info->p += 2; + if (expr_with_flag.expr == NULL) { + struct Expr *expr = calloc_or_die(sizeof(*expr)); + expr->kind = EX_FIXNUM; + expr->fixnum = 0; + expr_with_flag.expr = expr; + } + return parse_indirect_register(info, &expr_with_flag, operand); + } + } + + return 0; +} + +const struct ParseInstTable kParseInstTable[] = { + [R_MOV] = + {11, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOV_RR, {R8, R8}}, + &(struct ParseOpArray){MOV_RR, {R16, R16}}, + &(struct ParseOpArray){MOV_RR, {R32, R32}}, + &(struct ParseOpArray){MOV_RR, {R64, R64}}, + &(struct ParseOpArray){MOV_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){MOV_IR, {IND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){MOV_RI, {R8 | R16 | R32 | R64, IND}}, + &(struct ParseOpArray){MOV_IIR, {IIND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){MOV_DR, {EXP, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){MOV_RD, {R8 | R16 | R32 | R64, EXP}}, + &(struct ParseOpArray){MOV_SR, {SEG, R32 | R64}}, + }}, + [R_MOVB] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVB_IMI, {IMM, IND}}, + &(struct ParseOpArray){MOVB_IMD, {IMM, EXP}}, + &(struct ParseOpArray){MOV_IR, {IND, R8}}, + &(struct ParseOpArray){MOV_RI, {R8, IND}}, + &(struct ParseOpArray){MOV_RR, {R8, R8}}, + &(struct ParseOpArray){MOV_IMR, {IMM, R8}}, + &(struct ParseOpArray){MOV_IIR, {IIND, R8}}, + }}, + [R_MOVW] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVW_IMI, {IMM, IND}}, + &(struct ParseOpArray){MOVW_IMD, {IMM, EXP}}, + &(struct ParseOpArray){MOV_IR, {IND, R16}}, + &(struct ParseOpArray){MOV_RI, {R16, IND}}, + &(struct ParseOpArray){MOV_RR, {R16, R16}}, + &(struct ParseOpArray){MOV_IMR, {IMM, R16}}, + &(struct ParseOpArray){MOV_IIR, {IIND, R16}}, + }}, + [R_MOVL] = + {8, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVL_IMI, {IMM, IND}}, + &(struct ParseOpArray){MOVL_IMD, {IMM, EXP}}, + &(struct ParseOpArray){MOV_IR, {IND, R32}}, + &(struct ParseOpArray){MOV_RI, {R32, IND}}, + &(struct ParseOpArray){MOV_RR, {R32, R32}}, + &(struct ParseOpArray){MOV_IMR, {IMM, R32}}, + &(struct ParseOpArray){MOV_IIR, {IIND, R32}}, + &(struct ParseOpArray){MOV_SR, {SEG, R32}}, + }}, + [R_MOVQ] = + {12, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVQ_IMI, {IMM, IND}}, + &(struct ParseOpArray){MOVQ_IMD, {IMM, EXP}}, + &(struct ParseOpArray){MOV_IR, {IND, R64}}, + &(struct ParseOpArray){MOV_RI, {R64, IND}}, + &(struct ParseOpArray){MOV_RR, {R64, R64}}, + &(struct ParseOpArray){MOV_IMR, {IMM, R64}}, + &(struct ParseOpArray){MOV_IIR, {IIND, R64}}, + &(struct ParseOpArray){MOV_SR, {SEG, R64}}, + /* bitwise gp<->xmm move, qbe's idiom for spilling a + * float through a gp register and for float negate's + * sign-bit xor against a constant */ + &(struct ParseOpArray){MOVQ_GP_XMM, {R64, XMM}}, + &(struct ParseOpArray){MOVQ_XMM_GP, {XMM, R64}}, + &(struct ParseOpArray){MOVQ_MEM_XMM, {IND, XMM}}, + &(struct ParseOpArray){MOVQ_XMM_MEM, {XMM, IND}}, + }}, + [R_MOVSX] = + {6, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVSX, {R8, R16}}, + &(struct ParseOpArray){MOVSX, {R8, R32}}, + &(struct ParseOpArray){MOVSX, {R8, R64}}, + &(struct ParseOpArray){MOVSX, {R16, R32}}, + &(struct ParseOpArray){MOVSX, {R16, R64}}, + &(struct ParseOpArray){MOVSX, {R32, R64}}, + }}, + [R_MOVZX] = + {6, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVZX, {R8, R16}}, + &(struct ParseOpArray){MOVZX, {R8, R32}}, + &(struct ParseOpArray){MOVZX, {R8, R64}}, + &(struct ParseOpArray){MOVZX, {R16, R32}}, + &(struct ParseOpArray){MOVZX, {R16, R64}}, + &(struct ParseOpArray){MOVZX, {R32, R64}}, + }}, + [R_LEA] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){LEA_IR, {IND, R64}}, + &(struct ParseOpArray){LEA_IIR, {IIND, R64}}, + }}, + [R_ADD] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ADD_RR, {R8, R8}}, + &(struct ParseOpArray){ADD_RR, {R16, R16}}, + &(struct ParseOpArray){ADD_RR, {R32, R32}}, + &(struct ParseOpArray){ADD_RR, {R64, R64}}, + &(struct ParseOpArray){ADD_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){ADD_IR, {IND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){ADD_IIR, {IIND, R8 | R16 | R32 | R64}}, + }}, + [R_ADDQ] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ADDQ, {IMM, IND}}, + &(struct ParseOpArray){ADD_RR, {R8, R8}}, + &(struct ParseOpArray){ADD_RR, {R16, R16}}, + &(struct ParseOpArray){ADD_RR, {R32, R32}}, + &(struct ParseOpArray){ADD_RR, {R64, R64}}, + &(struct ParseOpArray){ADD_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){ADD_IR, {IND, R64}}, + }}, + [R_SUB] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SUB_RR, {R8, R8}}, + &(struct ParseOpArray){SUB_RR, {R16, R16}}, + &(struct ParseOpArray){SUB_RR, {R32, R32}}, + &(struct ParseOpArray){SUB_RR, {R64, R64}}, + &(struct ParseOpArray){SUB_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SUB_IR, {IND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SUB_IIR, {IIND, R8 | R16 | R32 | R64}}, + }}, + [R_SUBQ] = + {6, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SUBQ, {IMM, IND}}, + &(struct ParseOpArray){SUB_RR, {R8, R8}}, + &(struct ParseOpArray){SUB_RR, {R16, R16}}, + &(struct ParseOpArray){SUB_RR, {R32, R32}}, + &(struct ParseOpArray){SUB_RR, {R64, R64}}, + &(struct ParseOpArray){SUB_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_MUL] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MUL, {R8 | R16 | R32 | R64}}}}, + [R_DIV] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DIV, {R8 | R16 | R32 | R64}}}}, + [R_IDIV] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){IDIV, {R8 | R16 | R32 | R64}}}}, + [R_NEG] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){NEG, {R8 | R16 | R32 | R64}}}}, + [R_NOT] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){NOT, {R8 | R16 | R32 | R64}}}}, + [R_INC] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INC, {R8 | R16 | R32 | R64}}}}, + [R_INCB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INCB, {IND}}}}, + [R_INCW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INCW, {IND}}}}, + [R_INCL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INCL, {IND}}}}, + [R_INCQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INCQ, {IND}}}}, + [R_DEC] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DEC, {R8 | R16 | R32 | R64}}}}, + [R_DECB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DECB, {IND}}}}, + [R_DECW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DECW, {IND}}}}, + [R_DECL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DECL, {IND}}}}, + [R_DECQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){DECQ, {IND}}}}, + [R_AND] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){AND_RR, {R8, R8}}, + &(struct ParseOpArray){AND_RR, {R16, R16}}, + &(struct ParseOpArray){AND_RR, {R32, R32}}, + &(struct ParseOpArray){AND_RR, {R64, R64}}, + &(struct ParseOpArray){AND_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_OR] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){OR_RR, {R8, R8}}, + &(struct ParseOpArray){OR_RR, {R16, R16}}, + &(struct ParseOpArray){OR_RR, {R32, R32}}, + &(struct ParseOpArray){OR_RR, {R64, R64}}, + &(struct ParseOpArray){OR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_XOR] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XOR_RR, {R8, R8}}, + &(struct ParseOpArray){XOR_RR, {R16, R16}}, + &(struct ParseOpArray){XOR_RR, {R32, R32}}, + &(struct ParseOpArray){XOR_RR, {R64, R64}}, + &(struct ParseOpArray){XOR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHL_RR, {R8CL, R8 | R16 | R32 | R64}}, /* %cl, %reg */ + &(struct ParseOpArray){SHL_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHR] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHR_RR, {R8CL, R8 | R16 | R32 | R64}}, /* %cl, %reg */ + &(struct ParseOpArray){SHR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SAR] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SAR_RR, {R8CL, R8 | R16 | R32 | R64}}, /* %cl, %reg */ + &(struct ParseOpArray){SAR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_CMP] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMP_RR, {R8, R8}}, + &(struct ParseOpArray){CMP_RR, {R16, R16}}, + &(struct ParseOpArray){CMP_RR, {R32, R32}}, + &(struct ParseOpArray){CMP_RR, {R64, R64}}, + &(struct ParseOpArray){CMP_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_TEST] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){TEST, {R8, R8}}, + &(struct ParseOpArray){TEST, {R16, R16}}, + &(struct ParseOpArray){TEST, {R32, R32}}, + &(struct ParseOpArray){TEST, {R64, R64}}, + }}, + [R_CWTL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CWTL}}}, + [R_CLTD] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CLTD}}}, + [R_CQTO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CQTO}}}, + [R_BSR] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BSR, {R16, R16}}, + &(struct ParseOpArray){BSR, {R32, R32}}, + &(struct ParseOpArray){BSR, {R64, R64}}, + }}, + [R_LZCNT] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){LZCNT, {R16, R16}}, + &(struct ParseOpArray){LZCNT, {R32, R32}}, + &(struct ParseOpArray){LZCNT, {R64, R64}}, + }}, + [R_TZCNT] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){TZCNT, {R16, R16}}, + &(struct ParseOpArray){TZCNT, {R32, R32}}, + &(struct ParseOpArray){TZCNT, {R64, R64}}, + }}, + [R_POPCNT] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){POPCNT, {R16, R16}}, + &(struct ParseOpArray){POPCNT, {R32, R32}}, + &(struct ParseOpArray){POPCNT, {R64, R64}}, + }}, + [R_SETO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETO, {R8}}}}, + [R_SETNO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETNO, {R8}}}}, + [R_SETB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETB, {R8}}}}, + [R_SETAE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETAE, {R8}}}}, + [R_SETE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETE, {R8}}}}, + [R_SETNE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETNE, {R8}}}}, + /* setz/setnz: same encoding as sete/setne, gcc/qbe just prefer + * this spelling for a zero-flag test not read as an equality */ + [R_SETZ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETE, {R8}}}}, + [R_SETNZ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETNE, {R8}}}}, + [R_SETBE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETBE, {R8}}}}, + [R_SETA] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETA, {R8}}}}, + [R_SETS] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETS, {R8}}}}, + [R_SETNS] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETNS, {R8}}}}, + [R_SETP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETP, {R8}}}}, + [R_SETNP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETNP, {R8}}}}, + [R_SETL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETL, {R8}}}}, + [R_SETGE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETGE, {R8}}}}, + [R_SETLE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETLE, {R8}}}}, + [R_SETG] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SETG, {R8}}}}, + [R_JMP] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){JMP_D, {EXP}}, + &(struct ParseOpArray){JMP_DER, {DER}}, + &(struct ParseOpArray){JMP_DEI, {DEI}}, + &(struct ParseOpArray){JMP_DEII, {DEII}}, + }}, + [R_JO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JO, {EXP}}}}, + [R_JNO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNO, {EXP}}}}, + [R_JB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JB, {EXP}}}}, + [R_JAE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JAE, {EXP}}}}, + [R_JE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JE, {EXP}}}}, + [R_JNE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNE, {EXP}}}}, + [R_JBE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JBE, {EXP}}}}, + [R_JA] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JA, {EXP}}}}, + [R_JS] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JS, {EXP}}}}, + [R_JNS] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNS, {EXP}}}}, + [R_JP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JP, {EXP}}}}, + [R_JNP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNP, {EXP}}}}, + [R_JL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JL, {EXP}}}}, + [R_JGE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JGE, {EXP}}}}, + [R_JLE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JLE, {EXP}}}}, + [R_JG] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JG, {EXP}}}}, + [R_CALL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CALL_D, {EXP}}, + &(struct ParseOpArray){CALL_DER, {DER}}, + }}, + [R_RET] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){RET}}}, + [R_PUSH] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){PUSH_R, {R64}}, + &(struct ParseOpArray){PUSH_IM, {IMM}}, + }}, + [R_POP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){POP, {R64}}}}, + [R_INT] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){INT, {IMM}}}}, + [R_SYSCALL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SYSCALL}}}, + + [R_MOVSD] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVSD_XX, {XMM, XMM}}, + &(struct ParseOpArray){MOVSD_IX, {IND, XMM}}, + &(struct ParseOpArray){MOVSD_XI, {XMM, IND}}, + }}, + [R_MOVSS] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MOVSS_XX, {XMM, XMM}}, + &(struct ParseOpArray){MOVSS_IX, {IND, XMM}}, + &(struct ParseOpArray){MOVSS_XI, {XMM, IND}}, + }}, + [R_ADDSD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ADDSD, {XMM, XMM}}, + }}, + [R_ADDSS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ADDSS, {XMM, XMM}}, + }}, + [R_SUBSD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SUBSD, {XMM, XMM}}, + }}, + [R_SUBSS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SUBSS, {XMM, XMM}}, + }}, + [R_MULSD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MULSD, {XMM, XMM}}, + }}, + [R_MULSS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){MULSS, {XMM, XMM}}, + }}, + [R_DIVSD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){DIVSD, {XMM, XMM}}, + }}, + [R_DIVSS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){DIVSS, {XMM, XMM}}, + }}, + [R_XORPD] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XORPD, {XMM, XMM}}, + &(struct ParseOpArray){XORPD_IX, {IND, XMM}}, + }}, + [R_XORPS] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XORPS, {XMM, XMM}}, + &(struct ParseOpArray){XORPS_IX, {IND, XMM}}, + }}, + [R_COMISD] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){COMISD, {XMM, XMM}}, + &(struct ParseOpArray){COMISD_IX, {IND, XMM}}, + }}, + [R_UCOMISD] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){UCOMISD, {XMM, XMM}}, + &(struct ParseOpArray){UCOMISD_IX, {IND, XMM}}, + }}, + [R_COMISS] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){COMISS, {XMM, XMM}}, + &(struct ParseOpArray){COMISS_IX, {IND, XMM}}, + }}, + [R_UCOMISS] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){UCOMISS, {XMM, XMM}}, + &(struct ParseOpArray){UCOMISS_IX, {IND, XMM}}, + }}, + [R_CVTSI2SD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTSI2SD, {R32 | R64, XMM}}, + }}, + [R_CVTSI2SS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTSI2SS, {R32 | R64, XMM}}, + }}, + [R_CVTTSD2SI] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSD2SI, {XMM, R32 | R64}}, + }}, + [R_CVTTSS2SI] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSS2SI, {XMM, R32 | R64}}, + }}, + [R_CVTSD2SS] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTSD2SS, {XMM, XMM}}, + }}, + [R_CVTSS2SD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTSS2SD, {XMM, XMM}}, + }}, + [R_SQRTSD] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SQRTSD, {XMM, XMM}}, + }}, + + [R_ENDBR64] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ENDBR64}, + }}, + + /* no-operand instructions */ + [R_NOP] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){NOP}}}, + [R_PUSHFQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){PUSHFQ}}}, + [R_POPFQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){POPFQ}}}, + [R_PUSHF] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){PUSHF}}}, + [R_POPF] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){POPF}}}, + [R_CPUID] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CPUID}}}, + [R_RDTSC] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){RDTSC}}}, + [R_UD2] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){UD2}}}, + [R_PAUSE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){PAUSE}}}, + [R_HLT] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){HLT}}}, + [R_CMC] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CMC}}}, + [R_CLC] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CLC}}}, + [R_STC] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STC}}}, + [R_CLI] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CLI}}}, + [R_STI] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STI}}}, + [R_CLD] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CLD}}}, + [R_STD] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STD}}}, + [R_CLTS] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CLTS}}}, + [R_WBINVD] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){WBINVD}}}, + [R_MFENCE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MFENCE}}}, + [R_LFENCE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LFENCE}}}, + [R_SFENCE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SFENCE}}}, + + /* register instructions */ + [R_IMUL] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){IMUL, {R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){IMUL_RR, {R8 | R16 | R32 | R64, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){IMUL_IRR, {IMM, R16 | R32 | R64}}, + }}, + [R_BSF] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BSF, {R16, R16}}, + &(struct ParseOpArray){BSF, {R32, R32}}, + &(struct ParseOpArray){BSF, {R64, R64}}, + }}, + [R_BSWAP] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BSWAP, {R32}}, + &(struct ParseOpArray){BSWAP, {R64}}, + }}, + [R_XADD] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XADD_RR, {R8, R8}}, + &(struct ParseOpArray){XADD_RR, {R16, R16}}, + &(struct ParseOpArray){XADD_RR, {R32, R32}}, + &(struct ParseOpArray){XADD_RR, {R64, R64}}, + &(struct ParseOpArray){XADD_RI, {R32 | R64, IND}}, + }}, + [R_CMPXCHG] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMPXCHG_RR, {R8, R8}}, + &(struct ParseOpArray){CMPXCHG_RR, {R16, R16}}, + &(struct ParseOpArray){CMPXCHG_RR, {R32, R32}}, + &(struct ParseOpArray){CMPXCHG_RR, {R64, R64}}, + &(struct ParseOpArray){CMPXCHG_RI, {R32 | R64, IND}}, + }}, + [R_LEAVE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LEAVE}}}, + [R_ENTER] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){ENTER, {IMM, IMM}}}}, + [R_XCHG] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XCHG_RR, {R8, R8}}, + &(struct ParseOpArray){XCHG_RR, {R16, R16}}, + &(struct ParseOpArray){XCHG_RR, {R32, R32}}, + &(struct ParseOpArray){XCHG_RR, {R64, R64}}, + &(struct ParseOpArray){XCHG_RI, {R32 | R64, IND}}, + }}, + + /* bit test */ + [R_BT] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BT_RR, {R16, R16}}, + &(struct ParseOpArray){BT_RR, {R32, R32}}, + &(struct ParseOpArray){BT_RR, {R64, R64}}, + &(struct ParseOpArray){BT_RR, {IMM, R16 | R32 | R64}}, + }}, + [R_BTS] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BTS_RR, {R16, R16}}, + &(struct ParseOpArray){BTS_RR, {R32, R32}}, + &(struct ParseOpArray){BTS_RR, {R64, R64}}, + &(struct ParseOpArray){BTS_RR, {IMM, R16 | R32 | R64}}, + }}, + [R_BTR] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BTR_RR, {R16, R16}}, + &(struct ParseOpArray){BTR_RR, {R32, R32}}, + &(struct ParseOpArray){BTR_RR, {R64, R64}}, + &(struct ParseOpArray){BTR_RR, {IMM, R16 | R32 | R64}}, + }}, + [R_BTC] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){BTC_RR, {R16, R16}}, + &(struct ParseOpArray){BTC_RR, {R32, R32}}, + &(struct ParseOpArray){BTC_RR, {R64, R64}}, + &(struct ParseOpArray){BTC_RR, {IMM, R16 | R32 | R64}}, + }}, + + /* conditional move */ + [R_CMOVO] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVO, {R16, R16}}, + &(struct ParseOpArray){CMOVO, {R32, R32}}, + &(struct ParseOpArray){CMOVO, {R64, R64}} + }}, + [R_CMOVNO] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNO, {R16, R16}}, + &(struct ParseOpArray){CMOVNO, {R32, R32}}, + &(struct ParseOpArray){CMOVNO, {R64, R64}} + }}, + [R_CMOVB] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVB, {R16, R16}}, + &(struct ParseOpArray){CMOVB, {R32, R32}}, + &(struct ParseOpArray){CMOVB, {R64, R64}} + }}, + [R_CMOVAE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVAE, {R16, R16}}, + &(struct ParseOpArray){CMOVAE, {R32, R32}}, + &(struct ParseOpArray){CMOVAE, {R64, R64}} + }}, + [R_CMOVE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVE, {R16, R16}}, + &(struct ParseOpArray){CMOVE, {R32, R32}}, + &(struct ParseOpArray){CMOVE, {R64, R64}} + }}, + [R_CMOVNE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNE, {R16, R16}}, + &(struct ParseOpArray){CMOVNE, {R32, R32}}, + &(struct ParseOpArray){CMOVNE, {R64, R64}} + }}, + [R_CMOVBE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVBE, {R16, R16}}, + &(struct ParseOpArray){CMOVBE, {R32, R32}}, + &(struct ParseOpArray){CMOVBE, {R64, R64}} + }}, + [R_CMOVA] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVA, {R16, R16}}, + &(struct ParseOpArray){CMOVA, {R32, R32}}, + &(struct ParseOpArray){CMOVA, {R64, R64}} + }}, + [R_CMOVS] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVS, {R16, R16}}, + &(struct ParseOpArray){CMOVS, {R32, R32}}, + &(struct ParseOpArray){CMOVS, {R64, R64}} + }}, + [R_CMOVNS] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNS, {R16, R16}}, + &(struct ParseOpArray){CMOVNS, {R32, R32}}, + &(struct ParseOpArray){CMOVNS, {R64, R64}} + }}, + [R_CMOVP] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVP, {R16, R16}}, + &(struct ParseOpArray){CMOVP, {R32, R32}}, + &(struct ParseOpArray){CMOVP, {R64, R64}} + }}, + [R_CMOVNP] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNP, {R16, R16}}, + &(struct ParseOpArray){CMOVNP, {R32, R32}}, + &(struct ParseOpArray){CMOVNP, {R64, R64}} + }}, + [R_CMOVL] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVL, {R16, R16}}, + &(struct ParseOpArray){CMOVL, {R32, R32}}, + &(struct ParseOpArray){CMOVL, {R64, R64}} + }}, + [R_CMOVGE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVGE, {R16, R16}}, + &(struct ParseOpArray){CMOVGE, {R32, R32}}, + &(struct ParseOpArray){CMOVGE, {R64, R64}} + }}, + [R_CMOVLE] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVLE, {R16, R16}}, + &(struct ParseOpArray){CMOVLE, {R32, R32}}, + &(struct ParseOpArray){CMOVLE, {R64, R64}} + }}, + [R_CMOVG] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVG, {R16, R16}}, + &(struct ParseOpArray){CMOVG, {R32, R32}}, + &(struct ParseOpArray){CMOVG, {R64, R64}} + }}, + + /* string operations */ + [R_MOVSB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSB}}}, + [R_MOVSW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSW}}}, + [R_MOVSL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSL}}}, + [R_MOVSQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSQ}}}, + [R_STOSB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STOSB}}}, + [R_STOSW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STOSW}}}, + [R_STOSL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STOSL}}}, + [R_STOSQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){STOSQ}}}, + [R_LODSB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LODSB}}}, + [R_LODSW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LODSW}}}, + [R_LODSL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LODSL}}}, + [R_LODSQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){LODSQ}}}, + [R_SCASB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SCASB}}}, + [R_SCASW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SCASW}}}, + [R_SCASL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SCASL}}}, + [R_SCASQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){SCASQ}}}, + [R_CMPSB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CMPSB}}}, + [R_CMPSW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CMPSW}}}, + [R_CMPSL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CMPSL}}}, + [R_CMPSQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CMPSQ}}}, + + /* gas conversion aliases */ + [R_CBW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CBW}}}, + [R_CDQE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CDQE}}}, + [R_CWD] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){CWD}}}, + + /* condition code aliases */ + [R_JC] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JB, {EXP}}}}, + [R_JNAE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JB, {EXP}}}}, + [R_JNB] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JAE, {EXP}}}}, + [R_JZ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JE, {EXP}}}}, + [R_JNZ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNE, {EXP}}}}, + [R_JNA] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JBE, {EXP}}}}, + [R_JNBE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JA, {EXP}}}}, + [R_JNGE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JL, {EXP}}}}, + [R_JNL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JGE, {EXP}}}}, + [R_JNG] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JLE, {EXP}}}}, + [R_JNLE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JG, {EXP}}}}, + [R_JPE] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JP, {EXP}}}}, + [R_JPO] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){JNP, {EXP}}}}, + + [R_CMOVZ] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVE, {R16, R16}}, + &(struct ParseOpArray){CMOVE, {R32, R32}}, + &(struct ParseOpArray){CMOVE, {R64, R64}} + }}, + [R_CMOVNZ] = { + 3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNE, {R16, R16}}, + &(struct ParseOpArray){CMOVNE, {R32, R32}}, + &(struct ParseOpArray){CMOVNE, {R64, R64}} + } + }, + + /* explicit-size gas mnemonics qbe's amd64_sysv backend emits: the + * suffix only disambiguates operand width when its unsuffixed + * sibling above cannot infer it from a register operand, so these + * accept exactly the same operand patterns as that sibling */ + [R_LEAQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){LEA_IR, {IND, R64}}, + &(struct ParseOpArray){LEA_IIR, {IIND, R64}}, + }}, + [R_ADDL] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){ADD_RR, {R8, R8}}, + &(struct ParseOpArray){ADD_RR, {R16, R16}}, + &(struct ParseOpArray){ADD_RR, {R32, R32}}, + &(struct ParseOpArray){ADD_RR, {R64, R64}}, + &(struct ParseOpArray){ADD_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){ADD_IR, {IND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){ADD_IIR, {IIND, R8 | R16 | R32 | R64}}, + }}, + [R_SUBL] = + {7, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SUB_RR, {R8, R8}}, + &(struct ParseOpArray){SUB_RR, {R16, R16}}, + &(struct ParseOpArray){SUB_RR, {R32, R32}}, + &(struct ParseOpArray){SUB_RR, {R64, R64}}, + &(struct ParseOpArray){SUB_IMR, {IMM, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SUB_IR, {IND, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SUB_IIR, {IIND, R8 | R16 | R32 | R64}}, + }}, + [R_IDIVL] = + {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){IDIV, {R8 | R16 | R32 | R64}}}}, + [R_ANDL] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){AND_RR, {R8, R8}}, + &(struct ParseOpArray){AND_RR, {R16, R16}}, + &(struct ParseOpArray){AND_RR, {R32, R32}}, + &(struct ParseOpArray){AND_RR, {R64, R64}}, + &(struct ParseOpArray){AND_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_ANDQ] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){AND_RR, {R8, R8}}, + &(struct ParseOpArray){AND_RR, {R16, R16}}, + &(struct ParseOpArray){AND_RR, {R32, R32}}, + &(struct ParseOpArray){AND_RR, {R64, R64}}, + &(struct ParseOpArray){AND_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_ORL] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){OR_RR, {R8, R8}}, + &(struct ParseOpArray){OR_RR, {R16, R16}}, + &(struct ParseOpArray){OR_RR, {R32, R32}}, + &(struct ParseOpArray){OR_RR, {R64, R64}}, + &(struct ParseOpArray){OR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_ORQ] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){OR_RR, {R8, R8}}, + &(struct ParseOpArray){OR_RR, {R16, R16}}, + &(struct ParseOpArray){OR_RR, {R32, R32}}, + &(struct ParseOpArray){OR_RR, {R64, R64}}, + &(struct ParseOpArray){OR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHLL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHL_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SHL_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHLQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHL_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SHL_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHRL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHR_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SHR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SHRQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SHR_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SHR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SARL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SAR_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SAR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_SARQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){SAR_RR, {R8CL, R8 | R16 | R32 | R64}}, + &(struct ParseOpArray){SAR_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_CMPL] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMP_RR, {R8, R8}}, + &(struct ParseOpArray){CMP_RR, {R16, R16}}, + &(struct ParseOpArray){CMP_RR, {R32, R32}}, + &(struct ParseOpArray){CMP_RR, {R64, R64}}, + &(struct ParseOpArray){CMP_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_CMPQ] = + {5, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMP_RR, {R8, R8}}, + &(struct ParseOpArray){CMP_RR, {R16, R16}}, + &(struct ParseOpArray){CMP_RR, {R32, R32}}, + &(struct ParseOpArray){CMP_RR, {R64, R64}}, + &(struct ParseOpArray){CMP_IMR, {IMM, R8 | R16 | R32 | R64}}, + }}, + [R_CALLQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CALL_D, {EXP}}, + &(struct ParseOpArray){CALL_DER, {DER}}, + }}, + [R_PUSHQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){PUSH_R, {R64}}, + &(struct ParseOpArray){PUSH_IM, {IMM}}, + }}, + [R_POPQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){POP, {R64}}}}, + [R_CVTTSD2SIL] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSD2SI, {XMM, R32 | R64}}, + }}, + [R_CVTTSD2SIQ] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSD2SI, {XMM, R32 | R64}}, + }}, + [R_CVTTSS2SIL] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSS2SI, {XMM, R32 | R64}}, + }}, + [R_CVTTSS2SIQ] = + {1, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CVTTSS2SI, {XMM, R32 | R64}}, + }}, + [R_XCHGL] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XCHG_RR, {R8, R8}}, + &(struct ParseOpArray){XCHG_RR, {R16, R16}}, + &(struct ParseOpArray){XCHG_RR, {R32, R32}}, + &(struct ParseOpArray){XCHG_RR, {R64, R64}}, + }}, + [R_XCHGQ] = + {4, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XCHG_RR, {R8, R8}}, + &(struct ParseOpArray){XCHG_RR, {R16, R16}}, + &(struct ParseOpArray){XCHG_RR, {R32, R32}}, + &(struct ParseOpArray){XCHG_RR, {R64, R64}}, + }}, + /* qbe emits the explicit-size spelling for both of these, not the + * bare mnemonic, for reg-reg xor/neg, and also for xor against an + * immediate (a boolean-negate idiom, `xorq $1, %reg`) */ + [R_XORL] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XOR_RR, {R32, R32}}, + &(struct ParseOpArray){XOR_IMR, {IMM, R32}}, + }}, + [R_XORQ] = + {2, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){XOR_RR, {R64, R64}}, + &(struct ParseOpArray){XOR_IMR, {IMM, R64}}, + }}, + [R_NEGL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){NEG, {R32}}}}, + [R_NEGQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){NEG, {R64}}}}, + /* asm_movszx_rr already handles every one of these size pairs, it + was just never reachable: no raw opcode dispatched to it */ + [R_MOVSLQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R32, R64}}}}, + [R_MOVSBW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R8, R16}}}}, + [R_MOVSBL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R8, R32}}}}, + [R_MOVSBQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R8, R64}}}}, + [R_MOVSWL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R16, R32}}}}, + [R_MOVSWQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVSX, {R16, R64}}}}, + [R_MOVZBW] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVZX, {R8, R16}}}}, + [R_MOVZBL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVZX, {R8, R32}}}}, + [R_MOVZBQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVZX, {R8, R64}}}}, + [R_MOVZWL] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVZX, {R16, R32}}}}, + [R_MOVZWQ] = {1, (const struct ParseOpArray *[]){&(struct ParseOpArray){MOVZX, {R16, R64}}}}, +}; diff --git a/cmd/dev/as/arch/x64/reloc_x64.c b/cmd/dev/as/arch/x64/reloc_x64.c @@ -0,0 +1,263 @@ +/* x64-specific code relocation resolution + * called from core resolve_relative_address for each IR_CODE node */ + +#include "../../../config.h" +#include "arch.h" + +#include <stdint.h> + +#include "inst.h" +#include "parse_asm.h" +#include "table.h" +#include "tcutil.h" + +static void +put_value(unsigned char *p, int64_t value, int size) +{ + for (int i = 0; i < size; ++i) { + *p++ = value; + value >>= 8; + } +} + +static int +make_jmp_long(struct IR *ir) +{ + if (ir->code.flag & INST_LONG_OFFSET) + return 0; + + struct Inst *inst = ir->code.inst; + /* change to long offset and recalculate */ + ir->code.flag |= INST_LONG_OFFSET; + ir->code.len = 0; + if (inst->op == JMP_D) + MAKE_CODE(inst, &ir->code, 0xe9, IM32(-1)); + else + MAKE_CODE(inst, &ir->code, 0x0f, 0x80 + (inst->op - JO), IM32(-1)); + return 1; +} + +static void +resolve_direct_mov( + struct IR *ir, + struct SectionInfo *section, + uint64_t address, + uint64_t start_address, + struct Table *label_table, + struct Vector *unresolved +) +{ + struct Inst *inst = ir->code.inst; + struct Operand *mem = inst->op == MOV_DR ? &inst->opr[0] : &inst->opr[1]; + struct Reg *reg = inst->op == MOV_DR ? &inst->opr[1].reg : &inst->opr[0].reg; + struct Value value = calc_expr(label_table, mem->direct.expr); + struct UnresolvedInfo *info; + + if (value.label == NULL) { + put_value(ir->code.buf + ir->code.len - 4, value.offset, sizeof(int32_t)); + return; + } + info = malloc_or_die(sizeof(*info)); + info->kind = inst->op == MOV_DR && reg->size == REG32 ? UNRES_X64_ABS32S : UNRES_X64_ABS32; + info->label = value.label; + info->src_section = section; + info->offset = address + ir->code.len - 4 - start_address; + info->add = value.offset; + vec_push(unresolved, info); +} + +void +x64_resolve_code_reloc( + struct IR *ir, + struct SectionInfo *section, + uint64_t address, + uint64_t start_address, + struct Table *label_table, + struct Vector *unresolved, + int *size_upgraded +) +{ + struct Inst *inst = ir->code.inst; + switch (inst->op) { + case MOV_DR: + case MOV_RD: + resolve_direct_mov(ir, section, address, start_address, label_table, unresolved); + break; + case MOV_IR: + /* this shape loads through a got slot (mov sym@gotpcrel(%rip), + %reg), not sym's address, so it needs a relocation even when + sym is local. unlike lea_ir there is no direct-address + fallback to patch in place */ + if (inst->opr[0].indirect.reg.no == RIP) { + struct Value value = calc_expr(label_table, inst->opr[0].indirect.offset.expr); + if (value.label != NULL) { + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_X64_GOT_LOAD; + info->label = value.label; + info->src_section = section; + info->offset = address + 3 - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); + } + } + break; + case ADD_IR: + /* addq sym@gottpoff(%rip), %reg: the second half of qbe's + initial-exec tls sequence (movq %fs:0, %reg first). it loads a + got-resident tp-offset, otherwise the same shape as mov_ir */ + if (inst->opr[0].indirect.reg.no == RIP) { + struct Value value = calc_expr(label_table, inst->opr[0].indirect.offset.expr); + if (value.label != NULL) { + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = (inst->opr[0].indirect.offset.flag & LF_GOTTPOFF) ? UNRES_X64_GOTTPOFF + : UNRES_X64_GOT_LOAD; + info->label = value.label; + info->src_section = section; + info->offset = address + 3 - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); + } + } + break; + case LEA_IR: + if (inst->opr[0].indirect.reg.no == RIP + && inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM) { + struct Value value = calc_expr(label_table, inst->opr[0].indirect.offset.expr); + if (value.label != NULL) { + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_EXTERN_PC32; + info->label = value.label; + info->src_section = section; + info->offset = address + 3 - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + put_value(ir->code.buf + 3, value.offset, sizeof(int32_t)); +#endif + } else { + int64_t offset = value.offset - (address + ir->code.len); + put_value(ir->code.buf + 3, offset, sizeof(int32_t)); + } + } + break; + case MOV_SR: + /* r_x86_64_tpoff32: a plain tp-relative displacement, not + pc-relative, so no address math here. the linker computes it + once the tls layout is known, like ir_asm.c's unres_abs64 + registration for .quad label */ + if (inst->opr[0].segment.offset.flag & LF_TPOFF) { + struct Value value = calc_expr(label_table, inst->opr[0].segment.offset.expr); + int reloc_offset = ir->code.len - 4; + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_X64_TPOFF32; + info->label = value.label; + info->src_section = section; + info->offset = address + reloc_offset - start_address; + info->add = value.offset; + vec_push(unresolved, info); + } + break; + case MOVSD_IX: + case MOVSS_IX: + case XORPD_IX: + case XORPS_IX: + case COMISD_IX: + case UCOMISD_IX: + case COMISS_IX: + case UCOMISS_IX: + /* rip-relative with a symbolic offset: disp32 is the last 4 + bytes, but unlike lea_ir these encodings may or may not have a + rex byte, so derive the offset from the encoded length */ + if (inst->opr[0].indirect.reg.no == RIP + && inst->opr[0].indirect.offset.expr->kind != EX_FIXNUM) { + struct Value value = calc_expr(label_table, inst->opr[0].indirect.offset.expr); + int reloc_offset = ir->code.len - 4; + if (value.label != NULL) { + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_EXTERN_PC32; + info->label = value.label; + info->src_section = section; + info->offset = address + reloc_offset - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); + } else { + int64_t offset = value.offset - (address + ir->code.len); + put_value(ir->code.buf + reloc_offset, offset, sizeof(int32_t)); + } + } + break; + case JMP_D: + case JO: + case JNO: + case JB: + case JAE: + case JE: + case JNE: + case JBE: + case JA: + case JS: + case JNS: + case JP: + case JNP: + case JL: + case JGE: + case JLE: + case JG: + if (inst->opr[0].type == DIRECT) { + struct Value value = calc_expr(label_table, inst->opr[0].direct.expr); + if (value.label != NULL) { + struct LabelInfo *label_info = table_get(label_table, value.label); + if (label_info == NULL) { + *size_upgraded |= make_jmp_long(ir); + + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_CALL; + info->label = value.label; + info->src_section = section; + info->offset = address + 1 - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); + break; + } else { + value.offset += label_info->address; + } + } + + int64_t offset = value.offset - (address + ir->code.len); + int long_offset = ir->code.flag & INST_LONG_OFFSET; + if (!long_offset) { + if (!is_im8(offset)) { + *size_upgraded |= make_jmp_long(ir); + } else { + put_value(ir->code.buf + 1, offset, sizeof(int8_t)); + } + } else { + if (!is_im32(offset)) + error("jump offset too far (over 32bit)"); + + int d = inst->op == JMP_D ? 1 : 2; + put_value(ir->code.buf + d, offset, sizeof(int32_t)); + } + } + break; + case CALL_D: + if (inst->opr[0].type == DIRECT) { + struct Value value = calc_expr(label_table, inst->opr[0].direct.expr); + if (value.label != NULL) { + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_CALL; + info->label = value.label; + info->src_section = section; + info->offset = address + 1 - start_address; + info->add = value.offset - 4; + vec_push(unresolved, info); + break; + } + int64_t offset = value.offset - (address + ir->code.len); + put_value(ir->code.buf + 1, offset, sizeof(int32_t)); + } + break; + default: + break; + } +} diff --git a/cmd/dev/as/as.c b/cmd/dev/as/as.c @@ -0,0 +1,291 @@ +#include "../config.h" + +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> /* qsort */ +#include <string.h> +#include <unistd.h> /* isatty */ + +#include "arch.h" +#include "format.h" +#include "ir_asm.h" +#include "parse_asm.h" +#include "table.h" +#include "tcutil.h" + +#define PROG_START (0x100) +#define START_ADDRESS (0x01000000 + PROG_START) +#define LOAD_ADDRESS START_ADDRESS + +static int +read_line_comment_skip(FILE *fp, struct ParseInfo *info) +{ + int block_comment = 0; + int wait_line_end = 1; + const char *p = info->p; + for (;;) { + if (p == NULL) { + ++info->lineno; + char *rawline = NULL; + size_t capa = 0; + ssize_t len = getline_chomp(&rawline, &capa, fp); + if (len == -1) { /* EOF */ + info->rawline = info->p = NULL; + if (block_comment) + parse_error(info, "block comment not closed"); + return 0; + } + info->rawline = p = rawline; + wait_line_end = 0; + } + + if (!block_comment) { + const char *q = block_comment_start(p); + if (q != NULL) { + block_comment = 1; + p = q + 2; + } + } + if (block_comment) { + p = block_comment_end(p); + if (p != NULL) + block_comment = 0; + wait_line_end = 1; + continue; /* continue block comment */ + } + + p = skip_whitespaces(p); + if (*p == '/' && p[1] == '/') { /* struct line comment */ + p = NULL; + continue; + } + + if (wait_line_end) { + if (*p != '\0') + parse_error(info, "line end expected"); + p = NULL; + continue; + } + + break; + } + + /* struct line */ + info->p = p; + return 1; +} + +static void +parse_file(FILE *fp, struct ParseInfo *info) +{ + info->lineno = 0; + info->rawline = info->p = NULL; + info->prefetched = NULL; + set_current_section(info, kSecText, kSegText, SF_EXECUTABLE); + + for (;;) { + if (!read_line_comment_skip(fp, info)) + break; + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + struct Line line; + if (!parse_line(&line, info)) + continue; + + if (line.label != NULL) { + vec_push(irs, new_ir_label(line.label)); + + if (!add_label_table(info->label_table, line.label, section, 1, 0)) + ++info->error_count; + } + + if (line.dir != NODIRECTIVE) + continue; + + if (line.inst != NULL) { + struct Code code; + arch.assemble_inst(line.inst, info, &code); + if (code.len > 0) + vec_push(irs, new_ir_code(&code)); + } + } +} + +static void +drop_all(FILE *fp) +{ + for (;;) { + char buf[4096]; + size_t size = fread(buf, 1, sizeof(buf), fp); + if (size < sizeof(buf)) + break; + } +} + +static struct LabelInfo * +make_label_referred(struct Table *label_table, const struct Name *label, int und) +{ + struct LabelInfo *label_info = table_get(label_table, label); + if (label_info == NULL) { + if (!und) + return NULL; + label_info = add_label_table(label_table, label, NULL, 0, 1); + } + label_info->flag |= LF_REFERRED; + return label_info; +} + +static void +fix_section_size(struct Vector *sections, uintptr_t start_address) +{ + uintptr_t addr = start_address; + for (int i = 0; i < sections->len; ++i) { + struct SectionInfo *section = sections->data[i]; + if ((section->flag & SF_BSS ? section->bss_size : section->ds->len) <= 0) + continue; + section->start_address = addr = ALIGN(addr, section->align); + addr += (section->flag & SF_BSS) ? section->bss_size : section->ds->len; + } +} + +static inline int +section_key(const struct SectionInfo *p) +{ + int flag = p->flag; + /* .text(0), .rodata(1), .data(2), .bss(6) */ + return (flag & (SF_BSS | SF_WRITABLE | SF_EXECUTABLE)) ^ SF_EXECUTABLE; +} + +static int +cmp_section(const void *pa, const void *pb) +{ + const struct SectionInfo *sa = *(const struct SectionInfo **)pa; + int ka = section_key(sa); + const struct SectionInfo *sb = *(const struct SectionInfo **)pb; + int kb = section_key(sb); + int d = ka - kb; + if (d != 0) + return d; + return pa < pb ? -1 : 1; +} + +static struct Vector * +sort_sections(struct Table *section_infos) +{ + struct Vector *sections = new_vector(); + const struct Name *name; + struct SectionInfo *section; + for (int it = 0; (it = table_iterate(section_infos, it, &name, (void **)&section)) != -1;) + vec_push(sections, section); + qsort(sections->data, sections->len, sizeof(void *), cmp_section); + return sections; +} + +static void +usage(FILE *fp) +{ + fprintf( + fp, + "Usage: as [options] file...\n" + "struct Options:\n" + " -o <filename> Set output filename (Default: " + "Standard output)\n" + ); +} + +int +main(int argc, char *argv[]) +{ + enum { + OPT_HELP = 128, + OPT_VERSION, + }; + static const struct option options[] = { + {"o", required_argument}, /* specify output filename */ + {"-help", no_argument, OPT_HELP}, + {"v", no_argument, OPT_VERSION}, + {"-version", no_argument, OPT_VERSION}, + {NULL}, + }; + + const char *ofn = NULL; + int opt; + while ((opt = optparse(argc, argv, options)) != -1) { + switch (opt) { + default: + assert(0); + break; + case OPT_HELP: + usage(stdout); + exit(0); + case OPT_VERSION: + show_version("as", TC_TARGET_ARCH); + return 0; + case 'o': + ofn = optarg; + break; + case '?': + fprintf(stderr, "Warning: unknown option: %s\n", argv[optind - 1]); + break; + } + } + int iarg = optind; + + struct Table section_infos; + table_init(&section_infos); + struct Table label_table; + table_init(&label_table); + + struct ParseInfo info; + info.error_count = 0; + info.section_infos = &section_infos; + info.label_table = &label_table; + + if (iarg >= argc) + error("No input files"); + + for (int i = iarg; i < argc; ++i) { + const char *filename = argv[i]; + FILE *fp; + if (strcmp(filename, "-") == 0) { + fp = stdin; + } else if (!is_file(filename) || (fp = fopen(filename, "r")) == NULL) { + error("Cannot open %s\n", argv[i]); + } + + info.filename = filename; + parse_file(fp, &info); + fclose(fp); + if (info.error_count != 0) + break; + } + + if (info.error_count != 0) { + return 1; + } + + struct Vector *sections = sort_sections(&section_infos); + struct Vector *unresolved = new_vector(); + int settle1, settle2; + do { + settle1 = calc_label_address(LOAD_ADDRESS, sections, &label_table); + settle2 = resolve_relative_address(sections, &label_table, unresolved); + } while (!(settle1 && settle2)); + + for (int i = 0; i < unresolved->len; ++i) { + struct UnresolvedInfo *u = unresolved->data[i]; + make_label_referred(&label_table, u->label, 1); + } + + emit_irs(sections); + + fix_section_size(sections, LOAD_ADDRESS); + + int result = EMIT_OBJ(ofn, sections, &label_table, unresolved); + if (result != 0) { + if (ofn == NULL && !isatty(STDIN_FILENO)) + drop_all(stdin); + } + return result; +} diff --git a/cmd/dev/as/as_util.c b/cmd/dev/as/as_util.c @@ -0,0 +1,48 @@ +#include "../config.h" + +#include "as_util.h" +#ifndef ELF_NOT_SUPPORTED + +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> /* realloc */ +#include <string.h> /* memcpy */ + +#include "tcutil.h" + +void +strtab_init(struct Strtab *strtab) +{ + table_init(&strtab->offsets); + strtab->size = 0; +} + +size_t +strtab_add(struct Strtab *strtab, const struct Name *name) +{ + void *result; + if (!table_try_get(&strtab->offsets, name, &result)) { + size_t offset = strtab->size; + table_put(&strtab->offsets, name, (void *)offset); + strtab->size += name->bytes + 1; + return offset; + } else { + return (size_t)result; + } +} + +void * +strtab_dump(const struct Strtab *strtab) +{ + void *buf = malloc_or_die(strtab->size); + unsigned char *p = buf; + const struct Name *name; + void *value; + for (int it = 0; (it = table_iterate(&strtab->offsets, it, &name, &value)) != -1;) { + uintptr_t offset = VOIDP2UINT(value); + memcpy(p + offset, name->chars, name->bytes); + p[offset + name->bytes] = '\0'; + } + return buf; +} +#endif /* !ELF_NOT_SUPPORTED */ diff --git a/cmd/dev/as/as_util.h b/cmd/dev/as/as_util.h @@ -0,0 +1,15 @@ +#pragma once + +#include <stddef.h> /* size_t */ + +#include "table.h" + +/* string table */ +struct Strtab { + struct Table offsets; + size_t size; +}; + +void strtab_init(struct Strtab *strtab); +size_t strtab_add(struct Strtab *strtab, const struct Name *name); +void *strtab_dump(const struct Strtab *strtab); diff --git a/cmd/dev/as/asm_code.h b/cmd/dev/as/asm_code.h @@ -0,0 +1,28 @@ +/* struct code: the binary output of a single encoded instruction + * arch-neutral. MAKE_CODE and IM* macros live in arch.h since they + * call into the arch backend */ + +#ifndef AS_ASM_CODE_H +#define AS_ASM_CODE_H + +#include "../config.h" + +struct Inst; + +/* max encoded instruction width in bytes */ +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 +#define ARCH_MAX_CODE_LEN 26 +#else +#define ARCH_MAX_CODE_LEN 14 +#endif + +#define INST_LONG_OFFSET (1 << 0) /* 32bit offset on jump etc */ + +struct Code { + struct Inst *inst; + char flag; + char len; + unsigned char buf[ARCH_MAX_CODE_LEN]; +}; + +#endif /* AS_ASM_CODE_H */ diff --git a/cmd/dev/as/emit_elf.c b/cmd/dev/as/emit_elf.c @@ -0,0 +1,729 @@ +#include "../config.h" +#include <alloca.h> + +#if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE +#include <assert.h> +#include <stdint.h> /* uint64_t */ +#include <stdio.h> +#include <string.h> + +#include "arch.h" +#include "as_util.h" +#include "elfutil.h" +#include "ir_asm.h" +#include "parse_asm.h" +#include "table.h" +#include "tcutil.h" + +#define ELF_MIN_ALIGN 0x08 + +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 +int isa_zbb = 0; +#endif + +struct Symtab { + struct Strtab strtab; + struct Table indices; + Elf64_Sym *buf; + int count; +}; + +void +symtab_init(struct Symtab *symtab) +{ + strtab_init(&symtab->strtab); + table_init(&symtab->indices); + symtab->buf = NULL; + symtab->count = 0; +} + +int +symtab_find(struct Symtab *symtab, const struct Name *name) +{ + intptr_t index; + if (table_try_get(&symtab->indices, name, (void **)&index)) + return index; + return -1; +} + +Elf64_Sym * +symtab_add(struct Symtab *symtab, const struct Name *name) +{ + uint32_t offset = strtab_add(&symtab->strtab, name); + if (name->bytes > 0) { + int index = symtab_find(symtab, name); + if (index >= 0) + return &symtab->buf[index]; + } + + int old_count = symtab->count; + int new_count = old_count + 1; + symtab->buf = realloc_or_die(symtab->buf, sizeof(*symtab->buf) * new_count); + symtab->count = new_count; + Elf64_Sym *sym = &symtab->buf[old_count]; + memset(sym, 0x00, sizeof(*sym)); + sym->st_name = offset; + table_put(&symtab->indices, name, INT2VOIDP(old_count)); + return sym; +} + +void +symtab_concat(struct Symtab *dest, struct Symtab *src) +{ + int n = src->count; + const struct Name **names = alloca(sizeof(*names) * n); + const struct Name *name; + intptr_t index; + for (int it = 0; (it = table_iterate(&src->indices, it, &name, (void **)&index)) != -1;) { + assert(index < n); + names[index] = name; + } + for (int i = 0; i < n; ++i) { + const struct Name *name = names[i]; + Elf64_Sym *p = symtab_add(dest, name); + Elf64_Word st_name_bak = p->st_name; + memcpy(p, &src->buf[i], sizeof(*p)); + p->st_name = st_name_bak; + } +} + +/* */ + +static int +construct_symtab(struct Symtab *symtab, struct Vector *sections, struct Table *label_table) +{ + symtab_init(symtab); + + struct Symtab symtab_global; + symtab_init(&symtab_global); + + struct Symtab symtab_weak; + symtab_init(&symtab_weak); + + struct Symtab *symtabs[] = { + [STB_LOCAL] = symtab, + [STB_GLOBAL] = &symtab_global, + [STB_WEAK] = &symtab_weak, + }; + + const struct Name *nulname = alloc_cname(""); + /* UND */ + Elf64_Sym *sym; + sym = symtab_add(symtab, nulname); + sym->st_info = ELF64_ST_INFO(STB_LOCAL, STT_NOTYPE); + /* SECTION */ + for (int i = 0; i < sections->len; ++i) { + struct SectionInfo *section = sections->data[i]; + if ((section->flag & SF_BSS ? section->bss_size : section->ds->len) <= 0) + continue; + sym = symtab_add(symtab, nulname); + sym->st_info = ELF64_ST_INFO(STB_LOCAL, STT_SECTION); + sym->st_shndx = section->index; /* section index */ + } + + const struct Name *name; + struct LabelInfo *info; + for (int it = 0; (it = table_iterate(label_table, it, &name, (void **)&info)) != -1;) { + int bind; + if (info->flag & LF_WEAK) { + bind = STB_WEAK; + } else if (info->flag & LF_GLOBAL) { + bind = STB_GLOBAL; + } else if (info->flag & LF_REFERRED || info->kind == LK_FUNC) { + bind = STB_LOCAL; + } else { + continue; + } + sym = symtab_add(symtabs[bind], name); + int type; + switch (info->kind) { + default: + assert(0); /* fallthrough to suppress warning */ + case LK_NONE: + type = STT_NOTYPE; + break; + case LK_FUNC: + type = STT_FUNC; + break; + case LK_OBJECT: + type = STT_OBJECT; + break; + } + sym->st_info = ELF64_ST_INFO(bind, type); + sym->st_value = (info->flag & LF_DEFINED) ? info->address - info->section->start_address : 0; + sym->st_size = info->size; + assert(info->section == NULL || info->section->index > 0); + Elf64_Section shndx = SHN_UNDEF; + if (info->section != NULL) { + if ((info->flag & (LF_COMM | LF_GLOBAL)) == (LF_COMM | LF_GLOBAL)) + shndx = SHN_COMMON; + else + shndx = info->section->index; /* symbol index for + * local section */ + } + sym->st_shndx = shndx; + } + + int local_symbol_count = symtab->count; + /* append global symbols after locals; */ + symtab_concat(symtab, &symtab_weak); + symtab_concat(symtab, &symtab_global); + + return local_symbol_count; +} + +static inline void +construct_rela_element_abs64( + struct Symtab *symtab, + struct Table *label_table, + const struct UnresolvedInfo *u, + Elf64_Rela *rela, + int type +) +{ + struct LabelInfo *label = table_get(label_table, u->label); + if (label == NULL || label->flag & (LF_GLOBAL | LF_REFERRED)) { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, type); + rela->r_addend = u->add; + } else { + int secidx = label->section->index; + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(secidx, type); + rela->r_addend = u->add + (label->address - label->section->start_address); + } +} + +#if TC_TARGET_ARCH == TC_ARCH_X64 +static inline void +construct_rela_element( + struct Symtab *symtab, + struct Table *label_table, + const struct UnresolvedInfo *u, + Elf64_Rela *rela +) +{ + switch (u->kind) { + default: + assert(0); + break; + case UNRES_ABS64: + construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_64); + break; + case UNRES_X64_ABS32S: + construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_32S); + break; + case UNRES_X64_ABS32: + construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_32); + break; + case UNRES_EXTERN: + case UNRES_EXTERN_PC32: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_X86_64_PC32); + rela->r_addend = u->add; + } break; + case UNRES_CALL: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_X86_64_PLT32); + rela->r_addend = u->add; + } break; + case UNRES_X64_GOT_LOAD: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_X86_64_GOTPCREL); + rela->r_addend = u->add; + } break; + case UNRES_X64_TPOFF32: + construct_rela_element_abs64(symtab, label_table, u, rela, R_X86_64_TPOFF32); + break; + case UNRES_X64_GOTTPOFF: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_X86_64_GOTTPOFF); + rela->r_addend = u->add; + } break; + } +} + +#elif TC_TARGET_ARCH == TC_ARCH_AARCH64 +static inline void +construct_rela_element( + struct Symtab *symtab, + struct Table *label_table, + const struct UnresolvedInfo *u, + Elf64_Rela *rela +) +{ + switch (u->kind) { + default: + assert(0); + break; + case UNRES_ABS64: + construct_rela_element_abs64(symtab, label_table, u, rela, R_AARCH64_ABS64); + break; + case UNRES_CALL: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_AARCH64_CALL26); + rela->r_addend = u->add; + } break; + + case UNRES_PCREL_HI: + case UNRES_PCREL_LO: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO( + symidx, u->kind == UNRES_PCREL_HI ? R_AARCH64_ADR_PREL_PG_HI21 : R_AARCH64_ADD_ABS_LO12_NC + ); + rela->r_addend = u->add; + } break; + + case UNRES_GOT_HI: + case UNRES_GOT_LO: { + struct LabelInfo *label = table_get(label_table, u->label); + int type = u->kind == UNRES_GOT_HI ? R_AARCH64_ADR_GOT_PAGE : R_AARCH64_LD64_GOT_LO12_NC; + if (label == NULL || label->flag & (LF_GLOBAL | LF_REFERRED)) { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, type); + rela->r_addend = u->add; + } else { + int secidx = label->section->index; + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(secidx, type); + rela->r_addend = u->add + (label->address - label->section->start_address); + } + } break; + } +} + +#elif TC_TARGET_ARCH == TC_ARCH_RISCV64 +static inline void +construct_rela_element( + struct Symtab *symtab, + struct Table *label_table, + const struct UnresolvedInfo *u, + Elf64_Rela *rela +) +{ + switch (u->kind) { + default: + assert(0); + break; + case UNRES_ABS64: + construct_rela_element_abs64(symtab, label_table, u, rela, R_RISCV_64); + break; + case UNRES_PCREL_HI: + case UNRES_PCREL_LO: + case UNRES_RISCV_HI20: + case UNRES_RISCV_LO12_I: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + Elf64_Xword type; + switch (u->kind) { + default: /* fallthrough to suppress warning */ + case UNRES_PCREL_HI: + type = R_RISCV_PCREL_HI20; + break; + case UNRES_PCREL_LO: + type = R_RISCV_PCREL_LO12_I; + break; + case UNRES_RISCV_HI20: + type = R_RISCV_HI20; + break; + case UNRES_RISCV_LO12_I: + type = R_RISCV_LO12_I; + break; + } + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, type); + rela->r_addend = u->add; + } break; + + case UNRES_CALL: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(symidx, R_RISCV_CALL); + rela->r_addend = u->add; + } break; + + case UNRES_RISCV_BRANCH: + case UNRES_RISCV_RVC_BRANCH: { + Elf64_Sym *sym = symtab_add(symtab, u->label); + size_t index = sym - symtab->buf; + + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO( + index, u->kind == UNRES_RISCV_RVC_BRANCH ? R_RISCV_RVC_BRANCH : R_RISCV_BRANCH + ); + rela->r_addend = u->add; + } break; + case UNRES_RISCV_JAL: + case UNRES_RISCV_RVC_JUMP: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + rela->r_offset = u->offset; + rela->r_info = + ELF64_R_INFO(symidx, u->kind == UNRES_RISCV_JAL ? R_RISCV_JAL : R_RISCV_RVC_JUMP); + rela->r_addend = u->add; + } break; + case UNRES_RISCV_RELAX: { + rela->r_offset = u->offset; + rela->r_info = ELF64_R_INFO(0, R_RISCV_RELAX); + rela->r_addend = u->add; + } break; + } +} +#endif + +static void +construct_relas(struct Vector *unresolved, struct Symtab *symtab, struct Table *label_table) +{ + for (int i = 0; i < unresolved->len; ++i) { + struct UnresolvedInfo *u = unresolved->data[i]; + struct SectionInfo *section = u->src_section; + int count = ++section->rela_count; + Elf64_Rela *rela_buf; + section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf)); + construct_rela_element(symtab, label_table, u, &rela_buf[count - 1]); + } +} + +/* */ + +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 +static const char kRiscvAttributesArch[] = "riscv"; +static const char *kRiscvAttributes[] = { + "rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_zicsr2p0_zmmul1p0_zaamo1p0_" + "zalrsc1p0", + "rv64i2p1_m2p0_a2p1_f2p2_d2p2_c2p0_zicsr2p0_zifencei2p0_zmmul1p0_" + "zaamo1p0_zalrsc1p0_zbb1p0", +}; +#endif + +struct Work { + struct DataStorage section_headers; + struct Symtab symtab; + struct Strtab shstrtab; + struct Vector *sections; + uint64_t sh_ofs; + uint64_t symtab_ofs; + uint64_t strtab_ofs; + uint64_t shstrtab_ofs; + int out_section_count; + int shnum; + int local_symbol_count; +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + const char *riscv_attributes; + size_t riscv_attributes_str_size; + size_t riscv_attributes_total_size; + uint64_t riscv_attributes_ofs; +#endif +}; + +static inline int +detect_output_sections(struct Vector *sections) +{ + int count = 0; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if ((section->flag & SF_BSS ? section->bss_size : section->ds->len) <= 0) + continue; + section->index = ++count; + } + return count; +} + +static inline uint64_t +arrange_section_offsets(struct Work *work) +{ + struct Vector *sections = work->sections; + + uint64_t offset = sizeof(Elf64_Ehdr); + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + size_t size; + if (section->ds == NULL || (size = section->ds->len) <= 0) + continue; + section->offset = offset = ALIGN(offset, ELF_MIN_ALIGN); + offset += size; + } + + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if (section->rela_count <= 0) + continue; + section->rela_ofs = offset = ALIGN(offset, ELF_MIN_ALIGN); + offset += sizeof(Elf64_Rela) * section->rela_count; + } + + work->symtab_ofs = offset = ALIGN(offset, ELF_MIN_ALIGN); + offset += sizeof(*work->symtab.buf) * work->symtab.count; + work->strtab_ofs = offset; + offset += work->symtab.strtab.size; + +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + work->riscv_attributes = kRiscvAttributes[isa_zbb]; + work->riscv_attributes_str_size = strlen(work->riscv_attributes) + 1; /* include '\0' */ + work->riscv_attributes_total_size = + 1 + 4 + sizeof(kRiscvAttributesArch) + 1 + 4 + 1 + work->riscv_attributes_str_size; + work->riscv_attributes_ofs = offset; + offset += work->riscv_attributes_total_size; +#endif + + return offset; +} + +static inline void +construct_section_headers(struct Work *work, uint64_t offset) +{ + struct Vector *sections = work->sections; + + /* section headers */ + strtab_init(&work->shstrtab); + struct DataStorage *section_headers = &work->section_headers; + data_init(section_headers); + + Elf64_Word index = 1 + work->out_section_count; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + index += section->rela_count > 0; + } +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + ++index; /* for .riscv.attributes section */ +#endif + const Elf64_Word strtab_index = index++; + const Elf64_Word symtab_index = index; + const int shnum = index + 2; /* symtab, shstrtab */ + + const Elf64_Shdr nulsec = { + .sh_name = strtab_add(&work->shstrtab, alloc_cname("")), + .sh_type = SHT_NULL, + .sh_addralign = 1, + }; + data_append(section_headers, &nulsec, sizeof(nulsec)); + + const struct Name *init_array_name = alloc_cname(".init_array"); + const struct Name *fini_array_name = alloc_cname(".fini_array"); + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + size_t size = section->ds != NULL ? section->ds->len : section->bss_size; + if (size <= 0) + continue; + Elf64_Xword flags = SHF_ALLOC; + if (section->flag & SF_EXECUTABLE) + flags |= SHF_EXECINSTR; + if (section->flag & SF_WRITABLE) + flags |= SHF_WRITE; + if (section->flag & SF_TLS) + flags |= SHF_TLS; + + Elf64_Word type; + if (section->flag & SF_BSS) + type = SHT_NOBITS; + else if (equal_name(section->name, init_array_name)) + type = SHT_INIT_ARRAY; + else if (equal_name(section->name, fini_array_name)) + type = SHT_FINI_ARRAY; + else + type = SHT_PROGBITS; + + const Elf64_Shdr shdr = { + .sh_name = strtab_add(&work->shstrtab, section->name), + .sh_type = type, + .sh_flags = flags, + .sh_offset = section->offset, + .sh_size = size, + .sh_addralign = section->align, + }; + data_append(section_headers, &shdr, sizeof(shdr)); + } + + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if (section->rela_count <= 0) + continue; + const struct Name *name = section->name; + char *buf = malloc_or_die(name->bytes + 6); /* sizeof(".rela\0") */ + snprintf(buf, name->bytes + 6, ".rela%.*s", name->bytes, name->chars); + + assert(section->index > 0); + const Elf64_Shdr shdr = { + .sh_name = strtab_add(&work->shstrtab, alloc_name(buf, NULL, 0)), + .sh_type = SHT_RELA, + .sh_flags = SHF_INFO_LINK, + .sh_offset = section->rela_ofs, + .sh_size = sizeof(Elf64_Rela) * section->rela_count, + .sh_link = symtab_index, + .sh_info = section->index, + .sh_addralign = 8, + .sh_entsize = sizeof(Elf64_Rela), + }; + data_append(section_headers, &shdr, sizeof(shdr)); + } + +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + const Elf64_Shdr riscv_attributes_sec = { + .sh_name = strtab_add(&work->shstrtab, alloc_cname(".riscv.attributes")), + .sh_type = SHT_RISCV_ATTRIBUTES, + .sh_offset = work->riscv_attributes_ofs, + .sh_size = work->riscv_attributes_total_size, + .sh_addralign = 1, + }; + data_append(section_headers, &riscv_attributes_sec, sizeof(riscv_attributes_sec)); +#endif + + const Elf64_Shdr strtabsec = { + .sh_name = strtab_add(&work->shstrtab, alloc_cname(".strtab")), + .sh_type = SHT_STRTAB, + .sh_offset = work->strtab_ofs, + .sh_size = work->symtab.strtab.size, + .sh_addralign = 1, + }; + data_append(section_headers, &strtabsec, sizeof(strtabsec)); + + const Elf64_Shdr symtabsec = { + .sh_name = strtab_add(&work->shstrtab, alloc_cname(".symtab")), + .sh_type = SHT_SYMTAB, + .sh_offset = work->symtab_ofs, + .sh_size = sizeof(*work->symtab.buf) * work->symtab.count, + .sh_link = strtab_index, + .sh_info = work->local_symbol_count, /* number of local symbols */ + .sh_addralign = 8, + .sh_entsize = sizeof(Elf64_Sym), + }; + data_append(section_headers, &symtabsec, sizeof(symtabsec)); + + const uint64_t shstrtab_ofs = offset; /* align(offset, 0x10); */ + const size_t shstrtab_name = strtab_add(&work->shstrtab, alloc_cname(".shstrtab")); + const Elf64_Shdr shstrtabsec = { + .sh_name = shstrtab_name, + .sh_type = SHT_STRTAB, + .sh_offset = shstrtab_ofs, + .sh_size = work->shstrtab.size, + .sh_addralign = 1, + }; + data_append(section_headers, &shstrtabsec, sizeof(shstrtabsec)); + offset += work->shstrtab.size; + + const uint64_t sh_ofs = offset = ALIGN(offset, 0x10); + /* offset += section_headers.len; */ + + work->sh_ofs = sh_ofs; + work->shstrtab_ofs = shstrtab_ofs; + work->shnum = shnum; +} + +static inline int +output_to_file(const char *ofn, const struct Work *work) +{ + FILE *ofp; + if (ofn == NULL) { + ofp = stdout; + } else { + ofp = fopen(ofn, "wb"); + if (ofp == NULL) { + fprintf(stderr, "Failed to open output file: %s\n", ofn); + return 1; + } + } + + const uint64_t entry = 0; + const int phnum = 0; +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + const int flags = EF_RISCV_RVC | EF_RISCV_FLOAT_ABI_DOUBLE; +#else + const int flags = 0; +#endif + out_elf_header(ofp, entry, phnum, work->shnum, flags, work->sh_ofs); + + struct Vector *sections = work->sections; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + struct DataStorage *ds = section->ds; + if (ds == NULL || ds->len <= 0) + continue; + put_padding(ofp, section->offset); + fwrite(ds->buf, ds->len, 1, ofp); + } + + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + int rela_count = section->rela_count; + if (rela_count > 0) { + put_padding(ofp, section->rela_ofs); + fwrite(section->rela_buf, sizeof(Elf64_Rela), rela_count, ofp); + } + } + + put_padding(ofp, work->symtab_ofs); + const struct Symtab *symtab = &work->symtab; + fwrite(symtab->buf, sizeof(*symtab->buf), symtab->count, ofp); + fwrite(strtab_dump(&symtab->strtab), symtab->strtab.size, 1, ofp); + +#if TC_TARGET_ARCH == TC_ARCH_RISCV64 + const unsigned char RISCV_ATTRIBUTES_MAGIC = 0x41; + fputc(RISCV_ATTRIBUTES_MAGIC, ofp); + { + uint32_t total_size = work->riscv_attributes_total_size - 1; + fwrite(&total_size, sizeof(total_size), 1, ofp); /* TODO: ensure little endian */ + } + fwrite(kRiscvAttributesArch, sizeof(kRiscvAttributesArch), 1, ofp); + fputc(0x01, ofp); /* ? */ + { + uint32_t size = 1 + 4 + 1 + work->riscv_attributes_str_size; + fwrite(&size, sizeof(size), 1, ofp); /* TODO: ensure little endian */ + } + fputc(0x05, ofp); /* ? */ + fwrite(work->riscv_attributes, work->riscv_attributes_str_size, 1, ofp); /* output last '\0' */ +#endif + + assert(ofp == stdout || ftell(ofp) == (long)work->shstrtab_ofs); + fwrite(strtab_dump(&work->shstrtab), work->shstrtab.size, 1, ofp); + + put_padding(ofp, work->sh_ofs); + fwrite(work->section_headers.buf, work->section_headers.len, 1, ofp); + + return 0; +} + +int +emit_elf_obj( + const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved +) +{ + struct Work work; + memset(&work, 0x00, sizeof(work)); + work.sections = sections; + work.out_section_count = detect_output_sections(sections); + work.local_symbol_count = construct_symtab(&work.symtab, sections, label_table); + construct_relas(unresolved, &work.symtab, label_table); + uint64_t offset = arrange_section_offsets(&work); + construct_section_headers(&work, offset); + return output_to_file(ofn, &work); +} +#endif diff --git a/cmd/dev/as/emit_macho.c b/cmd/dev/as/emit_macho.c @@ -0,0 +1,561 @@ +#include "../config.h" + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +#include <assert.h> +#include <stdint.h> /* uint64_t */ +#include <stdio.h> +#include <string.h> + +#include <mach-o/loader.h> +#include <mach-o/nlist.h> +#include <mach-o/reloc.h> +#include <mach/machine.h> + +#if TC_TARGET_ARCH == TC_ARCH_AARCH64 +#include <mach-o/arm64/reloc.h> +#elif TC_TARGET_ARCH == TC_ARCH_X64 +#include <mach-o/x86_64/reloc.h> +#else +#error "Unsupported architecture" +#endif + +#include "arch.h" +#include "as_util.h" +#include "ir_asm.h" +#include "parse_asm.h" +#include "table.h" +#include "tcutil.h" + +#if !defined(__NO_BITFIELD) || !defined(__TC) +#define SET_RELOCATION_INFO(rela, adr, sym, pcr, len, ext, typ) \ + do { \ + (rela)->r_address = (adr); \ + (rela)->r_symbolnum = (sym); \ + (rela)->r_pcrel = (pcr); \ + (rela)->r_length = (len); \ + (rela)->r_extern = (ext); \ + (rela)->r_type = (typ); \ + } while (0) +#else +#define SET_RELOCATION_INFO(rela, adr, sym, pcr, len, ext, typ) \ + do { \ + (rela)->r_address = (adr); \ + (rela)->r_pack = \ + (((sym) & ((1U << 24) - 1U)) | (((pcr) & 1U) << 24) | (((len) & 3U) << 25) \ + | (((ext) & 1U) << 27) | (((typ) & 0x0f) << 28)); \ + } while (0) +#endif + +struct Symtab { + struct Strtab strtab; + struct Table indices; + struct nlist_64 *buf; + int ilocalsym, iextdefsym, iundefsym; /* for dysymtab */ + int count; +}; + +void +symtab_init(struct Symtab *symtab) +{ + strtab_init(&symtab->strtab); + table_init(&symtab->indices); + symtab->buf = NULL; + symtab->count = 0; +} + +int +symtab_find(struct Symtab *symtab, const struct Name *name) +{ + intptr_t index; + if (table_try_get(&symtab->indices, name, (void **)&index)) + return index; + return -1; +} + +struct nlist_64 * +symtab_add(struct Symtab *symtab, const struct Name *name) +{ + uint32_t offset = strtab_add(&symtab->strtab, name); + if (name->bytes > 0) { + int index = symtab_find(symtab, name); + if (index >= 0) + return &symtab->buf[index]; + } + + int old_count = symtab->count; + int new_count = old_count + 1; + symtab->buf = realloc_or_die(symtab->buf, sizeof(*symtab->buf) * new_count); + symtab->count = new_count; + struct nlist_64 *sym = &symtab->buf[old_count]; + memset(sym, 0x00, sizeof(*sym)); + sym->n_un.n_strx = offset; + table_put(&symtab->indices, name, INT2VOIDP(old_count)); + return sym; +} + +/* */ + +static void +construct_symtab(struct Symtab *symtab, struct Table *label_table, uint64_t start_address) +{ + symtab_init(symtab); + + /* NUL */ + strtab_add(&symtab->strtab, alloc_cname("")); + + enum SymbolKind { + LOCAL, /* local */ + EXTERNAL, /* external defined */ + UNDEF, /* undefined (including common) */ + }; + int *pcounts[3] = { + &symtab->ilocalsym, + &symtab->iextdefsym, + &symtab->iundefsym, + }; + for (enum SymbolKind sk = 0; sk < (int)ARRAY_SIZE(pcounts); ++sk) { + const struct Name *name; + struct LabelInfo *info; + *pcounts[sk] = symtab->count; + for (int it = 0; (it = table_iterate(label_table, it, &name, (void **)&info)) != -1;) { + switch (sk) { + case LOCAL: + if (!(!(info->flag & LF_GLOBAL) && (info->flag & LF_REFERRED))) + continue; + break; + case EXTERNAL: + if (!((info->flag & LF_GLOBAL) && (info->flag & LF_DEFINED) && !(info->flag & LF_COMM))) + continue; + break; + case UNDEF: + if (!((info->flag & LF_GLOBAL) && (!(info->flag & LF_DEFINED) || (info->flag & LF_COMM)))) + continue; + break; + } + + struct nlist_64 *sym = symtab_add(symtab, name); + uint8_t type = 0; + int sect = 0; + if (info->flag & LF_GLOBAL) { + type = N_EXT; + sect = (info->flag & LF_DEFINED) != 0; + } else if (info->flag & LF_REFERRED || info->flag & LF_DEFINED) { + sect = 1; + } else { + assert(0); + } + + if (info->section != NULL && info->flag & LF_COMM) { + /* .comm */ + assert(info->align > 0 && IS_POWER_OF_2(info->align)); + SET_COMM_ALIGN(sym->n_desc, most_significant_bit(info->align)); + sym->n_value = info->size; + } else if (sect) { + type |= N_SECT; + sym->n_sect = info->section->index; + sym->n_desc = info->flag & LF_WEAK ? N_WEAK_DEF : 0; + sym->n_value = (info->flag & LF_DEFINED) ? info->address - start_address : 0; + } + sym->n_type = type; + } + } +} + +static inline void +construct_rela_element_abs64( + struct Symtab *symtab, + const struct UnresolvedInfo *u, + struct relocation_info *rela, + uint32_t type +) +{ + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + SET_RELOCATION_INFO(rela, u->offset, symidx, 0, 3, 1, type); +} + +#if TC_TARGET_ARCH == TC_ARCH_X64 +static inline void +construct_rela_element( + struct Symtab *symtab, + struct Table *label_table, + struct SectionInfo *section, + const struct UnresolvedInfo *u, + struct relocation_info *rela +) +{ + UNUSED(label_table); + UNUSED(section); + switch (u->kind) { + default: + assert(0); + break; + case UNRES_ABS64: + construct_rela_element_abs64(symtab, u, rela, X86_64_RELOC_UNSIGNED); + break; + + case UNRES_EXTERN: + case UNRES_EXTERN_PC32: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_SIGNED); + } break; + case UNRES_CALL: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_BRANCH); + } break; + case UNRES_X64_GOT_LOAD: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + /* assert(u->add == 0); */ + SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, X86_64_RELOC_GOT_LOAD); + } break; + } +} + +#elif TC_TARGET_ARCH == TC_ARCH_AARCH64 +static inline void +construct_rela_element( + struct Symtab *symtab, + struct Table *label_table, + struct SectionInfo *section, + const struct UnresolvedInfo *u, + struct relocation_info *rela +) +{ + UNUSED(label_table); + switch (u->kind) { + default: + assert(0); + break; + case UNRES_ABS64: + construct_rela_element_abs64(symtab, u, rela, ARM64_RELOC_UNSIGNED); + break; + + case UNRES_EXTERN_PC32: + case UNRES_CALL: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + assert(u->add == 0); + SET_RELOCATION_INFO(rela, u->offset, symidx, 1, 2, 1, ARM64_RELOC_BRANCH26); + } break; + + case UNRES_GOT_HI: + case UNRES_GOT_LO: { + assert(table_get(label_table, u->label) != NULL); + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + assert(u->add == 0); + uint32_t type = + u->kind == UNRES_GOT_HI ? ARM64_RELOC_GOT_LOAD_PAGE21 : ARM64_RELOC_GOT_LOAD_PAGEOFF12; + SET_RELOCATION_INFO(rela, u->offset, symidx, u->kind == UNRES_GOT_HI ? 1 : 0, 2, 1, type); + } break; + + case UNRES_PCREL_HI: + case UNRES_PCREL_LO: { + int symidx = symtab_find(symtab, u->label); + assert(symidx >= 0); + + uint32_t type = u->kind == UNRES_PCREL_HI ? ARM64_RELOC_PAGE21 : ARM64_RELOC_PAGEOFF12; + SET_RELOCATION_INFO(rela, u->offset, symidx, u->kind == UNRES_PCREL_HI ? 1 : 0, 2, 1, type); + + if (u->add != 0) { + int count = ++section->rela_count; + struct relocation_info *rela_buf; + section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf)); + + struct relocation_info *rela2 = &rela_buf[count - 1]; + SET_RELOCATION_INFO(rela2, u->offset, u->add, 0, 2, 0, ARM64_RELOC_ADDEND); + } + } break; + } +} +#endif + +static void +construct_relas(struct Vector *unresolved, struct Symtab *symtab, struct Table *label_table) +{ + for (int i = 0; i < unresolved->len; ++i) { + struct UnresolvedInfo *u = unresolved->data[i]; + struct SectionInfo *section = u->src_section; + int count = ++section->rela_count; + struct relocation_info *rela_buf; + section->rela_buf = rela_buf = realloc_or_die(section->rela_buf, count * sizeof(*rela_buf)); + construct_rela_element(symtab, label_table, section, u, &rela_buf[count - 1]); + } +} + +/* */ + +struct Work { + struct Symtab symtab; + struct mach_header_64 header; + struct segment_command_64 segmentcmd; + struct build_version_command buildversioncmd; + struct symtab_command symtabcmd; + struct dysymtab_command dysymtabcmd; + + struct Vector *sections; + uint64_t start_address; + uint64_t reloc_start_off; + uint64_t section_start_off; + uint32_t size_of_cmds; +}; + +static inline int +detect_output_sections(struct Vector *sections, struct Work *work) +{ + int count = 0; + uint64_t start_address = 0; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if ((section->ds == NULL || section->ds->len <= 0) && section->bss_size <= 0) + continue; + section->index = ++count; + if (start_address == 0) + start_address = section->start_address; + } + work->start_address = start_address; + return count; +} + +static inline void +reverse_relas(struct Vector *sections) +{ + /* reverse the order of relas */ + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + int n = section->rela_count, mid = n >> 1; + struct relocation_info *buf = section->rela_buf; + for (int j = 0; j < mid; ++j) { + struct relocation_info *p = &buf[j]; + struct relocation_info *q = &buf[n - j - 1]; + struct relocation_info tmp = *p; + *p = *q; + *q = tmp; + } + } +} + +static inline uint64_t +arrange_section_offsets(struct Work *work, int section_count) +{ + const uint32_t size_of_cmds = sizeof(struct segment_command_64) + + sizeof(struct section_64) * section_count + + sizeof(struct build_version_command) + + sizeof(struct symtab_command) + sizeof(struct dysymtab_command); + work->size_of_cmds = size_of_cmds; + const uint64_t section_start_off = sizeof(struct mach_header_64) + size_of_cmds; + work->section_start_off = section_start_off; + uint64_t addr = 0, off_p = section_start_off; + struct Vector *sections = work->sections; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + uint64_t size = section->ds != NULL ? section->ds->len : section->bss_size; + if (size <= 0) + continue; + uint64_t align = section->align; + section->start_address = addr = ALIGN(addr, align); + off_p = ALIGN(off_p, align); + if (section->ds != NULL) { + section->offset = off_p; + off_p += size; + } else { + section->offset = 0; + } + addr += size; + } + work->reloc_start_off = off_p; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if (section->ds == NULL) + continue; + section->rela_ofs = 0; + int rela_count = section->rela_count; + if (rela_count > 0) { + section->rela_ofs = off_p; + off_p += sizeof(struct relocation_info) * rela_count; + } + } + + return off_p; +} + +static inline void +construct_load_commands(struct Work *work, uint64_t symbol_start_off, int section_count) +{ + work->header = (struct mach_header_64){ + .magic = MH_MAGIC_64, +#if TC_TARGET_ARCH == TC_ARCH_AARCH64 + .cputype = CPU_TYPE_ARM64, + .cpusubtype = CPU_SUBTYPE_ARM_ALL, +#elif TC_TARGET_ARCH == TC_ARCH_X64 + .cputype = CPU_TYPE_X86_64, + .cpusubtype = CPU_SUBTYPE_X86_ALL, +#else +#error "Unsupported architecture" +#endif + .filetype = MH_OBJECT, + .ncmds = 4, + .sizeofcmds = work->size_of_cmds, + .flags = MH_SUBSECTIONS_VIA_SYMBOLS, /* TODO: handle this flag + */ + }; + uint64_t vmsize = 0, filesize = 0; + struct Vector *sections = work->sections; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + if (section->ds != NULL) { + size_t size = section->ds->len; + if (size <= 0) + continue; + vmsize = ALIGN(vmsize, section->align) + size; + filesize = ALIGN(filesize, section->align) + size; + } else { + size_t size = section->bss_size; + assert(size > 0); + vmsize = ALIGN(vmsize, section->align) + size; + } + } + work->segmentcmd = (struct segment_command_64){ + .cmd = LC_SEGMENT_64, + .cmdsize = sizeof(work->segmentcmd) + sizeof(struct section_64) * section_count, + .segname = "", + .vmaddr = 0, + .vmsize = vmsize, + .fileoff = work->section_start_off, + .filesize = filesize, + .maxprot = 7, /* rwx */ + .initprot = 7, /* rwx */ + .nsects = section_count, + .flags = 0, + }; + work->buildversioncmd = (struct build_version_command){ + .cmd = LC_BUILD_VERSION, + .cmdsize = sizeof(work->buildversioncmd), + .platform = PLATFORM_MACOS, + .minos = 0x000e0000, /* 14.0.0 */ + .sdk = 0x000e0500, /* 14.5.0 */ + .ntools = 0, + }; + const struct Symtab *symtab = &work->symtab; + const uint64_t str_start_off = symbol_start_off + sizeof(*symtab->buf) * symtab->count; + work->symtabcmd = (struct symtab_command){ + .cmd = LC_SYMTAB, + .cmdsize = sizeof(work->symtabcmd), + .symoff = symbol_start_off, + .nsyms = symtab->count, + .stroff = str_start_off, + .strsize = symtab->strtab.size, + }; + work->dysymtabcmd = (struct dysymtab_command){ + .cmd = LC_DYSYMTAB, + .cmdsize = sizeof(work->dysymtabcmd), + .ilocalsym = symtab->ilocalsym, + .nlocalsym = symtab->iextdefsym - symtab->ilocalsym, + .iextdefsym = symtab->iextdefsym, + .nextdefsym = symtab->iundefsym - symtab->iextdefsym, + .iundefsym = symtab->iundefsym, + .nundefsym = symtab->count - symtab->iundefsym, + }; +} + +static inline int +output_to_file(const char *ofn, const struct Work *work) +{ + FILE *ofp; + if (ofn == NULL) { + ofp = stdout; + } else { + ofp = fopen(ofn, "wb"); + if (ofp == NULL) { + fprintf(stderr, "Failed to open output file: %s\n", ofn); + return 1; + } + } + + fwrite(&work->header, sizeof(work->header), 1, ofp); + fwrite(&work->segmentcmd, sizeof(work->segmentcmd), 1, ofp); + struct Vector *sections = work->sections; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + size_t size = section->ds != NULL ? section->ds->len : section->bss_size; + if (size <= 0) + continue; + uint32_t flags = 0; + if (section->flag & SF_INIT_FUNCS) + flags |= S_MOD_INIT_FUNC_POINTERS; + else if (section->flag & SF_CSTRLITERALS) + flags |= S_CSTRING_LITERALS; + else if (section->flag & SF_BSS) + flags |= S_ZEROFILL; + else if (section->flag & SF_EXECUTABLE) + flags |= S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS; + struct section_64 sect = { + .addr = section->start_address, + .size = size, + .offset = section->offset, + .align = most_significant_bit(section->align), + .reloff = section->rela_ofs, + .nreloc = section->rela_count, + .flags = flags, + }; + strncpy( + sect.sectname, + section->name->chars, + MIN(sizeof(sect.sectname), (size_t)section->name->bytes) + ); + if (section->segname != NULL) + strncpy(sect.segname, section->segname, sizeof(sect.segname)); + fwrite(&sect, sizeof(sect), 1, ofp); + } + fwrite(&work->buildversioncmd, sizeof(work->buildversioncmd), 1, ofp); + fwrite(&work->symtabcmd, sizeof(work->symtabcmd), 1, ofp); + fwrite(&work->dysymtabcmd, sizeof(work->dysymtabcmd), 1, ofp); + + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + struct DataStorage *ds = section->ds; + if (ds == NULL || ds->len <= 0) + continue; + put_padding(ofp, section->offset); + fwrite(ds->buf, ds->len, 1, ofp); + } + put_padding(ofp, work->reloc_start_off); + for (int i = 0; i < sections->len; ++i) { + struct SectionInfo *section = sections->data[i]; + int rela_count = section->rela_count; + if (rela_count > 0) { + put_padding(ofp, section->rela_ofs); + fwrite(section->rela_buf, sizeof(struct relocation_info), rela_count, ofp); + } + } + fwrite(work->symtab.buf, sizeof(*work->symtab.buf), work->symtab.count, ofp); + fwrite(strtab_dump(&work->symtab.strtab), work->symtab.strtab.size, 1, ofp); + + return 0; +} + +int +emit_macho_obj( + const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved +) +{ + struct Work work; + memset(&work, 0x00, sizeof(work)); + work.sections = sections; + + const int section_count = detect_output_sections(sections, &work); + construct_symtab(&work.symtab, label_table, work.start_address); + construct_relas(unresolved, &work.symtab, label_table); + reverse_relas(sections); + + uint64_t off_p = arrange_section_offsets(&work, section_count); + construct_load_commands(&work, off_p, section_count); + return output_to_file(ofn, &work); +} +#endif diff --git a/cmd/dev/as/format.h b/cmd/dev/as/format.h @@ -0,0 +1,25 @@ +/* format dispatch: selects the output object format at compile time + * a new format adds its emit function below and its source file + * alongside emit_elf.c / emit_macho.c */ + +#ifndef AS_FORMAT_H +#define AS_FORMAT_H + +#include "../config.h" + +struct Table; +struct Vector; + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +int emit_macho_obj( + const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved +); +#define EMIT_OBJ emit_macho_obj +#else +int emit_elf_obj( + const char *ofn, struct Vector *sections, struct Table *label_table, struct Vector *unresolved +); +#define EMIT_OBJ emit_elf_obj +#endif + +#endif /* AS_FORMAT_H */ diff --git a/cmd/dev/as/ir_asm.c b/cmd/dev/as/ir_asm.c @@ -0,0 +1,301 @@ +#include "../config.h" + +#include "ir_asm.h" + +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "arch.h" +#include "parse_asm.h" +#include "table.h" +#include "tcutil.h" + +/* ir constructors */ + +struct IR * +new_ir_label(const struct Name *label) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_LABEL; + ir->label = label; + return ir; +} + +struct IR * +new_ir_code(const struct Code *code) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_CODE; + ir->code = *code; + return ir; +} + +struct IR * +new_ir_data(const void *data, size_t size) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_DATA; + ir->data.len = size; + ir->data.buf = (unsigned char *)data; + return ir; +} + +struct IR * +new_ir_bss(size_t size) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_BSS; + ir->bss = size; + return ir; +} + +struct IR * +new_ir_zero(size_t size) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_ZERO; + ir->zero = size; + return ir; +} + +struct IR * +new_ir_align(int align) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_ALIGN; + ir->align = align; + return ir; +} + +struct IR * +new_ir_expr(enum IrKind kind, const struct Expr *expr) +{ + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = kind; + ir->expr.expr = expr; + ir->expr.addend = 0; + return ir; +} + +/* section data helpers */ + +static void +sec_add_data(struct SectionInfo *section, const void *data, size_t bytes) +{ + assert(!(section->flag & SF_BSS)); + data_append(section->ds, data, bytes); +} + +static void +sec_add_code(struct SectionInfo *section, const void *buf, size_t bytes) +{ + sec_add_data(section, buf, bytes); +} + +static void +sec_add_bss(struct SectionInfo *section, size_t size) +{ + assert(section->flag & SF_BSS); + section->bss_size += size; +} + +static void +sec_align_size(struct SectionInfo *section, size_t align) +{ + if (align > section->align) + section->align = align; + + if (section->flag & SF_BSS) { + section->bss_size = ALIGN(section->bss_size, align); + } else if (section->flag & SF_EXECUTABLE) { + /* data_align pads with zero bytes, which decode as real (and + wrong) instructions if control flow falls through them; pad + with single-byte nops instead */ + size_t len = section->ds->len; + size_t aligned_len = ALIGN(len, align); + if (aligned_len > len) { + unsigned char *nops = malloc_or_die(aligned_len - len); + memset(nops, 0x90, aligned_len - len); + data_append(section->ds, nops, aligned_len - len); + free(nops); + } + } else { + data_align(section->ds, align); + } +} + +/* label address assignment */ + +int +calc_label_address(uint64_t start_address, struct Vector *sections, struct Table *label_table) +{ + int settle = 1; + uint64_t address = start_address; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + address = ALIGN(address, section->align); + section->start_address = address; + + struct Vector *irs = section->irs; + for (int i = 0, len = irs->len; i < len; ++i) { + struct IR *ir = irs->data[i]; + ir->address = address; + switch (ir->kind) { + case IR_LABEL: { + struct LabelInfo *info; + if (!table_try_get(label_table, ir->label, (void **)&info)) { + fprintf(stderr, "[%.*s] not found\n", NAMES(ir->label)); + assert(!"unexpected"); + } else { + info->address = address; + } + } break; + case IR_CODE: + address += ir->code.len; + break; + case IR_DATA: + address += ir->data.len; + break; + case IR_BSS: + address += ir->bss; + break; + case IR_ZERO: + address += ir->zero; + break; + case IR_ALIGN: + ir->address = address = ALIGN(address, ir->align); + if ((size_t)ir->align > section->align) { + section->align = ir->align; + settle = 0; + } + break; + case IR_EXPR_BYTE: + address += BYTE_SIZE; + break; + case IR_EXPR_SHORT: + address += SHORT_SIZE; + break; + case IR_EXPR_LONG: + address += LONG_SIZE; + break; + case IR_EXPR_QUAD: + address += QUAD_SIZE; + break; + } + } + } + return settle; +} + +/* relative address resolution */ + +static void +put_value(unsigned char *p, int64_t value, int size) +{ + for (int i = 0; i < size; ++i) { + *p++ = value; + value >>= 8; + } +} + +int +resolve_relative_address( + struct Vector *sections, struct Table *label_table, struct Vector *unresolved +) +{ + assert(unresolved != NULL); + vec_clear(unresolved); + int size_upgraded = 0; + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + struct Vector *irs = section->irs; + uint64_t start_address = irs->len > 0 ? ((struct IR *)irs->data[0])->address : 0; + for (int i = 0, len = irs->len; i < len; ++i) { + struct IR *ir = irs->data[i]; + uint64_t address = ir->address; + switch (ir->kind) { + case IR_CODE: + arch.resolve_code_reloc( + ir, section, address, start_address, label_table, unresolved, &size_upgraded + ); + break; + case IR_EXPR_BYTE: + case IR_EXPR_SHORT: + case IR_EXPR_LONG: + case IR_EXPR_QUAD: { + struct Value value = calc_expr(label_table, ir->expr.expr); + assert(value.label != NULL); + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_ABS64; + info->label = value.label; + info->src_section = section; + info->offset = address - start_address; + info->add = value.offset; + ir->expr.addend = value.offset; + vec_push(unresolved, info); + } break; + case IR_LABEL: + case IR_DATA: + case IR_BSS: + case IR_ZERO: + case IR_ALIGN: + break; + } + } + } + + return !size_upgraded; +} + +/* emit section data */ + +void +emit_irs(struct Vector *sections) +{ + for (int sec = 0; sec < sections->len; ++sec) { + struct SectionInfo *section = sections->data[sec]; + struct Vector *irs = section->irs; + for (int i = 0, len = irs->len; i < len; ++i) { + struct IR *ir = irs->data[i]; + switch (ir->kind) { + case IR_LABEL: + break; + case IR_CODE: + sec_add_code(section, ir->code.buf, ir->code.len); + break; + case IR_DATA: + sec_add_data(section, ir->data.buf, ir->data.len); + break; + case IR_BSS: + sec_add_bss(section, ir->bss); + break; + case IR_ZERO: + if (section->flag & SF_BSS) { + sec_add_bss(section, ir->zero); + } else { + void *buf = calloc_or_die(ir->zero); + sec_add_data(section, buf, ir->zero); + } + break; + case IR_ALIGN: + sec_align_size(section, ir->align); + break; + case IR_EXPR_BYTE: + case IR_EXPR_SHORT: + case IR_EXPR_LONG: + case IR_EXPR_QUAD: { +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + int64_t value = ir->expr.addend; +#else + int64_t value = 0; +#endif + int size = 1 << (ir->kind - IR_EXPR_BYTE); + sec_add_data(section, &value, size); + } break; + } + } + } +} diff --git a/cmd/dev/as/ir_asm.h b/cmd/dev/as/ir_asm.h @@ -0,0 +1,97 @@ +/* intermediate representation for assembly */ + +#ifndef AS_IR_ASM_H +#define AS_IR_ASM_H + +#include <stddef.h> /* size_t */ +#include <stdint.h> /* uint64_t, int64_t */ + +#include "asm_code.h" /* struct code */ + +#define BYTE_SIZE (1) +#define SHORT_SIZE (2) +#define LONG_SIZE (4) +#define QUAD_SIZE (8) + +struct Expr; +struct Name; +struct SectionInfo; +struct Table; +struct Vector; + +/* unresolved relocation categories. the generic kinds are shared across + * all arch backends. arch-specific kinds are defined in each archs + * inst.h starting from UNRES_ARCH_BASE so they dont collide */ +enum UnresolvedKind { + /* arch-neutral */ + UNRES_EXTERN, + UNRES_EXTERN_PC32, + UNRES_ABS64, + UNRES_CALL, + UNRES_PCREL_HI, + UNRES_PCREL_LO, + UNRES_GOT_HI, + UNRES_GOT_LO, + /* arch-specific kinds start here */ + UNRES_ARCH_BASE = 0x1000, +}; + +struct UnresolvedInfo { + const struct Name *label; + uintptr_t offset; + struct SectionInfo *src_section; + int add; + enum UnresolvedKind kind; +}; + +struct Data { + size_t len; + unsigned char *buf; +}; + +enum IrKind { + IR_LABEL, + IR_CODE, + IR_DATA, + IR_BSS, + IR_ZERO, + IR_ALIGN, + IR_EXPR_BYTE, + IR_EXPR_SHORT, + IR_EXPR_LONG, + IR_EXPR_QUAD, +}; + +struct IR { + enum IrKind kind; + union { + const struct Name *label; + struct Code code; + struct Data data; + struct { + const struct Expr *expr; + int64_t addend; /* calculated in resolve_relative_address */ + } expr; + size_t bss; + size_t zero; + int align; + int section; + }; + uint64_t address; +}; + +struct IR *new_ir_label(const struct Name *label); +struct IR *new_ir_code(const struct Code *code); +struct IR *new_ir_data(const void *data, size_t size); +struct IR *new_ir_bss(size_t size); +struct IR *new_ir_zero(size_t size); +struct IR *new_ir_align(int align); +struct IR *new_ir_expr(enum IrKind kind, const struct Expr *expr); + +int calc_label_address(uint64_t start_address, struct Vector *sections, struct Table *label_table); +int resolve_relative_address( + struct Vector *sections, struct Table *label_table, struct Vector *unresolved +); +void emit_irs(struct Vector *sections); + +#endif /* AS_IR_ASM_H */ diff --git a/cmd/dev/as/parse_asm.c b/cmd/dev/as/parse_asm.c @@ -0,0 +1,1566 @@ +#include "../config.h" + +#include "parse_asm.h" +#include <assert.h> +#include <ctype.h> +#include <stdint.h> +#include <stdlib.h> /* strtoul */ +#include <string.h> +#include <strings.h> + +#if __STDC_NO_VLA__ +#include <alloca.h> +#endif + +#include "ir_asm.h" +#include "table.h" +#include "tcutil.h" + +#include "arch.h" + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +const char kSegText[] = "__TEXT"; +const char kSecText[] = "__text"; +const char kSegRodata[] = "__DATA"; +const char kSecRodata[] = "__const"; +const char kSegData[] = "__DATA"; +const char kSecData[] = "__data"; +const char kSegBss[] = "__DATA"; +const char kSecBss[] = "__bss"; +#else +const char kSecText[] = ".text"; +const char kSecRodata[] = ".rodata"; +const char kSecData[] = ".data"; +const char kSecBss[] = ".bss"; +#endif + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +#define WEAK "weak_definition" +#else +#define WEAK "weak" +#endif + +static const char *kDirectiveTable[] = { + "ascii", + "string", + "section", + "text", + "data", + "bss", + "align", + "p2align", + "balign", + "type", + "byte", + "short", + "long", + "quad", + "comm", + "zero", + "globl", + "local", + WEAK, + "extern", + "int", + "word", + "2byte", + "4byte", + "8byte", + "fill", + "space", + "skip", + "set", + "equ", + "file", + "loc", + "ident", + "previous", +#ifndef __NO_FLONUM + "float", + "double", +#endif +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + "subsections_via_symbols", +#endif + "size", +}; + +struct SectionInfo * +get_section_info(struct ParseInfo *info, const char *name, const char *segname, int flag) +{ + const struct Name *key = alloc_name(name, NULL, 1); + struct SectionInfo *section; + if (!table_try_get(info->section_infos, key, (void **)&section)) { + section = calloc_or_die(sizeof(*section)); + section->name = key; + section->segname = segname; + section->irs = new_vector(); + section->flag = flag; + section->index = 0; + section->start_address = 0; + section->ds = NULL; + section->align = 1; + section->bss_size = 0; + section->rela_count = 0; + section->rela_buf = NULL; + if (!(flag & SF_BSS)) { + struct DataStorage *ds = calloc_or_die(sizeof(*ds)); + data_init(ds); + section->ds = ds; + } + table_put(info->section_infos, key, section); + } + return section; +} + +struct SectionInfo * +set_current_section(struct ParseInfo *info, const char *name, const char *segname, int flag) +{ + struct SectionInfo *section = get_section_info(info, name, segname, flag); + info->current_section = section; + return section; +} + +static struct LabelInfo * +new_label(struct SectionInfo *section) +{ + struct LabelInfo *info = calloc_or_die(sizeof(*info)); + info->section = section; + info->flag = 0; + info->address = 0; + info->kind = LK_NONE; + info->size = 0; + info->align = 0; + return info; +} + +struct LabelInfo * +add_label_table( + struct Table *label_table, + const struct Name *label, + struct SectionInfo *section, + int define, + int global +) +{ + struct LabelInfo *info = table_get(label_table, label); + if (info != NULL) { + if (define) { + if ((info->flag & LF_DEFINED) != 0) { + fprintf(stderr, "`%.*s' already defined\n", NAMES(label)); + return NULL; + } + info->address = 1; + info->section = section; + } + } else { + info = new_label(section); + table_put(label_table, label, info); + } + if (define) + info->flag |= LF_DEFINED; + if (global) + info->flag |= LF_GLOBAL; + return info; +} + +int +parse_error(struct ParseInfo *info, const char *message) +{ + fprintf(stderr, "%s(%d): %s\n", info->filename, info->lineno, message); + fprintf(stderr, "%s\n", info->rawline); + ++info->error_count; + return 0; +} + +static enum DirectiveType +find_directive(const char *p, size_t n) +{ + const char **table = kDirectiveTable; + size_t i; + + for (i = 0; i < ARRAY_SIZE(kDirectiveTable); ++i) { + const char *name = table[i]; + if (strncasecmp(p, name, n) == 0 && name[n] == '\0') { + return i + 1; + } + } + /* cfi directives are a family, tolerate them all */ + if (n >= 4 && strncasecmp(p, "cfi_", 4) == 0) + return DT_CFI; + return NODIRECTIVE; +} + +int +immediate(const char **pp, int64_t *value) +{ + const char *p = *pp; + int negative = 0; + if (*p == '-') { + negative = 1; + ++p; + } + + int base = 10; + if (*p == '0') { + char c = tolower(p[1]); + if (c == 'x') { + base = 16; + p += 2; + c = tolower(*p); + if (!isxdigit(c)) + return 0; + } else if (isdigit(c)) { + if (c >= '8') + return 0; + base = 8; + } + } + const char *q = p; + unsigned long val = strtoul(p, (char **)&p, base); + if (p == q) + return 0; + + *value = negative ? -val : val; + *pp = p; + return 1; +} + +int +is_label_first_chr(char c) +{ + return isalpha(c) || c == '_' || c == '.'; +} + +int +is_label_chr(char c) +{ + return is_label_first_chr(c) || isdigit(c); +} + +static const char * +get_label_end(struct ParseInfo *info) +{ + const char *start = info->p; + const char *p = start; + if (*p == '"') { + ++p; + for (;;) { + char c = *p; + if (c == '\0') { + parse_error(info, "string not closed"); + break; + } + + ++p; + if (c == '"') + break; + if (c == '\\') + ++p; + } + /* a properly closed quoted string is valid even when empty (""); + * the p <= start check below exists for the bare-identifier + * branch, where reaching it unmoved means no label was found at + * all, so it does not apply here */ + return p; + } else { + const unsigned char *q = (const unsigned char *)p; + int ucc = 0; + for (;;) { + int uc = *++q; + if (ucc > 0) { + if (!isutf8follow(uc)) { + parse_error(info, "illegal byte sequence"); + return NULL; + } + --ucc; + continue; + } + if ((ucc = isutf8first(uc) - 1) > 0) + continue; + if (!is_label_chr(uc)) + break; + } + p = (const char *)q; + } + if (p <= start) + parse_error(info, "empty label"); + return p; +} + +const struct Name * +unquote_label(const char *p, const char *q) +{ + if (*p != '"') + return alloc_name(p, q, 0); + if (q[-1] != '"' || q == p + 2) + return NULL; + /* TODO: unescape */ + return alloc_name(p + 1, q - 1, 0); +} + +static const struct Name * +parse_label(struct ParseInfo *info) +{ + const char *start = info->p; + const char *p = get_label_end(info); + if (p == start) + return NULL; + + info->p = p; + return unquote_label(start, p); +} + +static const struct Name * +parse_section_name(struct ParseInfo *info) +{ + const char *p = info->p; + const char *start = p; + + if (!is_label_first_chr(*p)) + return NULL; + + do { + ++p; + } while (isalnum_(*p) || *p == '.' || *p == '-' || *p == '_'); + info->p = p; + return alloc_name(start, p, 0); +} + +enum TokenKind { + TK_EOF, + TK_UNKNOWN, + TK_LABEL, + TK_FIXNUM, + TK_ADD, + TK_SUB, + TK_MUL, + TK_DIV, + TK_FLONUM, +}; + +struct Token { + enum TokenKind kind; + union { + struct { + const struct Name *name; + } label; + int64_t fixnum; +#ifndef __NO_FLONUM + Flonum flonum; +#endif + }; +}; + +static struct Token * +new_token(enum TokenKind kind) +{ + struct Token *token = calloc_or_die(sizeof(*token)); + token->kind = kind; + return token; +} + +#ifndef __NO_FLONUM +static struct Token * +read_flonum(struct ParseInfo *info, int base) +{ + const char *start = info->p; + char *next; +#ifdef __TC + /* long double in the toolchain compiler is same as double, and if the target platform uses + */ + /* system library, it makes discrepancy */ + Flonum val = strtod(start, &next); +#else + Flonum val = strtold(start, &next); +#endif + struct Token *tok = new_token(TK_FLONUM); + tok->flonum = val; + info->p = next; + + if (base == 16) { + /* check exponent part exists */ + const char *q; + for (q = start; q < next; ++q) { + if (tolower(*q) == 'p') + break; + } + if (q >= next) { + parse_error(info, "hex float literal must have exponent part"); + } + } + + return tok; +} +#endif + +static const struct Token * +fetch_token(struct ParseInfo *info) +{ + static const struct Token kTokEOF = {.kind = TK_EOF}; + const char *start = skip_whitespaces(info->p); + const char *p = start; + char c = *p; + switch (c) { + case '\0': + return &kTokEOF; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + int base = 10; + if (c == '0' && tolower(p[1]) == 'x') { +#ifndef __NO_FLONUM + if (c == '.') /* hex float literal */ + return read_flonum(info, 16); +#endif + if (isxdigit(p[2])) { + p += 2; + base = 16; + } + } + char *q; + unsigned long long v = strtoull(p, &q, base); +#ifndef __NO_FLONUM + if (*q == '.' || tolower(*q) == 'e') { + info->p = p; + return read_flonum(info, 10); + } +#endif + struct Token *token = new_token(TK_FIXNUM); + token->fixnum = v; + info->p = q; + return token; + } + case '"': { + info->p = p; + const struct Name *label = parse_label(info); + if (label != NULL) { + struct Token *token = new_token(TK_LABEL); + token->label.name = label; + return token; + } + } break; + case '+': + case '-': + case '*': + case '/': { + enum TokenKind kind; + switch (c) { + default: + assert(0); /* to suppress warning */ + case '+': + kind = TK_ADD; + break; + case '-': + kind = TK_SUB; + break; + case '*': + kind = TK_MUL; + break; + case '/': + kind = TK_DIV; + break; + } + info->p = p + 1; + return new_token(kind); + } +#ifndef __NO_FLONUM + case '.': + if (isdigit(p[1])) { + info->p = p; + return read_flonum(info, 10); + } + break; +#endif + default: + break; + } + + if (is_label_first_chr(c)) { + const char *label = p; + while (c = *++p, is_label_chr(c)) + ; + struct Token *token = new_token(TK_LABEL); + token->label.name = alloc_name(label, p, 0); + info->p = p; + return token; + } + + static const struct Token kTokUnknown = {.kind = TK_UNKNOWN}; + return &kTokUnknown; +} + +static const struct Token * +match(struct ParseInfo *info, enum TokenKind kind) +{ + const struct Token *token = info->prefetched; + if (token == NULL) + token = fetch_token(info); + + if (token->kind != kind) { + info->prefetched = token; + return NULL; + } + info->prefetched = NULL; + return token; +} + +struct Expr * +new_expr(enum ExprKind kind) +{ + struct Expr *expr = calloc_or_die(sizeof(*expr)); + expr->kind = kind; + return expr; +} + +static struct Expr * +prim(struct ParseInfo *info) +{ + struct Expr *expr = NULL; + const struct Token *tok; + if ((tok = match(info, TK_LABEL)) != NULL) { + expr = new_expr(EX_LABEL); + expr->label.name = tok->label.name; + } else if ((tok = match(info, TK_FIXNUM)) != NULL) { + expr = new_expr(EX_FIXNUM); + expr->fixnum = tok->fixnum; +#ifndef __NO_FLONUM + } else if ((tok = match(info, TK_FLONUM)) != NULL) { + expr = new_expr(EX_FLONUM); + expr->flonum = tok->flonum; +#endif + } + return expr; +} + +static struct Expr * +unary(struct ParseInfo *info) +{ + const struct Token *tok; + if ((tok = match(info, TK_ADD)) != NULL) { + struct Expr *expr = unary(info); + if (expr == NULL) + return NULL; + switch (expr->kind) { + case EX_FIXNUM: + case EX_FLONUM: + return expr; + default: { + struct Expr *op = new_expr(EX_POS); + op->unary.sub = expr; + return op; + } + } + } + + if ((tok = match(info, TK_SUB)) != NULL) { + struct Expr *expr = unary(info); + if (expr == NULL) + return NULL; + switch (expr->kind) { + case EX_FIXNUM: + expr->fixnum = -expr->fixnum; + return expr; +#ifndef __NO_FLONUM + case EX_FLONUM: + expr->flonum = -expr->flonum; + return expr; +#endif + default: { + struct Expr *op = new_expr(EX_NEG); + op->unary.sub = expr; + return op; + } + } + } + + return prim(info); +} + +static struct Expr * +parse_mul(struct ParseInfo *info) +{ + struct Expr *expr = unary(info); + if (expr == NULL) + return expr; + + const struct Token *tok; + while ((tok = match(info, TK_MUL)) != NULL || (tok = match(info, TK_DIV)) != NULL) { + struct Expr *rhs = unary(info); + if (rhs == NULL) { + parse_error(info, "expression error"); + break; + } + + struct Expr *lhs = expr; + if (lhs->kind == EX_FIXNUM && rhs->kind == EX_FIXNUM) { + switch (tok->kind) { + case TK_MUL: + lhs->fixnum *= rhs->fixnum; + break; + case TK_DIV: + lhs->fixnum /= rhs->fixnum; + break; + default: + assert(0); + break; + } + } else { + expr = new_expr((enum ExprKind)(tok->kind + (EX_MUL - TK_MUL))); /* assume exprkind is same + * order with tokenkind */ + expr->bop.lhs = lhs; + expr->bop.rhs = rhs; + } + } + return expr; +} + +static struct Expr * +parse_add(struct ParseInfo *info) +{ + struct Expr *expr = parse_mul(info); + if (expr == NULL) + return expr; + + const struct Token *tok; + while ((tok = match(info, TK_ADD)) != NULL || (tok = match(info, TK_SUB)) != NULL) { + struct Expr *rhs = parse_mul(info); + if (rhs == NULL) { + parse_error(info, "expression error"); + break; + } + + struct Expr *lhs = expr; + if (lhs->kind == EX_FIXNUM && rhs->kind == EX_FIXNUM) { + switch (tok->kind) { + case TK_ADD: + lhs->fixnum += rhs->fixnum; + break; + case TK_SUB: + lhs->fixnum -= rhs->fixnum; + break; + default: + assert(0); + break; + } + } else { + /* assume exprkind is same order with tokenkind */ + expr = new_expr((enum ExprKind)(tok->kind + (EX_ADD - TK_ADD))); + expr->bop.lhs = lhs; + expr->bop.rhs = rhs; + } + } + return expr; +} + +struct Expr * +parse_expr(struct ParseInfo *info) +{ + info->prefetched = NULL; + return parse_add(info); +} + +#define R_NOOP 0 + +static /* enum rawopcode */ int +find_raw_opcode(struct ParseInfo *info) +{ + const char *p = info->p; + const char *start = p; + + while (isalnum(*p) || *p == '.') + ++p; + if (*p == '\0' || isspace(*p)) { + size_t n = p - start; + for (int i = 0;; ++i) { + const char *name = arch.raw_op_table[i]; + if (name == NULL) + break; + size_t len = strlen(name); + if (n == len && strncasecmp(start, name, n) == 0) { + info->p = skip_whitespaces(p); + return i + 1; + } + } + } + return R_NOOP; +} + +static int +parse_inst(struct ParseInfo *info, struct Line *line) +{ + struct Inst inst; + inst.op = NOOP; + inst.prefix = 0; + for (int i = 0; i < (int)ARRAY_SIZE(inst.opr); ++i) + inst.opr[i].type = NOOPERAND; + + /* scan for arch-specific instruction prefixes (lock, rep, etc) */ + if (arch.scan_prefix) { + unsigned char pfx; + while ((pfx = arch.scan_prefix(info)) != 0) + inst.prefix |= pfx; + } + + /* enum rawopcode */ int op = find_raw_opcode(info); + if (op != R_NOOP) { + const struct ParseInstTable *pt = &arch.parse_inst_table[op]; + int n = pt->count; +#if __STDC_NO_VLA__ + const struct ParseOpArray **candidates = alloca(n * sizeof(*candidates)); + assert(candidates != NULL); +#else + const struct ParseOpArray *candidates[n]; +#endif + memcpy(candidates, pt->array, n * sizeof(*candidates)); + for (int i = 0; i < (int)ARRAY_SIZE(inst.opr); ++i) { + unsigned int opr_flags = 0; + for (int j = 0; j < n; ++j) + opr_flags |= candidates[j]->opr_flags[i]; + if (opr_flags == 0) + break; + + if (i > 0) { + if (*info->p != ',') { + if (candidates[0]->opr_flags[i] == 0) + break; + parse_error(info, "comma expected"); + return 0; /* error */ + } + info->p = skip_whitespaces(info->p + 1); + } + + struct Operand *opr = &inst.opr[i]; + unsigned int result = arch.parse_operand(info, opr_flags, opr); + if (result == 0) { + parse_error(info, "illegal operand"); + info->p = NULL; + return 0; /* error */ + } + + for (int j = 0; j < n; ++j) { + if ((candidates[j]->opr_flags[i] & result) == 0) { + memmove(&candidates[j], &candidates[j + 1], (n - j - 1) * sizeof(*candidates)); + --n; + --j; + } + } + + info->p = skip_whitespaces(info->p); + } + + if (n > 0) { + inst.op = candidates[0]->op; + } else { + return parse_error(info, "illegal operand"); + } + if (*info->p != '\0') + return parse_error(info, "instruction text after operands"); + } else { + return parse_error(info, "unknown instruction"); + } + + if (inst.op != NOOP) { + struct Inst *cloned = calloc_or_die(sizeof(inst)); + *cloned = inst; + line->inst = cloned; + } + return 1; +} + +void +parse_set_p(struct ParseInfo *info, const char *p) +{ + info->p = p; + info->prefetched = NULL; +} + +static char +unescape_char(struct ParseInfo *info) +{ + const char *p = info->p; + char c = *p++; + switch (c) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + /* octal, but accepts '8' and '9' */ + int x = 0; + --p; + for (int i = 0; i < 3; ++i, ++p) { /* "the numeric code is 3 octal digits." */ + char cc = *p; + if (!isdigit(cc)) + break; + x = (x << 3) | (cc - '0'); + } + info->p = p - 1; + return x; + } + case 'x': { + int x = 0; + for (;; ++p) { /* "all trailing hex digits are combined." */ + int v = xvalue(*p); + if (v < 0) + break; /* TODO: error */ + x = (x << 4) | v; + } + info->p = p - 1; + return x; + } + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + + default: + parse_error(info, "illegal escape"); + /* fallthrough */ + case '\'': + case '"': + case '\\': + return c; + } +} + +static size_t +unescape_string(struct ParseInfo *info, char *dst) +{ + size_t len = 0; + for (; *info->p != '"'; ++info->p, ++len) { + char c = *info->p; + if (c == '\0') + parse_error(info, "string not closed"); + if (c == '\\') { + ++info->p; + c = unescape_char(info); + } + if (dst != NULL) + *dst++ = c; + } + ++info->p; + return len; +} + +#if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE +static char * +parse_string(struct ParseInfo *info) +{ + const char *start = skip_whitespaces(info->p); + if (*start != '"') + return NULL; + + info->p = start; + const char *p = get_label_end(info); + if (p == start) + return NULL; + + info->p = p; + + const char *s = start + 1, *e = p - 1; + return strndup(s, e - s); +} + +static uint32_t +parse_section_flag(struct ParseInfo *info) +{ + uint32_t flag = 0; + char *flag_str = parse_string(info); + if (flag_str == NULL) { + parse_error(info, ".section: flag string expected"); + } else { + for (char *p = flag_str; *p != '\0'; ++p) { + switch (*p) { + case 'a': /* ignore */ + break; + case 'w': + flag |= SF_WRITABLE; + break; + case 'x': + flag |= SF_EXECUTABLE; + break; + case 'T': + flag |= SF_TLS; + break; + default: + parse_error(info, ".section: illegal flag character"); + break; + } + } + } + return flag; +} +#endif + +static int +dir_string(struct ParseInfo *info, enum DirectiveType dir) +{ + if (*info->p != '"') + return parse_error(info, "`\"' expected"); + ++info->p; + const char *p = info->p; + size_t len = unescape_string(info, NULL); + if (dir == DT_STRING) + ++len; + char *str = calloc_or_die(len); + info->p = p; /* again */ + unescape_string(info, str); + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + vec_push(irs, new_ir_data(str, len)); + return 1; +} + +static int +dir_comm(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + const struct Name *name = parse_label(info); + if (name == NULL) + return parse_error(info, ".comm: label expected"); + info->p = skip_whitespaces(info->p); + if (*info->p != ',') + return parse_error(info, ".comm: `,' expected"); + info->p = skip_whitespaces(info->p + 1); + int64_t size; + if (!immediate(&info->p, &size) || size <= 0) + return parse_error(info, ".comm: size expected"); + + int64_t align = 0; + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if ( + !immediate(&info->p, &align) || +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + align < 0 +#else + align < 1 +#endif + ) { + return parse_error(info, ".comm: optional alignment expected"); + } +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + /* p2align on macos */ + align = 1 << align; +#endif + } + + struct SectionInfo *section = get_section_info(info, kSecBss, kSegBss, SF_BSS | SF_WRITABLE); + struct Vector *irs = section->irs; + if (align > 1) + vec_push(irs, new_ir_align(align)); + vec_push(irs, new_ir_label(name)); + vec_push(irs, new_ir_bss(size)); + + struct LabelInfo *label = add_label_table(info->label_table, name, section, 1, 0); + if (label == NULL) + return 0; + label->size = size; + label->align = align; + label->flag |= LF_COMM; + return 1; +} + +static int +dir_zero(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + int64_t num; + if (!immediate(&info->p, &num)) + return parse_error(info, ".zero: number expected"); + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + vec_push(irs, new_ir_zero(num)); + return 1; +} + +static int +dir_text(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + set_current_section(info, kSecText, kSegText, SF_EXECUTABLE); + return 1; +} + +static int +dir_data(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + set_current_section(info, kSecData, kSegData, SF_WRITABLE); + return 1; +} + +static int +dir_bss(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + set_current_section(info, kSecBss, kSegBss, SF_BSS | SF_WRITABLE); + return 1; +} + +static int +dir_align(struct ParseInfo *info, enum DirectiveType dir) +{ + int64_t align; + if (!immediate(&info->p, &align)) + return parse_error(info, ".align: number expected"); + if (dir == DT_P2ALIGN) + align = 1 << align; + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + vec_push(irs, new_ir_align(align)); + return 1; +} + +static int +dir_type(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + const struct Name *name = parse_label(info); + if (name == NULL) + return parse_error(info, ".type: label expected"); + if (*info->p != ',') + return parse_error(info, ".type: `,' expected"); + info->p = skip_whitespaces(info->p + 1); + enum LabelKind kind = LK_NONE; + if (strcmp(info->p, "@function") == 0) { + kind = LK_FUNC; + info->p += 9; + } else if (strcmp(info->p, "@object") == 0) { + kind = LK_OBJECT; + info->p += 7; + } else { + return parse_error(info, "illegal .type"); + } + + struct SectionInfo *section = info->current_section; + struct LabelInfo *label = add_label_table(info->label_table, name, section, 0, 0); + if (label != NULL) { + label->kind = kind; + } + return 1; +} + +static int +dir_bytes(struct ParseInfo *info, enum DirectiveType dir) +{ + struct Expr *expr = parse_expr(info); + if (expr == NULL) + return parse_error(info, "expression expected"); + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + + assert(expr->kind != EX_FLONUM); + if (expr->kind == EX_FIXNUM) { + /* TODO: target endian */ + long value = expr->fixnum; + int size = 1 << (dir - DT_BYTE); + unsigned char *buf = malloc_or_die(size); + for (int i = 0; i < size; ++i) + buf[i] = value >> (8 * i); + vec_push(irs, new_ir_data(buf, size)); + } else { + vec_push(irs, new_ir_expr((enum IrKind)(IR_EXPR_BYTE + (dir - DT_BYTE)), expr)); + } + return 1; +} + +/* .size is parsed but ignored, the linker computes sizes from section layout */ +static int +dir_size(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + /* consume the symbol name and comma */ + parse_label(info); + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + /* consume the rest of the line as an expression */ + parse_expr(info); + } + return 1; +} + +#ifndef __NO_FLONUM +static int +dir_float(struct ParseInfo *info, enum DirectiveType dir) +{ + struct Expr *expr = parse_expr(info); + if (expr == NULL) + return parse_error(info, "expression expected"); + + Flonum value; + switch (expr->kind) { + case EX_FIXNUM: + value = expr->fixnum; + break; + case EX_FLONUM: + value = expr->flonum; + break; + default: + assert(0); + value = -1; + break; + } + int size; + switch (dir) { + default: + assert(0); /* fallthrough */ + case DT_DOUBLE: + size = sizeof(double); + break; + case DT_FLOAT: + size = sizeof(float); + break; + } + unsigned char *buf = malloc_or_die(size); + if (dir == DT_FLOAT) { + float fval = value; + memcpy(buf, (void *)&fval, sizeof(fval)); /* TODO: endian */ + } else { + double dval = value; + memcpy(buf, (void *)&dval, sizeof(dval)); /* TODO: endian */ + } + + struct SectionInfo *section = info->current_section; + struct Vector *irs = section->irs; + vec_push(irs, new_ir_data(buf, size)); + return 1; +} +#endif + +static int +dir_label_attrib(struct ParseInfo *info, enum DirectiveType dir) +{ + const struct Name *name = parse_label(info); + if (name == NULL) { + char buf[32]; + snprintf(buf, sizeof(buf), "%s: label expected", dir == DT_GLOBL ? ".globl" : ".local"); + return parse_error(info, buf); + } + + struct SectionInfo *section = info->current_section; + struct LabelInfo *label = add_label_table(info->label_table, name, section, 0, dir == DT_GLOBL); + if (label == NULL) { + ++info->error_count; + } else { + if (dir == DT_WEAK) + label->flag |= LF_WEAK; + } + return 1; +} + +static int +dir_section(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + const struct Name *name = parse_section_name(info); + if (name == NULL) + return parse_error(info, ".section: section name expected"); +#if TC_TARGET_PLATFORM != TC_PLATFORM_APPLE + int flag = 0; + const char *p = skip_whitespaces(info->p); + if (*p == ',') { + info->p = p + 1; + flag = parse_section_flag(info); + } + + /* optional third field, elf section type (@progbits, @nobits, @note, + * ...): this assembler infers the section type from the section + * name/flags itself, so the field is accepted and discarded rather + * than fed into set_current_section below */ + p = skip_whitespaces(info->p); + if (*p == ',') { + const char *q = p + 1; + q = skip_whitespaces(q); + if (*q == '@') { + ++q; + while (isalpha((unsigned char)*q) || isdigit((unsigned char)*q)) + ++q; + info->p = q; + } + } + + char *sectname = strndup(name->chars, name->bytes); + set_current_section(info, sectname, kSegRodata, flag); +#else + const char *p = skip_whitespaces(info->p); + if (*p != ',') + return parse_error(info, "`,' expected"); + info->p = skip_whitespaces(p + 1); + const struct Name *name2 = parse_section_name(info); + if (name2 == NULL) + return parse_error(info, ".section: section name expected"); + + int flag = 0; + p = skip_whitespaces(info->p); + if (*p == ',') { + info->p = p + 1; + const struct Name *modname = parse_section_name(info); + if (modname != NULL) { + if (equal_name(modname, alloc_cname("mod_init_funcs"))) { + flag |= SF_INIT_FUNCS; + } else if (equal_name(modname, alloc_cname("cstring_literals"))) { + flag |= SF_CSTRLITERALS; + } + } + if (flag == 0) + return parse_error(info, ".section: section name expected"); + } + + char *segname = strndup(name->chars, name->bytes); + char *sectname = strndup(name2->chars, name2->bytes); + set_current_section(info, sectname, segname, flag); +#endif + return 1; +} + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +static int +dir_subsections_via_symbols(struct ParseInfo *info, enum DirectiveType dir) +{ + /* TODO: handle this flag */ + UNUSED(info); + UNUSED(dir); + return 1; +} +#endif + +/* data directive aliases: .int/.word/.nbyte map to .long/.short/etc */ +static int +dir_bytes_alias(struct ParseInfo *info, enum DirectiveType dir) +{ + switch (dir) { + case DT_INT: + dir = DT_LONG; + break; /* .int = 4 bytes */ + case DT_WORD: + dir = DT_SHORT; + break; /* .word = 2 bytes */ + case DT_2BYTE: + dir = DT_SHORT; + break; + case DT_4BYTE: + dir = DT_LONG; + break; + case DT_8BYTE: + dir = DT_QUAD; + break; + default: + break; + } + return dir_bytes(info, dir); +} + +/* .fill repeat, size, value (gas manual) + * repeat: number of data units, size: 1/2/4/8, value: fill pattern */ +static int +dir_fill(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + int64_t repeat = 1; + int64_t size = 1; + int64_t value = 0; + struct SectionInfo *section; + struct Vector *irs; + int64_t i; + + if (!immediate(&info->p, &repeat)) + return parse_error(info, ".fill: repeat count expected"); + + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if (!immediate(&info->p, &size)) + return parse_error(info, ".fill: size expected"); + if (size != 1 && size != 2 && size != 4 && size != 8) + return parse_error(info, ".fill: size must be 1, 2, 4, or 8"); + + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if (!immediate(&info->p, &value)) + return parse_error(info, ".fill: value expected"); + } + } + + section = info->current_section; + irs = section->irs; + if (value == 0) { + /* a bss section has no data buffer to hold literal bytes; a + zero fill is exactly what ir_zero already reserves */ + vec_push(irs, new_ir_zero(repeat * size)); + return 1; + } + for (i = 0; i < repeat; ++i) { + unsigned char *buf = malloc_or_die(size); + int j; + for (j = 0; j < size; ++j) + buf[j] = value >> (8 * j); + vec_push(irs, new_ir_data(buf, size)); + } + return 1; +} + +/* .space size[, fill] and .skip alias + * reserves size bytes filled with fill (default 0) */ +static int +dir_space(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + int64_t size; + int64_t fill = 0; + struct SectionInfo *section; + struct Vector *irs; + unsigned char *buf; + int i; + + if (!immediate(&info->p, &size)) + return parse_error(info, ".space: size expected"); + + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + if (!immediate(&info->p, &fill)) + return parse_error(info, ".space: fill value expected"); + } + + section = info->current_section; + irs = section->irs; + if (fill == 0) { + /* a bss section has no data buffer to hold literal bytes; a + zero fill is exactly what ir_zero already reserves */ + vec_push(irs, new_ir_zero(size)); + return 1; + } + buf = malloc_or_die(size); + for (i = 0; i < size; ++i) + buf[i] = (unsigned char)fill; + vec_push(irs, new_ir_data(buf, size)); + return 1; +} + +/* .set/.equ: symbol assignment. tolerated for now, full evaluation + * would require registering the symbol in the expression evaluator */ +static int +dir_set(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + parse_label(info); + info->p = skip_whitespaces(info->p); + if (*info->p == ',') { + info->p = skip_whitespaces(info->p + 1); + parse_expr(info); + } + return 1; +} + +/* tolerated directives: consume arguments and discard + * used for .file, .loc, .ident, .extern, .previous, .cfi_* */ +static int +dir_ignore(struct ParseInfo *info, enum DirectiveType dir) +{ + UNUSED(dir); + UNUSED(info); + return 1; +} + +static inline int +handle_directive(struct ParseInfo *info, enum DirectiveType dir) +{ + typedef int (*DirectiveFunc)(struct ParseInfo *info, enum DirectiveType dir); + + static const DirectiveFunc kDirectiveFuncTable[] = { + [NODIRECTIVE] = NULL, + [DT_ASCII] = dir_string, + [DT_STRING] = dir_string, + [DT_SECTION] = dir_section, + [DT_TEXT] = dir_text, + [DT_DATA] = dir_data, + [DT_BSS] = dir_bss, + [DT_ALIGN] = dir_align, + [DT_P2ALIGN] = dir_align, + [DT_BALIGN] = dir_align, + [DT_TYPE] = dir_type, + [DT_BYTE] = dir_bytes, + [DT_SHORT] = dir_bytes, + [DT_LONG] = dir_bytes, + [DT_QUAD] = dir_bytes, + [DT_COMM] = dir_comm, + [DT_ZERO] = dir_zero, + [DT_GLOBL] = dir_label_attrib, + [DT_LOCAL] = dir_label_attrib, + [DT_WEAK] = dir_label_attrib, + [DT_EXTERN] = dir_ignore, + [DT_INT] = dir_bytes_alias, + [DT_WORD] = dir_bytes_alias, + [DT_2BYTE] = dir_bytes_alias, + [DT_4BYTE] = dir_bytes_alias, + [DT_8BYTE] = dir_bytes_alias, + [DT_FILL] = dir_fill, + [DT_SPACE] = dir_space, + [DT_SKIP] = dir_space, + [DT_SET] = dir_set, + [DT_EQU] = dir_set, + [DT_FILE] = dir_ignore, + [DT_LOC] = dir_ignore, + [DT_IDENT] = dir_ignore, + [DT_PREVIOUS] = dir_ignore, +#ifndef __NO_FLONUM + [DT_FLOAT] = dir_float, + [DT_DOUBLE] = dir_float, +#endif +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + [DT_SUBSECTIONS_VIA_SYMBOLS] = dir_subsections_via_symbols, +#endif + [DT_SIZE] = dir_size, + [DT_CFI] = dir_ignore, + }; + + DirectiveFunc func = kDirectiveFuncTable[dir]; + if (func == NULL) + return 1; + return (*func)(info, dir); +} + +int +parse_line(struct Line *line, struct ParseInfo *info) +{ + memset(line, 0, sizeof(*line)); + line->label = NULL; + line->inst = NULL; + line->dir = NODIRECTIVE; + + const char *p = skip_whitespaces(info->p); + info->p = p; + const char *q = get_label_end(info); + const char *r = skip_whitespaces(q); + if (*r == ':') { + const struct Name *label = unquote_label(p, q); + if (label == NULL) + return parse_error(info, "illegal label"); + line->label = label; + info->p = p = skip_whitespaces(r + 1); + } else if (*p == '.') { + enum DirectiveType dir = find_directive(p + 1, q - p - 1); + if (dir == NODIRECTIVE) { + parse_error(info, "unknown directive"); + return 0; + } + line->dir = dir; + info->p = r; + return handle_directive(info, dir); + } + + if (*p != '\0') { + info->p = p; + if (!parse_inst(info, line)) + return 0; + } + return 1; +} + +struct Value +calc_expr(struct Table *label_table, const struct Expr *expr) +{ + assert(expr != NULL); + switch (expr->kind) { + case EX_LABEL: + return (struct Value){.label = expr->label.name, .offset = 0}; + case EX_FIXNUM: + return (struct Value){.label = NULL, .offset = expr->fixnum}; + case EX_ADD: + case EX_SUB: + case EX_MUL: + case EX_DIV: { + struct Value lhs = calc_expr(label_table, expr->bop.lhs); + struct Value rhs = calc_expr(label_table, expr->bop.rhs); + if (rhs.label != NULL) { + if (expr->kind == EX_SUB && lhs.label != NULL) { + struct LabelInfo *llabel, *rlabel; + if (table_try_get(label_table, lhs.label, (void **)&llabel) + && table_try_get(label_table, rhs.label, (void **)&rlabel)) { + return (struct Value){.label = NULL, .offset = llabel->address - rlabel->address}; + } else { + error("Unresolved"); + } + } + if (expr->kind != EX_ADD || lhs.label != NULL) { + error("Illegal expression"); + } + /* offset + label */ + return (struct Value){.label = rhs.label, .offset = lhs.offset + rhs.offset}; + } + if (lhs.label != NULL) { + if (expr->kind != EX_ADD) { + error("Illegal expression"); + } + /* label + offset */ + return (struct Value){.label = lhs.label, .offset = lhs.offset + rhs.offset}; + } + + assert(lhs.label == NULL && rhs.label == NULL); + switch (expr->kind) { + case EX_ADD: + lhs.offset += rhs.offset; + break; + case EX_SUB: + lhs.offset -= rhs.offset; + break; + case EX_MUL: + lhs.offset *= rhs.offset; + break; + case EX_DIV: + lhs.offset /= rhs.offset; + break; + default: + assert(0); + break; + } + return lhs; + } + + case EX_POS: + case EX_NEG: { + struct Value value = calc_expr(label_table, expr->unary.sub); + if (value.label != NULL) { + error("Illegal expression"); + } + if (expr->kind == EX_NEG) + value.offset = -value.offset; + return value; + } + + default: + assert(0); + break; + } + return (struct Value){.label = NULL, .offset = 0}; +} diff --git a/cmd/dev/as/parse_asm.h b/cmd/dev/as/parse_asm.h @@ -0,0 +1,236 @@ +/* parser for assembler */ + +#ifndef AS_PARSE_ASM_H +#define AS_PARSE_ASM_H + +#include <stddef.h> /* size_t */ +#include <stdint.h> /* int64_t */ + +struct DataStorage; +struct Inst; +struct Name; +struct Operand; +struct Table; +struct Token; +struct Vector; + +enum DirectiveType { + NODIRECTIVE, + DT_ASCII, + DT_STRING, + DT_SECTION, + DT_TEXT, + DT_DATA, + DT_BSS, + DT_ALIGN, + DT_P2ALIGN, + DT_BALIGN, + DT_TYPE, + DT_BYTE, + DT_SHORT, + DT_LONG, + DT_QUAD, + DT_COMM, + DT_ZERO, + DT_GLOBL, + DT_LOCAL, + DT_WEAK, + DT_EXTERN, + /* gas integer-data directives. .int/.word and the explicit .nbyte forms + * are aliases of the sized data emitters but need their own table slots + * because the directive dispatch is table-indexed */ + DT_INT, + DT_WORD, + DT_2BYTE, + DT_4BYTE, + DT_8BYTE, + /* space-filling directives: .fill repeats a sized unit, .space/.skip + * reserve a byte run. in a nobits section a zero fill reserves address + * space instead of emitting file bytes */ + DT_FILL, + DT_SPACE, + DT_SKIP, + /* gas compatibility directives */ + DT_SET, /* .set sym, expr */ + DT_EQU, /* .equ sym, expr (alias for .set) */ + DT_FILE, /* .file (debug info, tolerated) */ + DT_LOC, /* .loc (debug info, tolerated) */ + DT_IDENT, /* .ident (compiler id string, tolerated) */ + DT_PREVIOUS, /* .previous (return to previous section, tolerated) */ +#ifndef __NO_FLONUM + DT_FLOAT, + DT_DOUBLE, +#endif +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE + DT_SUBSECTIONS_VIA_SYMBOLS, +#endif + DT_SIZE, + DT_CFI, /* .cfi_* prefix, not in table, tolerated */ +}; + +#define SF_EXECUTABLE (1 << 0) +#define SF_WRITABLE (1 << 1) +#define SF_BSS (1 << 2) +#define SF_TLS (1 << 3) +#define SF_INIT_FUNCS (1 << 8) +#define SF_CSTRLITERALS (1 << 9) + +struct SectionInfo { + const struct Name *name; + const char *segname; + struct Vector *irs; + int flag; + + int index; + uint64_t start_address; + struct DataStorage *ds; + size_t align; + size_t bss_size; + uint64_t offset; /* struct file offset */ + + int rela_count; + void *rela_buf; + uint64_t rela_ofs; +}; + +struct ParseInfo { + const char *filename; + const char *rawline; + const char *p; + int lineno; + int error_count; + + const struct Token *prefetched; + + struct Table *section_infos; /* <struct sectioninfo*> */ + struct Table *label_table; + struct Table *size_expr_table; + struct SectionInfo *current_section; +}; + +struct SectionInfo * +set_current_section(struct ParseInfo *info, const char *name, const char *segname, int flag); +struct SectionInfo * +get_section_info(struct ParseInfo *info, const char *name, const char *segname, int flag); + +extern const char kSecText[]; +extern const char kSecRodata[]; +extern const char kSecData[]; +extern const char kSecBss[]; + +#if TC_TARGET_PLATFORM == TC_PLATFORM_APPLE +extern const char kSegText[]; +extern const char kSegRodata[]; +extern const char kSegData[]; +extern const char kSegBss[]; +#else +#define kSegText NULL +#define kSegRodata NULL +#define kSegData NULL +#define kSegBss NULL +#endif + +struct Line { + const struct Name *label; + struct Inst *inst; + enum DirectiveType dir; +}; + +enum ExprKind { + EX_LABEL, + EX_FIXNUM, + EX_POS, + EX_NEG, + EX_ADD, + EX_SUB, + EX_MUL, + EX_DIV, + EX_FLONUM, +}; + +#ifndef __NO_FLONUM +typedef long double Flonum; +#endif + +struct Expr { + enum ExprKind kind; + union { + struct { + const struct Name *name; + } label; + int64_t fixnum; + struct { + struct Expr *lhs; + struct Expr *rhs; + } bop; + struct { + struct Expr *sub; + } unary; +#ifndef __NO_FLONUM + Flonum flonum; +#endif + }; +}; + +int parse_line(struct Line *line, struct ParseInfo *info); +void parse_set_p(struct ParseInfo *info, const char *p); +int parse_error(struct ParseInfo *info, const char *message); + +struct ParseOpArray { + /* enum opcode */ int op; + int opr_flags[4 + 1]; +}; + +struct ParseInstTable { + int count; + const struct ParseOpArray **array; +}; + +/* table externs and parse_operand are declared via struct arch_backend + * in arch.h */ + +int immediate(const char **pp, int64_t *value); +const struct Name *unquote_label(const char *p, const char *q); +struct Expr *parse_expr(struct ParseInfo *info); +struct Expr *new_expr(enum ExprKind kind); + +struct Value { + const struct Name *label; + int64_t offset; +}; + +struct Value calc_expr(struct Table *label_table, const struct Expr *expr); + +int is_label_first_chr(char c); +int is_label_chr(char c); + +#define LF_GLOBAL (1 << 0) +#define LF_DEFINED (1 << 1) +#define LF_REFERRED (1 << 2) +#define LF_COMM (1 << 3) +#define LF_WEAK (1 << 4) + +enum LabelKind { + LK_NONE, + LK_FUNC, + LK_OBJECT, +}; + +struct LabelInfo { + struct SectionInfo *section; + int flag; + uint64_t address; + enum LabelKind kind; + int size; + int align; +}; + +struct LabelInfo *add_label_table( + struct Table *label_table, + const struct Name *label, + struct SectionInfo *section, + int define, + int global +); + +#endif /* AS_PARSE_ASM_H */ diff --git a/cmd/dev/build.sh b/cmd/dev/build.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# build dev toolchain directly without the shared aruu library +set -e + +DEVDIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$DEVDIR/../.." && pwd)" +OUT="${DEVDIR}/bin" +mkdir -p "$OUT" + +CC=${CC:-cc} +WARN="-Wno-discarded-qualifiers -Wno-unused-function -Wno-unused-variable \ + -Wno-incompatible-pointer-types -Wno-int-to-pointer-cast \ + -Wno-pointer-to-int-cast -Wno-implicit-function-declaration \ + -Wno-parentheses -Wno-int-conversion -Wno-sign-compare" +CFLAGS="$WARN -std=c11 -D_POSIX_C_SOURCE=200809L \ + -I${ROOT}/shared/libtcutil -I${ROOT}/shared/libtcutil/elf -I${ROOT}/shared/libtcutil/ar \ + -I${DEVDIR} -I${DEVDIR}/as -I${DEVDIR}/as/arch/x64 \ + -I${DEVDIR}/ld -I${DEVDIR}/cc" + +# generate config if missing +if [ ! -f "${DEVDIR}/config.h" ]; then + sh "${DEVDIR}/configure" +fi + +TCU="${ROOT}/shared/libtcutil/tcutil.c ${ROOT}/shared/libtcutil/table.c \ + ${ROOT}/shared/libtcutil/elf/elfutil.c ${ROOT}/shared/libtcutil/ar/archive.c" + +# assembler +echo "building as..." +$CC $CFLAGS -o "$OUT/as" \ + ${DEVDIR}/as/as.c ${DEVDIR}/as/as_util.c ${DEVDIR}/as/parse_asm.c \ + ${DEVDIR}/as/ir_asm.c ${DEVDIR}/as/arch/x64/asm_code.c \ + ${DEVDIR}/as/arch/x64/parse_x64.c ${DEVDIR}/as/arch/x64/reloc_x64.c \ + ${DEVDIR}/as/arch/x64/backend.c ${DEVDIR}/as/emit_elf.c $TCU + +# linker +echo "building ld..." +$CC $CFLAGS -I${DEVDIR}/ld/arch/x64 -I${DEVDIR}/ld/arch/x86 \ + -I${DEVDIR}/ld/arch/arm -I${DEVDIR}/ld/arch/aarch64 -I${DEVDIR}/ld/arch/riscv64 \ + -o "$OUT/ld" \ + ${DEVDIR}/ld/ld.c ${DEVDIR}/ld/arch.c \ + ${DEVDIR}/ld/arch/x64/reloc_x64.c ${DEVDIR}/ld/arch/x86/reloc_x86.c \ + ${DEVDIR}/ld/arch/arm/reloc_arm.c ${DEVDIR}/ld/arch/aarch64/reloc_aarch64.c \ + ${DEVDIR}/ld/arch/riscv64/reloc_riscv64.c $TCU + +# shared cc objects (everything except entry points) +CC_COMMON="${DEVDIR}/cc/attr.c ${DEVDIR}/cc/decl.c \ + ${DEVDIR}/cc/eval.c ${DEVDIR}/cc/expr.c ${DEVDIR}/cc/init.c \ + ${DEVDIR}/cc/map.c ${DEVDIR}/cc/pp.c ${DEVDIR}/cc/scan.c \ + ${DEVDIR}/cc/scope.c ${DEVDIR}/cc/stmt.c ${DEVDIR}/cc/targ.c \ + ${DEVDIR}/cc/token.c ${DEVDIR}/cc/tree.c ${DEVDIR}/cc/type.c \ + ${DEVDIR}/cc/utf.c ${DEVDIR}/cc/util.c ${DEVDIR}/cc/qbe.c" + +# cc1 (cproc) +echo "building cc1..." +$CC $CFLAGS -o "$OUT/cc1" \ + ${DEVDIR}/cc/cc1.c $CC_COMMON + +# preprocessor +echo "building cpp..." +$CC $CFLAGS -o "$OUT/cpp" \ + ${DEVDIR}/cc/cpp.c $CC_COMMON + +# driver +echo "building cc..." +$CC $CFLAGS -o "$OUT/cc" ${DEVDIR}/cc/driver.c ${DEVDIR}/cc/util.c + +echo "done. binaries in $OUT" diff --git a/cmd/dev/cc/LICENSE b/cmd/dev/cc/LICENSE @@ -0,0 +1,14 @@ +Copyright (c) 2020-2026 Michael Forney <mforney@mforney.org> +Copyright (c) 2026 xplshn <anto@xplshn.com.ar> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/cmd/dev/cc/arg.h b/cmd/dev/cc/arg.h @@ -0,0 +1,19 @@ +#define ARGBEGIN \ + for (;;) { \ + if (argc > 0) \ + ++argv, --argc; \ + if (argc == 0 || (*argv)[0] != '-') \ + break; \ + if ((*argv)[1] == '-' && !(*argv)[2]) { \ + ++argv, --argc; \ + break; \ + } \ + for (char *opt_ = &(*argv)[1], done_ = 0; !done_ && *opt_; ++opt_) { \ + switch (*opt_) + +#define ARGEND \ + } \ + } + +#define EARGF(x) \ + (done_ = 1, opt_[1] ? ++opt_ : argv[1] ? --argc, *++argv : ((x), abort(), (char *)0)) diff --git a/cmd/dev/cc/attr.c b/cmd/dev/cc/attr.c @@ -0,0 +1,156 @@ +#include <limits.h> +#include <stdbool.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +enum attrprefix { + PREFIXNONE = 1, /* standard attribute */ + PREFIXGNU, +}; + +static const char * +strip(const char *name, char *buf, size_t buflen) +{ + size_t len; + + len = strlen(name); + if (len >= 4 && name[0] == '_' && name[1] == '_' && name[len - 2] == '_' + && name[len - 1] == '_') { + if (len - 4 >= buflen) + return ""; + memcpy(buf, name + 2, len - 4); + buf[len - 4] = '\0'; + return buf; + } + return name; +} + +static bool +parseattr(struct attr *a, enum attrkind allowed, enum attrprefix prefix) +{ + const char *name, *prefixname = ""; + char namebuf[32], *section; + enum attrkind kind; + int paren; + + if (tok.kind < TIDENT) + return false; + name = strip(tokenstr(tok.kind), namebuf, sizeof namebuf); + next(); + if (!prefix) { + if (consume(TCOLONCOLON)) { + if (strcmp(name, "gnu") == 0) + prefix = PREFIXGNU; + name = strip(expect(TIDENT, "after attribute prefix"), namebuf, sizeof namebuf); + } else { + prefix = PREFIXNONE; + } + } + kind = 0; + switch (prefix) { + case PREFIXNONE: + if (strcmp(name, "noreturn") == 0 || strcmp(name, "_Noreturn") == 0) + kind = ATTRNORETURN; + break; + case PREFIXGNU: + prefixname = "GNU "; + if (strcmp(name, "aligned") == 0) { + kind = ATTRALIGNED; + if (consume(TLPAREN)) { + unsigned long long i; + + i = intconstexpr(&filescope, false); + if (!i || i & i - 1 || i > INT_MAX) + error(&tok.loc, "invalid alignment %llu", i); + if (a) + a->align = i; + expect(TRPAREN, "after alignment"); + } else { + if (a) + a->align = 16; + } + } else if (strcmp(name, "constructor") == 0) { + kind = ATTRCONSTRUCTOR; + } else if (strcmp(name, "destructor") == 0) { + kind = ATTRDESTRUCTOR; + } else if (strcmp(name, "packed") == 0) { + kind = ATTRPACKED; + } else if (strcmp(name, "section") == 0) { + kind = ATTRSECTION; + expect(TLPAREN, "after 'section'"); + section = expect(TSTRINGLIT, "for section name"); + if (a) + a->section = section; + expect(TRPAREN, "after section name"); + } + break; + } + if (kind) { + if (!(kind & allowed)) + error(&tok.loc, "%sattribute '%s' is not supported here", prefixname, name); + if (a) + a->kind |= kind; + } else if (consume(TLPAREN)) { + /* skip arguments */ + for (paren = 1; paren > 0; next()) { + switch (tok.kind) { + case TLPAREN: + ++paren; + break; + case TRPAREN: + --paren; + break; + } + } + } + return true; +} + +static bool +attrspec(struct attr *a, enum attrkind allowed) +{ + if (tok.kind != TLBRACK || !peek(TLBRACK)) + return false; + while (parseattr(a, allowed, 0) || consume(TCOMMA)) + ; + expect(TRBRACK, "to end attribute specifier"); + expect(TRBRACK, "to end attribute specifier"); + return true; +} + +bool +attr(struct attr *a, enum attrkind allowed) +{ + if (!attrspec(a, allowed)) + return false; + while (attrspec(a, allowed)) + ; + return true; +} + +static bool +gnuattrspec(struct attr *a, enum attrkind allowed) +{ + if (!consume(T__ATTRIBUTE__)) + return false; + while (parseattr(a, allowed, PREFIXGNU) || consume(TCOMMA)) + ; + expect(TLPAREN, "after '__attribute__' to begin attribute specifier"); + expect(TLPAREN, "after '__attribute__' to begin attribute specifier"); + while (parseattr(a, allowed, PREFIXGNU) || consume(TCOMMA)) + ; + expect(TRPAREN, "to end attribute specifier"); + expect(TRPAREN, "to end attribute specifier"); + return true; +} + +bool +gnuattr(struct attr *a, enum attrkind allowed) +{ + if (!gnuattrspec(a, allowed)) + return false; + while (gnuattrspec(a, allowed)) + ; + return true; +} diff --git a/cmd/dev/cc/cc.h b/cmd/dev/cc/cc.h @@ -0,0 +1,507 @@ +#include <stdbool.h> +#include <stddef.h> +#include <stdio.h> + +#ifndef noreturn +#if __STDC_VERSION__ >= 201112L +#define noreturn _Noreturn +#else +#define noreturn +#endif +#endif + +struct func; + +enum tokenkind { +#define TOKEN(t, s) t, +#include "tokens.h" +#undef TOKEN + + TPPIDENT = TALIGNAS, + TIDENT = TDEFINE +}; + +struct location { + const char *file; + size_t line, col; +}; + +struct token { + enum tokenkind kind; + /* whether or not the token is ineligible for expansion */ + bool hide; + /* whether or not the token was preceeded by a space */ + bool space; + struct location loc; + char *lit; +}; + +enum typequal { + QUALNONE, + + QUALCONST = 1 << 1, + QUALRESTRICT = 1 << 2, + QUALVOLATILE = 1 << 3, + QUALATOMIC = 1 << 4 +}; + +enum typekind { + TYPENONE, + + TYPEVOID, + TYPEBOOL, + TYPECHAR, + TYPESHORT, + TYPEINT, + TYPEENUM, + TYPELONG, + TYPELLONG, + TYPEFLOAT, + TYPEDOUBLE, + TYPELDOUBLE, + TYPEPOINTER, + TYPEARRAY, + TYPEFUNC, + TYPESTRUCT, + TYPEUNION, + TYPENULLPTR, + TYPEBITINT, + TYPEINT128, + TYPECOMPLEX, +}; + +enum typeprop { + PROPNONE, + + PROPCHAR = 1 << 0, + PROPINT = 1 << 1, + PROPREAL = 1 << 2, + PROPARITH = 1 << 3, + PROPSCALAR = 1 << 4, + PROPFLOAT = 1 << 5, + PROPVM = 1 << 6, /* variably-modified type */ + PROPFLEX = 1 << 7, /* struct with flexible array member */ +}; + +struct bitfield { + short before; /* number of bits in the storage unit before the bit-field + */ + short after; /* number of bits in the storage unit after the bit-field + */ +}; + +struct member { + char *name; + struct type *type; + enum typequal qual; + unsigned long long offset; + struct bitfield bits; + struct member *next; +}; + +struct type { + enum typekind kind; + enum typeprop prop; + int align; + unsigned long long size; + struct value *value; /* used by the backend */ + struct type *base; + struct list link; /* used only during construction of type */ + /* qualifiers of the base type */ + enum typequal qual; + bool incomplete; + union { + struct { + bool issigned, iscomplex; + int width; + } arith; + struct { + struct expr *length; + enum typequal ptrqual; + struct value *size; + } array; + struct { + bool isvararg; + struct decl *params; + size_t nparam; + } func; + struct { + char *tag; + struct member *members; + } structunion; + } u; +}; + +enum declkind { + DECLTYPE, + DECLOBJECT, + DECLFUNC, + DECLCONST, + DECLBUILTIN, +}; + +enum linkage { + LINKNONE, + LINKINTERN, + LINKEXTERN, +}; + +enum storageduration { + SDSTATIC, + SDTHREAD, + SDAUTO, +}; + +enum builtinkind { + BUILTINALLOCA, + BUILTINCONSTANTP, + BUILTINEXPECT, + BUILTININFF, + BUILTINNANF, + BUILTINOFFSETOF, + BUILTINTYPESCOMPATIBLEP, + BUILTINUNREACHABLE, + BUILTINVAARG, + BUILTINVACOPY, + BUILTINVAEND, + BUILTINVALIST, + BUILTINVASTART, + BUILTINATOMICLOAD, + BUILTINATOMICSTORE, + BUILTINATOMICEXCHANGE, + BUILTINATOMICCOMPAREEXCHANGE, + BUILTINATOMICFETCHADD, + BUILTINATOMICFETCHSUB, + BUILTINATOMICFETCHAND, + BUILTINATOMICFETCHOR, + BUILTINATOMICFETCHXOR, +}; + +struct decl { + char *name; + enum declkind kind; + enum linkage linkage; + struct type *type; + enum typequal qual; + struct value *value; + char *asmname; + bool defined; + bool tentative; + struct decl *next; + + union { + struct { + /* alignment of object storage (may be stricter than + * type requires) */ + int align; + enum storageduration storage; + } obj; + struct { + /* the function might have an "inline definition" + * (C11 6.7.4p7) */ + bool inlinedefn; + bool isnoreturn; + } func; + unsigned long long enumconst; + enum builtinkind builtin; + } u; +}; + +struct scope { + struct map tags; + struct map decls; + struct block *breaklabel; + struct block *continuelabel; + struct switchcases *switchcases; + struct scope *parent; +}; + +enum exprkind { + /* primary expression */ + EXPRIDENT, + EXPRCONST, + EXPRSTRING, + + /* postfix expression */ + EXPRCALL, + /* member E.M gets transformed to *(typeof(e.m) *)((char *)e + + * offsetof(typeof(e), m)) */ + EXPRBITFIELD, + EXPRINCDEC, + EXPRCOMPOUND, + /* subscript E1[E2] gets transformed to *((E1)+(E2)) */ + + EXPRUNARY, + EXPRCAST, + EXPRBINARY, + EXPRCOND, + EXPRASSIGN, + EXPRCOMMA, + + EXPRBUILTIN, + EXPRTEMP, + EXPRSIZEOF, +}; + +struct stringlit { + size_t size; + void *data; +}; + +struct expr { + enum exprkind kind; + /* whether this expression is an lvalue */ + bool lvalue; + /* whether this expression is a pointer decayed from an array or + * function designator */ + bool decayed; + /* the unqualified type of the expression */ + struct type *type; + /* the type qualifiers of the object this expression refers to (ignored + * for non-lvalues) */ + enum typequal qual; + enum tokenkind op; + struct expr *base; + struct expr *next; + struct expr *toeval; + union { + struct { + struct decl *decl; + } ident; + union { + unsigned long long u; + long long i; + double f; + } constant; + struct stringlit string; + struct { + struct expr *args; + size_t nargs; + } call; + struct { + struct bitfield bits; + } bitfield; + struct { + struct decl *decl; + struct init *init; + } compound; + struct { + bool post; + } incdec; + struct { + struct expr *l, *r; + } binary; + struct { + struct expr *t, *f; + } cond; + struct { + struct expr *l, *r; + } assign; + struct { + enum builtinkind kind; + struct expr *val, *val2; + } builtin; + struct { + struct type *type; + } szof; + struct value *temp; + } u; +}; + +struct init { + unsigned long long start, end; + struct expr *expr; + struct bitfield bits; + struct init *next; +}; + +/* token */ + +extern struct token tok; + +void tokeninit(void); +int tokenget(const void *, size_t); +void tokenprint(const struct token *, FILE *); +char *tokenstr(enum tokenkind); +char *tokencheck(const struct token *, enum tokenkind, const char *); +void diagloc(const struct location *); +noreturn void error(const struct location *, const char *, ...); + +/* scan */ + +void scanfrom(const char *, FILE *); +void scanopen(void); +void scansetloc(struct location loc); +void scan(struct token *); +char *scaninclude(bool *); + +/* preprocessor */ + +enum ppflags { + /* preserve newlines in preprocessor output */ + PPNEWLINE = 1 << 0, +}; + +extern enum ppflags ppflags; + +void ppinit(void); +void addincdir(const char *); + +void next(void); +bool peek(enum tokenkind); +char *expect(enum tokenkind, const char *); +bool consume(enum tokenkind); + +/* type */ + +struct type *mktype(enum typekind, enum typeprop); +struct type *mkpointertype(struct type *, enum typequal); +struct type *mkarraytype(struct type *, enum typequal, unsigned long long); +struct type *mkbitinttype(int width, bool sign); + +bool typecompatible(struct type *, struct type *); +bool typesame(struct type *, struct type *); +struct type *typecomposite(struct type *, struct type *); +struct type *typeunqual(struct type *, enum typequal *); +struct type *typecommonreal(struct type *, unsigned, struct type *, unsigned); +struct type *typepromote(struct type *, unsigned); +struct type *typeadjust(struct type *, enum typequal *); +enum typeprop typeprop(struct type *); +struct member *typemember(struct type *, const char *, unsigned long long *); +bool typehasint(struct type *, unsigned long long, bool); + +extern struct type typevoid; +extern struct type typebool; +extern struct type typechar, typeschar, typeuchar; +extern struct type typeshort, typeushort; +extern struct type typeint, typeuint; +extern struct type typelong, typeulong; +extern struct type typellong, typeullong; +extern struct type typeint128, typeuint128; +extern struct type typefloat, typedouble, typeldouble; +extern struct type typefloatcomplex, typedoublecomplex; +extern struct type typenullptr; +extern struct type *typeadjvalist; + +/* targ */ + +struct target { + const char *name; + struct type *typevalist; + struct type *typewchar; + int signedchar; +}; + +extern const struct target *targ; + +void targinit(const char *); + +/* attr */ + +enum attrkind { + ATTRNORETURN = 1 << 0, + + /* GNU attributes */ + ATTRALIGNED = 1 << 2, + ATTRCONSTRUCTOR = 1 << 3, + ATTRDESTRUCTOR = 1 << 4, + ATTRPACKED = 1 << 5, + ATTRSECTION = 1 << 6, +}; + +struct attr { + enum attrkind kind; + int align; + char *section; +}; + +bool attr(struct attr *, enum attrkind); +bool gnuattr(struct attr *, enum attrkind); + +/* decl */ + +struct decl *mkdecl(char *name, enum declkind, struct type *, enum typequal, enum linkage); +bool decl(struct scope *, struct func *); +struct type *typename(struct scope *, enum typequal *, struct expr **); + +struct decl *stringdecl(struct expr *); + +void emittentativedefns(void); + +/* scope */ + +void scopeinit(void); +struct scope *mkscope(struct scope *); +struct scope *delscope(struct scope *); + +void scopeputdecl(struct scope *, struct decl *); +struct decl *scopegetdecl(struct scope *, const char *, bool); + +void scopeputtag(struct scope *, const char *, struct type *); +struct type *scopegettag(struct scope *, const char *, bool); + +extern struct scope filescope; + +/* expr */ + +struct type *stringconcat(struct stringlit *, bool); + +struct expr *expr(struct scope *); +struct expr *assignexpr(struct scope *); +struct expr *condexpr(struct scope *); +unsigned long long intconstexpr(struct scope *, bool); +void delexpr(struct expr *); + +struct expr *exprassign(struct expr *, struct type *); +struct expr *exprpromote(struct expr *); + +/* eval */ + +struct expr *eval(struct expr *); + +/* init */ + +struct init *mkinit(unsigned long long, unsigned long long, struct bitfield, struct expr *); +struct init *parseinit(struct scope *, struct type *); + +/* stmt */ + +void stmt(struct func *, struct scope *); + +/* backend */ + +struct gotolabel { + struct block *label; + bool defined; +}; + +struct switchcases { + void *root; + struct type *type; + struct block *defaultlabel; +}; + +void switchcase(struct switchcases *, unsigned long long, struct block *); + +struct block *mkblock(char *); + +struct value *mkglobal(struct decl *); + +struct value *mkintconst(unsigned long long); + +struct func *mkfunc(struct decl *, char *, struct type *, struct scope *); +void delfunc(struct func *); +struct type *functype(struct func *); +void funclabel(struct func *, struct block *); +struct value *funcbranch(struct func *, struct expr *, struct block *, struct block *); +struct value *funcexpr(struct func *, struct expr *); +void funcjmp(struct func *, struct block *); +void funcjnz(struct func *, struct value *, struct type *, struct block *, struct block *); +void funcret(struct func *, struct value *); +void funchlt(struct func *); +struct gotolabel *funcgoto(struct func *, char *); +void funcswitch(struct func *, struct value *, struct switchcases *, struct block *); +void funcinit(struct func *, struct decl *, struct init *, bool); + +void emitfunc(struct func *, bool); +void emitdata(struct decl *, struct init *); diff --git a/cmd/dev/cc/cc1.c b/cmd/dev/cc/cc1.c @@ -0,0 +1,79 @@ +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include "util.h" +#include "arg.h" +#include "cc.h" + +static void +usage(void) +{ + fprintf(stderr, "usage: %s [input]\n", argv0); + exit(2); +} + +int +main(int argc, char *argv[]) +{ + bool pponly = false; + char *output = NULL, *target = NULL; + + argv0 = progname(argv[0], "cproc-qbe"); + ARGBEGIN + { + case 'E': + pponly = true; + break; + case 't': + target = EARGF(usage()); + break; + case 'o': + output = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + + targinit(target); + + if (output && !freopen(output, "w", stdout)) + fatal("open %s:", output); + + if (argc) { + while (argc--) + scanfrom(argv[argc], NULL); + scanopen(); + } else { + scanfrom("<stdin>", stdin); + } + + tokeninit(); + ppinit(); + if (pponly) { + ppflags |= PPNEWLINE; + while (tok.kind != TEOF) { + tokenprint(&tok, stdout); + next(); + } + } else { + scopeinit(); + while (tok.kind != TEOF) { + if (!decl(&filescope, NULL)) { + if (tok.kind == TSEMICOLON) + error(&tok.loc, "unexpected ';' at top-level"); + error( + &tok.loc, + "expected declaration or " + "function definition" + ); + } + } + emittentativedefns(); + } + + fflush(stdout); + if (ferror(stdout)) + fatal("write failed"); + return 0; +} diff --git a/cmd/dev/cc/cpp.c b/cmd/dev/cc/cpp.c @@ -0,0 +1,215 @@ +/* see license file for copyright and license details */ +#define _POSIX_C_SOURCE 200809L +#include "util.h" +#include "arg.h" +#include "cc.h" +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +static void +usage(void) +{ + fprintf( + stderr, + "usage: %s [-D name[=val]] [-U name] [-I dir] [-o out] [file " + "...]\n", + argv0 + ); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + char *output = NULL; + char *arg; + char *cmdline_buf = NULL; + size_t cmdline_len = 0; + size_t cmdline_cap = 0; + bool undef = false; + int i; + + for (i = 1; i < argc; i++) { + if (strcmp(argv[i], "-undef") == 0) + undef = true; + } + + argv0 = progname(argv[0], "cpp"); + if (!undef) { + char predefs[2048]; + char *p = predefs; + size_t predefs_len; + + p += sprintf(p, "#define __LP64__ 1\n"); + p += sprintf(p, "#define __STDC_NO_ATOMICS__ 1\n"); + p += sprintf(p, "#define __STDC_NO_COMPLEX__ 1\n"); + p += sprintf(p, "#define __SIZEOF_LONG__ 8\n"); + p += sprintf(p, "#define __SIZEOF_POINTER__ 8\n"); + p += sprintf(p, "#define __SIZEOF_SIZE_T__ 8\n"); + p += sprintf(p, "#define __SIZEOF_PTRDIFF_T__ 8\n"); + p += sprintf(p, "#define __SIZE_TYPE__ unsigned long\n"); + p += sprintf(p, "#define __PTRDIFF_TYPE__ long\n"); + p += sprintf(p, "#define __WCHAR_TYPE__ int\n"); + p += sprintf(p, "#define __WINT_TYPE__ unsigned int\n"); + p += sprintf(p, "#define __INTMAX_TYPE__ long\n"); + p += sprintf(p, "#define __UINTMAX_TYPE__ unsigned long\n"); + +#if defined(__x86_64__) || defined(__amd64__) + p += sprintf(p, "#define __x86_64__ 1\n"); + p += sprintf(p, "#define __amd64__ 1\n"); +#elif defined(__aarch64__) + p += sprintf(p, "#define __aarch64__ 1\n"); +#elif defined(__riscv) || defined(__riscv__) + p += sprintf(p, "#define __riscv 1\n"); +#endif + +#if defined(__linux__) + p += sprintf(p, "#define __linux__ 1\n"); + p += sprintf(p, "#define __unix__ 1\n"); +#elif defined(__FreeBSD__) + p += sprintf(p, "#define __FreeBSD__ 1\n"); + p += sprintf(p, "#define __unix__ 1\n"); +#elif defined(__NetBSD__) + p += sprintf(p, "#define __NetBSD__ 1\n"); + p += sprintf(p, "#define __unix__ 1\n"); +#elif defined(__OpenBSD__) + p += sprintf(p, "#define __OpenBSD__ 1\n"); + p += sprintf(p, "#define __unix__ 1\n"); +#elif defined(__APPLE__) + p += sprintf(p, "#define __APPLE__ 1\n"); + p += sprintf(p, "#define __unix__ 1\n"); +#elif defined(__unix__) + p += sprintf(p, "#define __unix__ 1\n"); +#endif + + predefs_len = p - predefs; + cmdline_cap = predefs_len + 2048; + cmdline_buf = xreallocarray(cmdline_buf, cmdline_cap, 1); + strcpy(cmdline_buf, predefs); + cmdline_len = predefs_len; + } + ARGBEGIN + { + case 'u': + if (strcmp(opt_, "undef") == 0) { + done_ = 1; + break; + } + usage(); + break; + case 'D': + arg = EARGF(usage()); + { + char *eq = strchr(arg, '='); + char line[1024]; + if (eq) { + *eq = '\0'; + snprintf(line, sizeof(line), "#define %s %s\n", arg, eq + 1); + *eq = '='; + } else { + snprintf(line, sizeof(line), "#define %s 1\n", arg); + } + size_t len = strlen(line); + if (cmdline_len + len + 1 > cmdline_cap) { + cmdline_cap = cmdline_cap ? cmdline_cap * 2 : 2048; + cmdline_buf = xreallocarray(cmdline_buf, cmdline_cap, 1); + } + strcpy(cmdline_buf + cmdline_len, line); + cmdline_len += len; + } + break; + case 'U': + arg = EARGF(usage()); + { + char line[1024]; + snprintf(line, sizeof(line), "#undef %s\n", arg); + size_t len = strlen(line); + if (cmdline_len + len + 1 > cmdline_cap) { + cmdline_cap = cmdline_cap ? cmdline_cap * 2 : 2048; + cmdline_buf = xreallocarray(cmdline_buf, cmdline_cap, 1); + } + strcpy(cmdline_buf + cmdline_len, line); + cmdline_len += len; + } + break; + case 'n': + if (strcmp(opt_, "nostdinc") == 0) { + done_ = 1; + break; + } + usage(); + break; + case 'i': + if (strcmp(opt_, "isystem") == 0 || strcmp(opt_, "iquote") == 0 + || strcmp(opt_, "idirafter") == 0) { + if (!--argc) + usage(); + addincdir(*++argv); + done_ = 1; + break; + } + usage(); + break; + case 'I': + arg = EARGF(usage()); + addincdir(arg); + break; + case 'P': + if (strcmp(opt_, "P") == 0) { + done_ = 1; + break; + } + usage(); + break; + case 's': + if (strncmp(opt_, "std=", 4) == 0) { + done_ = 1; + break; + } + usage(); + break; + case 'o': + output = EARGF(usage()); + break; + default: + usage(); + } + ARGEND + + targinit(NULL); + if (output && !freopen(output, "w", stdout)) + fatal("open %s:", output); + + if (argc) { + while (argc--) + scanfrom(argv[argc], NULL); + } else { + scanfrom("<stdin>", stdin); + } + + if (cmdline_len > 0) { + FILE *f = fmemopen(cmdline_buf, cmdline_len, "r"); + if (!f) + fatal("fmemopen failed"); + scanfrom("<cmdline>", f); + } + + scanopen(); + + tokeninit(); + ppinit(); + ppflags |= PPNEWLINE; + while (tok.kind != TEOF) { + tokenprint(&tok, stdout); + next(); + } + + fflush(stdout); + if (ferror(stdout)) + fatal("write failed"); + + free(cmdline_buf); + return 0; +} diff --git a/cmd/dev/cc/decl.c b/cmd/dev/cc/decl.c @@ -0,0 +1,1503 @@ +#include <assert.h> +#include <limits.h> +#include <stdbool.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +static struct decl *tentativedefns, **tentativedefnsend = &tentativedefns; + +struct qualtype { + struct type *type; + enum typequal qual; + struct expr *expr; +}; + +enum storageclass { + SCNONE, + + SCTYPEDEF = 1 << 1, + SCEXTERN = 1 << 2, + SCSTATIC = 1 << 3, + SCAUTO = 1 << 4, + SCREGISTER = 1 << 5, + SCTHREADLOCAL = 1 << 6, +}; + +enum typespec { + SPECNONE, + + SPECVOID = 1 << 1, + SPECCHAR = 1 << 2, + SPECBOOL = 1 << 3, + SPECINT = 1 << 4, + SPECFLOAT = 1 << 5, + SPECDOUBLE = 1 << 6, + SPECSHORT = 1 << 7, + SPECLONG = 1 << 8, + SPECLONG2 = 1 << 9, + SPECSIGNED = 1 << 10, + SPECUNSIGNED = 1 << 11, + SPECCOMPLEX = 1 << 12, + SPECBITINT = 1 << 13, + SPECINT128 = 1 << 14, + + SPECLONGLONG = SPECLONG | SPECLONG2, +}; + +enum funcspec { + FUNCNONE, + + FUNCINLINE = 1 << 1, + FUNCNORETURN = 1 << 2, +}; + +struct structbuilder { + struct type *type; + struct member **last; + unsigned bits; /* number of bits remaining in the last byte */ + bool pack; +}; + +struct decl * +mkdecl(char *name, enum declkind k, struct type *t, enum typequal tq, enum linkage linkage) +{ + struct decl *d; + + d = xmalloc(sizeof(*d)); + memset(d, 0, sizeof(*d)); + d->name = name; + d->kind = k; + d->linkage = linkage; + d->type = t; + d->qual = tq; + if (k == DECLOBJECT && t) + d->u.obj.align = t->align; + + return d; +} + +/* 6.7.1 storage-class specifiers */ +static int +storageclass(enum storageclass *sc) +{ + enum storageclass allowed, new; + + switch (tok.kind) { + case TTYPEDEF: + new = SCTYPEDEF; + break; + case TEXTERN: + new = SCEXTERN; + break; + case TSTATIC: + new = SCSTATIC; + break; + case TTHREAD_LOCAL: + new = SCTHREADLOCAL; + break; + case TAUTO: + new = SCAUTO; + break; + case TREGISTER: + new = SCREGISTER; + break; + default: + return 0; + } + if (!sc) + error(&tok.loc, "storage class not allowed in this declaration"); + switch (*sc) { + case SCNONE: + allowed = ~SCNONE; + break; + case SCTHREADLOCAL: + allowed = SCSTATIC | SCEXTERN; + break; + case SCSTATIC: + case SCEXTERN: + allowed = SCTHREADLOCAL; + break; + default: + allowed = SCNONE; + break; + } + if (new & ~allowed) + error(&tok.loc, "invalid combination of storage class specifiers"); + *sc |= new; + next(); + + return 1; +} + +/* 6.7.3 type qualifiers */ +static int +typequal(enum typequal *tq) +{ + switch (tok.kind) { + case TCONST: + *tq |= QUALCONST; + break; + case TVOLATILE: + *tq |= QUALVOLATILE; + break; + case TRESTRICT: + *tq |= QUALRESTRICT; + break; + case T_ATOMIC: + /* only the qualifier form (_Atomic int x;), not the specifier + * form (_Atomic(int) x;): atomicity is achieved entirely + * through the __atomic_* builtins operating on an ordinary + * pointer to the object (see qbe.c's mkatomicfn), so the + * qualifier itself carries no codegen weight beyond being + * recorded, the same as const/volatile */ + *tq |= QUALATOMIC; + break; + default: + return 0; + } + next(); + + return 1; +} + +/* 6.7.4 function specifiers */ +static int +funcspec(enum funcspec *fs) +{ + enum funcspec new; + + switch (tok.kind) { + case TINLINE: + new = FUNCINLINE; + break; + case T_NORETURN: + new = FUNCNORETURN; + break; + default: + return 0; + } + if (!fs) + error(&tok.loc, "function specifier not allowed in this declaration"); + *fs |= new; + next(); + + return 1; +} + +static void structdecl(struct scope *, struct structbuilder *); +static struct qualtype declspecs(struct scope *, enum storageclass *, enum funcspec *, int *); + +static struct type * +tagspec(struct scope *s) +{ + static struct type *const inttypes[][2] = { + {&typeuint, &typeint}, + {&typeulong, &typelong}, + {&typeullong, &typellong}, + }; + struct type *t, *et; + char *tag, *name; + enum typekind kind; + struct decl *d, *enumconsts; + struct expr *e; + struct attr a; + enum attrkind allowedattr; + struct structbuilder b; + unsigned long long value, max, min; + bool sign; + int i; + + allowedattr = 0; + switch (tok.kind) { + case TSTRUCT: + kind = TYPESTRUCT, allowedattr |= ATTRPACKED; + break; + case TUNION: + kind = TYPEUNION, allowedattr |= ATTRPACKED; + break; + case TENUM: + kind = TYPEENUM; + break; + default: + fatal("internal error: unknown tag kind"); + } + next(); + a.kind = 0; + attr(&a, allowedattr); + gnuattr(&a, allowedattr); + tag = 0; + t = NULL; + et = NULL; + if (tok.kind >= TIDENT) { + tag = tokenstr(tok.kind); + next(); + } + if (kind == TYPEENUM && consume(TCOLON)) { + et = declspecs(s, NULL, NULL, NULL).type; + if (!et) + error(&tok.loc, "no type in enum type specifier"); + } + if (tag) + t = scopegettag(s, tag, tok.kind != TLBRACE && tok.kind != TSEMICOLON); + if (t) { + if (t->kind != kind) + error(&tok.loc, "redeclaration of tag '%s' with different kind", tag); + } else { + if (kind == TYPEENUM) { + t = mktype(kind, PROPSCALAR | PROPARITH | PROPREAL | PROPINT); + t->base = et; + } else { + t = mktype(kind, 0); + t->size = 0; + t->align = 0; + t->u.structunion.tag = tag; + t->u.structunion.members = NULL; + } + t->incomplete = true; + if (tag) + scopeputtag(s, tag, t); + } + if (tok.kind != TLBRACE) + return t; + if (!t->incomplete) + error(&tok.loc, "redefinition of tag '%s'", tag); + next(); + switch (t->kind) { + case TYPESTRUCT: + case TYPEUNION: + b.type = t; + b.last = &t->u.structunion.members; + b.bits = 0; + b.pack = a.kind & ATTRPACKED; + do + structdecl(s, &b); + while (tok.kind != TRBRACE); + if (!t->u.structunion.members) + error(&tok.loc, "struct/union has no members"); + next(); + if (!b.pack) + t->size = ALIGNUP(t->size, t->align); + break; + case TYPEENUM: + enumconsts = NULL; + if (et) { + t->size = t->base->size; + t->align = t->base->align; + t->u.arith.issigned = t->base->u.arith.issigned; + t->u.arith.width = t->base->u.arith.width; + t->incomplete = false; + et = t; + } else { + et = &typeint; + } + max = 0; + min = 0; + for (value = 0; tok.kind >= TIDENT; ++value) { + name = tokenstr(tok.kind); + next(); + attr(NULL, 0); + if (consume(TASSIGN)) { + e = eval(condexpr(s)); + if (e->kind != EXPRCONST || !(e->type->prop & PROPINT)) + error( + &tok.loc, + "expected integer " + "constant expression" + ); + value = e->u.constant.u; + if (!t->base) + et = typehasint(&typeint, value, e->type->u.arith.issigned) ? &typeint : e->type; + else if (!typehasint(et, value, e->type->u.arith.issigned)) + goto invalid; + } else if ( + value == 0 && !et->u.arith.issigned || value == 1ull << 63 && et->u.arith.issigned + ) { + error( + &tok.loc, + "no %ssigned integer type can represent " + "enumerator value", + et->u.arith.issigned ? "" : "un" + ); + } else if (!typehasint(et, value, et->u.arith.issigned)) { + if (t->base) { + invalid: + /* fixed underlying type */ + error( + &tok.loc, + "enumerator '%s' value cannot be " + "represented in underlying type", + name + ); + } + sign = et->u.arith.issigned; + for (i = 0; i < countof(inttypes); ++i) { + et = inttypes[i][sign]; + if (typehasint(et, value, sign)) + break; + } + assert(i < countof(inttypes)); + } + d = mkdecl(name, DECLCONST, et, QUALNONE, LINKNONE); + d->u.enumconst = value; + d->value = mkintconst(value); + d->next = enumconsts; + enumconsts = d; + if (et->u.arith.issigned && value >= 1ull << 63) { + if (-value > min) + min = -value; + } else if (value > max) { + max = value; + } + scopeputdecl(s, d); + if (!consume(TCOMMA)) + break; + } + expect(TRBRACE, "to close enum specifier"); + if (!t->base) { + if (min <= 0x80000000 && max <= 0x7fffffff) { + t->base = min ? &typeint : &typeuint; + } else { + sign = min > 0; + for (i = 0; i < countof(inttypes); ++i) { + et = inttypes[i][sign]; + if (typehasint(et, max, false) && typehasint(et, -min, true)) + break; + } + if (i == countof(inttypes)) + error( + &tok.loc, + "no integer type can represent " + "all enumerator values" + ); + t->base = et; + for (d = enumconsts; d; d = d->next) + d->type = t; + } + t->size = t->base->size; + t->align = t->base->align; + t->u.arith.issigned = t->base->u.arith.issigned; + t->u.arith.width = t->base->u.arith.width; + } + } + t->incomplete = false; + + return t; +} + +/* 6.7 declarations */ +static struct qualtype +declspecs(struct scope *s, enum storageclass *sc, enum funcspec *fs, int *align) +{ + struct type *t, *other; + struct decl *d; + struct expr *e; + enum typespec ts = SPECNONE; + enum typequal tq = QUALNONE; + enum tokenkind op; + int ntypes = 0; + unsigned long long i, bits; + struct expr *typeofexpr = NULL; + + t = NULL; + if (sc) + *sc = SCNONE; + if (fs) + *fs = FUNCNONE; + if (align) + *align = 0; + for (;;) { + if (typequal(&tq) || storageclass(sc) || funcspec(fs)) + continue; + op = tok.kind; + switch (op) { + /* 6.7.2 type specifiers */ + case TVOID: + t = &typevoid; + ++ntypes; + next(); + break; + case TCHAR: + ts |= SPECCHAR; + ++ntypes; + next(); + break; + case TSHORT: + if (ts & SPECSHORT) + error(&tok.loc, "duplicate 'short'"); + ts |= SPECSHORT; + next(); + break; + case TINT: + ts |= SPECINT; + ++ntypes; + next(); + break; + case TLONG: + if (ts & SPECLONG2) + error(&tok.loc, "too many 'long'"); + if (ts & SPECLONG) + ts |= SPECLONG2; + ts |= SPECLONG; + next(); + break; + case TFLOAT: + ts |= SPECFLOAT; + ++ntypes; + next(); + break; + case TDOUBLE: + ts |= SPECDOUBLE; + ++ntypes; + next(); + break; + case TSIGNED: + if (ts & SPECSIGNED) + error(&tok.loc, "duplicate 'signed'"); + ts |= SPECSIGNED; + next(); + break; + case TUNSIGNED: + if (ts & SPECUNSIGNED) + error(&tok.loc, "duplicate 'unsigned'"); + ts |= SPECUNSIGNED; + next(); + break; + case T_BITINT: + ts |= SPECBITINT; + ++ntypes; + next(); + expect(TLPAREN, "after _BitInt"); + bits = intconstexpr(s, false); + expect(TRPAREN, "after _BitInt width"); + break; + case TBOOL: + t = &typebool; + ++ntypes; + next(); + break; + case T_INT128: + ts |= SPECINT128; + ++ntypes; + next(); + break; + case T_COMPLEX: + if (ts & SPECCOMPLEX) + error(&tok.loc, "duplicate '_Complex'"); + ts |= SPECCOMPLEX; + next(); + break; + case T_ATOMIC: + error(&tok.loc, "_Atomic is not yet supported"); + break; + case TSTRUCT: + case TUNION: + case TENUM: + t = tagspec(s); + ++ntypes; + break; + case TTYPEOF: + case TTYPEOF_UNQUAL: + next(); + expect(TLPAREN, "after 'typeof'"); + t = typename(s, &tq, &typeofexpr); + if (!t) { + e = expr(s); + if (e->decayed) + e = e->base; + t = e->type; + if (op == TTYPEOF) + tq |= e->qual; + if (t->prop & PROPVM) + typeofexpr = e; + } + ++ntypes; + expect(TRPAREN, "to close 'typeof'"); + break; + + /* 6.7.5 alignment specifier */ + case TALIGNAS: + if (!align) + error( + &tok.loc, + "alignment specifier not " + "allowed in this declaration" + ); + next(); + expect(TLPAREN, "after 'alignas'"); + other = typename(s, NULL, NULL); + i = other ? other->align : intconstexpr(s, false); + if (i & i - 1 || i > INT_MAX) + error(&tok.loc, "invalid alignment: %llu", i); + if (i > *align) + *align = i; + expect(TRPAREN, "to close 'alignas' specifier"); + break; + + case T__ATTRIBUTE__: + gnuattr(NULL, 0); + break; + + default: + if (op < TIDENT || t || ts) + goto done; + d = scopegetdecl(s, tokenstr(tok.kind), 1); + if (!d || d->kind != DECLTYPE) + goto done; + t = d->type; + tq |= d->qual; + ++ntypes; + next(); + break; + } + if (ntypes > 1 || (t && ts)) + error(&tok.loc, "multiple types in declaration specifiers"); + } +done: + switch ((int)ts) { + case SPECNONE: + break; + case SPECCHAR: + t = &typechar; + break; + case SPECSIGNED | SPECCHAR: + t = &typeschar; + break; + case SPECUNSIGNED | SPECCHAR: + t = &typeuchar; + break; + case SPECSHORT: + case SPECSHORT | SPECINT: + case SPECSIGNED | SPECSHORT: + case SPECSIGNED | SPECSHORT | SPECINT: + t = &typeshort; + break; + case SPECUNSIGNED | SPECSHORT: + case SPECUNSIGNED | SPECSHORT | SPECINT: + t = &typeushort; + break; + case SPECINT: + case SPECSIGNED: + case SPECSIGNED | SPECINT: + t = &typeint; + break; + case SPECUNSIGNED: + case SPECUNSIGNED | SPECINT: + t = &typeuint; + break; + case SPECLONG: + case SPECLONG | SPECINT: + case SPECSIGNED | SPECLONG: + case SPECSIGNED | SPECLONG | SPECINT: + t = &typelong; + break; + case SPECUNSIGNED | SPECLONG: + case SPECUNSIGNED | SPECLONG | SPECINT: + t = &typeulong; + break; + case SPECLONGLONG: + case SPECLONGLONG | SPECINT: + case SPECSIGNED | SPECLONGLONG: + case SPECSIGNED | SPECLONGLONG | SPECINT: + t = &typellong; + break; + case SPECUNSIGNED | SPECLONGLONG: + case SPECUNSIGNED | SPECLONGLONG | SPECINT: + t = &typeullong; + break; + case SPECBITINT: + case SPECBITINT | SPECSIGNED: + t = mkbitinttype(bits, true); + break; + case SPECBITINT | SPECUNSIGNED: + t = mkbitinttype(bits, false); + break; + case SPECINT128: + case SPECINT128 | SPECSIGNED: + t = &typeint128; + break; + case SPECINT128 | SPECUNSIGNED: + t = &typeuint128; + break; + case SPECFLOAT: + t = &typefloat; + break; + case SPECDOUBLE: + t = &typedouble; + break; + case SPECLONG | SPECDOUBLE: + t = &typeldouble; + break; + case SPECFLOAT | SPECCOMPLEX: + t = &typefloatcomplex; + break; + case SPECDOUBLE | SPECCOMPLEX: + t = &typedoublecomplex; + break; + case SPECLONG | SPECDOUBLE | SPECCOMPLEX: + error(&tok.loc, "long double _Complex is not yet supported"); + break; + default: + error(&tok.loc, "invalid combination of type specifiers"); + } + if (tq & QUALRESTRICT) { + /* C23 6.7.4.1p2 */ + other = t; + while (other->kind == TYPEARRAY) + other = other->base; + if (!other || other->kind != TYPEPOINTER) + error(&tok.loc, "'restrict' applied to non-pointer type"); + if (other->base->kind == TYPEFUNC) + error(&tok.loc, "'restrict' applied to function pointer"); + } + if (!t && (tq || sc && *sc || fs && *fs)) + error(&tok.loc, "declaration has no type specifier"); + /* + * TODO: consider delaying attribute parsing to declarator(), + * so we can tell the difference between the start of an + * attribute and an array declarator + */ + attr(NULL, 0); + + return (struct qualtype){t, tq, typeofexpr}; +} + +/* 6.7.6 declarators */ +static struct decl *parameter(struct scope *); + +static bool +istypename(struct scope *s, const char *name) +{ + struct decl *d; + + d = scopegetdecl(s, name, 1); + return d && d->kind == DECLTYPE; +} + +/* + * when parsing a declarator, qualifiers for derived types are temporarily + * stored in the `qual` field of the type itself (elsewhere this field + * is used for the qualifiers of the base type). this is corrected in + * declarator() + */ +static void +declaratortypes( + struct scope *s, + struct list *result, + char **name, + int *align, + struct scope **funcscope, + bool allowabstract +) +{ + struct list *ptr; + struct type *t; + struct decl *d, **paramend; + struct expr *e; + struct attr a; + enum typequal tq; + int allowedattr; + + while (consume(TMUL)) { + attr(NULL, 0); + tq = QUALNONE; + while (typequal(&tq)) + ; + t = mkpointertype(NULL, tq); + listinsert(result, &t->link); + } + if (name) + *name = NULL; + a.kind = 0; + ptr = result->next; + switch (tok.kind) { + case TLPAREN: + next(); + if (allowabstract) { + switch (tok.kind) { + case TMUL: + case TLPAREN: + break; + default: + if (tok.kind >= TIDENT && !istypename(s, tokenstr(tok.kind))) + break; + goto func; + } + } + declaratortypes(s, result, name, align, funcscope, allowabstract); + expect(TRPAREN, "after parenthesized declarator"); + allowedattr = -1; + break; + default: + if (tok.kind >= TIDENT) { + if (!name) + error( + &tok.loc, + "identifier not allowed in " + "abstract declarator" + ); + *name = tokenstr(tok.kind); + next(); + } else if (!allowabstract) { + error(&tok.loc, "expected '(' or identifier"); + } + /* + * the aligned attribute is used in the definition of + * max_align_t from gcc/clang (used with glibc), + * dragonflybsd, freebsd, and openbsd + */ + allowedattr = align ? ATTRALIGNED : 0; + } + for (;;) { + switch (tok.kind) { + case TLPAREN: /* function declarator */ + next(); + func: + t = mktype(TYPEFUNC, 0); + t->qual = QUALNONE; + t->u.func.isvararg = false; + t->u.func.params = NULL; + t->u.func.nparam = 0; + paramend = &t->u.func.params; + s = mkscope(s); + d = NULL; + do { + if (consume(TELLIPSIS)) { + t->u.func.isvararg = true; + break; + } + if (tok.kind == TRPAREN) + break; + d = parameter(s); + if (d->name) + scopeputdecl(s, d); + *paramend = d; + paramend = &d->next; + ++t->u.func.nparam; + } while (consume(TCOMMA)); + expect(TRPAREN, "to close function declarator"); + if (funcscope && ptr->prev == result) { + /* we may need to re-open the scope later if + * this is a function definition */ + *funcscope = s; + s = s->parent; + } else { + s = delscope(s); + } + if (t->u.func.nparam == 1 && !t->u.func.isvararg && d->type->kind == TYPEVOID && !d->name) { + t->u.func.params = NULL; + t->u.func.nparam = 0; + } + listinsert(ptr->prev, &t->link); + allowedattr = 0; + break; + case TLBRACK: /* array declarator */ + if (allowedattr != -1 && attr(&a, allowedattr)) + goto attr; + next(); + t = mkarraytype(NULL, QUALNONE, 0); + while (consume(TSTATIC) || typequal(&t->u.array.ptrqual)) + ; + if (tok.kind == TMUL && peek(TRBRACK)) { + t->prop |= PROPVM; + t->incomplete = false; + } else if (!consume(TRBRACK)) { + e = assignexpr(s); + if (!(e->type->prop & PROPINT)) + error( + &tok.loc, + "array length expression must " + "have integer type" + ); + t->u.array.length = e; + t->incomplete = false; + expect(TRBRACK, "after array length"); + } + listinsert(ptr->prev, &t->link); + allowedattr = 0; + break; + case T__ATTRIBUTE__: + if (allowedattr == -1) + error( + &tok.loc, + "attribute not allowed after " + "parenthesized declarator" + ); + gnuattr(&a, allowedattr); + attr: + /* attribute applies to identifier if ptr->prev == + * result, otherwise type ptr->prev */ + if (ptr->prev == result) { + if (a.kind & ATTRALIGNED && a.align > *align) + *align = a.align; + } + break; + default: + return; + } + } +} + +static struct qualtype +declarator( + struct scope *s, + struct qualtype base, + char **name, + int *align, + struct scope **funcscope, + bool allowabstract +) +{ + struct type *t; + enum typequal tq; + struct expr *e; + struct list result = {&result, &result}, *l, *prev; + + if (funcscope) + *funcscope = NULL; + declaratortypes(s, &result, name, align, funcscope, allowabstract); + for (l = result.prev; l != &result; l = prev) { + prev = l->prev; + t = listelement(l, struct type, link); + tq = t->qual; + t->base = base.type; + t->qual = base.qual; + t->prop |= base.type->prop & PROPVM; + switch (t->kind) { + case TYPEFUNC: + if (base.type->kind == TYPEFUNC) + error( + &tok.loc, + "function declarator specifies " + "function return type" + ); + if (base.type->kind == TYPEARRAY) + error( + &tok.loc, + "function declarator specifies " + "array return type" + ); + break; + case TYPEARRAY: + if (base.type->incomplete) + error(&tok.loc, "array element has incomplete type"); + if (base.type->kind == TYPEFUNC) + error(&tok.loc, "array element has function type"); + if (t->u.array.ptrqual) { + /* TODO: check if we are in a function prototype + * if (?) + * error(&tok.loc, "array type has + * qualifiers outside of a function prototype"); + */ + if (prev != &result) + error( + &tok.loc, + "nested array type has " + "qualifiers" + ); + } + t->align = base.type->align; + t->size = 0; + if (t->u.array.length) { + e = eval(t->u.array.length); + if (e->kind == EXPRCONST && base.type->size) { + if (e->type->u.arith.issigned && e->u.constant.u >> 63) + error( + &tok.loc, + "array length must be " + "non-negative" + ); + if (e->u.constant.u > ULLONG_MAX / base.type->size) + error( + &tok.loc, + "array length " + "is too large" + ); + t->size = base.type->size * e->u.constant.u; + } else { + t->prop |= PROPVM; + t->u.array.length = e; + t->u.array.size = NULL; + } + } + break; + } + base.type = t; + base.qual = tq; + } + + return base; +} + +static struct decl * +parameter(struct scope *s) +{ + struct decl *d; + char *name; + struct qualtype t; + enum storageclass sc; + + attr(NULL, 0); + t = declspecs(s, &sc, NULL, NULL); + if (!t.type) + error(&tok.loc, "no type in parameter declaration"); + if (sc && sc != SCREGISTER) + error( + &tok.loc, + "parameter declaration has invalid " + "storage-class specifier" + ); + t = declarator(s, t, &name, NULL, NULL, true); + t.type = typeadjust(t.type, &t.qual); + d = mkdecl(name, DECLOBJECT, t.type, t.qual, LINKNONE); + d->u.obj.storage = SDAUTO; + return d; +} + +static void +addmember( + struct structbuilder *b, struct qualtype mt, char *name, int align, unsigned long long width +) +{ + struct type *t = b->type; + struct member *m; + size_t end; + + if (t->kind == TYPESTRUCT && t->prop & PROPFLEX) + error(&tok.loc, "struct has member '%s' after flexible array member", name); + if (mt.type->incomplete) { + if (mt.type->kind != TYPEARRAY) + error(&tok.loc, "struct member '%s' has incomplete type", name); + t->prop |= PROPFLEX; + } + if (mt.type->prop & PROPFLEX) { + /* + * ISO c doesnt allow structures with members containing + * fams, but allow it as an extension + */ + t->prop |= PROPFLEX; + } + if (mt.type->kind == TYPEFUNC) + error(&tok.loc, "struct member '%s' has function type", name); + if (mt.type->prop & PROPVM) + error(&tok.loc, "struct member '%s' has variably modified type", name); + assert(mt.type->align > 0); + if (name || width == -1) { + m = xmalloc(sizeof(*m)); + m->type = mt.type; + m->qual = mt.qual; + m->name = name; + m->next = NULL; + *b->last = m; + b->last = &m->next; + } else { + m = NULL; + } + if (width == -1) { + m->bits.before = 0; + m->bits.after = 0; + if (align < mt.type->align) { + if (align) + error( + &tok.loc, + "specified alignment of struct member " + "'%s' is less strict than is required by " + "type", + name + ); + align = b->pack ? 1 : mt.type->align; + } + if (t->kind == TYPESTRUCT) { + m->offset = ALIGNUP(t->size, align); + t->size = m->offset + mt.type->size; + } else { + m->offset = 0; + if (t->size < mt.type->size) + t->size = mt.type->size; + } + b->bits = 0; + } else { /* bit-field */ + if (!(mt.type->prop & PROPINT)) + error(&tok.loc, "bit-field '%s' has invalid type", name); + if (align) + error(&tok.loc, "alignment specified for bit-field '%s'", name); + if (b->pack) + error( + &tok.loc, + "bit-field '%s' in packed struct is not " + "supported", + name + ); + if (!width && name) + error( + &tok.loc, + "bit-field '%s' with zero width must not have " + "declarator", + name + ); + if (width > mt.type->u.arith.width) + error(&tok.loc, "bit-field '%s' exceeds width of underlying type", name); + align = mt.type->align; + if (t->kind == TYPESTRUCT) { + /* calculate end of the storage-unit for this bit-field + */ + end = ALIGNUP(t->size, mt.type->size); + if (!width || width > (end - t->size) * 8 + b->bits) { + /* no room, allocate a new storage-unit */ + t->size = end; + b->bits = 0; + } + if (m) { + m->offset = ALIGNDOWN(t->size - !!b->bits, mt.type->size); + m->bits.before = (t->size - m->offset) * 8 - b->bits; + m->bits.after = mt.type->size * 8 - width - m->bits.before; + } + t->size += (width - b->bits + 7) / 8; + b->bits = (b->bits - width) % 8; + } else if (m) { + m->offset = 0; + m->bits.before = 0; + m->bits.after = mt.type->size * 8 - width; + if (t->size < mt.type->size) + t->size = mt.type->size; + } + } + if (m && t->align < align) + t->align = align; +} + +static bool +staticassert(struct scope *s) +{ + struct stringlit msg; + unsigned long long c; + + if (!consume(TSTATIC_ASSERT)) + return false; + expect(TLPAREN, "after static_assert"); + c = intconstexpr(s, true); + if (consume(TCOMMA)) { + tokencheck(&tok, TSTRINGLIT, "after static assertion expression"); + stringconcat(&msg, true); + if (!c) + error(&tok.loc, "static assertion failed: %.*s", (int)(msg.size - 1), (char *)msg.data); + } else if (!c) { + error(&tok.loc, "static assertion failed"); + } + expect(TRPAREN, "after static assertion"); + expect(TSEMICOLON, "after static assertion"); + return true; +} + +static void +structdecl(struct scope *s, struct structbuilder *b) +{ + struct qualtype base, mt; + char *name; + unsigned long long width; + int align; + + if (staticassert(s)) + return; + attr(NULL, 0); + base = declspecs(s, NULL, NULL, &align); + if (!base.type) + error(&tok.loc, "no type in struct member declaration"); + if (tok.kind == TSEMICOLON) { + if ((base.type->kind != TYPESTRUCT && base.type->kind != TYPEUNION) + || base.type->u.structunion.tag) + error( + &tok.loc, + "struct declaration must declare at " + "least one member" + ); + next(); + addmember(b, base, NULL, align, -1); + return; + } + for (;;) { + if (consume(TCOLON)) { + width = intconstexpr(s, false); + addmember(b, base, NULL, 0, width); + } else { + mt = declarator(s, base, &name, &align, NULL, false); + width = consume(TCOLON) ? intconstexpr(s, false) : -1; + addmember(b, mt, name, align, width); + } + if (tok.kind == TSEMICOLON) + break; + expect(TCOMMA, "or ';' after declarator"); + } + next(); +} + +/* 6.7.7 type names */ +struct type *typename(struct scope *s, enum typequal *tq, struct expr **toeval) +{ + struct qualtype t; + + t = declspecs(s, NULL, NULL, NULL); + if (t.type) { + t = declarator(s, t, NULL, NULL, NULL, true); + if (tq) + *tq |= t.qual; + if (toeval) + *toeval = t.expr; + } + return t.type; +} + +static enum linkage +getlinkage(enum declkind kind, enum storageclass sc, struct decl *prior, bool filescope) +{ + if (sc & SCSTATIC) + return filescope ? LINKINTERN : LINKNONE; + if (sc & SCEXTERN || kind == DECLFUNC) + return prior ? prior->linkage : LINKEXTERN; + return filescope ? LINKEXTERN : LINKNONE; +} + +static struct decl * +declcommon( + struct scope *s, + enum declkind kind, + char *name, + char *asmname, + struct type *t, + enum typequal tq, + enum storageclass sc, + struct decl *prior +) +{ + struct decl *d; + enum linkage linkage; + const char *kindstr = kind == DECLFUNC ? "function" : "object"; + + if (prior) { + if (prior->linkage == LINKNONE) + error(&tok.loc, "%s '%s' with no linkage redeclared", kindstr, name); + linkage = getlinkage(kind, sc, prior, s == &filescope); + if (prior->linkage != linkage) + error(&tok.loc, "%s '%s' redeclared with different linkage", kindstr, name); + if (!typecompatible(t, prior->type) || tq != prior->qual) + error(&tok.loc, "%s '%s' redeclared with incompatible type", kindstr, name); + if (asmname && (!prior->asmname || strcmp(prior->asmname, asmname) != 0)) + error( + &tok.loc, + "%s '%s' redeclared with different assembler " + "name", + kindstr, + name + ); + prior->type = typecomposite(t, prior->type); + return prior; + } + if (s->parent) + prior = scopegetdecl(s->parent, name, true); + linkage = getlinkage(kind, sc, prior, s == &filescope); + if (linkage != LINKNONE && s->parent) { + /* XXX: should maintain map of identifiers with linkage to their + * declaration, and use that */ + if (s->parent != &filescope) + prior = scopegetdecl(&filescope, name, false); + if (prior && prior->linkage != LINKNONE) { + if (prior->kind != kind) + error(&tok.loc, "'%s' redeclared with different kind", name); + if (prior->linkage != linkage) + error( + &tok.loc, + "%s '%s' redeclared with different " + "linkage", + kindstr, + name + ); + if (!typecompatible(t, prior->type) || tq != prior->qual) + error( + &tok.loc, + "%s '%s' redeclared with incompatible " + "type", + kindstr, + name + ); + if (!asmname) + asmname = prior->asmname; + else if (!prior->asmname || strcmp(prior->asmname, asmname) != 0) + error( + &tok.loc, + "%s '%s' redeclared with different " + "assembler name", + kindstr, + name + ); + t = typecomposite(t, prior->type); + } + } + d = mkdecl(name, kind, t, tq, linkage); + d->asmname = asmname; + scopeputdecl(s, d); + return d; +} + +static void +defineobj(struct decl *d, struct init *init, bool hasinit, struct func *f) +{ + if (d->type->incomplete) + error(&tok.loc, "object '%s' has incomplete type", d->name); + if (d->u.obj.align < d->type->align) + d->u.obj.align = d->type->align; + if (d->u.obj.storage == SDAUTO) + funcinit(f, d, init, hasinit); + else + emitdata(d, init); + d->defined = true; +} + +bool +decl(struct scope *s, struct func *f) +{ + struct qualtype base, qt; + struct type *t; + enum typequal tq; + enum storageclass sc; + enum funcspec fs; + struct attr a; + struct init *init; + bool hasinit; + char *name, *asmname; + int allowfunc = !f; + struct decl *d, *prior; + enum declkind kind; + struct scope *funcscope; + int align; + + if (staticassert(s)) + return true; + a.kind = 0; + if (attr(&a, ATTRNORETURN) && consume(TSEMICOLON)) + return true; + base = declspecs(s, &sc, &fs, &align); + if (!base.type) + return false; + if (f) { + if (sc == SCTHREADLOCAL) + error( + &tok.loc, + "block scope declaration containing " + "'thread_local' must contain 'static' " + "or 'extern'" + ); + } else { + /* 6.9p2 */ + if (sc & SCAUTO) + error(&tok.loc, "external declaration must not contain 'auto'"); + if (sc & SCREGISTER) + error( + &tok.loc, + "external declaration must not contain " + "'register'" + ); + } + if (consume(TSEMICOLON)) { + /* XXX 6.7p2 error unless in function parameter/struct/union, or + * tag/enum members are declared */ + return true; + } + for (;;) { + qt = declarator(s, base, &name, NULL, &funcscope, false); + t = qt.type; + tq = qt.qual; + if (consume(T__ASM__)) { + struct stringlit lit; + + expect(TLPAREN, "after __asm__"); + tokencheck(&tok, TSTRINGLIT, "after __asm__"); + stringconcat(&lit, true); + asmname = lit.data; + expect(TRPAREN, "after assembler name"); + allowfunc = 0; + } else { + asmname = NULL; + } + gnuattr(&a, 0); /* appertains to identifier */ + kind = sc & SCTYPEDEF ? DECLTYPE : t->kind == TYPEFUNC ? DECLFUNC : DECLOBJECT; + prior = scopegetdecl(s, name, false); + if (prior && prior->kind != kind) + error(&tok.loc, "'%s' redeclared with different kind", name); + switch (kind) { + case DECLTYPE: + if (align) + error( + &tok.loc, + "typedef '%s' declared with alignment " + "specifier", + name + ); + if (asmname) + error( + &tok.loc, + "typedef '%s' declared with assembler " + "label", + name + ); + if (!prior) + scopeputdecl(s, mkdecl(name, DECLTYPE, t, tq, LINKNONE)); + else if (!typesame(prior->type, t) || prior->qual != tq) + error( + &tok.loc, + "typedef '%s' redefined with different " + "type", + name + ); + break; + case DECLOBJECT: + if (align && align < t->align) + error( + &tok.loc, + "object '%s' requires alignment %d, " + "which is stricter than specified " + "alignment %d", + name, + t->align, + align + ); + d = declcommon(s, kind, name, asmname, t, tq, sc, prior); + if (d->u.obj.align < align) + d->u.obj.align = align; + if (d->linkage == LINKNONE && !(sc & SCSTATIC)) { + d->u.obj.storage = SDAUTO; + } else { + d->u.obj.storage = sc & SCTHREADLOCAL ? SDTHREAD : SDSTATIC; + if (t->prop & PROPVM) + error( + &tok.loc, + "object '%s' with %s storage " + "duration cannot have variably " + "modified type", + name, + d->u.obj.storage == SDSTATIC ? "static" : "thread" + ); + d->value = mkglobal(d); + } + + if (base.expr) + funcexpr(f, base.expr); + init = NULL; + hasinit = false; + if (consume(TASSIGN)) { + if (f && d->linkage != LINKNONE) + error( + &tok.loc, + "object '%s' with block scope " + "and %s linkage cannot have " + "initializer", + name, + d->linkage == LINKEXTERN ? "external" : "internal" + ); + if (d->defined) + error(&tok.loc, "object '%s' redefined", name); + init = parseinit(s, d->type); + hasinit = true; + } else if (sc & SCEXTERN) { + break; + } else if (d->linkage != LINKNONE && d->u.obj.storage == SDSTATIC) { + if (!d->defined && !d->tentative) { + d->tentative = true; + *tentativedefnsend = d; + tentativedefnsend = &d->next; + } + break; + } + defineobj(d, init, hasinit, f); + break; + case DECLFUNC: + if (align) + error( + &tok.loc, + "function '%s' declared with alignment " + "specifier", + name + ); + if (f && sc && sc != SCEXTERN) /* 6.7.1p7 */ + error( + &tok.loc, + "function '%s' with block scope may only " + "have storage class 'extern'", + name + ); + d = declcommon(s, kind, name, asmname, t, tq, sc, prior); + d->value = mkglobal(d); + d->u.func.inlinedefn = d->linkage == LINKEXTERN && fs & FUNCINLINE && !(sc & SCEXTERN) + && (!prior || prior->u.func.inlinedefn); + d->u.func.isnoreturn = fs & FUNCNORETURN || a.kind & ATTRNORETURN; + if (tok.kind == TLBRACE) { + if (!allowfunc) + error( + &tok.loc, + "function definition " + "not allowed" + ); + if (d->defined) + error(&tok.loc, "function '%s' redefined", name); + /* re-open scope from function declarator */ + assert(funcscope); + s = funcscope; + f = mkfunc(d, name, t, s); + stmt(f, s); + if (d->u.func.isnoreturn) + funchlt(f); + /* XXX: need to keep track of function in case a + * later declaration specifies extern */ + if (!d->u.func.inlinedefn) + emitfunc(f, d->linkage == LINKEXTERN); + s = delscope(s); + delfunc(f); + d->defined = true; + return true; + } else if (funcscope) { + delscope(funcscope); + } + break; + } + if (consume(TSEMICOLON)) + return true; + expect(TCOMMA, "or ';' after declarator"); + allowfunc = 0; + } +} + +struct decl * +stringdecl(struct expr *expr) +{ + static struct map strings; + struct mapkey key; + struct decl *d; + size_t i; + + if (!strings.len) + mapinit(&strings, 64); + assert(expr->kind == EXPRSTRING); + mapkey(&key, expr->u.string.data, expr->u.string.size); + if (mapput(&strings, &key, &i)) { + d = mkdecl("string", DECLOBJECT, expr->type, QUALNONE, LINKNONE); + d->value = mkglobal(d); + emitdata(d, mkinit(0, expr->type->size, (struct bitfield){0}, expr)); + strings.vals[i].p = d; + } else { + d = strings.vals[i].p; + } + return d; +} + +void +emittentativedefns(void) +{ + struct decl *d; + + for (d = tentativedefns; d; d = d->next) { + if (!d->defined) + defineobj(d, NULL, false, NULL); + } +} diff --git a/cmd/dev/cc/driver.c b/cmd/dev/cc/driver.c @@ -0,0 +1,661 @@ +#define _POSIX_C_SOURCE 200809L +#include <errno.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <fcntl.h> +#include <limits.h> +#include <signal.h> +#include <spawn.h> +#include <sys/stat.h> +#include <sys/wait.h> +#include <unistd.h> + +#include "util.h" +#include "paths.h" + +enum filetype { + NONE, /* detect based on file extension */ + ASM, /* assembly source */ + ASMPP, /* assembly source requiring preprocessing */ + C, /* c source */ + CHDR, /* c header */ + CPPOUT, /* preprocessed c source */ + OBJ, /* object file */ + QBE, /* QBE IL */ +}; + +enum stage { + PREPROCESS, + COMPILE, + CODEGEN, + ASSEMBLE, + LINK, +}; + +#include "config.h" + +struct stageinfo { + const char *name; + struct array cmd; + size_t cmdbase; + pid_t pid; +}; + +struct input { + char *name; + unsigned stages; + enum filetype filetype; + bool lib; +}; + +static struct { + bool nostdlib; + bool verbose; +} flags; + +static struct stageinfo stages[] = { + [PREPROCESS] = {.name = "preprocess"}, + [COMPILE] = {.name = "compile"}, + [CODEGEN] = {.name = "codegen"}, + [ASSEMBLE] = {.name = "assemble"}, + [LINK] = {.name = "link"}, +}; + +static const char *const ignoreflags[] = { + "fno-builtin", "ffreestanding", "pedantic", "pedantic-errors", "pipe" +}; + +static void +usage(const char *fmt, ...) +{ + va_list ap; + + if (fmt) { + fprintf(stderr, "%s: ", argv0); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); + } + fprintf( + stderr, + "usage: %s [-c|-S|-E] [-D name[=value]] [-U name] [-I dir] " + "[-isystem dir] [-iquote dir] [-idirafter dir] [-std=standard] " + "[-nostdinc] [-L dir] [-l library] [-static] [-pthread] [-P] [-s] " + + "[-g] [-o output] input...\n", + argv0 + ); + exit(2); +} + +static enum filetype +detectfiletype(const char *name) +{ + const char *dot; + + dot = strrchr(name, '.'); + if (dot) { + ++dot; + if (strcmp(dot, "c") == 0) + return C; + if (strcmp(dot, "h") == 0) + return CHDR; + if (strcmp(dot, "i") == 0) + return CPPOUT; + if (strcmp(dot, "qbe") == 0) + return QBE; + if (strcmp(dot, "s") == 0) + return ASM; + if (strcmp(dot, "S") == 0) + return ASMPP; + } + + return OBJ; +} + +static char * +changeext(const char *name, const char *ext) +{ + const char *slash, *dot; + char *result; + size_t baselen; + + slash = strrchr(name, '/'); + if (slash) + name = slash + 1; + dot = strrchr(name, '.'); + baselen = dot ? (size_t)(dot - name) : strlen(name); + result = xmalloc(baselen + strlen(ext) + 2); + memcpy(result, name, baselen); + result[baselen] = '.'; + strcpy(result + baselen + 1, ext); + + return result; +} + +static int +spawn(pid_t *pid, struct array *args, posix_spawn_file_actions_t *actions) +{ + extern char **environ; + char **arg; + + if (flags.verbose) { + fprintf(stderr, "%s: spawning", argv0); + for (arg = args->val; *arg; ++arg) + fprintf(stderr, " %s", *arg); + fputc('\n', stderr); + } + return posix_spawnp(pid, *(char **)args->val, actions, NULL, args->val, environ); +} + +static int +spawnphase(struct stageinfo *phase, int *fd, char *input, char *output, bool last) +{ + int ret, pipefd[2]; + posix_spawn_file_actions_t actions; + + phase->cmd.len = phase->cmdbase; + if (last && output) { + arrayaddptr(&phase->cmd, "-o"); + arrayaddptr(&phase->cmd, output); + } + arrayaddptr(&phase->cmd, input && *fd == -1 ? input : "-"); + arrayaddptr(&phase->cmd, NULL); + + ret = posix_spawn_file_actions_init(&actions); + if (ret) + goto err0; + if (*fd != -1) + ret = posix_spawn_file_actions_adddup2(&actions, *fd, 0); + if (!last) { + if (pipe(pipefd) < 0) { + ret = errno; + goto err1; + } + if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) < 0) { + ret = errno; + goto err2; + } + if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) < 0) { + ret = errno; + goto err2; + } + ret = posix_spawn_file_actions_adddup2(&actions, pipefd[1], 1); + if (ret) + goto err2; + } + + ret = spawn(&phase->pid, &phase->cmd, &actions); + if (ret) + goto err2; + if (!last) { + *fd = pipefd[0]; + close(pipefd[1]); + } + posix_spawn_file_actions_destroy(&actions); + + return 0; + +err2: + if (!last) { + close(pipefd[0]); + close(pipefd[1]); + } +err1: + posix_spawn_file_actions_destroy(&actions); +err0: + return ret; +} + +static bool +succeeded(const char *phase, pid_t pid, int status) +{ + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == 0) + return true; + warn("%s: process %ju exited with status %d", phase, (uintmax_t)pid, WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + warn("%s: process signaled: %s", phase, strsignal(WTERMSIG(status))); + } else { + warn("%s: process failed", phase); + } + return false; +} + +static void +buildobj(struct input *input, char *output) +{ + const char *phase; + size_t i, npids; + pid_t pid; + int status, ret, fd; + bool success = true; + + if (input->filetype == OBJ) + return; + if (input->stages & 1 << LINK) { + input->stages &= ~(1 << LINK); + output = xmalloc(strlen(ARUU_PATH_TMP) + sizeof("/cproc-XXXXXX")); + sprintf(output, "%s/cproc-XXXXXX", ARUU_PATH_TMP); + fd = mkstemp(output); + if (fd < 0) + fatal("mkstemp:"); + close(fd); + } else if (output) { + if (strcmp(output, "-") == 0) + output = NULL; + } else if (input->stages & 1 << ASSEMBLE) { + output = changeext(input->name, "o"); + } else if (input->stages & 1 << CODEGEN) { + output = changeext(input->name, "s"); + } else if (input->stages & 1 << COMPILE) { + output = changeext(input->name, "qbe"); + } + if (strcmp(input->name, "-") == 0) + input->name = NULL; + + npids = 0; + for (i = PREPROCESS, fd = -1; input->stages; ++i) { + if (!(input->stages & 1 << i)) + continue; + input->stages &= ~(1 << i); + ret = spawnphase(&stages[i], &fd, input->name, output, !input->stages); + if (ret) { + warn("%s: spawn \"%s\": %s", stages[i].name, *(char **)stages[i].cmd.val, strerror(ret)); + goto kill; + } + ++npids; + } + input->name = output; + + while (npids > 0) { + pid = wait(&status); + if (pid < 0) + fatal("waitpid:"); + for (i = 0; i < countof(stages); ++i) { + if (pid == stages[i].pid) { + --npids; + stages[i].pid = 0; + phase = stages[i].name; + break; + } + } + if (i == countof(stages)) + continue; + if (!succeeded(phase, pid, status)) { + kill: + if (success && npids > 0) { + for (i = 0; i < countof(stages); ++i) { + if (stages[i].pid) + kill(stages[i].pid, SIGTERM); + } + } + success = false; + } + } + if (!success) { + if (output) + unlink(output); + exit(1); + } +} + +static void +buildexe(struct input *inputs, size_t ninputs, char *output) +{ + struct stageinfo *s = &stages[LINK]; + size_t i; + int ret, status; + pid_t pid; + + arrayaddptr(&s->cmd, "-o"); + arrayaddptr(&s->cmd, output); + if (!flags.nostdlib && startfiles[0]) + arrayaddbuf(&s->cmd, startfiles, sizeof(startfiles)); + for (i = 0; i < ninputs; ++i) { + if (inputs[i].lib) + arrayaddptr(&s->cmd, "-l"); + arrayaddptr(&s->cmd, inputs[i].name); + } + if (!flags.nostdlib && endfiles[0]) + arrayaddbuf(&s->cmd, endfiles, sizeof(endfiles)); + arrayaddptr(&s->cmd, NULL); + + ret = spawn(&pid, &s->cmd, NULL); + if (ret) + fatal("%s: spawn \"%s\": %s", s->name, *(char **)s->cmd.val, strerror(errno)); + if (waitpid(pid, &status, 0) < 0) + fatal("waitpid %ju:", (uintmax_t)pid); + for (i = 0; i < ninputs; ++i) { + if (inputs[i].filetype != OBJ) + unlink(inputs[i].name); + } + exit(!succeeded(s->name, pid, status)); +} + +static char * +nextarg(char ***argv) +{ + if ((**argv)[2] != '\0') + return &(**argv)[2]; + ++*argv; + if (!**argv) + usage(NULL); + return **argv; +} + +static char * +resolvepath(const char *arg0, const char *binname, const char *devrelpath) +{ + char self[PATH_MAX], *dir, *path; + size_t n; + struct stat st; + + n = readlink("/proc/self/exe", self, sizeof(self) - 1); + if (n == -1) { + n = strlen(arg0); + if (n > sizeof(self) - 1) + n = sizeof(self) - 1; + memcpy(self, arg0, n); + } + self[n] = '\0'; + + dir = strrchr(self, '/'); + if (dir) { + *dir = '\0'; + } else { + strcpy(self, "."); + } + + path = xmalloc(strlen(self) + strlen(devrelpath) + 2); + sprintf(path, "%s/%s", self, devrelpath); + if (stat(path, &st) == 0) + return path; + + free(path); + + path = xmalloc(strlen(self) + strlen(binname) + 2); + sprintf(path, "%s/%s", self, binname); + return path; +} + +static int +hasprefix(const char *str, const char *pfx) +{ + return memcmp(str, pfx, strlen(pfx)) == 0; +} + +int +main(int argc, char *argv[]) +{ + enum stage last = LINK; + enum filetype filetype = 0; + char *arg, *end, *output = NULL, *arch, *qbearch; + struct array inputs = {0}, *cmd; + struct input *input; + size_t i; + + argv0 = progname(argv[0], "cc"); + + char *cpp_path = resolvepath(argv[0], "cpp", "cpp"); + char *cc1_path = resolvepath(argv[0], "cc1", "cc1"); + char *qbe_path = resolvepath(argv[0], "qbe", "../../../externalRepos/qbe/qbe"); + char *as_path = resolvepath(argv[0], "as", "../../../cmd/dev/as/as"); + char *ld_path = resolvepath(argv[0], "ld", "../ld/ld"); + + arrayaddptr(&stages[PREPROCESS].cmd, cpp_path); + if (countof(preprocesscmd) > 1) { + arrayaddbuf( + &stages[PREPROCESS].cmd, preprocesscmd + 1, sizeof(preprocesscmd) - sizeof(preprocesscmd[0]) + ); + } + + arrayaddptr(&stages[COMPILE].cmd, cc1_path); + + arrayaddptr(&stages[CODEGEN].cmd, qbe_path); + if (countof(codegencmd) > 1) { + arrayaddbuf(&stages[CODEGEN].cmd, codegencmd + 1, sizeof(codegencmd) - sizeof(codegencmd[0])); + } + + arrayaddptr(&stages[ASSEMBLE].cmd, as_path); + if (countof(assemblecmd) > 1) { + arrayaddbuf( + &stages[ASSEMBLE].cmd, assemblecmd + 1, sizeof(assemblecmd) - sizeof(assemblecmd[0]) + ); + } + + arrayaddptr(&stages[LINK].cmd, ld_path); + if (countof(linkcmd) > 1) { + arrayaddbuf(&stages[LINK].cmd, linkcmd + 1, sizeof(linkcmd) - sizeof(linkcmd[0])); + } + + if (hasprefix(target, "x86_64-apple-")) { + arch = "x86_64-sysv"; + qbearch = "amd64_apple"; + } else if (hasprefix(target, "x86_64-") || hasprefix(target, "amd64-")) { + arch = "x86_64-sysv"; + qbearch = "amd64_sysv"; + } else if (hasprefix(target, "aarch64-")) { + arch = "aarch64"; + qbearch = "arm64"; + } else if (hasprefix(target, "riscv64-")) { + arch = "riscv64"; + qbearch = "rv64"; + } else { + fatal("unsupported target '%s'", target); + } + arrayaddptr(&stages[COMPILE].cmd, "-t"); + arrayaddptr(&stages[COMPILE].cmd, arch); + arrayaddptr(&stages[CODEGEN].cmd, "-t"); + arrayaddptr(&stages[CODEGEN].cmd, qbearch); + + for (;;) { + ignore: + ++argv, --argc; + arg = *argv; + if (!arg) + break; + if (arg[0] != '-' || arg[1] == '\0') { + input = arrayadd(&inputs, sizeof(*input)); + input->name = arg; + input->lib = false; + input->filetype = filetype == NONE && arg[1] ? detectfiletype(arg) : filetype; + switch (input->filetype) { + case ASM: + input->stages = 1 << ASSEMBLE | 1 << LINK; + break; + case ASMPP: + input->stages = 1 << PREPROCESS | 1 << ASSEMBLE | 1 << LINK; + break; + case C: + input->stages = 1 << PREPROCESS | 1 << COMPILE | 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; + break; + case CHDR: + input->stages = 1 << PREPROCESS; + break; + case CPPOUT: + input->stages = 1 << COMPILE | 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; + break; + case QBE: + input->stages = 1 << CODEGEN | 1 << ASSEMBLE | 1 << LINK; + break; + case OBJ: + input->stages = 1 << LINK; + break; + default: + usage( + "reading from standard input requires " + "-x" + ); + } + continue; + } + + for (i = 0; i < countof(ignoreflags); ++i) { + if (strcmp(arg + 1, ignoreflags[i]) == 0) + goto ignore; + } + + if (strcmp(arg, "-nostdlib") == 0) { + flags.nostdlib = true; + } else if (strcmp(arg, "-nostdinc") == 0) { + arrayaddptr(&stages[PREPROCESS].cmd, arg); + } else if (strcmp(arg, "-static") == 0) { + arrayaddptr(&stages[LINK].cmd, arg); + } else if (strcmp(arg, "-emit-qbe") == 0) { + if (last > COMPILE) + last = COMPILE; + } else if ( + strcmp(arg, "-idirafter") == 0 || strcmp(arg, "-isystem") == 0 + || strcmp(arg, "-iquote") == 0 + ) { + if (!--argc) + usage(NULL); + arrayaddptr(&stages[PREPROCESS].cmd, arg); + arrayaddptr(&stages[PREPROCESS].cmd, *++argv); + } else if (strncmp(arg, "-std=", 5) == 0) { + arrayaddptr(&stages[PREPROCESS].cmd, arg); + } else if (strcmp(arg, "-pthread") == 0) { + arrayaddptr(&stages[LINK].cmd, "-l"); + arrayaddptr(&stages[LINK].cmd, "pthread"); + } else if (strcmp(arg, "-dumpmachine") == 0) { + puts(target); + return 0; + } else { + if (arg[2] != '\0' && strchr("cESsv", arg[1])) + usage(NULL); + switch (arg[1]) { + case 'c': + if (last > ASSEMBLE) + last = ASSEMBLE; + break; + case 'D': + arrayaddptr(&stages[PREPROCESS].cmd, "-D"); + arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); + break; + case 'E': + if (last > PREPROCESS) + last = PREPROCESS; + break; + case 'g': + break; + case 'I': + arrayaddptr(&stages[PREPROCESS].cmd, "-I"); + arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); + break; + case 'L': + arrayaddptr(&stages[LINK].cmd, "-L"); + arrayaddptr(&stages[LINK].cmd, nextarg(&argv)); + break; + case 'l': + input = arrayadd(&inputs, sizeof(*input)); + input->name = nextarg(&argv); + input->lib = true; + input->filetype = OBJ; + input->stages = 1 << LINK; + break; + case 'O': + break; + case 'o': + output = nextarg(&argv); + break; + case 'P': + arrayaddptr(&stages[PREPROCESS].cmd, "-P"); + break; + case 'S': + if (last > CODEGEN) + last = CODEGEN; + break; + case 's': + arrayaddptr(&stages[LINK].cmd, "-s"); + break; + case 'U': + arrayaddptr(&stages[PREPROCESS].cmd, "-U"); + arrayaddptr(&stages[PREPROCESS].cmd, nextarg(&argv)); + break; + case 'v': + flags.verbose = true; + break; + case 'W': + if (arg[2] && arg[3] == ',') { + switch (arg[2]) { + case 'p': + cmd = &stages[PREPROCESS].cmd; + break; + case 'a': + cmd = &stages[ASSEMBLE].cmd; + break; + case 'l': + cmd = &stages[LINK].cmd; + break; + default: + usage(NULL); + } + for (arg += 4; arg; arg = end ? end + 1 : NULL) { + end = strchr(arg, ','); + if (end) + *end = '\0'; + arrayaddptr(cmd, arg); + } + } + break; + case 'x': + arg = nextarg(&argv); + if (strcmp(arg, "none") == 0) + filetype = NONE; + else if (strcmp(arg, "c") == 0) + filetype = C; + else if (strcmp(arg, "c-header") == 0) + filetype = CHDR; + else if (strcmp(arg, "cpp-output") == 0) + filetype = CPPOUT; + else if (strcmp(arg, "qbe") == 0) + filetype = QBE; + else if (strcmp(arg, "assembler") == 0) + filetype = ASM; + else if (strcmp(arg, "assembler-with-cpp") == 0) + filetype = ASMPP; + else + usage("unknown language '%s'", arg); + break; + default: + usage("unknown option '%s'", arg); + } + } + } + + for (i = 0; i < countof(stages); ++i) + stages[i].cmdbase = stages[i].cmd.len; + if (inputs.len == 0) + usage(NULL); + if (output) { + if (strcmp(output, "-") == 0) { + if (last >= ASSEMBLE) + usage("cannot write object to stdout"); + } else if (last != LINK && inputs.len > sizeof(*input)) { + usage( + "cannot specify -o with multiple input files " + "without linking" + ); + } + } + arrayforeach(&inputs, input) + { + if (!(input->stages & 1 << last)) + continue; + input->stages &= (1 << last + 1) - 1; + buildobj(input, output); + } + if (last == LINK) { + if (!output) + output = "a.out"; + buildexe(inputs.val, inputs.len / sizeof(*input), output); + } + return 0; +} diff --git a/cmd/dev/cc/eval.c b/cmd/dev/cc/eval.c @@ -0,0 +1,310 @@ +#include <stdbool.h> +#include <stddef.h> +#include "util.h" +#include "cc.h" + +enum { F = 1 << 8, S = 2 << 8 }; + +static void +cast(struct expr *expr) +{ + struct type *t; + unsigned long long m; + + t = expr->type; + if (t->prop & PROPFLOAT) { + if (t->size == 4) + expr->u.constant.f = (float)expr->u.constant.f; + } else if (t->prop & PROPINT) { + m = 1ull << t->u.arith.width - 1; + expr->u.constant.u &= m | m - 1; + if (t->u.arith.issigned) + expr->u.constant.u = (expr->u.constant.u ^ m) - m; + } +} + +static void +unary(struct expr *expr, enum tokenkind op, struct expr *l) +{ + expr->kind = EXPRCONST; + if (l->type->prop & PROPFLOAT) + op |= F; + switch (op) { + case TSUB: + expr->u.constant.u = -l->u.constant.u; + break; + case TSUB | F: + expr->u.constant.f = -l->u.constant.f; + break; + default: + fatal("internal error; unknown unary expression"); + } + cast(expr); +} + +static void +binary(struct expr *expr, enum tokenkind op, struct expr *l, struct expr *r) +{ + expr->kind = EXPRCONST; + if (l->type->prop & PROPFLOAT) + op |= F; + else if (l->type->prop & PROPINT && l->type->u.arith.issigned) + op |= S; + switch (op) { + case TMUL: + case TMUL | S: + expr->u.constant.u = l->u.constant.u * r->u.constant.u; + break; + case TMUL | F: + expr->u.constant.f = l->u.constant.f * r->u.constant.f; + break; + case TDIV: + expr->u.constant.u = l->u.constant.u / r->u.constant.u; + break; + case TDIV | S: + expr->u.constant.i = l->u.constant.i / r->u.constant.i; + break; + case TDIV | F: + expr->u.constant.f = l->u.constant.f / r->u.constant.f; + break; + case TMOD: + expr->u.constant.u = l->u.constant.u % r->u.constant.u; + break; + case TMOD | S: + expr->u.constant.i = l->u.constant.i % r->u.constant.i; + break; + case TADD: + case TADD | S: + expr->u.constant.u = l->u.constant.u + r->u.constant.u; + break; + case TADD | F: + expr->u.constant.f = l->u.constant.f + r->u.constant.f; + break; + case TSUB: + case TSUB | S: + expr->u.constant.u = l->u.constant.u - r->u.constant.u; + break; + case TSUB | F: + expr->u.constant.f = l->u.constant.f - r->u.constant.f; + break; + case TSHL: + case TSHL | S: + expr->u.constant.u = l->u.constant.u << (r->u.constant.u & 63); + break; + case TSHR: + expr->u.constant.u = l->u.constant.u >> (r->u.constant.u & 63); + break; + case TSHR | S: + expr->u.constant.i = l->u.constant.i >> (r->u.constant.u & 63); + break; + case TBAND: + case TBAND | S: + expr->u.constant.u = l->u.constant.u & r->u.constant.u; + break; + case TBOR: + case TBOR | S: + expr->u.constant.u = l->u.constant.u | r->u.constant.u; + break; + case TXOR: + case TXOR | S: + expr->u.constant.u = l->u.constant.u ^ r->u.constant.u; + break; + case TLESS: + expr->u.constant.u = l->u.constant.u < r->u.constant.u; + break; + case TLESS | S: + expr->u.constant.u = l->u.constant.i < r->u.constant.i; + break; + case TLESS | F: + expr->u.constant.u = l->u.constant.f < r->u.constant.f; + break; + case TGREATER: + expr->u.constant.u = l->u.constant.u > r->u.constant.u; + break; + case TGREATER | S: + expr->u.constant.u = l->u.constant.i > r->u.constant.i; + break; + case TGREATER | F: + expr->u.constant.u = l->u.constant.f > r->u.constant.f; + break; + case TLEQ: + expr->u.constant.u = l->u.constant.u <= r->u.constant.u; + break; + case TLEQ | S: + expr->u.constant.u = l->u.constant.i <= r->u.constant.i; + break; + case TLEQ | F: + expr->u.constant.u = l->u.constant.f <= r->u.constant.f; + break; + case TGEQ: + expr->u.constant.u = l->u.constant.u >= r->u.constant.u; + break; + case TGEQ | S: + expr->u.constant.u = l->u.constant.i >= r->u.constant.i; + break; + case TGEQ | F: + expr->u.constant.u = l->u.constant.f >= r->u.constant.f; + break; + case TEQL: + case TEQL | S: + expr->u.constant.u = l->u.constant.u == r->u.constant.u; + break; + case TEQL | F: + expr->u.constant.u = l->u.constant.f == r->u.constant.f; + break; + case TNEQ: + case TNEQ | S: + expr->u.constant.u = l->u.constant.u != r->u.constant.u; + break; + case TNEQ | F: + expr->u.constant.u = l->u.constant.f != r->u.constant.f; + break; + default: + fatal("internal error; unknown binary expression"); + } + cast(expr); +} + +struct expr * +eval(struct expr *expr) +{ + struct expr *l, *r, *c; + struct decl *d; + struct type *t; + + t = expr->type; + switch (expr->kind) { + case EXPRIDENT: + d = expr->u.ident.decl; + if (d->kind != DECLCONST) + break; + expr->kind = EXPRCONST; + expr->u.constant.u = d->u.enumconst; + break; + case EXPRCOMPOUND: + d = expr->u.compound.decl; + if (d->u.obj.storage != SDSTATIC) + break; + d->value = mkglobal(d); + emitdata(d, expr->u.compound.init); + expr->kind = EXPRIDENT; + expr->u.ident.decl = d; + break; + case EXPRUNARY: + l = eval(expr->base); + switch (expr->op) { + case TBAND: + switch (l->kind) { + case EXPRUNARY: + if (l->op == TMUL) + expr = eval(l->base); + break; + case EXPRSTRING: + l->u.ident.decl = stringdecl(l); + l->kind = EXPRIDENT; + expr->base = l; + break; + } + break; + case TMUL: + break; + default: + if (l->kind != EXPRCONST) + break; + unary(expr, expr->op, l); + break; + } + break; + case EXPRCAST: + l = eval(expr->base); + if (l->kind == EXPRCONST) { + expr->kind = EXPRCONST; + if (l->type->prop & PROPINT && t->prop & PROPFLOAT) { + if (l->type->u.arith.issigned) + expr->u.constant.f = l->u.constant.i; + else + expr->u.constant.f = l->u.constant.u; + } else if (l->type->prop & PROPFLOAT && t->prop & PROPINT) { + if (t->u.arith.issigned) { + if (l->u.constant.f < -0x1p63 || l->u.constant.f >= 0x1p63) + error( + &tok.loc, + "integer part of " + "floating-point constant " + "%g cannot be " + "represented as signed " + "integer", + l->u.constant.f + ); + expr->u.constant.i = l->u.constant.f; + } else { + if (l->u.constant.f < 0.0 || l->u.constant.f >= 0x1p64) + error( + &tok.loc, + "integer part of " + "floating-point constant " + "%g cannot be " + "represented as unsigned " + "integer", + l->u.constant.f + ); + expr->u.constant.u = l->u.constant.f; + } + } else { + expr->u.constant = l->u.constant; + } + cast(expr); + } else if (l->type->kind == TYPEPOINTER) { + /* + * a cast from a pointer to integer is not a valid constant + * expression, but C11 allows implementations to recognize + * other forms of constant expressions (6.6p10), and some + * programs expect this functionality + */ + if (t->kind == TYPEPOINTER || t->prop & PROPINT && t->size == typelong.size) + expr = l; + } + break; + case EXPRBINARY: + l = eval(expr->u.binary.l); + r = eval(expr->u.binary.r); + expr->u.binary.l = l; + expr->u.binary.r = r; + switch (expr->op) { + case TADD: + if (r->kind == EXPRBINARY) + c = l, l = r, r = c; + /* fallthrough */ + case TSUB: + if (r->kind != EXPRCONST) + break; + if (l->kind == EXPRCONST) { + binary(expr, expr->op, l, r); + } else if ( + l->kind == EXPRBINARY && l->type->kind == TYPEPOINTER && l->op == TADD + && l->u.binary.r->kind == EXPRCONST + ) { + /* (p + C1) C2 -> p + (C1 C2) */ + binary(expr->u.binary.r, expr->op, l->u.binary.r, r); + expr->op = TADD; + expr->u.binary.l = l->u.binary.l; + } + break; + case TLOR: + if (l->kind != EXPRCONST) + break; + return l->u.constant.u ? l : r; + case TLAND: + if (l->kind != EXPRCONST) + break; + return l->u.constant.u ? r : l; + default: + if (l->kind != EXPRCONST || r->kind != EXPRCONST) + break; + binary(expr, expr->op, l, r); + } + break; + } + + return expr; +} diff --git a/cmd/dev/cc/expr.c b/cmd/dev/cc/expr.c @@ -0,0 +1,1827 @@ +#include "util.h" +#include "cc.h" +#include <assert.h> +#include <limits.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> + +#include "utf.h" + +static struct expr * +mkexpr(enum exprkind k, struct type *t, struct expr *b) +{ + struct expr *e; + + e = xmalloc(sizeof(*e)); + e->qual = QUALNONE; + e->type = t; + e->lvalue = false; + e->decayed = false; + e->kind = k; + e->base = b; + e->next = NULL; + e->toeval = NULL; + + return e; +} + +void +delexpr(struct expr *e) +{ + struct expr *sub; + + switch (e->kind) { + case EXPRCALL: + delexpr(e->base); + while (sub = e->u.call.args) { + e->u.call.args = sub->next; + delexpr(sub); + } + break; + case EXPRBITFIELD: + case EXPRINCDEC: + case EXPRUNARY: + case EXPRCAST: + delexpr(e->base); + break; + case EXPRBINARY: + delexpr(e->u.binary.l); + delexpr(e->u.binary.r); + break; + case EXPRCOND: + delexpr(e->base); + if (e->u.cond.t != e->base) + delexpr(e->u.cond.t); + delexpr(e->u.cond.f); + break; + /* + * XXX: compound assignment causes some reuse of expressions, + * so we cant free them without risk of a double-free + * + * case EXPRASSIGN: + * delexpr(e->assign.l); + * delexpr(e->assign.r); + * break; + */ + case EXPRCOMMA: + while (sub = e->base) { + e->base = sub->next; + delexpr(sub); + } + break; + } + free(e); +} + +static struct expr * +mkconstexpr(struct type *t, unsigned long long n) +{ + struct expr *e; + + e = mkexpr(EXPRCONST, t, NULL); + e->u.constant.u = n; + + return e; +} + +static struct expr *mkunaryexpr(enum tokenkind, struct expr *); + +/* 6.3.2.1 conversion of arrays and function designators */ +static struct expr * +decay(struct expr *e) +{ + struct type *t; + enum typequal tq; + + /* XXX: combine with decl.c:adjust in some way? */ + t = e->type; + tq = e->qual; + switch (t->kind) { + case TYPEARRAY: + /* + * XXX: qualifiers should be applied to the element + * type of array types, not the array type itself + * + * assert(tq == QUALNONE); + */ + e = mkunaryexpr(TBAND, e); + e->type = mkpointertype(t->base, t->qual | tq); + e->decayed = true; + break; + case TYPEFUNC: + e = mkunaryexpr(TBAND, e); + e->decayed = true; + break; + } + + return e; +} + +static struct expr * +mkunaryexpr(enum tokenkind op, struct expr *base) +{ + struct expr *expr; + struct type *type; + + switch (op) { + case TBAND: + if (base->decayed) { + expr = base; + base = base->base; + free(expr); + } + /* + * allow struct and union types even if they are not lvalues, + * since we take their address when compiling member access + */ + if (!base->lvalue && base->type->kind != TYPEFUNC && base->type->kind != TYPESTRUCT + && base->type->kind != TYPEUNION) + error( + &tok.loc, + "'&' operand is not an lvalue or " + "function designator" + ); + if (base->kind == EXPRBITFIELD) + error(&tok.loc, "cannot take address of bit-field"); + expr = mkexpr(EXPRUNARY, mkpointertype(base->type, base->qual), base); + expr->op = op; + return expr; + case TMUL: + if (base->type->kind != TYPEPOINTER) + error(&tok.loc, "cannot dereference non-pointer"); + if (base->kind == EXPRUNARY && base->op == TBAND && base->base->kind != EXPRSTRING) { + type = base->type->base; + expr = base->base; + expr->type = type; + } else { + expr = mkexpr(EXPRUNARY, base->type->base, base); + expr->qual = base->type->qual; + expr->lvalue = true; + expr->op = op; + } + return decay(expr); + } + /* other unary operators get compiled as equivalent binary ones */ + fatal("internal error: unknown unary operator %d", op); + return NULL; +} + +static unsigned +bitfieldwidth(struct expr *e) +{ + if (e->kind != EXPRBITFIELD) + return -1; + return e->type->size * 8 - e->u.bitfield.bits.before - e->u.bitfield.bits.after; +} + +static struct expr * +exprconvert(struct expr *e, struct type *t) +{ + if (typecompatible(e->type, t)) + return e; + return mkexpr(EXPRCAST, t, e); +} + +static bool +nullpointer(struct expr *e) +{ + if (e->kind != EXPRCONST) + return false; + if (e->type->kind == TYPENULLPTR) + return true; + if (!(e->type->prop & PROPINT) && (e->type->kind != TYPEPOINTER || e->type->base != &typevoid)) + return false; + return e->u.constant.u == 0; +} + +struct expr * +exprassign(struct expr *e, struct type *t) +{ + struct type *et; + + et = e->type; + switch (t->kind) { + case TYPEBOOL: + if (!(et->prop & PROPARITH) && et->kind != TYPEPOINTER && et->kind != TYPENULLPTR) + error( + &tok.loc, + "assignment to bool must be from arithmetic, " + "pointer, or nullptr_t type" + ); + break; + case TYPEPOINTER: + if (nullpointer(e)) + break; + if (et->kind != TYPEPOINTER) + error( + &tok.loc, + "assignment to pointer must be from " + "pointer or null pointer constant" + ); + if (t->base != &typevoid && et->base != &typevoid && !typecompatible(t->base, et->base)) + error( + &tok.loc, + "base types of pointer assignment must " + "be compatible or void" + ); + if ((et->qual & t->qual) != et->qual) + error(&tok.loc, "assignment to pointer discards qualifiers"); + break; + case TYPENULLPTR: + if (!nullpointer(e)) + error( + &tok.loc, + "assignment to nullptr_t must be from " + "null pointer constant or expression " + "with type nullptr_t" + ); + break; + case TYPESTRUCT: + case TYPEUNION: + case TYPECOMPLEX: + if (!typecompatible(t, et)) + error( + &tok.loc, + "assignment to %s type must be from compatible " + "type", + t->kind == TYPEUNION ? "union" + : t->kind == TYPECOMPLEX ? "complex" + : "struct" + ); + break; + default: + assert(t->prop & PROPARITH); + if (!(et->prop & PROPARITH)) + error( + &tok.loc, + "assignment to arithmetic type must be " + "from arithmetic type" + ); + break; + } + return exprconvert(e, t); +} + +struct expr * +exprpromote(struct expr *e) +{ + struct type *t; + + t = typepromote(e->type, bitfieldwidth(e)); + return exprconvert(e, t); +} + +static struct type * +commonreal(struct expr **e1, struct expr **e2) +{ + struct type *t; + + t = typecommonreal((*e1)->type, bitfieldwidth(*e1), (*e2)->type, bitfieldwidth(*e2)); + *e1 = exprconvert(*e1, t); + *e2 = exprconvert(*e2, t); + + return t; +} + +static struct expr * +mksizeofexpr(struct type *t) +{ + struct expr *e; + + if (t->kind == TYPEARRAY && t->size == 0) { + e = mkexpr(EXPRSIZEOF, &typeulong, NULL); + e->u.szof.type = t; + } else { + e = mkconstexpr(&typeulong, t->size); + } + + return e; +} + +/* complex has none of PROPARITH/PROPSCALAR/PROPREAL (see type.c), so + * it never reaches the usual-arithmetic-conversion paths below on its + * own; every operator that accepts it checks for it explicitly, up + * front, and requires an exact type match on both sides (no mixed + * float/double complex, no mixed real/complex, matching how far this + * compiler's complex support currently goes) */ +static int +iscomplexop(struct expr *l, struct expr *r) +{ + return l->type->kind == TYPECOMPLEX || r->type->kind == TYPECOMPLEX; +} + +static struct expr * +mkbinaryexpr(struct location *loc, enum tokenkind op, struct expr *l, struct expr *r) +{ + struct expr *e; + struct type *t = NULL; + enum typeprop lp, rp; + + lp = l->type->prop; + rp = r->type->prop; + switch (op) { + case TLOR: + case TLAND: + if (!(lp & PROPSCALAR)) + error(loc, "left operand of '%s' operator must be scalar", tokenstr(op)); + if (!(rp & PROPSCALAR)) + error(loc, "right operand of '%s' operator must be scalar", tokenstr(op)); + t = &typeint; + break; + case TEQL: + case TNEQ: + t = &typeint; + if (iscomplexop(l, r)) { + if (l->type->kind != TYPECOMPLEX || r->type->kind != TYPECOMPLEX || l->type != r->type) + error( + loc, + "'%s' between complex operands requires the same complex type on both sides", + tokenstr(op) + ); + break; + } + if (lp & PROPARITH && rp & PROPARITH) { + commonreal(&l, &r); + break; + } + if (l->type->kind != TYPEPOINTER) + e = l, l = r, r = e; + if (l->type->kind != TYPEPOINTER) + error(loc, "invalid operands to '%s' operator", tokenstr(op)); + if (nullpointer(eval(r))) { + r = exprconvert(r, l->type); + break; + } + if (nullpointer(eval(l))) { + l = exprconvert(l, r->type); + break; + } + if (r->type->kind != TYPEPOINTER) + error(loc, "invalid operands to '%s' operator", tokenstr(op)); + if (l->type->base->kind == TYPEVOID) + e = l, l = r, r = e; + if (r->type->base->kind == TYPEVOID && l->type->base->kind != TYPEFUNC) + r = exprconvert(r, l->type); + else if (!typecompatible(l->type->base, r->type->base)) + error( + loc, + "pointer operands to '%s' operator are to " + "incompatible types", + tokenstr(op) + ); + break; + case TLESS: + case TGREATER: + case TLEQ: + case TGEQ: + t = &typeint; + if (lp & PROPREAL && rp & PROPREAL) { + commonreal(&l, &r); + } else if (l->type->kind == TYPEPOINTER && r->type->kind == TYPEPOINTER) { + if (!typecompatible(l->type->base, r->type->base) || l->type->base->kind == TYPEFUNC) + error( + loc, + "pointer operands to '%s' operator must " + "be to compatible object types", + tokenstr(op) + ); + } else { + error(loc, "invalid operands to '%s' operator", tokenstr(op)); + } + break; + case TBOR: + case TXOR: + case TBAND: + t = commonreal(&l, &r); + break; + case TADD: + if (iscomplexop(l, r)) { + if (l->type->kind != TYPECOMPLEX || r->type->kind != TYPECOMPLEX || l->type != r->type) + error(loc, "'+' between complex operands requires the same complex type on both sides"); + t = l->type; + break; + } + if (lp & PROPARITH && rp & PROPARITH) { + t = commonreal(&l, &r); + break; + } + if (r->type->kind == TYPEPOINTER) + e = l, l = r, r = e, rp = lp; + if (l->type->kind != TYPEPOINTER || !(rp & PROPINT)) + error(loc, "invalid operands to '+' operator"); + t = l->type; + if (t->base->incomplete || t->base->kind == TYPEFUNC) + error( + loc, + "pointer operand to '+' must be to complete " + "object type" + ); + r = mkbinaryexpr(loc, TMUL, exprconvert(r, &typeulong), mksizeofexpr(t->base)); + break; + case TSUB: + if (iscomplexop(l, r)) { + if (l->type->kind != TYPECOMPLEX || r->type->kind != TYPECOMPLEX || l->type != r->type) + error(loc, "'-' between complex operands requires the same complex type on both sides"); + t = l->type; + break; + } + if (lp & PROPARITH && rp & PROPARITH) { + t = commonreal(&l, &r); + break; + } + if (l->type->kind != TYPEPOINTER || !(rp & PROPINT) && r->type->kind != TYPEPOINTER) + error(loc, "invalid operands to '-' operator"); + if (l->type->base->incomplete || l->type->base->kind == TYPEFUNC) + error( + loc, + "pointer operand to '-' must be to complete " + "object type" + ); + if (rp & PROPINT) { + t = l->type; + r = mkbinaryexpr(loc, TMUL, exprconvert(r, &typeulong), mksizeofexpr(t->base)); + } else { + if (!typecompatible(l->type->base, r->type->base)) + error( + &tok.loc, + "pointer operands to '-' are " + "to incompatible types" + ); + op = TDIV; + t = &typelong; + e = mkbinaryexpr(loc, TSUB, exprconvert(l, &typelong), exprconvert(r, &typelong)); + r = mksizeofexpr(l->type->base); + l = e; + } + break; + case TMOD: + if (!(lp & PROPINT) || !(rp & PROPINT)) + error(loc, "operands to '%%' operator must be integer"); + t = commonreal(&l, &r); + break; + case TMUL: + case TDIV: + if (iscomplexop(l, r)) { + if (l->type->kind != TYPECOMPLEX || r->type->kind != TYPECOMPLEX || l->type != r->type) + error(loc, "'%s' between complex operands requires the same complex type on both sides", tokenstr(op)); + t = l->type; + break; + } + if (!(lp & PROPARITH) || !(rp & PROPARITH)) + error(loc, "operands to '%s' operator must be arithmetic", tokenstr(op)); + t = commonreal(&l, &r); + break; + case TSHL: + case TSHR: + if (!(lp & PROPINT) || !(rp & PROPINT)) + error(loc, "operands to '%s' operator must be integer", tokenstr(op)); + l = exprpromote(l); + r = exprpromote(r); + t = l->type; + break; + default: + fatal("internal error: unknown binary operator %d", op); + } + e = mkexpr(EXPRBINARY, t, NULL); + e->op = op; + e->u.binary.l = l; + e->u.binary.r = r; + + return e; +} + +static struct type * +inttype(unsigned long long val, bool decimal, char *suffix) +{ + enum { + U = 1, + L = 2, + LL = 4, + WB = 8, + }; + static struct type *const types[] = { + &typeint, + &typeuint, /* u */ + &typelong, /* l */ + &typeulong, /* ul */ + &typellong, /* ll */ + &typeullong, /* ull */ + }; + int flags, i, step; + bool sign; + char *s; + struct type *t; + + /* parse suffix */ + flags = 0; + for (s = suffix; *s; ++s) { + int new; + + switch (*s) { + case 'u': + case 'U': + new = U; + break; + case 'l': + case 'L': + new = s[1] == s[0] ? (++s, LL) : L; + break; + case 'w': + if (s[1] != 'b') + goto invalid; + ++s, new = WB; + break; + case 'W': + if (s[1] != 'B') + goto invalid; + ++s, new = WB; + break; + default: + invalid: + error(&tok.loc, "invalid integer constant suffix '%s'", suffix); + } + if (flags & new || flags & ~U &&new & ~U) + goto invalid; + flags |= new; + } + + /* find integer type */ + sign = !(flags & U); + if (flags & WB) { + for (i = 1;; ++i) { + if (i > 64 - sign) + goto notype; + if (val <= 0xffffffffffffffff >> 64 - i) + break; + } + return mkbitinttype(i + sign, sign); + } + assert(flags < countof(types)); + step = !sign || decimal ? 2 : 1; + for (i = flags; i < countof(types); i += step) { + t = types[i]; + if (typehasint(t, val, false)) + return t; + } +notype: + error(&tok.loc, "no suitable type for constant '%s'", tok.lit); +} + +static int +octval(int c) +{ + if ('0' <= c && c <= '7') + return c - '0'; + return -1; +} + +static int +hexval(int c) +{ + if ('0' <= c && c <= '9') + return c - '0'; + if ('a' <= c && c <= 'f') + return c - 'a' + 10; + if ('A' <= c && c <= 'F') + return c - 'A' + 10; + return -1; +} + +static size_t +decodechar( + const char *src, uint_least32_t *chr, bool *hexoct, const char *desc, struct location *loc +) +{ + uint_least32_t c; + size_t n; + int i, v; + const unsigned char *s = (const unsigned char *)src; + + *hexoct = false; + if (*s == '\\') { + ++s; + switch (*s) { + case '\'': + case '"': + case '?': + case '\\': + c = *s; + ++s; + break; + case 'a': + c = '\a'; + ++s; + break; + case 'b': + c = '\b'; + ++s; + break; + case 'f': + c = '\f'; + ++s; + break; + case 'n': + c = '\n'; + ++s; + break; + case 'r': + c = '\r'; + ++s; + break; + case 't': + c = '\t'; + ++s; + break; + case 'v': + c = '\v'; + ++s; + break; + case 'x': + ++s; + c = 0; + v = hexval(*s); + assert(v >= 0); + do { + if (c > 0xffffffff / 16) + error( + &tok.loc, + "character constant escape is " + "out of range" + ); + c = c * 16 + v; + v = hexval(*++s); + } while (v >= 0); + *hexoct = true; + break; + default: + c = 0; + v = octval(*s); + assert(v >= 0); + i = 0; + do { + if (c > 0xffffffff / 8) + error( + &tok.loc, + "character constant escape is " + "out of range" + ); + c = c * 8 + v; + v = octval(*++s); + } while (v >= 0 && ++i < 3); + *hexoct = true; + } + } else { + n = utf8dec(&c, s, 4); + if (n == (size_t)-1) + error(loc, "%s contains invalid UTF-8", desc); + s += n; + } + *chr = c; + return s - (const unsigned char *)src; +} + +static size_t +encodechar8(void *dst, uint_least32_t chr, bool hexoct) +{ + if (!hexoct) + return utf8enc(dst, chr); + *(unsigned char *)dst = chr; + return 1; +} + +static size_t +encodechar16(void *dst, uint_least32_t chr, bool hexoct) +{ + if (!hexoct) + return utf16enc(dst, chr) * sizeof(uint_least16_t); + *(uint_least16_t *)dst = chr; + return sizeof(uint_least16_t); +} + +static size_t +encodechar32(void *dst, uint_least32_t chr, bool hexoct) +{ + *(uint_least32_t *)dst = chr; + return sizeof(uint_least32_t); +} + +struct type * +stringconcat(struct stringlit *str, bool forceutf8) +{ + static struct array parts; + struct { + struct location loc; + char *str; + } *p; + int kind, newkind; + struct type *t; + size_t (*encodechar)(void *, uint_least32_t, bool); + char *src; + unsigned char *buf, *dst; + uint_least32_t chr; + bool hexoct; + size_t len, width; + + assert(tok.kind == TSTRINGLIT); + parts.len = 0; + len = 0; + kind = 0; + do { + src = tok.lit; + switch (*src) { + case 'u': + if (src[1] == '8') + ++src; /* fallthrough */ + case 'L': + case 'U': + newkind = *src, ++src; + break; + case '"': + newkind = 0; + break; + default: + assert(0); + } + if (kind != newkind && kind && newkind) + error( + &tok.loc, + "adjacent string literals have " + "differing prefixes" + ); + if (newkind) + kind = newkind; + p = arrayadd(&parts, sizeof(*p)); + p->loc = tok.loc; + p->str = src + 1; + len += strlen(src) - 2; + next(); + } while (tok.kind == TSTRINGLIT); + if (forceutf8) + kind = '8'; + ++len; /* null byte */ + switch (kind) { + case 0: + t = &typechar; + break; + case '8': + t = &typeuchar; + break; + case 'u': + t = &typeushort; + break; + case 'U': + t = &typeuint; + break; + case 'L': + t = targ->typewchar; + break; + default: + assert(0); + } + switch (t->size) { + case 1: + width = 1; + encodechar = encodechar8; + break; + case 2: + width = sizeof(uint_least16_t); + encodechar = encodechar16; + break; + case 4: + width = sizeof(uint_least32_t); + encodechar = encodechar32; + break; + default: + assert(0); + } + buf = xreallocarray(NULL, len, width); + str->data = buf; + dst = buf; + arrayforeach(&parts, p) + { + src = p->str; + while (*src != '"') { + src += decodechar(src, &chr, &hexoct, "string literal", &p->loc); + dst += encodechar(dst, chr, hexoct); + } + } + dst += encodechar(dst, 0, false); + str->size = (dst - buf) / width; + return t; +} + +static struct expr * +generic(struct scope *s) +{ + struct expr *e, *match = NULL, *def = NULL; + struct type *t, *want; + enum typequal qual; + + next(); + expect(TLPAREN, "after '_Generic'"); + e = assignexpr(s); + expect(TCOMMA, "after generic selector expression"); + want = e->type; + delexpr(e); + do { + if (consume(TDEFAULT)) { + if (def) + error( + &tok.loc, + "multiple default expressions " + "in generic association list" + ); + expect(TCOLON, "after 'default'"); + def = assignexpr(s); + } else { + qual = QUALNONE; + t = typename(s, &qual, NULL); + if (!t) + error( + &tok.loc, + "expected typename for generic " + "association" + ); + if (t->kind == TYPEFUNC) + error( + &tok.loc, + "generic association must have " + "object type" + ); + if (t->incomplete) + error( + &tok.loc, + "generic association must have " + "complete type" + ); + if (t->prop & PROPVM) + error( + &tok.loc, + "generic association has " + "variably modified type" + ); + expect(TCOLON, "after type name"); + e = assignexpr(s); + if (typecompatible(t, want) && qual == QUALNONE) { + if (match) + error( + &tok.loc, + "generic selector matches " + "multiple associations" + ); + match = e; + } else { + delexpr(e); + } + } + } while (consume(TCOMMA)); + expect(TRPAREN, "after generic assocation list"); + if (!match) { + if (!def) + error( + &tok.loc, + "generic selector matches no associations and no " + "default was specified" + ); + match = def; + } else if (def) { + delexpr(def); + } + return match; +} + +/* 6.5 expressions */ +static struct expr * +primaryexpr(struct scope *s) +{ + struct expr *e; + struct decl *d; + struct type *t; + char *src, *end; + uint_least32_t chr; + unsigned long long val; + bool hexoct, ordinary; + int base; + + switch (tok.kind) { + case TSTRINGLIT: + e = mkexpr(EXPRSTRING, NULL, NULL); + t = stringconcat(&e->u.string, false); + e->type = mkarraytype(t, QUALNONE, e->u.string.size); + e->lvalue = true; + e = decay(e); + break; + case TCHARCONST: + src = tok.lit; + ordinary = false; + switch (*src) { + case 'L': + ++src; + t = targ->typewchar; + break; + case 'u': + ++src; + t = *src == '8' ? ++src, &typeuchar : &typeushort; + break; + case 'U': + ++src; + t = &typeuint; + break; + default: + t = &typeuchar, ordinary = true; + } + assert(*src == '\''); + ++src; + src += decodechar(src, &chr, &hexoct, "character constant", &tok.loc); + if (hexoct && !typehasint(t, chr, false)) + error(&tok.loc, "character constant escape is out of range"); + val = chr; + if (ordinary) { + if (typechar.u.arith.issigned) + val = (val ^ 0x80) - 0x80; + t = &typeint; + } + e = mkconstexpr(t, val); + if (*src != '\'') + error( + &tok.loc, + "character constant contains more than one " + "character: %c", + *src + ); + next(); + break; + case TNUMBER: + e = mkexpr(EXPRCONST, NULL, NULL); + if (tok.lit[0] == '0') { + switch (tok.lit[1]) { + case 'x': + case 'X': + base = 16; + break; + case 'b': + case 'B': + base = 2; + break; + default: + base = 8; + break; + } + } else { + base = 10; + } + if (strpbrk(tok.lit, base == 16 ? ".pP" : ".eE")) { + /* floating constant */ + e->u.constant.f = strtod(tok.lit, &end); + if (end == tok.lit) + error(&tok.loc, "invalid floating constant '%s'", tok.lit); + if (!end[0]) + e->type = &typedouble; + else if ((end[0] == 'f' || end[0] == 'F') && !end[1]) + e->type = &typefloat; + else if ((end[0] == 'l' || end[0] == 'L') && !end[1]) + e->type = &typeldouble; + else + error(&tok.loc, "invalid floating constant suffix '%s'", end); + } else { + src = tok.lit; + if (base == 2) + src += 2; + /* integer constant */ + e->u.constant.u = strtoull(src, &end, base); + if (end == src) + error(&tok.loc, "invalid integer constant '%s'", tok.lit); + e->type = inttype(e->u.constant.u, base == 10, end); + } + next(); + break; + case TTRUE: + case TFALSE: + e = mkexpr(EXPRCONST, &typebool, NULL); + e->u.constant.u = tok.kind == TTRUE; + next(); + break; + case TNULLPTR: + e = mkexpr(EXPRCONST, &typenullptr, NULL); + e->u.constant.u = 0; + next(); + break; + case TLPAREN: + next(); + e = expr(s); + expect(TRPAREN, "after expression"); + break; + case T_GENERIC: + e = generic(s); + break; + default: + if (tok.kind >= TIDENT) { + d = scopegetdecl(s, tokenstr(tok.kind), 1); + if (!d) + error(&tok.loc, "undeclared identifier: %s", tokenstr(tok.kind)); + e = mkexpr(EXPRIDENT, d->type, NULL); + e->qual = d->qual; + e->lvalue = d->kind == DECLOBJECT; + e->u.ident.decl = d; + if (d->kind != DECLBUILTIN) + e = decay(e); + next(); + break; + } + error(&tok.loc, "expected primary expression"); + } + + return e; +} + +/* TODO: merge with init.c:designator() */ +static void +designator(struct scope *s, struct type *t, unsigned long long *offset) +{ + char *name; + struct member *m; + unsigned long long i; + + for (;;) { + switch (tok.kind) { + case TLBRACK: + if (t->kind != TYPEARRAY) + error( + &tok.loc, + "index designator is only " + "valid for array types" + ); + next(); + i = intconstexpr(s, false); + expect(TRBRACK, "for index designator"); + t = t->base; + *offset += i * t->size; + break; + case TPERIOD: + if (t->kind != TYPESTRUCT && t->kind != TYPEUNION) + error( + &tok.loc, + "member designator only valid " + "for struct/union types" + ); + next(); + name = expect(TIDENT, "for member designator"); + m = typemember(t, name, offset); + if (!m) + error( + &tok.loc, + "%s has no member named '%s'", + t->kind == TYPEUNION ? "union" : "struct", + name + ); + t = m->type; + break; + default: + return; + } + } +} + +/* every atomic builtin's first argument is a pointer whose pointee + * type drives the rest of the call, checked the same way regardless + * of which builtin is asking */ +static struct expr * +atomicptrarg(struct scope *s, const char *msg) +{ + struct expr *ptr = assignexpr(s); + if (ptr->type->kind != TYPEPOINTER) + error(&tok.loc, "%s must be a pointer", msg); + expect(TCOMMA, "after pointer argument"); + return ptr; +} + +static struct expr * +builtinfunc(struct scope *s, enum builtinkind kind) +{ + struct expr *e, *toeval; + struct expr *ptr, *val, *val2; + struct type *t, *pointee; + struct member *m; + char *name; + unsigned long long offset; + + switch (kind) { + case BUILTINATOMICLOAD: + ptr = atomicptrarg(s, "first argument to __atomic_load_n"); + pointee = ptr->type->base; + delexpr(assignexpr(s)); /* memorder: every access is treated as seq_cst */ + e = mkexpr(EXPRBUILTIN, pointee, ptr); + e->u.builtin.kind = BUILTINATOMICLOAD; + break; + case BUILTINATOMICSTORE: + ptr = atomicptrarg(s, "first argument to __atomic_store_n"); + pointee = ptr->type->base; + val = exprassign(assignexpr(s), pointee); + expect(TCOMMA, "after value argument"); + delexpr(assignexpr(s)); /* memorder */ + e = mkexpr(EXPRBUILTIN, &typevoid, ptr); + e->u.builtin.kind = BUILTINATOMICSTORE; + e->u.builtin.val = val; + break; + case BUILTINATOMICEXCHANGE: + ptr = atomicptrarg(s, "first argument to __atomic_exchange_n"); + pointee = ptr->type->base; + val = exprassign(assignexpr(s), pointee); + expect(TCOMMA, "after value argument"); + delexpr(assignexpr(s)); /* memorder */ + e = mkexpr(EXPRBUILTIN, pointee, ptr); + e->u.builtin.kind = BUILTINATOMICEXCHANGE; + e->u.builtin.val = val; + break; + case BUILTINATOMICCOMPAREEXCHANGE: + ptr = atomicptrarg(s, "first argument to __atomic_compare_exchange_n"); + pointee = ptr->type->base; + val2 = atomicptrarg(s, "second argument to __atomic_compare_exchange_n"); /* &expected */ + val = exprassign(assignexpr(s), pointee); /* desired */ + expect(TCOMMA, "after desired-value argument"); + delexpr(assignexpr(s)); /* weak */ + expect(TCOMMA, "after weak argument"); + delexpr(assignexpr(s)); /* success memorder */ + expect(TCOMMA, "after success memorder argument"); + delexpr(assignexpr(s)); /* failure memorder */ + e = mkexpr(EXPRBUILTIN, &typebool, ptr); + e->u.builtin.kind = BUILTINATOMICCOMPAREEXCHANGE; + e->u.builtin.val = val; + e->u.builtin.val2 = val2; + break; + case BUILTINATOMICFETCHADD: + case BUILTINATOMICFETCHSUB: + case BUILTINATOMICFETCHAND: + case BUILTINATOMICFETCHOR: + case BUILTINATOMICFETCHXOR: + ptr = atomicptrarg(s, "first argument to atomic fetch builtin"); + pointee = ptr->type->base; + val = exprassign(assignexpr(s), pointee); + expect(TCOMMA, "after value argument"); + delexpr(assignexpr(s)); /* memorder */ + e = mkexpr(EXPRBUILTIN, pointee, ptr); + e->u.builtin.kind = kind; + e->u.builtin.val = val; + break; + case BUILTINALLOCA: + e = exprassign(assignexpr(s), &typeulong); + e = mkexpr(EXPRBUILTIN, mkpointertype(&typevoid, QUALNONE), e); + e->u.builtin.kind = BUILTINALLOCA; + break; + case BUILTINCONSTANTP: + e = mkconstexpr(&typeint, eval(condexpr(s))->kind == EXPRCONST); + break; + case BUILTINEXPECT: + /* just a no-op for now */ + /* TODO: check that the expression and the expected value have + * type 'long' */ + e = assignexpr(s); + expect(TCOMMA, "after expression"); + delexpr(assignexpr(s)); + break; + case BUILTININFF: + e = mkexpr(EXPRCONST, &typefloat, NULL); + /* TODO: use INFINITY here when we can handle musl's math.h */ + e->u.constant.f = strtod("inf", NULL); + break; + case BUILTINNANF: + e = assignexpr(s); + if (!e->decayed || e->base->kind != EXPRSTRING || e->base->u.string.size > 1) + error( + &tok.loc, + "__builtin_nanf currently only " + "supports empty string literals" + ); + e = mkexpr(EXPRCONST, &typefloat, NULL); + /* TODO: use NAN here when we can handle musl's math.h */ + e->u.constant.f = strtod("nan", NULL); + break; + case BUILTINOFFSETOF: + t = typename(s, NULL, NULL); + expect(TCOMMA, "after type name"); + name = expect(TIDENT, "after ','"); + if (t->kind != TYPESTRUCT && t->kind != TYPEUNION) + error(&tok.loc, "type is not a struct/union type"); + offset = 0; + m = typemember(t, name, &offset); + if (!m) + error(&tok.loc, "struct/union has no member named '%s'", name); + designator(s, m->type, &offset); + e = mkconstexpr(&typeulong, offset); + break; + case BUILTINTYPESCOMPATIBLEP: + t = typename(s, NULL, NULL); + expect(TCOMMA, "after type name"); + e = mkconstexpr(&typeint, typecompatible(t, typename(s, NULL, NULL))); + break; + case BUILTINUNREACHABLE: + e = mkexpr(EXPRBUILTIN, &typevoid, NULL); + e->u.builtin.kind = BUILTINUNREACHABLE; + break; + case BUILTINVAARG: + e = mkexpr(EXPRBUILTIN, NULL, assignexpr(s)); + e->u.builtin.kind = BUILTINVAARG; + if (!typesame(e->base->type, typeadjvalist)) + error(&tok.loc, "va_arg argument must have type va_list"); + if (typeadjvalist == targ->typevalist) + e->base = mkunaryexpr(TBAND, e->base); + expect(TCOMMA, "after va_list"); + e->type = typename(s, &e->qual, &toeval); + e->toeval = toeval; + break; + case BUILTINVACOPY: + e = mkexpr(EXPRASSIGN, &typevoid, NULL); + e->u.assign.l = assignexpr(s); + if (!typesame(e->u.assign.l->type, typeadjvalist)) + error(&tok.loc, "va_copy destination must have type va_list"); + if (typeadjvalist != targ->typevalist) + e->u.assign.l = mkunaryexpr(TMUL, e->u.assign.l); + expect(TCOMMA, "after target va_list"); + e->u.assign.r = assignexpr(s); + if (!typesame(e->u.assign.r->type, typeadjvalist)) + error(&tok.loc, "va_copy source must have type va_list"); + if (typeadjvalist != targ->typevalist) + e->u.assign.r = mkunaryexpr(TMUL, e->u.assign.r); + break; + case BUILTINVAEND: + e = assignexpr(s); + if (!typesame(e->type, typeadjvalist)) + error(&tok.loc, "va_end argument must have type va_list"); + e = mkexpr(EXPRCAST, &typevoid, e); + break; + case BUILTINVASTART: + e = mkexpr(EXPRBUILTIN, &typevoid, assignexpr(s)); + e->u.builtin.kind = BUILTINVASTART; + if (!typesame(e->base->type, typeadjvalist)) + error(&tok.loc, "va_start argument must have type va_list"); + if (typeadjvalist == targ->typevalist) + e->base = mkunaryexpr(TBAND, e->base); + if (consume(TCOMMA)) + delexpr(assignexpr(s)); + break; + default: + fatal("internal error; unknown builtin"); + } + return e; +} + +static struct expr * +mkincdecexpr(enum tokenkind op, struct expr *base, bool post) +{ + struct expr *e; + + if (!base->lvalue) + error(&tok.loc, "operand of '%s' operator must be an lvalue", tokenstr(op)); + if (base->qual & QUALCONST) + error(&tok.loc, "operand of '%s' operator is const qualified", tokenstr(op)); + e = mkexpr(EXPRINCDEC, base->type, base); + e->op = op; + e->u.incdec.post = post; + return e; +} + +static struct expr * +postfixexpr(struct scope *s, struct expr *r) +{ + struct expr *e, *arr, *idx, *tmp, **end; + struct type *t; + struct decl *p; + struct member *m; + unsigned long long offset; + enum typequal tq; + enum tokenkind op; + bool lvalue; + + if (!r) + r = primaryexpr(s); + for (;;) { + switch (tok.kind) { + case TLBRACK: /* subscript */ + next(); + arr = r; + idx = expr(s); + if (arr->type->kind != TYPEPOINTER) { + if (idx->type->kind != TYPEPOINTER) + error( + &tok.loc, + "either array or index " + "must be pointer type" + ); + tmp = arr; + arr = idx; + idx = tmp; + } + if (arr->type->base->incomplete) + error(&tok.loc, "array is pointer to incomplete type"); + if (!(idx->type->prop & PROPINT)) + error(&tok.loc, "index is not an integer type"); + e = mkunaryexpr(TMUL, mkbinaryexpr(&tok.loc, TADD, arr, idx)); + expect(TRBRACK, "after array index"); + break; + case TLPAREN: /* function call */ + next(); + if (r->kind == EXPRIDENT && r->u.ident.decl->kind == DECLBUILTIN) { + e = builtinfunc(s, r->u.ident.decl->u.builtin); + expect(TRPAREN, "after builtin parameters"); + break; + } + if (r->type->kind != TYPEPOINTER || r->type->base->kind != TYPEFUNC) + error(&tok.loc, "called object is not a function"); + t = r->type->base; + e = mkexpr(EXPRCALL, t->base, r); + e->u.call.args = NULL; + e->u.call.nargs = 0; + p = t->u.func.params; + end = &e->u.call.args; + while (tok.kind != TRPAREN) { + if (e->u.call.args) + expect( + TCOMMA, + "or ')' after function " + "call argument" + ); + if (!p && !t->u.func.isvararg) + error( + &tok.loc, + "too many arguments " + "for function call" + ); + *end = assignexpr(s); + if (t->u.func.isvararg && !p) + *end = exprpromote(*end); + else + *end = exprassign(*end, p->type); + end = &(*end)->next; + ++e->u.call.nargs; + if (p) + p = p->next; + } + if (p && !t->u.func.isvararg) + error(&tok.loc, "not enough arguments for function call"); + e = decay(e); + next(); + break; + case TPERIOD: + r = mkunaryexpr(TBAND, r); + /* fallthrough */ + case TARROW: + op = tok.kind; + if (r->type->kind != TYPEPOINTER) + error( + &tok.loc, + "'%s' operator must be applied to " + "pointer to struct/union", + tokenstr(op) + ); + t = r->type->base; + tq = r->type->qual; + if (t->kind != TYPESTRUCT && t->kind != TYPEUNION) + error( + &tok.loc, + "'%s' operator must be applied to " + "pointer to struct/union", + tokenstr(op) + ); + next(); + if (tok.kind < TIDENT) + error(&tok.loc, "expected identifier after '%s' operator", tokenstr(op)); + lvalue = op == TARROW || r->base->lvalue; + offset = 0; + m = typemember(t, tokenstr(tok.kind), &offset); + if (!m) + error(&tok.loc, "struct/union has no member named '%s'", tok.lit); + r = mkbinaryexpr( + &tok.loc, TADD, exprconvert(r, &typeulong), mkconstexpr(&typeulong, offset) + ); + r->type = mkpointertype(m->type, tq | m->qual); + r = mkunaryexpr(TMUL, r); + r->lvalue = lvalue; + if (m->bits.before || m->bits.after) { + e = mkexpr(EXPRBITFIELD, r->type, r); + e->lvalue = lvalue; + e->u.bitfield.bits = m->bits; + } else { + e = r; + } + next(); + break; + case TINC: + case TDEC: + e = mkincdecexpr(tok.kind, r, true); + next(); + break; + default: + return r; + } + r = e; + } +} + +static struct expr *castexpr(struct scope *); + +static struct expr * +unaryexpr(struct scope *s) +{ + enum tokenkind op; + struct expr *e, *l; + struct type *t; + + op = tok.kind; + switch (op) { + case TINC: + case TDEC: + next(); + l = unaryexpr(s); + e = mkincdecexpr(op, l, false); + break; + case TBAND: + case TMUL: + next(); + return mkunaryexpr(op, castexpr(s)); + case TADD: + next(); + e = castexpr(s); + if (e->type->kind != TYPECOMPLEX) { + if (!(e->type->prop & PROPARITH)) + error( + &tok.loc, + "operand of unary '+' operator must " + "have arithmetic type" + ); + if (e->type->prop & PROPINT) + e = exprpromote(e); + } + break; + case TSUB: + next(); + e = castexpr(s); + if (e->type->kind != TYPECOMPLEX) { + if (!(e->type->prop & PROPARITH)) + error( + &tok.loc, + "operand of unary '-' operator must " + "have arithmetic type" + ); + if (e->type->prop & PROPINT) + e = exprpromote(e); + } + e = mkexpr(EXPRUNARY, e->type, e); + e->op = op; + break; + case TBNOT: + next(); + e = castexpr(s); + if (!(e->type->prop & PROPINT)) + error(&tok.loc, "operand of '~' operator must have integer type"); + e = exprpromote(e); + e = mkbinaryexpr(&tok.loc, TXOR, e, mkconstexpr(e->type, -1)); + break; + case TLNOT: + next(); + e = castexpr(s); + if (!(e->type->prop & PROPSCALAR)) + error(&tok.loc, "operator '!' must have scalar operand"); + e = mkbinaryexpr(&tok.loc, TEQL, e, mkconstexpr(&typeint, 0)); + break; + case TSIZEOF: + case TALIGNOF: + case T__ALIGNOF__: + next(); + if (consume(TLPAREN)) { + t = typename(s, NULL, NULL); + if (t) { + expect(TRPAREN, "after type name"); + /* might be part of a compound literal */ + if (op == TSIZEOF && tok.kind == TLBRACE) + parseinit(s, t); + e = NULL; + } else { + e = expr(s); + expect(TRPAREN, "after expression"); + if (op == TSIZEOF) + e = postfixexpr(s, e); + } + } else if (op == TSIZEOF) { + t = NULL; + e = unaryexpr(s); + } else { + error(&tok.loc, "expected ')' after 'alignof'"); + } + if (!t) { + if (e->decayed) + e = e->base; + if (e->kind == EXPRBITFIELD) + error( + &tok.loc, + "%s operator applied to bitfield " + "expression", + tokenstr(op) + ); + t = e->type; + } + if (t->incomplete) + error(&tok.loc, "%s operator applied to incomplete type", tokenstr(op)); + if (t->kind == TYPEFUNC) + error(&tok.loc, "%s operator applied to function type", tokenstr(op)); + if (t->kind == TYPEARRAY && t->size == 0 && op == TSIZEOF) { + e = mkexpr(EXPRSIZEOF, &typeulong, e); + e->u.szof.type = t; + } else { + /* + * XXX: __alignof__ is not the same as alignof on 32-bit + * archs this needs to be considered if we gain support for + * those archs + */ + e = mkconstexpr(&typeulong, op == TSIZEOF ? t->size : t->align); + } + break; + default: + e = postfixexpr(s, NULL); + } + + return e; +} + +static struct expr * +castexpr(struct scope *s) +{ + struct type *t, *ct; + struct decl *d; + enum typequal tq; + struct expr *r, *e, **end, *toeval; + + ct = NULL; + end = &r; + while (consume(TLPAREN)) { + tq = QUALNONE; + t = typename(s, &tq, &toeval); + if (!t) { + e = expr(s); + expect(TRPAREN, "after expression to match '('"); + e = postfixexpr(s, e); + goto done; + } + expect(TRPAREN, "after type name"); + if (tok.kind == TLBRACE) { + e = mkexpr(EXPRCOMPOUND, t, NULL); + e->toeval = toeval; + e->qual = tq; + e->lvalue = true; + d = mkdecl(NULL, DECLOBJECT, t, tq, LINKNONE); + d->u.obj.storage = s == &filescope ? SDSTATIC : SDAUTO; + e->u.compound.decl = d; + e->u.compound.init = parseinit(s, t); + e = postfixexpr(s, decay(e)); + goto done; + } + if (t != &typevoid && t->kind != TYPECOMPLEX && !(t->prop & PROPSCALAR)) + error(&tok.loc, "cast type must be scalar"); + e = mkexpr(EXPRCAST, t, NULL); + e->toeval = toeval; + *end = e; + end = &e->base; + ct = t; + } + e = unaryexpr(s); + +done: + if (ct && ct != &typevoid && e->type->kind != TYPECOMPLEX && !(e->type->prop & PROPSCALAR)) + error(&tok.loc, "cast operand must have scalar type"); + *end = e; + return r; +} + +static int +precedence(enum tokenkind t) +{ + switch (t) { + case TLOR: + return 0; + case TLAND: + return 1; + case TBOR: + return 2; + case TXOR: + return 3; + case TBAND: + return 4; + case TEQL: + case TNEQ: + return 5; + case TLESS: + case TGREATER: + case TLEQ: + case TGEQ: + return 6; + case TSHL: + case TSHR: + return 7; + case TADD: + case TSUB: + return 8; + case TMUL: + case TDIV: + case TMOD: + return 9; + } + return -1; +} + +static struct expr * +binaryexpr(struct scope *s, struct expr *l, int i) +{ + struct expr *r; + struct location loc; + enum tokenkind op; + int j, k; + + if (!l) + l = castexpr(s); + while ((j = precedence(tok.kind)) >= i) { + op = tok.kind; + loc = tok.loc; + next(); + r = castexpr(s); + while ((k = precedence(tok.kind)) > j) + r = binaryexpr(s, r, k); + l = mkbinaryexpr(&loc, op, l, r); + } + return l; +} + +struct expr * +condexpr(struct scope *s) +{ + struct expr *e, *l, *r; + struct type *t, *lt, *rt; + enum typequal tq; + + e = binaryexpr(s, NULL, 0); + if (!consume(TQUESTION)) + return e; + l = tok.kind == TCOLON ? e : expr(s); + expect(TCOLON, "in conditional expression"); + r = condexpr(s); + + lt = l->type; + rt = r->type; + if (lt == rt) { + t = lt; + } else if (lt->prop & PROPARITH && rt->prop & PROPARITH) { + t = typecommonreal(lt, bitfieldwidth(l), rt, bitfieldwidth(r)); + } else if (lt == &typevoid && rt == &typevoid) { + t = &typevoid; + } else { + l = eval(l); + r = eval(r); + if (nullpointer(l) && rt->kind == TYPEPOINTER) { + t = rt; + } else if (nullpointer(r) && lt->kind == TYPEPOINTER) { + t = lt; + } else if (lt->kind == TYPEPOINTER && rt->kind == TYPEPOINTER) { + tq = lt->qual | rt->qual; + lt = lt->base; + rt = rt->base; + if (lt == &typevoid || rt == &typevoid) { + t = &typevoid; + } else if (typecompatible(lt, rt)) { + t = typecomposite(lt, rt); + } else { + error( + &tok.loc, + "operands of conditional operator must " + "have compatible types" + ); + } + t = mkpointertype(t, tq); + } else { + error(&tok.loc, "invalid operands to conditional operator"); + } + } + e = eval(e); + if (e->kind == EXPRCONST && e->type->prop & PROPINT) + return exprconvert(e->u.constant.u ? l : r, t); + e = mkexpr(EXPRCOND, t, e); + e->u.cond.t = l; + e->u.cond.f = r; + return e; +} + +unsigned long long +intconstexpr(struct scope *s, bool allowneg) +{ + struct expr *e; + + e = eval(condexpr(s)); + if (e->kind != EXPRCONST || !(e->type->prop & PROPINT)) + error(&tok.loc, "not an integer constant expression"); + if (!allowneg && e->type->u.arith.issigned && e->u.constant.u >> 63) + error(&tok.loc, "integer constant expression cannot be negative"); + return e->u.constant.u; +} + +static struct expr * +mkassignexpr(struct expr *l, struct expr *r) +{ + struct expr *e; + + e = mkexpr(EXPRASSIGN, l->type, NULL); + e->u.assign.l = l; + e->u.assign.r = exprassign(r, l->type); + return e; +} + +struct expr * +assignexpr(struct scope *s) +{ + struct expr *e, *l, *r, *tmp, *bit; + enum tokenkind op; + + l = condexpr(s); + if (l->kind == EXPRBINARY || l->kind == EXPRCOMMA || l->kind == EXPRCAST) + return l; + switch (tok.kind) { + case TASSIGN: + op = TNONE; + break; + case TMULASSIGN: + op = TMUL; + break; + case TDIVASSIGN: + op = TDIV; + break; + case TMODASSIGN: + op = TMOD; + break; + case TADDASSIGN: + op = TADD; + break; + case TSUBASSIGN: + op = TSUB; + break; + case TSHLASSIGN: + op = TSHL; + break; + case TSHRASSIGN: + op = TSHR; + break; + case TBANDASSIGN: + op = TBAND; + break; + case TXORASSIGN: + op = TXOR; + break; + case TBORASSIGN: + op = TBOR; + break; + default: + return l; + } + if (!l->lvalue) + error(&tok.loc, "left side of assignment expression is not an lvalue"); + next(); + r = assignexpr(s); + if (!op) + return mkassignexpr(l, r); + /* rewrite `E1 OP= E2` as `t = &E1, *t = *t OP E2`, where t is a + * temporary slot */ + if (l->kind == EXPRBITFIELD) { + bit = l; + l = l->base; + } else { + bit = NULL; + } + tmp = mkexpr(EXPRTEMP, mkpointertype(l->type, l->qual), NULL); + tmp->lvalue = true; + tmp->u.temp = NULL; + e = mkassignexpr(tmp, mkunaryexpr(TBAND, l)); + l = mkunaryexpr(TMUL, tmp); + if (bit) { + bit->base = l; + l = bit; + } + r = mkbinaryexpr(&tok.loc, op, l, r); + e->next = mkassignexpr(l, r); + return mkexpr(EXPRCOMMA, l->type, e); +} + +struct expr * +expr(struct scope *s) +{ + struct expr *r, *e, **end; + + end = &r; + for (;;) { + e = assignexpr(s); + *end = e; + end = &e->next; + if (tok.kind != TCOMMA) + break; + next(); + } + if (!r->next) + return r; + return mkexpr(EXPRCOMMA, e->type, r); +} diff --git a/cmd/dev/cc/include/float.h b/cmd/dev/cc/include/float.h @@ -0,0 +1,75 @@ +#ifndef _FLOAT_H_ +#define _FLOAT_H_ + +#define FLT_RADIX 2 + +/* IEEE float */ +#define FLT_MANT_DIG 24 +#define FLT_DIG 6 +#define FLT_ROUNDS 1 +#define FLT_EPSILON 1.19209290e-07F +#define FLT_MIN_EXP (-125) +#define FLT_MIN 1.17549435e-38F +#define FLT_MIN_10_EXP (-37) +#define FLT_MAX_EXP 128 +#define FLT_MAX 3.40282347e+38F +#define FLT_MAX_10_EXP 38 + +/* IEEE double */ +#define DBL_MANT_DIG 53 +#define DBL_DIG 15 +#define DBL_EPSILON 2.2204460492503131e-16 +#define DBL_MIN_EXP (-1021) +#define DBL_MIN 2.2250738585072014e-308 +#define DBL_MIN_10_EXP (-307) +#define DBL_MAX_EXP 1024 +#define DBL_MAX 1.7976931348623157e+308 +#define DBL_MAX_10_EXP 308 + +/* horrible intel long double */ +#if defined __i386__ || defined __x86_64__ + +#define LDBL_MANT_DIG 64 +#define LDBL_DIG 18 +#define LDBL_EPSILON 1.08420217248550443401e-19L +#define LDBL_MIN_EXP (-16381) +#define LDBL_MIN 3.36210314311209350626e-4932L +#define LDBL_MIN_10_EXP (-4931) +#define LDBL_MAX_EXP 16384 +#define LDBL_MAX 1.18973149535723176502e+4932L +#define LDBL_MAX_10_EXP 4932 +#define DECIMAL_DIG 21 + +#elif defined __aarch64__ || defined __riscv +/* + * use values from: + * gcc -dM -E -xc /dev/null | grep LDBL | sed -e "s/__// g" + */ +#define LDBL_MANT_DIG 113 +#define LDBL_DIG 33 +#define LDBL_EPSILON 1.92592994438723585305597794258492732e-34L +#define LDBL_MIN_EXP (-16381) +#define LDBL_MIN 3.36210314311209350626267781732175260e-4932L +#define LDBL_MIN_10_EXP (-4931) +#define LDBL_MAX_EXP 16384 +#define LDBL_MAX 1.18973149535723176508575932662800702e+4932L +#define LDBL_MAX_10_EXP 4932 +#define DECIMAL_DIG 36 + +#else + +/* same as IEEE double */ +#define LDBL_MANT_DIG 53 +#define LDBL_DIG 15 +#define LDBL_EPSILON 2.2204460492503131e-16L +#define LDBL_MIN_EXP (-1021) +#define LDBL_MIN 2.2250738585072014e-308L +#define LDBL_MIN_10_EXP (-307) +#define LDBL_MAX_EXP 1024 +#define LDBL_MAX 1.7976931348623157e+308L +#define LDBL_MAX_10_EXP 308 +#define DECIMAL_DIG 17 + +#endif + +#endif /* _FLOAT_H_ */ diff --git a/cmd/dev/cc/include/stdalign.h b/cmd/dev/cc/include/stdalign.h @@ -0,0 +1,15 @@ +#ifndef _STDALIGN_H +#define _STDALIGN_H + +#if __STDC_VERSION__ < 201112L && (defined(__GNUC__) || defined(__TINYC__)) +#define _Alignas(t) __attribute__((__aligned__(t))) +#define _Alignof(t) __alignof__(t) +#endif + +#define alignas _Alignas +#define alignof _Alignof + +#define __alignas_is_defined 1 +#define __alignof_is_defined 1 + +#endif /* _STDALIGN_H */ diff --git a/cmd/dev/cc/include/stdarg.h b/cmd/dev/cc/include/stdarg.h @@ -0,0 +1,14 @@ +#ifndef _STDARG_H +#define _STDARG_H + +typedef __builtin_va_list va_list; +#define va_start __builtin_va_start +#define va_arg __builtin_va_arg +#define va_copy __builtin_va_copy +#define va_end __builtin_va_end + +/* fix a buggy dependency on GCC in libio.h */ +typedef va_list __gnuc_va_list; +#define _VA_LIST_DEFINED + +#endif /* _STDARG_H */ diff --git a/cmd/dev/cc/include/stdatomic.h b/cmd/dev/cc/include/stdatomic.h @@ -0,0 +1,80 @@ +#ifndef _STDATOMIC_H +#define _STDATOMIC_H + +/* ISOC11 atomics. cc1's own __atomic_* builtins pick the right size + * from the pointer argument at compile time, so unlike a _Generic- + * dispatched implementation these macros need no per-type expansion + * at all. every memory order argument is accepted for source + * compatibility but ignored: cc1 lowers every access to a seq_cst + * runtime call, see cmd/dev/cc/qbe.c's mkatomicfn */ + +typedef enum { + memory_order_relaxed, + memory_order_consume, + memory_order_acquire, + memory_order_release, + memory_order_acq_rel, + memory_order_seq_cst, +} memory_order; + +typedef _Atomic _Bool atomic_bool; +typedef _Atomic char atomic_char; +typedef _Atomic signed char atomic_schar; +typedef _Atomic unsigned char atomic_uchar; +typedef _Atomic short atomic_short; +typedef _Atomic unsigned short atomic_ushort; +typedef _Atomic int atomic_int; +typedef _Atomic unsigned int atomic_uint; +typedef _Atomic long atomic_long; +typedef _Atomic unsigned long atomic_ulong; +typedef _Atomic long long atomic_llong; +typedef _Atomic unsigned long long atomic_ullong; + +#define ATOMIC_VAR_INIT(value) (value) +#define atomic_init(obj, value) (*(obj) = (value)) + +#define atomic_load(obj) __atomic_load_n((obj), memory_order_seq_cst) +#define atomic_load_explicit(obj, order) __atomic_load_n((obj), (order)) +#define atomic_store(obj, val) __atomic_store_n((obj), (val), memory_order_seq_cst) +#define atomic_store_explicit(obj, val, order) __atomic_store_n((obj), (val), (order)) +#define atomic_exchange(obj, val) __atomic_exchange_n((obj), (val), memory_order_seq_cst) +#define atomic_exchange_explicit(obj, val, order) \ + __atomic_exchange_n((obj), (val), (order)) + +#define atomic_compare_exchange_strong(obj, exp, val) \ + __atomic_compare_exchange_n((obj), (exp), (val), 0, memory_order_seq_cst, memory_order_seq_cst) +#define atomic_compare_exchange_weak(obj, exp, val) \ + __atomic_compare_exchange_n((obj), (exp), (val), 1, memory_order_seq_cst, memory_order_seq_cst) +#define atomic_compare_exchange_strong_explicit(obj, exp, val, succ, fail) \ + __atomic_compare_exchange_n((obj), (exp), (val), 0, (succ), (fail)) +#define atomic_compare_exchange_weak_explicit(obj, exp, val, succ, fail) \ + __atomic_compare_exchange_n((obj), (exp), (val), 1, (succ), (fail)) + +#define atomic_fetch_add(obj, val) __atomic_fetch_add((obj), (val), memory_order_seq_cst) +#define atomic_fetch_add_explicit(obj, val, order) __atomic_fetch_add((obj), (val), (order)) +#define atomic_fetch_sub(obj, val) __atomic_fetch_sub((obj), (val), memory_order_seq_cst) +#define atomic_fetch_sub_explicit(obj, val, order) __atomic_fetch_sub((obj), (val), (order)) +#define atomic_fetch_and(obj, val) __atomic_fetch_and((obj), (val), memory_order_seq_cst) +#define atomic_fetch_and_explicit(obj, val, order) __atomic_fetch_and((obj), (val), (order)) +#define atomic_fetch_or(obj, val) __atomic_fetch_or((obj), (val), memory_order_seq_cst) +#define atomic_fetch_or_explicit(obj, val, order) __atomic_fetch_or((obj), (val), (order)) +#define atomic_fetch_xor(obj, val) __atomic_fetch_xor((obj), (val), memory_order_seq_cst) +#define atomic_fetch_xor_explicit(obj, val, order) __atomic_fetch_xor((obj), (val), (order)) + +#define atomic_is_lock_free(obj) ((void)(obj), 1) + +typedef struct { + atomic_bool _flag; +} atomic_flag; + +#define ATOMIC_FLAG_INIT \ + { 0 } +#define atomic_flag_test_and_set(f) __atomic_exchange_n(&(f)->_flag, 1, memory_order_seq_cst) +#define atomic_flag_test_and_set_explicit(f, order) __atomic_exchange_n(&(f)->_flag, 1, (order)) +#define atomic_flag_clear(f) __atomic_store_n(&(f)->_flag, 0, memory_order_seq_cst) +#define atomic_flag_clear_explicit(f, order) __atomic_store_n(&(f)->_flag, 0, (order)) + +#define atomic_thread_fence(order) ((void)(order)) +#define atomic_signal_fence(order) ((void)(order)) + +#endif /* _STDATOMIC_H */ diff --git a/cmd/dev/cc/include/stdbool.h b/cmd/dev/cc/include/stdbool.h @@ -0,0 +1,11 @@ +#ifndef _STDBOOL_H +#define _STDBOOL_H + +/* ISOC99 boolean */ + +#define bool _Bool +#define true 1 +#define false 0 +#define __bool_true_false_are_defined 1 + +#endif /* _STDBOOL_H */ diff --git a/cmd/dev/cc/include/stddef.h b/cmd/dev/cc/include/stddef.h @@ -0,0 +1,42 @@ +#ifndef _STDDEF_H +#define _STDDEF_H + +typedef __SIZE_TYPE__ size_t; +typedef __PTRDIFF_TYPE__ ssize_t; +typedef __WCHAR_TYPE__ wchar_t; +typedef __PTRDIFF_TYPE__ ptrdiff_t; +typedef __PTRDIFF_TYPE__ intptr_t; +typedef __SIZE_TYPE__ uintptr_t; + +#if __STDC_VERSION__ >= 201112L +typedef union { + long long __ll; + long double __ld; +} max_align_t; +#endif + +#ifndef NULL +#define NULL ((void *)0) +#endif + +#undef offsetof +#define offsetof(type, field) __builtin_offsetof(type, field) + +void *alloca(size_t size); + +#endif + +/* older glibc require a wint_t from <stddef.h> (when requested + * by __need_wint_t, as otherwise stddef.h isnt allowed to + * define this type). note that this must be outside the normal + * _STDDEF_H guard, so that it works even when we've included the file + * already (without requiring wint_t). some other libs define _WINT_T + * if they've already provided that type, so we can use that as guard + * TCC defines __WINT_TYPE__ for us */ +#if defined(__need_wint_t) +#ifndef _WINT_T +#define _WINT_T +typedef __WINT_TYPE__ wint_t; +#endif +#undef __need_wint_t +#endif diff --git a/cmd/dev/cc/include/stdnoreturn.h b/cmd/dev/cc/include/stdnoreturn.h @@ -0,0 +1,7 @@ +#ifndef _STDNORETURN_H +#define _STDNORETURN_H + +/* ISOC11 noreturn */ +#define noreturn _Noreturn + +#endif /* _STDNORETURN_H */ diff --git a/cmd/dev/cc/init.c b/cmd/dev/cc/init.c @@ -0,0 +1,324 @@ +#include <assert.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +struct object { + unsigned long long offset; + struct type *type; + union { + struct member *mem; + unsigned long long idx; + } u; + bool iscur; +}; + +struct initparser { + /* TODO: keep track of type depth, and allocate maximum possible + * number of nested objects in initializer */ + struct object obj[32], *cur, *sub; + struct init *init, **last; +}; + +struct init * +mkinit(unsigned long long start, unsigned long long end, struct bitfield bits, struct expr *expr) +{ + struct init *init; + + init = xmalloc(sizeof(*init)); + init->start = start; + init->end = end; + init->expr = expr; + init->bits = bits; + init->next = NULL; + + return init; +} + +static void +initadd(struct initparser *p, struct init *new) +{ + struct init **init, *old; + + init = p->last; + for (; old = *init; init = &old->next) { + if (old->end * 8 - old->bits.after <= new->start * 8 + new->bits.before) + continue; + /* no overlap, insert before `old` */ + if (new->end * 8 - new->bits.after <= old->start * 8 + old->bits.before) + break; + /* replace any initializers that `new` covers */ + if (old->end * 8 - old->bits.after <= new->end * 8 - new->bits.after) { + do + old = old->next; + while (old && old->end * 8 - old->bits.after <= new->end * 8 - new->bits.after); + break; + } + /* `old` covers `new`, keep looking */ + } + new->next = old; + *init = new; + p->last = &new->next; +} + +static void +subobj(struct initparser *p, struct type *t, unsigned long long off) +{ + /* the subobject could be incomplete if its a flexible array member */ + if (t->incomplete) + error(&tok.loc, "initializer specified for incomplete type"); + off += p->sub->offset; + if (++p->sub == p->obj + countof(p->obj)) + fatal("internal error: too many designators"); + p->sub->type = t; + p->sub->offset = off; + p->sub->iscur = false; +} + +static bool +findmember(struct initparser *p, const char *name) +{ + struct member *m; + + for (m = p->sub->type->u.structunion.members; m; m = m->next) { + if (m->name) { + if (strcmp(m->name, name) == 0) { + p->sub->u.mem = m; + subobj(p, m->type, m->offset); + return true; + } + } else { + subobj(p, m->type, m->offset); + if (findmember(p, name)) + return true; + --p->sub; + } + } + return false; +} + +static void +designator(struct scope *s, struct initparser *p) +{ + struct type *t; + char *name; + + p->last = &p->init; + p->sub = p->cur; + for (;;) { + t = p->sub->type; + switch (tok.kind) { + case TLBRACK: + if (t->kind != TYPEARRAY) + error( + &tok.loc, + "index designator is only " + "valid for array types" + ); + next(); + p->sub->u.idx = intconstexpr(s, false) * t->base->size; + if (p->sub->u.idx >= t->size) { + if (!t->incomplete) + error( + &tok.loc, + "index designator is larger than " + "array length" + ); + t->size = p->sub->u.idx + t->base->size; + } + expect(TRBRACK, "for index designator"); + subobj(p, t->base, p->sub->u.idx); + break; + case TPERIOD: + if (t->kind != TYPESTRUCT && t->kind != TYPEUNION) + error( + &tok.loc, + "member designator only valid " + "for struct/union types" + ); + next(); + name = expect(TIDENT, "for member designator"); + if (!findmember(p, name)) + error( + &tok.loc, + "%s has no member named '%s'", + t->kind == TYPEUNION ? "union" : "struct", + name + ); + break; + default: + expect(TASSIGN, "after designator"); + return; + } + } +} + +static void +focus(struct initparser *p) +{ + struct type *t; + + switch (p->sub->type->kind) { + case TYPEARRAY: + t = p->sub->type->base; + p->sub->u.idx = 0; + if (p->sub->type->incomplete) + p->sub->type->size = t->size; + break; + case TYPESTRUCT: + case TYPEUNION: + p->sub->u.mem = p->sub->type->u.structunion.members; + t = p->sub->u.mem->type; + break; + default: + fatal("internal error: init cursor has unexpected type"); + } + subobj(p, t, 0); +} + +static void +advance(struct initparser *p) +{ + struct type *t; + + for (;;) { + --p->sub; + t = p->sub->type; + switch (t->kind) { + case TYPEARRAY: + p->sub->u.idx += t->base->size; + if (p->sub->u.idx == t->size) { + if (!t->incomplete) + break; + t->size += t->base->size; + } + subobj(p, t->base, p->sub->u.idx); + return; + case TYPESTRUCT: + p->sub->u.mem = p->sub->u.mem->next; + if (p->sub->u.mem) { + subobj(p, p->sub->u.mem->type, p->sub->u.mem->offset); + return; + } + break; + } + if (p->sub == p->cur) + error(&tok.loc, "too many initializers for type"); + } +} + +/* 6.7.9 initialization */ +struct init * +parseinit(struct scope *s, struct type *t) +{ + struct initparser p; + struct expr *expr; + struct type *base; + struct bitfield bits; + + p.cur = NULL; + p.sub = p.obj; + p.sub->offset = 0; + p.sub->type = t; + p.sub->iscur = false; + p.init = NULL; + p.last = &p.init; + if (t->incomplete && t->kind != TYPEARRAY) + error(&tok.loc, "initializer specified for incomplete type"); + if (t->kind == TYPEARRAY && t->base->size == 0) + error(&tok.loc, "initializer specified for variable length array type"); + for (;;) { + if (p.cur) { + if (tok.kind == TLBRACK || tok.kind == TPERIOD) + designator(s, &p); + else if (p.sub != p.cur) + advance(&p); + else if (p.cur->type->kind == TYPESTRUCT || p.cur->type->kind == TYPEUNION) + focus(&p); + } + if (consume(TLBRACE)) { + if (consume(TRBRACE)) { + if (p.sub->type->incomplete) + error( + &tok.loc, + "array of unknown size has empty " + "initializer" + ); + goto next; + } + if (p.cur == p.sub) { + if (p.cur->type->prop & PROPSCALAR) + error( + &tok.loc, + "nested braces around " + "scalar initializer" + ); + assert(p.cur->type->kind == TYPEARRAY); + focus(&p); + } + p.cur = p.sub; + p.cur->iscur = true; + continue; + } + expr = assignexpr(s); + for (;;) { + t = p.sub->type; + switch (t->kind) { + case TYPEARRAY: + if (!expr->decayed || expr->base->kind != EXPRSTRING || !(t->base->prop & PROPINT)) + break; + base = t->base; + expr = expr->base; + if (!(base->prop & PROPCHAR && expr->type->base->prop & PROPCHAR) + && !typecompatible(base, expr->type->base)) + error( + &tok.loc, + "cannot initialize array with " + "string literal of different " + "width" + ); + if (t->incomplete) + t->size = expr->type->size; + goto add; + case TYPESTRUCT: + case TYPEUNION: + case TYPECOMPLEX: + if (typecompatible(expr->type, t)) + goto add; + break; + default: /* scalar type */ + assert(t->prop & PROPSCALAR); + expr = exprassign(expr, t); + goto add; + } + focus(&p); + } + add: + if (p.sub > p.obj && (p.sub[-1].type->kind == TYPESTRUCT || p.sub[-1].type->kind == TYPEUNION)) + bits = p.sub[-1].u.mem->bits; + else + bits = (struct bitfield){0}; + initadd(&p, mkinit(p.sub->offset, p.sub->offset + p.sub->type->size, bits, expr)); + for (;;) { + if (p.sub->type->incomplete) + p.sub->type->incomplete = false; + next: + if (!p.cur) + return p.init; + if (tok.kind == TCOMMA) { + next(); + if (tok.kind != TRBRACE) + break; + } else if (tok.kind != TRBRACE) { + error(&tok.loc, "expected ',' or '}' after initializer"); + } + next(); + p.sub = p.cur; + do + p.cur = p.cur == p.obj ? NULL : p.cur - 1; + while (p.cur && !p.cur->iscur); + } + } +} diff --git a/cmd/dev/cc/map.c b/cmd/dev/cc/map.c @@ -0,0 +1,121 @@ +#include <assert.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" + +static unsigned long +hash(const void *ptr, size_t len) +{ + unsigned long h; + const unsigned char *pos, *end; + + /* fnv-1a */ + h = 0x811c9dc5; + for (pos = ptr, end = pos + len; pos != end; ++pos) + h = (h ^ *pos) * 0x1000193; + return h; +} + +void +mapkey(struct mapkey *k, const void *s, size_t n) +{ + k->str = s; + k->len = n; + k->hash = hash(s, n); +} + +void +mapinit(struct map *h, size_t cap) +{ + size_t i; + + assert(!(cap & cap - 1)); + h->len = 0; + h->cap = cap; + h->keys = xreallocarray(NULL, cap, sizeof(h->keys[0])); + h->vals = xreallocarray(NULL, cap, sizeof(h->vals[0])); + for (i = 0; i < cap; ++i) + h->keys[i].str = NULL; +} + +void +mapfree(struct map *h, void del(void *)) +{ + size_t i; + + if (del) { + for (i = 0; i < h->cap; ++i) { + if (h->keys[i].str) + del(h->vals[i].p); + } + } + free(h->keys); + free(h->vals); +} + +static bool +keyequal(struct mapkey *k1, struct mapkey *k2) +{ + if (k1->hash != k2->hash || k1->len != k2->len) + return false; + return memcmp(k1->str, k2->str, k1->len) == 0; +} + +static size_t +keyindex(struct map *h, struct mapkey *k) +{ + size_t i; + + i = k->hash & h->cap - 1; + while (h->keys[i].str && !keyequal(&h->keys[i], k)) + i = i + 1 & h->cap - 1; + return i; +} + +bool +mapput(struct map *h, struct mapkey *k, size_t *idx) +{ + struct mapkey *oldkeys; + union mapval *oldvals; + size_t i, j, oldcap; + + if (h->cap / 2 < h->len) { + oldkeys = h->keys; + oldvals = h->vals; + oldcap = h->cap; + h->cap *= 2; + h->keys = xreallocarray(NULL, h->cap, sizeof(h->keys[0])); + h->vals = xreallocarray(NULL, h->cap, sizeof(h->vals[0])); + for (i = 0; i < h->cap; ++i) + h->keys[i].str = NULL; + for (i = 0; i < oldcap; ++i) { + if (oldkeys[i].str) { + j = keyindex(h, &oldkeys[i]); + h->keys[j] = oldkeys[i]; + h->vals[j] = oldvals[i]; + } + } + free(oldkeys); + free(oldvals); + } + *idx = i = keyindex(h, k); + if (!h->keys[i].str) { + h->keys[i] = *k; + ++h->len; + return true; + } + + return false; +} + +void * +mapget(struct map *h, struct mapkey *k, size_t *idx) +{ + size_t i; + + i = keyindex(h, k); + if (idx) + *idx = i; + return h->keys[i].str ? h->vals[i].p : NULL; +} diff --git a/cmd/dev/cc/ops.h b/cmd/dev/cc/ops.h @@ -0,0 +1,104 @@ +/* arithmetic and bits */ +OP(IADD, "add") +OP(ISUB, "sub") +OP(INEG, "neg") +OP(IDIV, "div") +OP(IMUL, "mul") +OP(IUDIV, "udiv") +OP(IREM, "rem") +OP(IUREM, "urem") +OP(IOR, "or") +OP(IXOR, "xor") +OP(IAND, "and") +OP(ISAR, "sar") +OP(ISHR, "shr") +OP(ISHL, "shl") + +/* memory */ +OP(ISTORED, "stored") +OP(ISTORES, "stores") +OP(ISTOREL, "storel") +OP(ISTOREW, "storew") +OP(ISTOREH, "storeh") +OP(ISTOREB, "storeb") +OP(ILOADD, "loadd") +OP(ILOADS, "loads") +OP(ILOADL, "loadl") +OP(ILOADW, "loadw") +OP(ILOADSH, "loadsh") +OP(ILOADUH, "loaduh") +OP(ILOADSB, "loadsb") +OP(ILOADUB, "loadub") +OP(IALLOC4, "alloc4") +OP(IALLOC8, "alloc8") +OP(IALLOC16, "alloc16") + +/* comparisons */ +OP(ICEQW, "ceqw") +OP(ICNEW, "cnew") +OP(ICSLEW, "cslew") +OP(ICSLTW, "csltw") +OP(ICSGEW, "csgew") +OP(ICSGTW, "csgtw") +OP(ICULEW, "culew") +OP(ICULTW, "cultw") +OP(ICUGEW, "cugew") +OP(ICUGTW, "cugtw") + +OP(ICEQL, "ceql") +OP(ICNEL, "cnel") +OP(ICSLEL, "cslel") +OP(ICSLTL, "csltl") +OP(ICSGEL, "csgel") +OP(ICSGTL, "csgtl") +OP(ICULEL, "culel") +OP(ICULTL, "cultl") +OP(ICUGEL, "cugel") +OP(ICUGTL, "cugtl") + +OP(ICEQS, "ceqs") +OP(ICNES, "cnes") +OP(ICLES, "cles") +OP(ICLTS, "clts") +OP(ICGES, "cges") +OP(ICGTS, "cgts") +OP(ICOS, "cos") +OP(ICUOS, "cuos") + +OP(ICEQD, "ceqd") +OP(ICNED, "cned") +OP(ICLED, "cled") +OP(ICLTD, "cltd") +OP(ICGED, "cged") +OP(ICGTD, "cgtd") +OP(ICOD, "cod") +OP(ICUOD, "cuod") + +/* conversions */ +OP(IEXTSW, "extsw") +OP(IEXTUW, "extuw") +OP(IEXTSH, "extsh") +OP(IEXTUH, "extuh") +OP(IEXTSB, "extsb") +OP(IEXTUB, "extub") +OP(IEXTS, "exts") +OP(ITRUNCD, "truncd") +OP(ISTOSI, "stosi") +OP(ISTOUI, "stoui") +OP(IDTOSI, "dtosi") +OP(IDTOUI, "dtoui") +OP(ISWTOF, "swtof") +OP(IUWTOF, "uwtof") +OP(ISLTOF, "sltof") +OP(IULTOF, "ultof") + +/* cast and copy */ +OP(ICAST, "cast") +OP(ICOPY, "copy") + +/* call */ +OP(ICALL, "call") + +/* variadic */ +OP(IVASTART, "vastart") +OP(IVAARG, "vaarg") diff --git a/cmd/dev/cc/pp.c b/cmd/dev/cc/pp.c @@ -0,0 +1,1290 @@ +#include <assert.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include "util.h" +#include "cc.h" + +struct macroparam { + char *name; + enum { + PARAMTOK = 1 << 0, /* the parameter is used normally */ + PARAMSTR = 1 << 1, /* the parameter is used with the '#' operator */ + PARAMVAR = 1 << 2, /* the parameter is __VA_ARGS__ */ + } flags; +}; + +struct macroarg { + struct token *token; + size_t ntoken; + /* stringized argument */ + struct token str; +}; + +struct macro { + enum { + MACROOBJ, + MACROFUNC, + } kind; + char *name; + /* whether or not this macro is ineligible for expansion */ + bool hide; + /* parameters of function-like macro */ + struct macroparam *param; + size_t nparam; + /* argument tokens of macro invocation */ + struct macroarg *arg; + /* replacement list */ + struct token *token; + size_t ntoken; +}; + +struct frame { + struct token *token; + size_t ntoken; + struct macro *macro; + struct token *alloc; + bool is_substituted; +}; + +enum ppflags ppflags; + +static struct array ctx; +static struct array macros; +/* number of macros currently undergoing expansion */ +static size_t macrodepth; +static struct macro *macroget(enum tokenkind); + +static bool disexpand; +static int cppoff; +static struct condstate { + int enabled; + int done; + int iselse; +} condstack[64]; +static int conddepth; + +static const char **incdirs; +static size_t nincdirs; + +void +addincdir(const char *dir) +{ + incdirs = xreallocarray(incdirs, nincdirs + 1, sizeof(*incdirs)); + incdirs[nincdirs++] = dir; +} + +static char * +strdup_internal(const char *s) +{ + size_t len = strlen(s); + char *d = xmalloc(len + 1); + memcpy(d, s, len + 1); + return d; +} + +static void +include(void) +{ + bool is_system; + char *name = scaninclude(&is_system); + if (!name) { + error(&tok.loc, "expected filename after #include"); + return; + } + + char path[FILENAME_MAX]; + FILE *f = NULL; + + if (!is_system) { + const char *curfile = tok.loc.file; + const char *slash = strrchr(curfile, '/'); + if (slash) { + size_t len = slash - curfile; + if (len + 1 + strlen(name) < sizeof(path)) { + memcpy(path, curfile, len); + path[len] = '/'; + strcpy(path + len + 1, name); + f = fopen(path, "r"); + } + } else { + if (strlen(name) < sizeof(path)) { + strcpy(path, name); + f = fopen(path, "r"); + } + } + } + + if (!f) { + for (size_t i = 0; i < nincdirs; i++) { + if (strlen(incdirs[i]) + 1 + strlen(name) < sizeof(path)) { + sprintf(path, "%s/%s", incdirs[i], name); + f = fopen(path, "r"); + if (f) + break; + } + } + } + + /* freestanding headers (stddef.h etc) ship in an include/ dir next to + the compiler binary itself, the same layout gcc and clang use for + their own built-in headers */ + if (!f) { + char self[FILENAME_MAX]; + ssize_t n = readlink("/proc/self/exe", self, sizeof(self) - 1); + if (n == -1) { + n = strlen(argv0); + if (n > (ssize_t)sizeof(self) - 1) + n = sizeof(self) - 1; + memcpy(self, argv0, n); + } + self[n] = '\0'; + + char *dir = strrchr(self, '/'); + if (dir) { + *dir = '\0'; + if (strlen(self) + sizeof("/include/") + strlen(name) < sizeof(path)) { + snprintf(path, sizeof(path), "%s/include/%s", self, name); + f = fopen(path, "r"); + } + } + } + + if (!f) { + error(&tok.loc, "included file '%s' not found", name); + free(name); + return; + } + + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + + scanfrom(strdup_internal(path), f); + free(name); +} + +struct PPVal { + enum tokenkind kind; + long long val; +}; + +static struct PPVal *ppvals; +static size_t nppvals, capppvals; +static size_t validx; + +static void +addval(enum tokenkind kind, long long val) +{ + if (nppvals >= capppvals) { + capppvals = capppvals ? capppvals * 2 : 16; + ppvals = xreallocarray(ppvals, capppvals, sizeof(*ppvals)); + } + ppvals[nppvals].kind = kind; + ppvals[nppvals].val = val; + nppvals++; +} + +static long long eval_cond_expr(void); + +static long long +eval_primary(void) +{ + if (validx >= nppvals) + return 0; + struct PPVal p = ppvals[validx++]; + if (p.kind == TNUMBER) { + return p.val; + } + if (p.kind == TLPAREN) { + long long val = eval_cond_expr(); + if (validx < nppvals && ppvals[validx].kind == TRPAREN) { + validx++; + } + return val; + } + if (p.kind == TADD) { + return eval_primary(); + } + if (p.kind == TSUB) { + return -eval_primary(); + } + if (p.kind == TLNOT) { + return !eval_primary(); + } + if (p.kind == TBNOT) { + return ~eval_primary(); + } + return 0; +} + +static long long +eval_mul(void) +{ + long long val = eval_primary(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TMUL || op == TDIV || op == TMOD) { + validx++; + long long rhs = eval_primary(); + if (op == TMUL) + val *= rhs; + else if (op == TDIV) + val = rhs ? val / rhs : 0; + else + val = rhs ? val % rhs : 0; + } else { + break; + } + } + return val; +} + +static long long +eval_add(void) +{ + long long val = eval_mul(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TADD || op == TSUB) { + validx++; + long long rhs = eval_mul(); + if (op == TADD) + val += rhs; + else + val -= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_shift(void) +{ + long long val = eval_add(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TSHL || op == TSHR) { + validx++; + long long rhs = eval_add(); + if (op == TSHL) + val <<= rhs; + else + val >>= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_rel(void) +{ + long long val = eval_shift(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TLESS || op == TGREATER || op == TLEQ || op == TGEQ) { + validx++; + long long rhs = eval_shift(); + if (op == TLESS) + val = val < rhs; + else if (op == TGREATER) + val = val > rhs; + else if (op == TLEQ) + val = val <= rhs; + else + val = val >= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_eq(void) +{ + long long val = eval_rel(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TEQL || op == TNEQ) { + validx++; + long long rhs = eval_rel(); + if (op == TEQL) + val = val == rhs; + else + val = val != rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_band(void) +{ + long long val = eval_eq(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TBAND) { + validx++; + long long rhs = eval_eq(); + val &= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_bxor(void) +{ + long long val = eval_band(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TXOR) { + validx++; + long long rhs = eval_band(); + val ^= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_bor(void) +{ + long long val = eval_bxor(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TBOR) { + validx++; + long long rhs = eval_bxor(); + val |= rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_and(void) +{ + long long val = eval_bor(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TLAND) { + validx++; + long long rhs = eval_bor(); + val = val && rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_or(void) +{ + long long val = eval_and(); + while (validx < nppvals) { + enum tokenkind op = ppvals[validx].kind; + if (op == TLOR) { + validx++; + long long rhs = eval_and(); + val = val || rhs; + } else { + break; + } + } + return val; +} + +static long long +eval_cond_expr(void) +{ + long long val = eval_or(); + if (validx < nppvals && ppvals[validx].kind == TQUESTION) { + validx++; + long long true_val = eval_cond_expr(); + if (validx < nppvals && ppvals[validx].kind == TCOLON) { + validx++; + } + long long false_val = eval_cond_expr(); + val = val ? true_val : false_val; + } + return val; +} + +static long long +eval_if_expr(void) +{ + enum ppflags old_flags = ppflags; + int old_cppoff = cppoff; + cppoff = 0; + ppflags |= PPNEWLINE; + nppvals = 0; + next(); + while (tok.kind != TNEWLINE && tok.kind != TEOF) { + if (tok.kind >= TPPIDENT && strcmp(tokenstr(tok.kind), "defined") == 0) { + bool paren = false; + disexpand = true; + next(); + if (tok.kind == TLPAREN) { + paren = true; + next(); + } + if (tok.kind < TPPIDENT) { + error( + &tok.loc, + "operator 'defined' requires " + "an identifier" + ); + } + struct macro *m = macroget(tok.kind); + long long res = (m != NULL); + if (paren) { + next(); + if (tok.kind != TRPAREN) + error(&tok.loc, "expected ')' in defined()"); + } + disexpand = false; + addval(TNUMBER, res); + next(); + } else if (tok.kind >= TPPIDENT) { + addval(TNUMBER, 0); + next(); + } else if (tok.kind == TNUMBER) { + long long v = strtoull(tok.lit, NULL, 0); + addval(TNUMBER, v); + next(); + } else { + addval(tok.kind, 0); + next(); + } + } + cppoff = old_cppoff; + ppflags = old_flags; + validx = 0; + return eval_cond_expr(); +} + +void +ppinit(void) +{ + next(); +} + +static void +macrodel(struct macro *m) +{ + free(m->param); + free(m->token); + free(m); +} + +/* check if two macro definitions are equal, as in C11 6.10.3p2 */ +static bool +macroequal(struct macro *m1, struct macro *m2) +{ + struct macroparam *p1, *p2; + struct token *t1, *t2; + + if (m1->kind != m2->kind) + return false; + if (m1->kind == MACROFUNC) { + if (m1->nparam != m2->nparam) + return false; + for (p1 = m1->param, p2 = m2->param; p1 < m1->param + m1->nparam; ++p1, ++p2) { + if (strcmp(p1->name, p2->name) != 0 || p1->flags != p2->flags) + return false; + } + } + if (m1->ntoken != m2->ntoken) + return false; + for (t1 = m1->token, t2 = m2->token; t1 < m1->token + m1->ntoken; ++t1, ++t2) { + if (t1->kind != t2->kind) + return false; + if (t1->lit && strcmp(t1->lit, t2->lit) != 0) + return false; + } + return true; +} + +/* find the index of a macro parameter with the given name */ +static size_t +macroparam(struct macro *m, struct token *t) +{ + size_t i; + + if (t->kind >= TPPIDENT) { + for (i = 0; i < m->nparam; ++i) { + if (strcmp(m->param[i].name, tokenstr(t->kind)) == 0) + return i; + } + } + return -1; +} + +/* lookup a macro by name */ +static struct macro * +macroget(enum tokenkind ident) +{ + return arraygetptr(&macros, ident - TPPIDENT); +} + +static void +macrodone(struct macro *m) +{ + m->hide = false; + if (m->kind == MACROFUNC && m->nparam > 0) { + free(m->arg[0].token); + free(m->arg); + } + --macrodepth; +} + +static bool +macrovarargs(struct macro *m) +{ + return m->kind == MACROFUNC && m->nparam > 0 && m->param[m->nparam - 1].flags & PARAMVAR; +} + +static struct token * +framenext(struct frame *f) +{ + return f->ntoken--, f->token++; +} + +/* push a new context frame */ +static struct frame * +ctxpush(struct token *t, size_t n, struct macro *m, bool space) +{ + struct frame *f; + + f = arrayadd(&ctx, sizeof(*f)); + f->token = t; + f->ntoken = n; + f->macro = m; + f->alloc = NULL; + f->is_substituted = false; + if (n > 0) + t[0].space = space; + return f; +} + +static struct frame * +ctxpush_alloc(struct token *t, size_t n, struct macro *m, bool space, struct token *alloc) +{ + struct frame *f; + + f = arrayadd(&ctx, sizeof(*f)); + f->token = t; + f->ntoken = n; + f->macro = m; + f->alloc = alloc; + f->is_substituted = true; + if (n > 0) + t[0].space = space; + return f; +} + +/* get the next token from the context */ +static struct token * +ctxnext(void) +{ + struct frame *f; + struct token *t; + struct macro *m; + bool space; + size_t i; + +again: + for (f = arraylast(&ctx, sizeof(*f)); ctx.len; --f, ctx.len -= sizeof(*f)) { + if (f->ntoken) + break; + if (f->macro) + macrodone(f->macro); + if (f->alloc) + free(f->alloc); + } + if (ctx.len == 0) + return NULL; + m = f->macro; + if (m && m->kind == MACROFUNC && !f->is_substituted) { + /* try to expand macro parameter */ + space = f->token->space; + switch (f->token->kind) { + case THASH: + framenext(f); + t = framenext(f); + assert(t); + i = macroparam(m, t); + assert(i != -1); + f = ctxpush(&m->arg[i].str, 1, NULL, space); + break; + default: + if (f->token->kind >= TPPIDENT) { + i = macroparam(m, f->token); + if (i == -1) + break; + framenext(f); + if (m->arg[i].ntoken == 0) + goto again; + f = ctxpush(m->arg[i].token, m->arg[i].ntoken, NULL, space); + } + break; + } + /* XXX: token concatenation */ + } + return framenext(f); +} + +static void +define(void) +{ + struct token *t; + enum tokenkind ident, prev; + struct macro *m, *other; + struct macroparam *p; + struct array params = {0}, repl = {0}; + size_t i; + + m = xmalloc(sizeof(*m)); + ident = tok.kind; + m->name = tokencheck(&tok, TPPIDENT, "after #define"); + m->hide = false; + t = arrayadd(&repl, sizeof(*t)); + scan(t); + if (t->kind == TLPAREN && !t->space) { + m->kind = MACROFUNC; + /* read macro parameter names */ + p = NULL; + while (scan(&tok), tok.kind != TRPAREN) { + if (p) { + if (p->flags & PARAMVAR) + tokencheck(&tok, TRPAREN, "after '...'"); + tokencheck(&tok, TCOMMA, "or ')' after macro parameter"); + scan(&tok); + } + p = arrayadd(&params, sizeof(*p)); + p->flags = 0; + if (tok.kind == TELLIPSIS) { + p->name = "__VA_ARGS__"; + p->flags |= PARAMVAR; + } else { + p->name = tokencheck(&tok, TPPIDENT, "of macro parameter name or '...'"); + } + } + scan(t); /* first token in replacement list */ + } else { + m->kind = MACROOBJ; + } + m->param = params.val; + m->nparam = params.len / sizeof(m->param[0]); + + /* read macro body */ + i = macroparam(m, t); + while (t->kind != TNEWLINE && t->kind != TEOF) { + prev = t->kind; + t = arrayadd(&repl, sizeof(*t)); + scan(t); + if (t->kind == T__VA_ARGS__ && !macrovarargs(m)) + error( + &t->loc, + "__VA_ARGS__ can only be used in " + "variadic function-like macros" + ); + if (m->kind != MACROFUNC) + continue; + if (i != -1) + m->param[i].flags |= PARAMTOK; + i = macroparam(m, t); + if (prev == THASH) { + tokencheck(t, TPPIDENT, "after '#' operator"); + if (i == -1) + error(&t->loc, "'%s' is not a macro parameter name", t->lit); + m->param[i].flags |= PARAMSTR; + i = -1; + } + } + m->token = repl.val; + m->ntoken = repl.len / sizeof(*t) - 1; + tok = *t; + + i = ident - TPPIDENT; + other = arraysetptr(&macros, i, m); + if (other) { + if (!macroequal(m, other)) + error(&tok.loc, "redefinition of macro '%s'", m->name); + macrodel(other); + } +} + +static void +undef(void) +{ + enum tokenkind ident; + struct macro *m; + + ident = tok.kind; + tokencheck(&tok, TPPIDENT, "after #undef"); + m = macroget(ident); + if (m) { + macrodel(m); + ((void **)macros.val)[ident - TPPIDENT] = NULL; + } + scan(&tok); +} + +static void +directive(void) +{ + struct location newloc; + enum ppflags oldflags; + enum tokenkind kind; + + scan(&tok); + if (tok.kind == TNEWLINE) + return; /* empty directive */ + oldflags = ppflags; + ppflags |= PPNEWLINE; + kind = tok.kind; + switch (kind) { + case TNUMBER: + goto line; /* gcc line markers */ + case TIF: { + int enabled = 0; + if (!cppoff) { + enabled = (eval_if_expr() != 0); + } else { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + } + if (conddepth >= 64) + error(&tok.loc, "too many nested #if"); + condstack[conddepth].iselse = 0; + condstack[conddepth].done = enabled || cppoff; + condstack[conddepth].enabled = enabled && !cppoff; + if (!condstack[conddepth].enabled) + cppoff++; + conddepth++; + break; + } + case TIFDEF: + case TIFNDEF: { + int enabled = 0; + if (!cppoff) { + scan(&tok); + struct macro *m = macroget(tok.kind); + enabled = (m != NULL); + if (kind == TIFNDEF) + enabled = !enabled; + } + if (conddepth >= 64) + error(&tok.loc, "too many nested #if"); + condstack[conddepth].iselse = 0; + condstack[conddepth].done = enabled || cppoff; + condstack[conddepth].enabled = enabled && !cppoff; + if (!condstack[conddepth].enabled) + cppoff++; + conddepth++; + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + case TELIF: { + if (conddepth == 0) + error(&tok.loc, "#elif without #if"); + if (condstack[conddepth - 1].iselse) + error(&tok.loc, "#elif after #else"); + int enabled = 0; + if (cppoff == 1 && !condstack[conddepth - 1].enabled && !condstack[conddepth - 1].done) { + enabled = (eval_if_expr() != 0); + if (enabled) { + condstack[conddepth - 1].enabled = 1; + condstack[conddepth - 1].done = 1; + cppoff = 0; + } + } else { + if (cppoff == 0) { + condstack[conddepth - 1].enabled = 0; + cppoff = 1; + } + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + } + break; + } + case TELSE: + if (conddepth == 0) + error(&tok.loc, "#else without #if"); + if (condstack[conddepth - 1].iselse) + error(&tok.loc, "multiple #else"); + condstack[conddepth - 1].iselse = 1; + if (cppoff == 1 && !condstack[conddepth - 1].enabled && !condstack[conddepth - 1].done) { + condstack[conddepth - 1].enabled = 1; + condstack[conddepth - 1].done = 1; + cppoff = 0; + } else if (cppoff == 0) { + condstack[conddepth - 1].enabled = 0; + cppoff = 1; + } + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + case TENDIF: + if (conddepth == 0) + error(&tok.loc, "#endif without #if"); + conddepth--; + if (!condstack[conddepth].enabled) { + cppoff--; + } + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + case TINCLUDE: { + if (cppoff) { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + include(); + break; + } + case TDEFINE: + if (cppoff) { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + scan(&tok); + define(); + break; + case TUNDEF: + if (cppoff) { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + scan(&tok); + undef(); + break; + case TLINE: + if (cppoff) { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + scan(&tok); + tokencheck(&tok, TNUMBER, "after #line"); + line: + newloc.line = strtoull(tok.lit, NULL, 0); + newloc.col = 1; + scan(&tok); + newloc.file = tok.loc.file; + if (tok.kind == TSTRINGLIT) { + char *quote; + + /* XXX: handle escape sequences (reuse string decoding + * from expr.c) */ + quote = strchr(tok.lit, '"'); + assert(quote); + newloc.file = quote + 1; + quote = strchr(quote + 1, '"'); + assert(quote); + *quote = '\0'; + scan(&tok); + } + while (tok.kind == TNUMBER) + scan(&tok); + scansetloc(newloc); + break; + case TERROR: + case TWARNING: + if (cppoff) { + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + } + diagloc(&tok.loc); + fprintf(stderr, "%s directive:", kind == TERROR ? "#error" : "#warning"); + scan(&tok); + while (tok.kind != TNEWLINE && tok.kind != TEOF) { + tokenprint(&tok, stderr); + scan(&tok); + } + fputc('\n', stderr); + if (kind == TERROR) + exit(1); + break; + case TPRAGMA: + while (tok.kind != TNEWLINE && tok.kind != TEOF) + scan(&tok); + break; + default: + error(&tok.loc, "invalid preprocessor directive #%s", tokenstr(tok.kind)); + } + tokencheck(&tok, TNEWLINE, "after preprocessing directive"); + ppflags = oldflags; +} + +/* get the next token without expanding it */ +static void +nextinto(struct token *t) +{ + static bool newline = true; + + for (;;) { + scan(t); + if (newline && t->kind == THASH) { + directive(); + if (cppoff) { + newline = true; + continue; + } + } else { + newline = tok.kind == TNEWLINE; + if (cppoff) { + continue; + } + break; + } + } +} + +static struct token * +rawnext(void) +{ + struct token *t; + + t = ctxnext(); + if (!t) { + t = &tok; + nextinto(t); + } + return t; +} + +static bool +peekparen(void) +{ + static struct array pending; + struct token *t; + struct frame *f; + + t = ctxnext(); + if (t) { + if (t->kind == TLPAREN) + return true; + f = arraylast(&ctx, sizeof(*f)); + --f->token; + ++f->ntoken; + return false; + } + pending.len = 0; + do + t = arrayadd(&pending, sizeof(*t)), nextinto(t); + while (t->kind == TNEWLINE); + if (t->kind == TLPAREN) + return true; + t = pending.val; + ctxpush(t, pending.len / sizeof(*t), NULL, t[0].space); + return false; +} + +static void +stringize(struct array *buf, struct token *t) +{ + const char *lit; + + if ((t->space || t->kind == TNEWLINE) && buf->len > 1 && ((char *)buf->val)[buf->len - 1] != ' ') + arrayaddbuf(buf, " ", 1); + lit = t->lit ? t->lit : tokenstr(t->kind); + if (t->kind == TSTRINGLIT || t->kind == TCHARCONST) { + for (; *lit; ++lit) { + if (*lit == '\\' || *lit == '"') + arrayaddbuf(buf, "\\", 1); + arrayaddbuf(buf, lit, 1); + } + } else if (lit) { + arrayaddbuf(buf, lit, strlen(lit)); + } +} + +static void expandfunc(struct macro *); + +static void +macroexpand(struct macro *m, bool space) +{ + struct array repl = {0}; + size_t i, j; + struct token *t; + int param_idx; + + for (i = 0; i < m->ntoken; ++i) { + t = &m->token[i]; + if (t->kind == THASH && m->kind == MACROFUNC && i + 1 < m->ntoken) { + struct token stringized; + struct array str = {0}; + t = &m->token[++i]; + param_idx = macroparam(m, t); + assert(param_idx != -1); + arrayaddbuf(&str, "\"", 1); + for (j = 0; j < m->arg[param_idx].ntoken; ++j) + stringize(&str, &m->arg[param_idx].token[j]); + arrayaddbuf(&str, "\"", 2); + stringized = (struct token){ + .kind = TSTRINGLIT, + .lit = str.val, + .space = t->space, + }; + arrayaddbuf(&repl, &stringized, sizeof(stringized)); + } else if (m->kind == MACROFUNC && (param_idx = macroparam(m, t)) != -1) { + struct macroarg *arg = &m->arg[param_idx]; + for (j = 0; j < arg->ntoken; ++j) { + struct token arg_t = arg->token[j]; + if (j == 0) + arg_t.space = t->space; + arrayaddbuf(&repl, &arg_t, sizeof(arg_t)); + } + } else { + arrayaddbuf(&repl, t, sizeof(*t)); + } + } + + struct array clean = {0}; + t = repl.val; + size_t n = repl.len / sizeof(*t); + for (i = 0; i < n; ++i) { + if (i + 1 < n && t[i + 1].kind == THASHHASH) { + struct token pasted = t[i]; + if (i + 2 < n) { + struct token *right = &t[i + 2]; + char *s1 = pasted.lit ? pasted.lit : tokenstr(pasted.kind); + char *s2 = right->lit ? right->lit : tokenstr(right->kind); + size_t len1 = strlen(s1); + size_t len2 = strlen(s2); + char *s = xmalloc(len1 + len2 + 1); + memcpy(s, s1, len1); + memcpy(s + len1, s2, len2); + s[len1 + len2] = '\0'; + + pasted.lit = s; + if (s[0] >= '0' && s[0] <= '9') { + pasted.kind = TNUMBER; + } else { + pasted.kind = tokenget(s, len1 + len2); + } + i += 2; + } else { + i += 1; + } + t[i] = pasted; + --i; + } else if (t[i].kind != THASHHASH) { + arrayaddbuf(&clean, &t[i], sizeof(t[i])); + } + } + free(repl.val); + + struct token *allocated = clean.val; + size_t n_clean = clean.len / sizeof(*allocated); + ctxpush_alloc(allocated, n_clean, m, space, allocated); +} + +static bool +expand(struct token *t) +{ + struct macro *m; + bool space; + + if (disexpand) + return false; + + if (t->kind < TPPIDENT) + return false; + m = macroget(t->kind); + if (!m || m->hide) + t->hide = true; + if (t->hide) + return false; + space = t->space; + if (m->kind == MACROFUNC) { + if (!peekparen()) + return false; + expandfunc(m); + } + macroexpand(m, space); + m->hide = true; + ++macrodepth; + return true; +} + +static void +expandfunc(struct macro *m) +{ + struct macroparam *p; + struct macroarg *arg; + struct array str, tok; + size_t i, depth, paren; + struct token *t; + + /* read macro arguments */ + paren = 0; + depth = macrodepth; + tok = (struct array){0}; + arg = xreallocarray(NULL, m->nparam, sizeof(*arg)); + t = rawnext(); + for (i = 0; i < m->nparam; ++i) { + p = &m->param[i]; + if (p->flags & PARAMSTR) { + str = (struct array){0}; + arrayaddbuf(&str, "\"", 1); + } + arg[i].ntoken = 0; + for (;;) { + if (t->kind == TEOF) + error(&t->loc, "EOF when reading macro parameters"); + if (macrodepth <= depth) { + /* adjust current macro depth, in case it got + * shallower */ + depth = macrodepth; + if (paren == 0 && (t->kind == TRPAREN || t->kind == TCOMMA && !(p->flags & PARAMVAR))) + break; + switch (t->kind) { + case TLPAREN: + ++paren; + break; + case TRPAREN: + --paren; + break; + } + if (p->flags & PARAMSTR) + stringize(&str, t); + } + if (p->flags & PARAMTOK && !expand(t)) { + arrayaddbuf(&tok, t, sizeof(*t)); + ++arg[i].ntoken; + } + t = rawnext(); + } + if (p->flags & PARAMSTR) { + arrayaddbuf(&str, "\"", 2); + arg[i].str = (struct token){ + .kind = TSTRINGLIT, + .lit = str.val, + }; + } + if (t->kind == TRPAREN) + break; + t = rawnext(); + } + if (i + 1 < m->nparam) + error(&t->loc, "not enough arguments for macro '%s'", m->name); + if (t->kind != TRPAREN) + error(&t->loc, "too many arguments for macro '%s'", m->name); + for (i = 0, t = tok.val; i < m->nparam; ++i) { + arg[i].token = t; + t += arg[i].ntoken; + } + m->arg = arg; +} + +void +next(void) +{ + struct token *t; + + do + t = rawnext(); + while (expand(t) || t->kind == TNEWLINE && !(ppflags & PPNEWLINE)); + tok = *t; + + /* keyword aliases */ + switch (tok.kind) { + case ALIAS_ALIGNAS: + tok.kind = TALIGNAS; + break; + case ALIAS_ALIGNOF: + tok.kind = TALIGNOF; + break; + case ALIAS_BOOL: + tok.kind = TBOOL; + break; + case ALIAS__INLINE: + case ALIAS__INLINE__: + tok.kind = TINLINE; + break; + case ALIAS__SIGNED: + case ALIAS__SIGNED__: + tok.kind = TSIGNED; + break; + case ALIAS_STATIC_ASSERT: + tok.kind = TSTATIC_ASSERT; + break; + case ALIAS_THREAD_LOCAL: + case ALIAS__THREAD: + tok.kind = TTHREAD_LOCAL; + break; + case ALIAS__TYPEOF: + case ALIAS__TYPEOF__: + tok.kind = TTYPEOF; + break; + case ALIAS__VOLATILE__: + tok.kind = TVOLATILE; + break; + case ALIAS__ASM: + tok.kind = T__ASM__; + break; + } +} + +bool +peek(enum tokenkind kind) +{ + static struct token pending; + struct token old; + + old = tok; + next(); + if (tok.kind == kind) { + next(); + return true; + } + pending = tok; + tok = old; + ctxpush(&pending, 1, NULL, pending.space); + return false; +} + +char * +expect(enum tokenkind kind, const char *msg) +{ + char *lit; + + lit = tokencheck(&tok, kind, msg); + next(); + + return lit; +} + +bool +consume(enum tokenkind kind) +{ + if (tok.kind != kind) + return false; + next(); + return true; +} diff --git a/cmd/dev/cc/qbe.c b/cmd/dev/cc/qbe.c @@ -0,0 +1,2306 @@ +#include "util.h" +#include "cc.h" +#include <assert.h> +#include <ctype.h> +#include <inttypes.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct value { + enum { + VALUE_NONE, + VALUE_GLOBAL, + VALUE_INTCONST, + VALUE_FLTCONST, + VALUE_DBLCONST, + VALUE_TEMP, + VALUE_TYPE, + VALUE_LABEL, + + VALUE_EXTERN = 1 << 4, + VALUE_THREAD = 1 << 5, + VALUE_QUOTE = 1 << 6, + } kind; + unsigned id; + union { + char *name; + unsigned long long i; + double f; + } u; +}; + +struct lvalue { + struct value *addr; + struct bitfield bits; +}; + +enum instkind { + INONE, + +#define OP(op, name) op, +#include "ops.h" +#undef OP + + IARG, + IVARARG, +}; + +struct qbetype { + char base, data; + enum instkind load, store; +}; + +struct inst { + enum instkind kind; + int class; + struct value res, *arg[2]; +}; + +struct jump { + enum { + JUMP_NONE, + JUMP_JMP, + JUMP_JNZ, + JUMP_RET, + JUMP_HLT, + } kind; + struct value *arg; + struct block *blk[2]; +}; + +struct block { + struct value label; + struct array insts; + struct { + int class; + struct block *blk[2]; + struct value *val[2]; + struct value res; + } phi; + struct jump jump; + + struct block *next; +}; + +struct switchcase { + struct treenode node; + struct block *body; +}; + +struct func { + struct decl *decl, *namedecl; + char *name; + struct value *paramtemps; + struct type *type; + struct block *start, *end; + struct map gotos; + unsigned lastid; +}; + +static const int ptrclass = 'l'; + +void +switchcase(struct switchcases *cases, unsigned long long i, struct block *b) +{ + struct switchcase *c; + + c = treeinsert(&cases->root, i, sizeof(*c)); + if (!c->node.new) + error(&tok.loc, "multiple 'case' labels with same value"); + c->body = b; +} + +/* values */ + +struct block * +mkblock(char *name) +{ + static unsigned id; + struct block *b; + + b = xmalloc(sizeof(*b)); + b->label.kind = VALUE_LABEL; + b->label.u.name = name; + b->label.id = ++id; + b->insts = (struct array){0}; + b->jump.kind = JUMP_NONE; + b->phi.res.kind = VALUE_NONE; + b->next = NULL; + + return b; +} + +struct value * +mkglobal(struct decl *d) +{ + static unsigned id; + struct value *v; + + v = xmalloc(sizeof(*v)); + v->kind = VALUE_GLOBAL; + if (d->linkage == LINKEXTERN) + v->kind |= VALUE_EXTERN; + if (d->kind == DECLOBJECT && d->u.obj.storage == SDTHREAD) + v->kind |= VALUE_THREAD; + if (d->asmname) { + v->kind |= VALUE_QUOTE; + v->u.name = d->asmname; + v->id = 0; + } else { + v->u.name = d->name; + v->id = d->linkage == LINKNONE ? ++id : 0; + } + + return v; +} + +/* extern reference to a plain-named runtime symbol with no struct decl + * behind it, since nothing in the translation unit ever declares one: + * the linker resolves it against aruu's own runtime (shared/libatomic + * for the atomic builtins, shared/libint128 for __int128 multiply and + * divide) */ +static struct value * +mkextfn(const char *name) +{ + struct value *v = xmalloc(sizeof(*v)); + v->kind = VALUE_GLOBAL | VALUE_EXTERN; + v->id = 0; + v->u.name = name; + return v; +} + +/* size-suffixed atomic runtime symbol (__atomic_load_4, + * __atomic_fetch_add_8, ...). 4 and 8 byte pointees only so far */ +static struct value * +mkatomicfn(struct type *pointee, const char *base) +{ + char *name; + int size = pointee->size; + + if (size != 4 && size != 8) + error(&tok.loc, "atomic builtins on %d-byte types are not yet supported", size); + name = xmalloc(strlen(base) + 3); + sprintf(name, "%s_%d", base, size); + return mkextfn(name); +} + +struct value * +mkintconst(unsigned long long n) +{ + struct value *v; + + v = xmalloc(sizeof(*v)); + v->kind = VALUE_INTCONST; + v->u.i = n; + + return v; +} + +static struct value * +mkfltconst(int kind, double n) +{ + struct value *v; + + v = xmalloc(sizeof(*v)); + v->kind = kind; + v->u.f = n; + + return v; +} + +static struct qbetype +qbetype(struct type *t) +{ + static const struct qbetype ub = {'w', 'b', ILOADUB, ISTOREB}, sb = {'w', 'b', ILOADSB, ISTOREB}, + uh = {'w', 'h', ILOADUH, ISTOREH}, sh = {'w', 'h', ILOADSH, ISTOREH}, + w = {'w', 'w', ILOADW, ISTOREW}, l = {'l', 'l', ILOADL, ISTOREL}, + s = {'s', 's', ILOADS, ISTORES}, d = {'d', 'd', ILOADD, ISTORED}, + v = {0}; + + if (t == &typevoid) + return v; + /* __int128 is arithmetic (PROPSCALAR) but, like a struct, has no + * qbe class of its own: every __int128 value is an address (see + * funcload/funcstore), so it takes the same l class an aggregate + * gets below */ + if (!(t->prop & PROPSCALAR) || t->kind == TYPEINT128) + return l; + switch (t->size) { + case 1: + return t->u.arith.issigned ? sb : ub; + case 2: + return t->u.arith.issigned ? sh : uh; + case 4: + return t->prop & PROPFLOAT ? s : w; + case 8: + return t->prop & PROPFLOAT ? d : l; + case 16: + fatal("long double is not yet supported"); + } + assert(0); +} + +/* functions */ + +static void emittype(struct type *); +static void emitname(struct value *); +static void emitvalue(struct value *); + +static void +functemp(struct func *f, struct value *v) +{ + v->kind = VALUE_TEMP; + v->u.name = NULL; + v->id = ++f->lastid; +} + +static const char *const instname[] = { +#define OP(op, name) [op] = name, +#include "ops.h" +#undef OP +}; + +static struct inst * +mkinst(struct func *f, int op, int class, struct value *arg0, struct value *arg1) +{ + struct inst *inst; + + inst = xmalloc(sizeof(*inst)); + inst->kind = op; + inst->class = class; + inst->arg[0] = arg0; + inst->arg[1] = arg1; + if (class && op != IARG) + functemp(f, &inst->res); + else + inst->res.kind = VALUE_NONE; + return inst; +} + +static struct value * +funcinst(struct func *f, int op, int class, struct value *arg0, struct value *arg1) +{ + struct inst *inst; + struct block *b; + + if (f->end->jump.kind) { + b = mkblock("dead"); + funclabel(f, b); + } + inst = mkinst(f, op, class, arg0, arg1); + arrayaddptr(&f->end->insts, inst); + return &inst->res; +} + +static struct value * +funcbits(struct func *f, struct type *t, struct value *v, struct bitfield b) +{ + int class, bits; + + class = t->size <= 4 ? 'w' : 'l'; + bits = b.after; + if (!bits && t->kind == TYPEBITINT) + bits = t->size * 8 - t->u.arith.width; + if (bits) { + bits += (t->size + 3 & -4) - t->size << 3; + v = funcinst(f, ISHL, class, v, mkintconst(bits)); + } + bits += b.before; + if (bits) + v = funcinst(f, t->u.arith.issigned ? ISAR : ISHR, class, v, mkintconst(bits)); + return v; +} + +struct int128parts { + struct value *lo, *hi; +}; + +/* a __int128 value is always an address (see funcload/funcstore), so + * every operator on one starts by pulling its two 64 bit words out + * of memory */ +static struct int128parts +load128(struct func *f, struct value *addr) +{ + struct int128parts p; + p.lo = funcinst(f, ILOADL, 'l', addr, NULL); + p.hi = funcinst(f, ILOADL, 'l', funcinst(f, IADD, 'l', addr, mkintconst(8)), NULL); + return p; +} + +/* mirror of load128: stores lo/hi into a fresh 16 byte slot and + * returns its address, the result every __int128 operator produces */ +static struct value * +store128(struct func *f, struct value *lo, struct value *hi) +{ + struct value *addr = funcinst(f, IALLOC16, ptrclass, mkintconst(16), NULL); + funcinst(f, ISTOREL, 0, lo, addr); + funcinst(f, ISTOREL, 0, hi, funcinst(f, IADD, 'l', addr, mkintconst(8))); + return addr; +} + +struct int128cmp { + struct value *lt, *eq; /* both 0 or 1, 'l' class */ +}; + +/* branchless 128 bit compare: compares the high words first (signed + * or unsigned per issigned) and only falls back to an unsigned low + * word compare when the high words are equal, the standard technique + * for ordering a multi-word integer with no way to chain a carry/ + * borrow flag between two independent qbe compare instructions */ +static struct int128cmp +cmp128(struct func *f, struct int128parts a, struct int128parts b, int issigned) +{ + struct int128cmp c; + struct value *hi_lt, *hi_eq, *lo_ult; + hi_lt = funcinst(f, issigned ? ICSLTL : ICULTL, 'l', a.hi, b.hi); + hi_eq = funcinst(f, ICEQL, 'l', a.hi, b.hi); + lo_ult = funcinst(f, ICULTL, 'l', a.lo, b.lo); + c.lt = funcinst(f, IOR, 'l', hi_lt, funcinst(f, IAND, 'l', hi_eq, lo_ult)); + c.eq = funcinst(f, IAND, 'l', hi_eq, funcinst(f, ICEQL, 'l', a.lo, b.lo)); + return c; +} + +/* __int128 multiply and divide both lower to a call into + * shared/libint128/int128_x64.s: qbe has neither a widening multiply + * nor any divide wider than 64 bits, and a real division needs a bit + * serial long-division loop no ir-level codegen could express, so + * both are out of line the same way atomics are (see mkatomicfn) */ +static struct value * +funcmul128(struct func *f, struct value *l, struct value *r) +{ + struct value *fn, *v; + + emittype(&typeint128); + fn = mkextfn("__multi3"); + v = funcinst(f, ICALL, 'l', fn, typeint128.value); + funcinst(f, IARG, 'l', l, typeint128.value); + funcinst(f, IARG, 'l', r, typeint128.value); + return v; +} + +/* x + mask, then xor mask again: negates a two's complement value + * when mask is all-ones, leaves it unchanged when mask is zero. used + * both to take a signed __int128's absolute value (mask = its own + * sign, replicated across both words) and, afterward, to flip a + * division result's sign back without branching on it */ +static struct int128parts +condneg128(struct func *f, struct int128parts a, struct value *mask) +{ + struct value *sum_lo, *carry, *sum_hi; + struct int128parts r; + sum_lo = funcinst(f, IADD, 'l', a.lo, mask); + carry = funcinst(f, ICULTL, 'l', sum_lo, a.lo); + sum_hi = funcinst(f, IADD, 'l', funcinst(f, IADD, 'l', a.hi, mask), carry); + r.lo = funcinst(f, IXOR, 'l', sum_lo, mask); + r.hi = funcinst(f, IXOR, 'l', sum_hi, mask); + return r; +} + +/* / and % on __int128 both call __udivmodti4, which only ever + * operates on magnitudes: a signed division negates both operands to + * their absolute value first (branchless, the standard mask = hi>>63 + * trick, reused afterward to flip the quotient's sign when the + * operands' signs differed and the remainder's sign to match the + * dividend, c's own rule for truncating division) */ +static struct value * +funcdiv128(struct func *f, struct type *t, struct value *l, struct value *r, int want_remainder) +{ + struct int128parts a, b, ua, ub, qp, rp, res; + struct value *fn, *remslot, *uaaddr, *ubaddr, *q, *qmask, *rmask; + + a = load128(f, l); + b = load128(f, r); + if (t->u.arith.issigned) { + struct value *amask = funcinst(f, ISAR, 'l', a.hi, mkintconst(63)); + struct value *bmask = funcinst(f, ISAR, 'l', b.hi, mkintconst(63)); + ua = condneg128(f, a, amask); + ub = condneg128(f, b, bmask); + qmask = funcinst(f, IXOR, 'l', amask, bmask); + rmask = amask; + } else { + ua = a; + ub = b; + qmask = rmask = mkintconst(0); + } + + emittype(&typeuint128); + /* every value the call arguments reference must be computed before + * the icall itself: emitinst's own call-printing groups an icall + * with whatever iargs immediately follow it in the block's + * instruction list, so nothing (store128's own alloc/store + * instructions included) may land between them */ + remslot = funcinst(f, IALLOC16, ptrclass, mkintconst(16), NULL); + uaaddr = store128(f, ua.lo, ua.hi); + ubaddr = store128(f, ub.lo, ub.hi); + fn = mkextfn("__udivmodti4"); + q = funcinst(f, ICALL, 'l', fn, typeuint128.value); + funcinst(f, IARG, 'l', uaaddr, typeuint128.value); + funcinst(f, IARG, 'l', ubaddr, typeuint128.value); + funcinst(f, IARG, ptrclass, remslot, NULL); + + if (!want_remainder) { + qp = load128(f, q); + res = condneg128(f, qp, qmask); + } else { + rp = load128(f, remslot); + res = condneg128(f, rp, rmask); + } + return store128(f, res.lo, res.hi); +} + +/* variable count << and >> on __int128: n is a plain 64 bit count (the + * shift count keeps its own promoted type instead of converting to + * match the shifted operand, per c's own rule for shift operators, so + * the caller widens it to 'l' before this point). qbe's shl/shr/sar + * mask their count the same way real x86 does, so a shift by exactly + * 64 (the one count where "shift the other word by 64-n" would itself + * mean shift-by-zero, silently wrong) and a shift by zero (where the + * complementary cross-word shift would itself mean shift-by-64) both + * need to be routed around the general n-in-1..63 formula rather than + * folded into it: two real branches, not a branchless trick */ +static struct value * +funcshift128(struct func *f, struct type *t, struct value *l, struct value *n, int isleft) +{ + struct int128parts a = load128(f, l); + struct block *bzero, *bnz, *bsmall, *blarge, *bnzjoin, *bjoin; + enum instkind shrop = t->u.arith.issigned ? ISAR : ISHR; + + bzero = mkblock(isleft ? "shl128_zero" : "shr128_zero"); + bnz = mkblock(isleft ? "shl128_nz" : "shr128_nz"); + bjoin = mkblock(isleft ? "shl128_join" : "shr128_join"); + funcjnz(f, funcinst(f, ICEQL, 'w', n, mkintconst(0)), NULL, bzero, bnz); + + funclabel(f, bzero); + bjoin->phi.val[0] = l; /* shift by 0: reuse the operand's own address unchanged */ + bjoin->phi.blk[0] = f->end; + funcjmp(f, bjoin); + + funclabel(f, bnz); + bsmall = mkblock(isleft ? "shl128_small" : "shr128_small"); + blarge = mkblock(isleft ? "shl128_large" : "shr128_large"); + bnzjoin = mkblock(isleft ? "shl128_nzjoin" : "shr128_nzjoin"); + funcjnz(f, funcinst(f, ICULTL, 'w', n, mkintconst(64)), NULL, bsmall, blarge); + + funclabel(f, bsmall); + { + /* n in 1..63 here: the complementary shift (64-n) is 1..63 too, + * never the 0-or-64 counts qbe/x86 would mask away */ + struct value *inv = funcinst(f, ISUB, 'l', mkintconst(64), n); + struct value *lo, *hi; + if (isleft) { + hi = + funcinst(f, IOR, 'l', funcinst(f, ISHL, 'l', a.hi, n), funcinst(f, ISHR, 'l', a.lo, inv)); + lo = funcinst(f, ISHL, 'l', a.lo, n); + } else { + lo = + funcinst(f, IOR, 'l', funcinst(f, ISHR, 'l', a.lo, n), funcinst(f, ISHL, 'l', a.hi, inv)); + hi = funcinst(f, shrop, 'l', a.hi, n); + } + bnzjoin->phi.val[0] = store128(f, lo, hi); + bnzjoin->phi.blk[0] = f->end; + funcjmp(f, bnzjoin); + } + + funclabel(f, blarge); + { + /* n in 64..127 (n >= 128 is ub, same as any other integer type's + * shift by more than its width): the whole low word has already + * shifted entirely into, or out of, the high word's position, so + * only a single n-64 shift (0..63, safe) is needed */ + struct value *nn = funcinst(f, ISUB, 'l', n, mkintconst(64)); + struct value *lo, *hi; + if (isleft) { + hi = funcinst(f, ISHL, 'l', a.lo, nn); + lo = mkintconst(0); + } else { + lo = funcinst(f, shrop, 'l', a.hi, nn); + hi = t->u.arith.issigned ? funcinst(f, ISAR, 'l', a.hi, mkintconst(63)) : mkintconst(0); + } + bnzjoin->phi.val[1] = store128(f, lo, hi); + bnzjoin->phi.blk[1] = f->end; + funcjmp(f, bnzjoin); + } + + funclabel(f, bnzjoin); + bnzjoin->phi.class = 'l'; + functemp(f, &bnzjoin->phi.res); + + bjoin->phi.val[1] = &bnzjoin->phi.res; + bjoin->phi.blk[1] = bnzjoin; + funclabel(f, bjoin); + bjoin->phi.class = 'l'; + functemp(f, &bjoin->phi.res); + return &bjoin->phi.res; +} + +struct complexparts { + struct value *re, *im; +}; + +/* same reasoning as load128: a complex value is always an address + * (see funcload/funcstore), so every operator on one starts by + * pulling its real and imaginary parts, back to back in memory, out + * of it. unlike __int128 the two halves are the underlying real + * type's own qbe class ('s' or 'd'), not always 'l' */ +static struct complexparts +loadcomplex(struct func *f, struct type *t, struct value *addr) +{ + struct qbetype qt = qbetype(t->base); + struct complexparts p; + p.re = funcinst(f, qt.load, qt.base, addr, NULL); + p.im = + funcinst(f, qt.load, qt.base, funcinst(f, IADD, 'l', addr, mkintconst(t->base->size)), NULL); + return p; +} + +/* mirror of loadcomplex: stores re/im into a fresh slot sized and + * aligned for t and returns its address, the result every complex + * operator produces */ +static struct value * +storecomplex(struct func *f, struct type *t, struct value *re, struct value *im) +{ + struct qbetype qt = qbetype(t->base); + struct value *addr = + funcinst(f, t->align <= 4 ? IALLOC4 : IALLOC8, ptrclass, mkintconst(t->size), NULL); + funcinst(f, qt.store, 0, re, addr); + funcinst(f, qt.store, 0, im, funcinst(f, IADD, 'l', addr, mkintconst(t->base->size))); + return addr; +} + +static struct value * +convert(struct func *f, struct type *dst, struct type *src, struct value *l) +{ + enum instkind op; + struct value *r = NULL; + int class; + + if (src == dst) + return l; + if (src->kind == TYPEPOINTER) + src = &typeulong; + if (dst->kind == TYPEPOINTER) + dst = &typeulong; + if (dst->kind == TYPEVOID) + return NULL; + if (dst->kind == TYPEINT128 && src->kind == TYPEINT128) + return l; /* signed <-> unsigned __int128: identical representation */ + if (dst->kind == TYPEINT128) { + struct value *lo, *hi; + int issigned; + if (src->prop & PROPFLOAT) { + /* truncate toward zero through a 64 bit intermediate: magnitude + * beyond 64 bits is lost, a documented gap rather than a + * crash, the same treatment this compiler already gives any + * other out-of-range float-to-int conversion */ + l = convert(f, dst->u.arith.issigned ? &typelong : &typeulong, src, l); + issigned = dst->u.arith.issigned; + } else { + issigned = src->u.arith.issigned; + if (src->size < 8) + l = convert(f, issigned ? &typelong : &typeulong, src, l); + } + lo = l; + hi = issigned ? funcinst(f, ISAR, 'l', l, mkintconst(63)) : mkintconst(0); + return store128(f, lo, hi); + } + if (src->kind == TYPEINT128) { + struct int128parts p = load128(f, l); + if (dst->kind == TYPEBOOL) + return funcinst(f, ICNEL, 'w', funcinst(f, IOR, 'l', p.lo, p.hi), mkintconst(0)); + /* every other destination depends only on the low word: exact for + * any value that fits, a documented magnitude loss otherwise, + * left to the same implementation-defined narrowing this compiler + * already leaves unchecked for every other lossy int conversion */ + return convert(f, dst, src->u.arith.issigned ? &typelong : &typeulong, p.lo); + } + if (dst->kind == TYPECOMPLEX && src->kind == TYPECOMPLEX) { + /* float _Complex <-> double _Complex: convert each component on + * its own, same as converting two independent reals */ + struct complexparts p = loadcomplex(f, src, l); + return storecomplex( + f, dst, convert(f, dst->base, src->base, p.re), convert(f, dst->base, src->base, p.im) + ); + } + if (dst->kind == TYPECOMPLEX) { + /* real -> complex: imaginary part is exactly 0 */ + struct qbetype qt = qbetype(dst->base); + return storecomplex( + f, + dst, + convert(f, dst->base, src, l), + mkfltconst(qt.base == 's' ? VALUE_FLTCONST : VALUE_DBLCONST, 0) + ); + } + if (src->kind == TYPECOMPLEX) { + /* complex -> real: the imaginary part is simply discarded, the + * same implementation-defined narrowing real compilers warn about + * and this one does not */ + struct complexparts p = loadcomplex(f, src, l); + return convert(f, dst, src->base, p.re); + } + if (!(src->prop & PROPREAL) || !(dst->prop & PROPREAL)) + fatal("internal error; unsupported conversion"); + if (dst->kind == TYPEBOOL) { + class = 'w'; + if (src->prop & PROPINT) { + r = mkintconst(0); + switch (src->size) { + case 1: + op = ICNEW; + if (src->kind != TYPEBITINT) + l = funcinst(f, IEXTUB, 'w', l, NULL); + break; + case 2: + op = ICNEW; + if (src->kind != TYPEBITINT) + l = funcinst(f, IEXTUH, 'w', l, NULL); + break; + case 4: + op = ICNEW; + break; + case 8: + op = ICNEL; + break; + default: + fatal( + "internal error; unknown integer " + "conversion" + ); + } + } else { + assert(src->prop & PROPFLOAT); + switch (src->size) { + case 4: + op = ICNES, r = mkfltconst(VALUE_FLTCONST, 0); + break; + case 8: + op = ICNED, r = mkfltconst(VALUE_DBLCONST, 0); + break; + default: + fatal( + "internal error; unknown floating point " + "conversion" + ); + } + } + } else if (dst->prop & PROPINT) { + class = dst->size == 8 ? 'l' : 'w'; + if (src->prop & PROPINT) { + if (dst->u.arith.width <= src->u.arith.width) { + if (dst->kind == TYPEBITINT) + return funcbits(f, dst, l, (struct bitfield){0}); + return l; + } + if (src->kind == TYPEBITINT && (src->size == 8 || dst->size == 4)) + return l; + switch (src->size) { + case 4: + op = src->u.arith.issigned ? IEXTSW : IEXTUW; + break; + case 2: + op = src->u.arith.issigned ? IEXTSH : IEXTUH; + break; + case 1: + op = src->u.arith.issigned ? IEXTSB : IEXTUB; + break; + default: + fatal( + "internal error; unknown integer " + "conversion" + ); + } + } else { + if (dst->u.arith.issigned) + op = src->size == 8 ? IDTOSI : ISTOSI; + else + op = src->size == 8 ? IDTOUI : ISTOUI; + } + } else { + class = dst->size == 8 ? 'd' : 's'; + if (src->prop & PROPINT) { + if (src->size < 4) + l = convert(f, src->u.arith.issigned ? &typeint : &typeuint, src, l); + if (src->u.arith.issigned) + op = src->size == 8 ? ISLTOF : ISWTOF; + else + op = src->size == 8 ? IULTOF : IUWTOF; + } else { + assert(src->prop & PROPFLOAT); + if (src->size == dst->size) + return l; + op = src->size < dst->size ? IEXTS : ITRUNCD; + } + } + + return funcinst(f, op, class, l, r); +} + +static void +calcvla(struct func *f, struct type *t) +{ + struct value *length, *basesize; + + if (!(t->prop & PROPVM)) + return; + if (t->base) + calcvla(f, t->base); + if (t->kind == TYPEFUNC || t->size) + return; + assert(t->kind == TYPEARRAY); + if (!t->u.array.size) { + assert(t->base->size || t->base->kind == TYPEARRAY); + assert(t->u.array.length); + length = convert(f, &typeulong, t->u.array.length->type, funcexpr(f, t->u.array.length)); + basesize = t->base->size ? mkintconst(t->base->size) : t->base->u.array.size; + t->u.array.size = funcinst(f, IMUL, 'l', length, basesize); + } +} + +static void +funcalloc(struct func *f, struct decl *d) +{ + enum instkind op; + struct block *end; + struct value *v; + int align; + + assert(!d->type->incomplete); + calcvla(f, d->type); + end = f->end; + if (d->type->size) { + f->end = f->start; + v = mkintconst(d->type->size); + } else { + assert(d->type->kind == TYPEARRAY); + assert(d->type->u.array.size); + v = d->type->u.array.size; + } + align = d->u.obj.align; + switch (align) { + case 1: + case 2: + case 4: + op = IALLOC4; + break; + case 8: + op = IALLOC8; + break; + default: + v = funcinst(f, IADD, ptrclass, v, mkintconst(align - 16)); /* fallthrough */ + case 16: + op = IALLOC16; + break; + } + v = funcinst(f, op, ptrclass, v, NULL); + if (align > 16) { + /* TODO: implement alloc32 in QBE and use that instead */ + v = funcinst(f, IADD, ptrclass, v, mkintconst(align - 16)); + v = funcinst(f, IAND, ptrclass, v, mkintconst(-align)); + } + d->value = v; + f->end = end; +} + +static void +funccopy(struct func *f, struct value *dst, struct value *src, unsigned long long size, int align) +{ + enum instkind load, store; + int class; + struct value *tmp, *inc; + unsigned long long off; + + assert((align & align - 1) == 0); + class = 'w'; + switch (align) { + case 1: + load = ILOADUB, store = ISTOREB; + break; + case 2: + load = ILOADUH, store = ISTOREH; + break; + case 4: + load = ILOADW, store = ISTOREW; + break; + default: + load = ILOADL, store = ISTOREL, align = 8, class = 'l'; + break; + } + inc = mkintconst(align); + off = 0; + for (;;) { + tmp = funcinst(f, load, class, src, NULL); + funcinst(f, store, 0, tmp, dst); + off += align; + if (off >= size) + break; + src = funcinst(f, IADD, ptrclass, src, inc); + dst = funcinst(f, IADD, ptrclass, dst, inc); + } +} + +static struct value * +funcstore(struct func *f, struct type *t, enum typequal tq, struct lvalue lval, struct value *v) +{ + struct value *r; + enum typeprop tp; + unsigned long long mask; + struct qbetype qt; + int bits; + + if (tq & QUALVOLATILE) + error(&tok.loc, "volatile store is not yet supported"); + if (tq & QUALCONST) + error(&tok.loc, "cannot store to 'const' object"); + tp = t->prop; + assert(!lval.bits.before && !lval.bits.after || tp & PROPINT); + r = v; + switch (t->kind) { + case TYPESTRUCT: + case TYPEUNION: + case TYPEARRAY: + case TYPEINT128: + case TYPECOMPLEX: + funccopy(f, lval.addr, v, t->size, t->align); + break; + case TYPEPOINTER: + t = &typeulong; + /* fallthrough */ + default: + assert(tp & PROPSCALAR); + qt = qbetype(t); + bits = lval.bits.before + lval.bits.after; + if (bits) { + mask = 0xffffffffffffffffu >> 64 - t->size * 8 + bits << lval.bits.before; + v = funcinst(f, ISHL, qt.base, v, mkintconst(lval.bits.before)); + r = funcbits(f, t, v, lval.bits); + v = funcinst(f, IAND, qt.base, v, mkintconst(mask)); + v = funcinst( + f, + IOR, + qt.base, + v, + funcinst( + f, IAND, qt.base, funcinst(f, qt.load, qt.base, lval.addr, NULL), mkintconst(~mask) + ) + ); + } + funcinst(f, qt.store, 0, v, lval.addr); + break; + } + return r; +} + +static struct value * +funcload(struct func *f, struct type *t, struct lvalue lval) +{ + struct value *v; + struct qbetype qt; + + switch (t->kind) { + case TYPESTRUCT: + case TYPEUNION: + case TYPEARRAY: + case TYPEINT128: + case TYPECOMPLEX: + return lval.addr; + } + qt = qbetype(t); + v = funcinst(f, qt.load, qt.base, lval.addr, NULL); + return funcbits(f, t, v, lval.bits); +} + +struct func * +mkfunc(struct decl *decl, char *name, struct type *t, struct scope *s) +{ + struct func *f; + struct decl *d; + struct value *v; + + f = xmalloc(sizeof(*f)); + f->decl = decl; + f->name = name; + f->type = t; + f->start = f->end = mkblock("start"); + f->lastid = 0; + mapinit(&f->gotos, 8); + emittype(t->base); + + /* allocate space for parameters */ + f->paramtemps = xreallocarray(NULL, t->u.func.nparam, sizeof *f->paramtemps); + for (d = t->u.func.params, v = f->paramtemps; d; d = d->next, ++v) { + emittype(d->type); + functemp(f, v); + if (!d->name) + continue; + if (d->type->value) { + d->value = v; + } else { + funcalloc(f, d); + funcstore(f, d->type, QUALNONE, (struct lvalue){d->value}, v); + } + } + + t = mkarraytype(&typechar, QUALCONST, strlen(name) + 1); + d = mkdecl("__func__", DECLOBJECT, t, QUALNONE, LINKNONE); + d->u.obj.storage = SDSTATIC; + d->value = mkglobal(d); + scopeputdecl(s, d); + f->namedecl = d; + + funclabel(f, mkblock("body")); + + return f; +} + +void +delfunc(struct func *f) +{ + struct block *b; + struct inst **inst; + + while (b = f->start) { + f->start = b->next; + arrayforeach(&b->insts, inst) free(*inst); + free(b->insts.val); + free(b); + } + mapfree(&f->gotos, free); + free(f); +} + +struct type * +functype(struct func *f) +{ + return f->type; +} + +void +funclabel(struct func *f, struct block *b) +{ + f->end->next = b; + f->end = b; +} + +void +funcjmp(struct func *f, struct block *l) +{ + struct block *b = f->end; + + if (!b->jump.kind) { + b->jump.kind = JUMP_JMP; + b->jump.blk[0] = l; + } +} + +void +funcjnz(struct func *f, struct value *v, struct type *t, struct block *l1, struct block *l2) +{ + struct block *b = f->end; + + if (b->jump.kind) + return; + if (t) { + assert(t->prop & PROPSCALAR); + /* + * ideally we would just do this conversion unconditionally, + * but QBE is not currently able to optimize the conversion + * away for int + */ + if (t->prop & PROPINT && t->size < 4) + v = convert(f, &typeint, t, v); + else if (t->prop & PROPFLOAT || t->size > 4) + v = convert(f, &typebool, t, v); + } + b->jump.kind = JUMP_JNZ; + b->jump.arg = v; + b->jump.blk[0] = l1; + b->jump.blk[1] = l2; +} + +void +funcret(struct func *f, struct value *v) +{ + struct block *b = f->end; + + if (!b->jump.kind) { + b->jump.kind = JUMP_RET; + b->jump.arg = v; + } +} + +void +funchlt(struct func *f) +{ + struct block *b = f->end; + + if (!b->jump.kind) + b->jump.kind = JUMP_HLT; +} + +struct gotolabel * +funcgoto(struct func *f, char *name) +{ + struct gotolabel *g; + struct mapkey key; + size_t idx; + + mapkey(&key, name, strlen(name)); + if (mapput(&f->gotos, &key, &idx)) { + g = xmalloc(sizeof(*g)); + g->label = mkblock(name); + f->gotos.vals[idx].p = g; + } + + return f->gotos.vals[idx].p; +} + +static struct lvalue +funclval(struct func *f, struct expr *e) +{ + struct lvalue lval = {0}; + struct decl *d; + + if (e->kind == EXPRBITFIELD) { + lval.bits = e->u.bitfield.bits; + e = e->base; + } + switch (e->kind) { + case EXPRIDENT: + d = e->u.ident.decl; + if (d->kind != DECLOBJECT && d->kind != DECLFUNC) + error(&tok.loc, "identifier '%s' is not an object or function", d->name); + if (d == f->namedecl) { + fputs("data ", stdout); + emitname(d->value); + printf(" = { b \"%s\", b 0 }\n", f->name); + f->namedecl = NULL; + } + lval.addr = d->value; + break; + case EXPRSTRING: + d = stringdecl(e); + lval.addr = d->value; + break; + case EXPRCOMPOUND: + if (e->toeval) + funcexpr(f, e->toeval); + d = e->u.compound.decl; + funcinit(f, d, e->u.compound.init, true); + lval.addr = d->value; + break; + case EXPRUNARY: + if (e->op != TMUL) + error(&tok.loc, "expression is not an object"); + lval.addr = funcexpr(f, e->base); + break; + default: + if (e->type->kind != TYPESTRUCT && e->type->kind != TYPEUNION) + error(&tok.loc, "expression is not an object"); + lval.addr = funcexpr(f, e); + } + return lval; +} + +/* returns the expression value in the true branch */ +struct value * +funcbranch(struct func *f, struct expr *e, struct block *bt, struct block *bf) +{ + static struct value one = {.kind = VALUE_INTCONST, .u.i = 1}; + struct expr *l, *r; + struct value *v; + struct block *b; + + /* maybe we we could do something for EXPRCOND as well */ + switch (e->kind) { + case EXPRBINARY: + l = e->u.binary.l; + r = e->u.binary.r; + switch (e->op) { + case TEQL: + case TNEQ: + r = eval(r); + if (r->kind == EXPRCONST && r->type->prop & PROPINT && r->u.constant.u == 0) { + if (e->op == TEQL) + b = bt, bt = bf, bf = b; + funcbranch(f, l, bt, bf); + return &one; + } + break; + case TLOR: + case TLAND: + if (e->op == TLOR) { + b = mkblock("logic_or"); + funcbranch(f, l, bt, b); + } else { + b = mkblock("logic_and"); + funcbranch(f, l, b, bf); + } + funclabel(f, b); + funcbranch(f, r, bt, bf); + return &one; + } + break; + case EXPRCOMMA: + for (e = e->base; e->next; e = e->next) + funcexpr(f, e); + return funcbranch(f, e, bt, bf); + } + v = funcexpr(f, e); + funcjnz(f, v, e->type, bt, bf); + return v; +} + +struct value * +funcexpr(struct func *f, struct expr *e) +{ + enum instkind op = INONE; + struct decl *d; + struct value *l, *r, *v, *v2, *fn, **argvals; + struct lvalue lval; + struct expr *arg; + struct block *b[3]; + struct type *t, *functype; + size_t i; + + calcvla(f, e->type); + switch (e->kind) { + case EXPRIDENT: + d = e->u.ident.decl; + switch (d->kind) { + case DECLOBJECT: + return funcload(f, e->type, (struct lvalue){d->value}); + case DECLCONST: + return d->value; + default: + fatal("unimplemented declaration kind %d", d->kind); + } + break; + case EXPRCONST: + t = e->type; + if (t->kind == TYPEINT128) { + /* the frontend's own constant representation is 64 bits wide + * (cc.h's expr.u.constant union), so every __int128 constant + * that reaches here already fits in one word: build the + * address load128/store128 callers expect by sign or zero + * extending it to the high word, rather than handing back the + * bare 64-bit scalar (which funcload/funcstore's own address + * convention for this type would then misread as a pointer) */ + long long lo = e->u.constant.i; + return store128(f, mkintconst(lo), mkintconst(t->u.arith.issigned && lo < 0 ? -1 : 0)); + } + if (t->prop & PROPINT || t->kind == TYPEPOINTER) + return mkintconst(e->u.constant.u); + assert(t->prop & PROPFLOAT); + return mkfltconst(t->size == 4 ? VALUE_FLTCONST : VALUE_DBLCONST, e->u.constant.f); + case EXPRBITFIELD: + case EXPRCOMPOUND: + lval = funclval(f, e); + return funcload(f, e->type, lval); + case EXPRINCDEC: + lval = funclval(f, e->base); + l = funcload(f, e->base->type, lval); + t = e->type; + if (t->kind == TYPEPOINTER) { + if (t->base->kind == TYPEARRAY && t->base->size == 0) { + r = t->base->u.array.size; + } else { + r = mkintconst(t->base->size); + } + } else if (t->prop & PROPINT) { + r = mkintconst(1); + } else if (t->prop & PROPFLOAT) { + r = mkfltconst(t->size == 4 ? VALUE_FLTCONST : VALUE_DBLCONST, 1); + } else { + fatal("not a scalar"); + } + v = funcinst(f, e->op == TINC ? IADD : ISUB, qbetype(t).base, l, r); + v = funcstore(f, e->type, e->qual, lval, v); + return e->u.incdec.post ? l : v; + case EXPRCALL: + argvals = xreallocarray(NULL, e->u.call.nargs, sizeof(argvals[0])); + for (arg = e->u.call.args, i = 0; arg; arg = arg->next, ++i) { + emittype(arg->type); + argvals[i] = funcexpr(f, arg); + } + t = e->type; + emittype(t); + v = funcinst(f, ICALL, qbetype(t).base, funcexpr(f, e->base), t->value); + functype = e->base->type->base; + for (arg = e->u.call.args, i = 0; arg; arg = arg->next, ++i) { + if (functype->u.func.isvararg && i == functype->u.func.nparam) + funcinst(f, IVARARG, 0, NULL, NULL); + t = arg->type; + funcinst(f, IARG, qbetype(t).base, argvals[i], t->value); + } + e = e->base; + if (e->kind == EXPRUNARY && e->op == TBAND) { + e = e->base; + if (e->kind == EXPRIDENT && e->u.ident.decl->u.func.isnoreturn) + funchlt(f); + } + return v; + case EXPRUNARY: + switch (e->op) { + case TBAND: + lval = funclval(f, e->base); + return lval.addr; + case TMUL: + r = funcexpr(f, e->base); + return funcload(f, e->type, (struct lvalue){r}); + case TSUB: + r = funcexpr(f, e->base); + if (e->type->kind == TYPEINT128) { + /* two's complement negation, same borrow logic as + * TSUB's binary case with lo_a/hi_a fixed at zero */ + struct int128parts a; + struct value *lo, *hi, *carry; + a = load128(f, r); + carry = funcinst(f, ICULTL, 'l', mkintconst(0), a.lo); + lo = funcinst(f, ISUB, 'l', mkintconst(0), a.lo); + hi = funcinst(f, ISUB, 'l', funcinst(f, ISUB, 'l', mkintconst(0), a.hi), carry); + return store128(f, lo, hi); + } + if (e->type->kind == TYPECOMPLEX) { + struct complexparts a; + struct qbetype qt; + a = loadcomplex(f, e->type, r); + qt = qbetype(e->type->base); + return storecomplex( + f, + e->type, + funcinst(f, INEG, qt.base, a.re, NULL), + funcinst(f, INEG, qt.base, a.im, NULL) + ); + } + return funcinst(f, INEG, qbetype(e->type).base, r, NULL); + } + fatal("internal error; unknown unary expression"); + break; + case EXPRCAST: + if (e->toeval) + funcexpr(f, e->toeval); + l = funcexpr(f, e->base); + return convert(f, e->type, e->base->type, l); + case EXPRBINARY: + if (e->op == TLOR || e->op == TLAND) { + b[0] = mkblock("logic_true"); + b[1] = mkblock("logic_false"); + b[2] = mkblock("logic_join"); + + funcbranch(f, e, b[0], b[1]); + funclabel(f, b[0]); + funcjmp(f, b[2]); + funclabel(f, b[1]); + + b[2]->phi.class = 'w'; + b[2]->phi.blk[0] = b[0]; + b[2]->phi.val[0] = mkintconst(1); + b[2]->phi.blk[1] = b[1]; + b[2]->phi.val[1] = mkintconst(0); + functemp(f, &b[2]->phi.res); + funclabel(f, b[2]); + + return &b[2]->phi.res; + } + l = funcexpr(f, e->u.binary.l); + r = funcexpr(f, e->u.binary.r); + t = e->u.binary.l->type; + if (t->kind == TYPEPOINTER) + t = &typeulong; + if (t->kind == TYPEINT128) { + /* qbe has no 128-bit register or op of its own, so a value + * of this type always lives in memory (l/r are addresses, + * see funcload/funcstore) and arithmetic works a word at a + * time. add/sub need a carry/borrow between the low and high + * words: (lo <u lo_a) after an add can only be true if the + * add wrapped past 2**64, the standard software-carry trick + * given no carry flag is reachable from qbe ir. multiply and + * divide call out to shared/libint128 (see funcmul128/ + * funcdiv128) */ + struct int128parts a, b; + struct value *lo, *hi, *carry; + if (e->op == TSHL || e->op == TSHR) { + /* the shift count keeps its own promoted type rather than + * converting to match the shifted operand (c's own rule + * for shift operators), so r here is a plain scalar, never + * a __int128 address like every other operand below */ + struct type *rt = e->u.binary.r->type; + struct value *n = r; + if (rt->kind == TYPEINT128) + n = load128(f, r).lo; + else if (rt->size < 8) + n = funcinst(f, rt->u.arith.issigned ? IEXTSW : IEXTUW, 'l', r, NULL); + return funcshift128(f, t, l, n, e->op == TSHL); + } + a = load128(f, l); + b = load128(f, r); + switch (e->op) { + case TADD: + lo = funcinst(f, IADD, 'l', a.lo, b.lo); + carry = funcinst(f, ICULTL, 'l', lo, a.lo); + hi = funcinst(f, IADD, 'l', funcinst(f, IADD, 'l', a.hi, b.hi), carry); + break; + case TSUB: + carry = funcinst(f, ICULTL, 'l', a.lo, b.lo); + lo = funcinst(f, ISUB, 'l', a.lo, b.lo); + hi = funcinst(f, ISUB, 'l', funcinst(f, ISUB, 'l', a.hi, b.hi), carry); + break; + case TBAND: + lo = funcinst(f, IAND, 'l', a.lo, b.lo); + hi = funcinst(f, IAND, 'l', a.hi, b.hi); + break; + case TBOR: + lo = funcinst(f, IOR, 'l', a.lo, b.lo); + hi = funcinst(f, IOR, 'l', a.hi, b.hi); + break; + case TXOR: + lo = funcinst(f, IXOR, 'l', a.lo, b.lo); + hi = funcinst(f, IXOR, 'l', a.hi, b.hi); + break; + case TMUL: + return funcmul128(f, l, r); + case TDIV: + return funcdiv128(f, t, l, r, 0); + case TMOD: + return funcdiv128(f, t, l, r, 1); + case TLESS: + case TGREATER: + case TLEQ: + case TGEQ: + case TEQL: + case TNEQ: { + /* e->type here is plain int (a comparison's own result + * type), not __int128, so this returns a scalar boolean + * directly instead of falling through to the store128 at + * the end of this case, which every arithmetic operator + * above shares */ + int issigned = t->u.arith.issigned; + struct int128cmp c; + struct value *res; + switch (e->op) { + case TLESS: + res = cmp128(f, a, b, issigned).lt; + break; + case TGREATER: + res = cmp128(f, b, a, issigned).lt; + break; + case TLEQ: + c = cmp128(f, b, a, issigned); + res = funcinst(f, IXOR, 'l', c.lt, mkintconst(1)); + break; + case TGEQ: + c = cmp128(f, a, b, issigned); + res = funcinst(f, IXOR, 'l', c.lt, mkintconst(1)); + break; + case TEQL: + res = cmp128(f, a, b, issigned).eq; + break; + default: /* TNEQ */ + c = cmp128(f, a, b, issigned); + res = funcinst(f, IXOR, 'l', c.eq, mkintconst(1)); + break; + } + return funcinst(f, ICNEL, 'w', res, mkintconst(0)); + } + default: + error(&tok.loc, "this operator is not yet supported for __int128"); + return NULL; + } + return store128(f, lo, hi); + } + if (t->kind == TYPECOMPLEX) { + /* complex addition and subtraction are componentwise, no + * carry propagation of any kind needed between the real and + * imaginary parts (unlike __int128's words above). multiply + * and divide use the ordinary cross-term formulas, real + * scalar mul/add/sub qbe already has, no new runtime or + * branching needed. == and != (the only orderings c defines + * for a complex type) compare both components and return a + * plain int, so those return early instead of falling + * through to the storecomplex every arithmetic operator above + * shares */ + struct complexparts a, b; + struct value *re, *im; + struct qbetype qt; + a = loadcomplex(f, t, l); + b = loadcomplex(f, t, r); + qt = qbetype(t->base); + switch (e->op) { + case TADD: + re = funcinst(f, IADD, qt.base, a.re, b.re); + im = funcinst(f, IADD, qt.base, a.im, b.im); + break; + case TSUB: + re = funcinst(f, ISUB, qt.base, a.re, b.re); + im = funcinst(f, ISUB, qt.base, a.im, b.im); + break; + case TMUL: + /* (a.re+a.im*i)(b.re+b.im*i) = (a.re*b.re - a.im*b.im) + + * (a.re*b.im + a.im*b.re)*i */ + re = funcinst( + f, + ISUB, + qt.base, + funcinst(f, IMUL, qt.base, a.re, b.re), + funcinst(f, IMUL, qt.base, a.im, b.im) + ); + im = funcinst( + f, + IADD, + qt.base, + funcinst(f, IMUL, qt.base, a.re, b.im), + funcinst(f, IMUL, qt.base, a.im, b.re) + ); + break; + case TDIV: { + /* multiply num and denom by conj(b): denom becomes the + * real scalar b.re^2+b.im^2, num becomes (a.re*b.re + + * a.im*b.im) + (a.im*b.re - a.re*b.im)*i */ + struct value *denom = funcinst( + f, + IADD, + qt.base, + funcinst(f, IMUL, qt.base, b.re, b.re), + funcinst(f, IMUL, qt.base, b.im, b.im) + ); + struct value *numre = funcinst( + f, + IADD, + qt.base, + funcinst(f, IMUL, qt.base, a.re, b.re), + funcinst(f, IMUL, qt.base, a.im, b.im) + ); + struct value *numim = funcinst( + f, + ISUB, + qt.base, + funcinst(f, IMUL, qt.base, a.im, b.re), + funcinst(f, IMUL, qt.base, a.re, b.im) + ); + re = funcinst(f, IDIV, qt.base, numre, denom); + im = funcinst(f, IDIV, qt.base, numim, denom); + break; + } + case TEQL: + case TNEQ: { + enum instkind eqop = t->base->size == 4 ? ICEQS : ICEQD; + struct value *req = funcinst(f, eqop, 'w', a.re, b.re); + struct value *ieq = funcinst(f, eqop, 'w', a.im, b.im); + struct value *both = funcinst(f, IAND, 'w', req, ieq); + if (e->op == TNEQ) + both = funcinst(f, IXOR, 'w', both, mkintconst(1)); + return funcinst(f, ICNEW, 'w', both, mkintconst(0)); + } + default: + error(&tok.loc, "this operator is not yet supported for complex types"); + return NULL; + } + return storecomplex(f, t, re, im); + } + switch (e->op) { + case TMUL: + op = IMUL; + break; + case TDIV: + op = !(t->prop & PROPINT) || t->u.arith.issigned ? IDIV : IUDIV; + break; + case TMOD: + op = t->u.arith.issigned ? IREM : IUREM; + break; + case TADD: + op = IADD; + break; + case TSUB: + op = ISUB; + break; + case TSHL: + op = ISHL; + break; + case TSHR: + op = t->u.arith.issigned ? ISAR : ISHR; + break; + case TBOR: + op = IOR; + break; + case TBAND: + op = IAND; + break; + case TXOR: + op = IXOR; + break; + case TLESS: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICLTS : t->u.arith.issigned ? ICSLTW : ICULTW; + else + op = t->prop & PROPFLOAT ? ICLTD : t->u.arith.issigned ? ICSLTL : ICULTL; + break; + case TGREATER: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICGTS : t->u.arith.issigned ? ICSGTW : ICUGTW; + else + op = t->prop & PROPFLOAT ? ICGTD : t->u.arith.issigned ? ICSGTL : ICUGTL; + break; + case TLEQ: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICLES : t->u.arith.issigned ? ICSLEW : ICULEW; + else + op = t->prop & PROPFLOAT ? ICLED : t->u.arith.issigned ? ICSLEL : ICULEL; + break; + case TGEQ: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICGES : t->u.arith.issigned ? ICSGEW : ICUGEW; + else + op = t->prop & PROPFLOAT ? ICGED : t->u.arith.issigned ? ICSGEL : ICUGEL; + break; + case TEQL: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICEQS : ICEQW; + else + op = t->prop & PROPFLOAT ? ICEQD : ICEQL; + break; + case TNEQ: + if (t->size <= 4) + op = t->prop & PROPFLOAT ? ICNES : ICNEW; + else + op = t->prop & PROPFLOAT ? ICNED : ICNEL; + break; + } + if (op == INONE) + fatal( + "internal error; unimplemented binary " + "expression" + ); + v = funcinst(f, op, qbetype(e->type).base, l, r); + if (t->kind == TYPEBITINT) + v = funcbits(f, t, v, (struct bitfield){0}); + return v; + case EXPRCOND: + b[0] = mkblock("cond_true"); + b[1] = mkblock("cond_false"); + b[2] = mkblock("cond_join"); + + v = funcbranch(f, e->base, b[0], b[1]); + + funclabel(f, b[0]); + if (e->u.cond.t != e->base) + v = funcexpr(f, e->u.cond.t); + b[2]->phi.val[0] = convert(f, e->type, e->u.cond.t->type, v); + b[2]->phi.blk[0] = f->end; + funcjmp(f, b[2]); + + funclabel(f, b[1]); + v = funcexpr(f, e->u.cond.f); + b[2]->phi.val[1] = convert(f, e->type, e->u.cond.f->type, v); + b[2]->phi.blk[1] = f->end; + + funclabel(f, b[2]); + if (e->type == &typevoid) + return NULL; + functemp(f, &b[2]->phi.res); + b[2]->phi.class = qbetype(e->type).base; + return &b[2]->phi.res; + case EXPRASSIGN: + r = funcexpr(f, e->u.assign.r); + if (e->u.assign.l->kind == EXPRTEMP) { + e->u.assign.l->u.temp = r; + } else { + lval = funclval(f, e->u.assign.l); + r = funcstore(f, e->u.assign.l->type, e->u.assign.l->qual, lval, r); + } + return r; + case EXPRCOMMA: + for (e = e->base; e->next; e = e->next) + funcexpr(f, e); + return funcexpr(f, e); + case EXPRBUILTIN: + switch (e->u.builtin.kind) { + case BUILTINVASTART: + l = funcexpr(f, e->base); + funcinst(f, IVASTART, 0, l, NULL); + break; + case BUILTINVAARG: + if (e->toeval) + funcexpr(f, e->toeval); + /* https:// todo.sr.ht/~mcf/cproc/52 */ + if (!(e->type->prop & PROPSCALAR)) + error( + &tok.loc, + "va_arg with non-scalar type " + "is not yet supported" + ); + l = funcexpr(f, e->base); + return funcinst(f, IVAARG, qbetype(e->type).base, l, NULL); + case BUILTINALLOCA: + l = funcexpr(f, e->base); + return funcinst(f, IALLOC16, ptrclass, l, NULL); + case BUILTINUNREACHABLE: + funchlt(f); + return NULL; + case BUILTINATOMICLOAD: + t = e->base->type->base; + l = funcexpr(f, e->base); + fn = mkatomicfn(t, "__atomic_load"); + v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); + funcinst(f, IARG, ptrclass, l, NULL); + return v; + case BUILTINATOMICSTORE: + t = e->base->type->base; + l = funcexpr(f, e->base); + r = funcexpr(f, e->u.builtin.val); + fn = mkatomicfn(t, "__atomic_store"); + funcinst(f, ICALL, 0, fn, NULL); + funcinst(f, IARG, ptrclass, l, NULL); + funcinst(f, IARG, qbetype(t).base, r, NULL); + return NULL; + case BUILTINATOMICEXCHANGE: + t = e->base->type->base; + l = funcexpr(f, e->base); + r = funcexpr(f, e->u.builtin.val); + fn = mkatomicfn(t, "__atomic_exchange"); + v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); + funcinst(f, IARG, ptrclass, l, NULL); + funcinst(f, IARG, qbetype(t).base, r, NULL); + return v; + case BUILTINATOMICCOMPAREEXCHANGE: + t = e->base->type->base; + l = funcexpr(f, e->base); + v2 = funcexpr(f, e->u.builtin.val2); + r = funcexpr(f, e->u.builtin.val); + fn = mkatomicfn(t, "__atomic_compare_exchange"); + v = funcinst(f, ICALL, qbetype(e->type).base, fn, NULL); + funcinst(f, IARG, ptrclass, l, NULL); + funcinst(f, IARG, ptrclass, v2, NULL); + funcinst(f, IARG, qbetype(t).base, r, NULL); + return v; + case BUILTINATOMICFETCHADD: + case BUILTINATOMICFETCHSUB: + case BUILTINATOMICFETCHAND: + case BUILTINATOMICFETCHOR: + case BUILTINATOMICFETCHXOR: + t = e->base->type->base; + l = funcexpr(f, e->base); + r = funcexpr(f, e->u.builtin.val); + switch (e->u.builtin.kind) { + case BUILTINATOMICFETCHADD: + fn = mkatomicfn(t, "__atomic_fetch_add"); + break; + case BUILTINATOMICFETCHSUB: + fn = mkatomicfn(t, "__atomic_fetch_sub"); + break; + case BUILTINATOMICFETCHAND: + fn = mkatomicfn(t, "__atomic_fetch_and"); + break; + case BUILTINATOMICFETCHOR: fn = mkatomicfn(t, "__atomic_fetch_or"); break; + default: fn = mkatomicfn(t, "__atomic_fetch_xor"); break; + } + v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); + funcinst(f, IARG, ptrclass, l, NULL); + funcinst(f, IARG, qbetype(t).base, r, NULL); + return v; + default: + fatal("internal error: unimplemented builtin"); + } + return NULL; + case EXPRTEMP: + assert(e->u.temp); + return e->u.temp; + case EXPRSIZEOF: + t = e->u.szof.type; + assert(t->kind == TYPEARRAY); + calcvla(f, t); + /* if the sizeof operand has VLA type, we must evaluate it */ + if (e->base) + funcexpr(f, e->base); + return t->u.array.size; + } + fatal("unimplemented expression %d", e->kind); + return NULL; +} + +static void +zero( + struct func *func, + struct value *addr, + int align, + unsigned long long offset, + unsigned long long end +) +{ + static const enum instkind store[] = { + [1] = ISTOREB, + [2] = ISTOREH, + [4] = ISTOREW, + [8] = ISTOREL, + }; + static struct value z = {.kind = VALUE_INTCONST}; + struct value *tmp; + int a = 1; + + while (offset < end) { + if ((align - (offset & align - 1)) & a) { + tmp = offset ? funcinst(func, IADD, ptrclass, addr, mkintconst(offset)) : addr; + funcinst(func, store[a], 0, &z, tmp); + offset += a; + } + if (a < align) + a <<= 1; + } +} + +void +funcinit(struct func *func, struct decl *d, struct init *init, bool hasinit) +{ + struct lvalue dst; + struct value *src, *v; + unsigned long long offset = 0, max = 0; + size_t i, w; + + funcalloc(func, d); + if (!hasinit) + return; + for (; init; init = init->next) { + zero(func, d->value, d->type->align, offset, init->start); + dst.bits = init->bits; + if (init->expr->kind == EXPRSTRING) { + w = init->expr->type->base->size; + for (i = 0; i < init->expr->u.string.size && i * w < init->end - init->start; ++i) { + v = mkintconst(init->start + i * w); + dst.addr = funcinst(func, IADD, ptrclass, d->value, v); + switch (w) { + case 1: + v = mkintconst(((unsigned char *)init->expr->u.string.data)[i]); + break; + case 2: + v = mkintconst(((uint_least16_t *)init->expr->u.string.data)[i]); + break; + case 4: + v = mkintconst(((uint_least32_t *)init->expr->u.string.data)[i]); + break; + } + funcstore(func, init->expr->type->base, QUALNONE, dst, v); + } + offset = init->start + i * w; + } else { + if (offset < init->end && (dst.bits.before || dst.bits.after)) + zero(func, d->value, d->type->align, offset, init->end); + dst.addr = d->value; + /* + * qbe's memopt does not eliminate the store for ptr + 0, + * so only emit the add if the offset is non-zero + */ + if (init->start > 0) + dst.addr = funcinst(func, IADD, ptrclass, dst.addr, mkintconst(init->start)); + src = funcexpr(func, init->expr); + funcstore(func, init->expr->type, QUALNONE, dst, src); + offset = init->end; + } + if (max < offset) + max = offset; + } + zero(func, d->value, d->type->align, max, d->type->size); +} + +static void +casesearch( + struct func *f, + int class, + struct value *v, + struct switchcase *c, + struct block *defaultlabel, + unsigned long long min, + unsigned long long max +) +{ + struct value *res, *key; + struct block *label[3]; + + if (!c) { + funcjmp(f, defaultlabel); + return; + } + if (min == max) { + funcjmp(f, c->body); + return; + } + label[0] = mkblock("switch_ne"); + label[1] = mkblock("switch_lt"); + label[2] = mkblock("switch_gt"); + + key = mkintconst(c->node.key); + res = funcinst(f, class == 'w' ? ICEQW : ICEQL, 'w', v, key); + funcjnz(f, res, NULL, c->body, label[0]); + funclabel(f, label[0]); + res = funcinst(f, class == 'w' ? ICULTW : ICULTL, 'w', v, key); + funcjnz(f, res, NULL, label[1], label[2]); + funclabel(f, label[1]); + casesearch(f, class, v, c->node.child[0], defaultlabel, min, c->node.key - 1); + funclabel(f, label[2]); + casesearch(f, class, v, c->node.child[1], defaultlabel, c->node.key + 1, max); +} + +void +funcswitch(struct func *f, struct value *v, struct switchcases *c, struct block *defaultlabel) +{ + casesearch(f, qbetype(c->type).base, v, c->root, defaultlabel, 0, -1); +} + +/* emit */ + +static void +emitname(struct value *v) +{ + static const char sigil[] = { + [VALUE_TEMP] = '%', + [VALUE_GLOBAL] = '$', + [VALUE_TYPE] = ':', + [VALUE_LABEL] = '@', + }; + int kind; + + kind = v->kind & 0xf; + if (kind >= countof(sigil) || !sigil[kind]) + fatal("invalid value"); + putchar(sigil[kind]); + if (kind == VALUE_GLOBAL && v->id) + fputs(".L", stdout); + if (v->kind & VALUE_QUOTE) + putchar('"'); + if (v->u.name) + fputs(v->u.name, stdout); + if (v->kind & VALUE_QUOTE) + putchar('"'); + if (v->id) + printf(".%u", v->id); +} + +static void +emitvalue(struct value *v) +{ + switch (v->kind & 0xf) { + case VALUE_INTCONST: + printf("%llu", v->u.i); + break; + case VALUE_FLTCONST: + printf("s_%.17g", v->u.f); + break; + case VALUE_DBLCONST: + printf("d_%.17g", v->u.f); + break; + case VALUE_GLOBAL: + if (v->kind & VALUE_EXTERN) + fputs("extern ", stdout); + if (v->kind & VALUE_THREAD) + fputs("thread ", stdout); + /* fallthrough */ + default: + emitname(v); + break; + } +} + +static void +emitclass(int class, struct value *v) +{ + if (v && v->kind == VALUE_TYPE) + emitname(v); + else if (class) + putchar(class); + else + fatal("type has no QBE representation"); +} + +static unsigned emittypeid; + +/* declares a synthetic two-word aggregate type for a value this + * compiler represents as memory (an address) but qbe has no native + * type for, __int128 (two 'l' words) and complex (two 's' or 'd' + * words) so far. once qbe sees the declaration, its own aggregate-type + * abi lowering classifies parameters and return values per the real + * system v abi (register pair or stack/memory as the fields dictate) + * exactly the way it already does for a real two-word struct, so + * neither caller needs any abi classification code of its own */ +static void +emitpairtype(struct type *t, const char *name, char class) +{ + t->value = xmalloc(sizeof(*t->value)); + t->value->kind = VALUE_TYPE; + t->value->u.name = name; + t->value->id = ++emittypeid; + fputs("type ", stdout); + emitname(t->value); + printf(" = { %c, %c }\n", class, class); +} + +/* XXX: need to consider _alignas on struct members */ +static void +emittype(struct type *t) +{ + struct member *m, *other; + struct type *sub; + unsigned long long off; + + if (t->value + || t->kind != TYPESTRUCT && t->kind != TYPEUNION && t->kind != TYPEINT128 + && t->kind != TYPECOMPLEX) + return; + if (t->kind == TYPEINT128) { + emitpairtype(t, t->u.arith.issigned ? "i128" : "u128", 'l'); + return; + } + if (t->kind == TYPECOMPLEX) { + emitpairtype(t, t->base == &typefloat ? "cfloat" : "cdouble", qbetype(t->base).base); + return; + } + t->value = xmalloc(sizeof(*t->value)); + t->value->kind = VALUE_TYPE; + t->value->u.name = t->u.structunion.tag; + t->value->id = ++emittypeid; + for (m = t->u.structunion.members; m; m = m->next) { + for (sub = m->type; sub->kind == TYPEARRAY; sub = sub->base) + ; + emittype(sub); + } + fputs("type ", stdout); + emitname(t->value); + if (t == targ->typevalist) { + printf(" = align %d { %llu }\n", t->align, t->size); + return; + } + fputs(" = { ", stdout); + for (m = t->u.structunion.members, off = 0; m;) { + if (t->kind == TYPESTRUCT) { + /* look for a subsequent member with a larger storage + * unit */ + for (other = m->next; other; other = other->next) { + if (other->offset >= ALIGNUP(m->offset + 1, 8)) + break; + if (other->offset <= m->offset) + m = other; + } + off = m->offset + m->type->size; + } else { + fputs("{ ", stdout); + } + for (sub = m->type; sub->kind == TYPEARRAY; sub = sub->base) + ; + emitclass(qbetype(sub).data, sub->value); + if (m->type->size > sub->size) + printf(" %llu", m->type->size / sub->size); + if (t->kind == TYPESTRUCT) { + fputs(", ", stdout); + /* skip subsequent members contained within the same + * storage unit */ + do + m = m->next; + while (m && m->offset < off); + } else { + fputs(" } ", stdout); + m = m->next; + } + } + puts("}"); +} + +static struct inst ** +emitinst(struct inst **instp, struct inst **instend) +{ + int op, first; + struct inst *inst = *instp; + + putchar('\t'); + assert(inst->kind < countof(instname)); + if (inst->res.kind) { + emitvalue(&inst->res); + fputs(" =", stdout); + emitclass(inst->class, inst->arg[1]); + putchar(' '); + } + fputs(instname[inst->kind], stdout); + putchar(' '); + emitvalue(inst->arg[0]); + ++instp; + op = inst->kind; + switch (op) { + case ICALL: + putchar('('); + for (first = 1; instp != instend; ++instp) { + inst = *instp; + if (inst->kind == IVARARG) { + fputs(", ...", stdout); + continue; + } + if (inst->kind != IARG) + break; + if (first) + first = 0; + else + fputs(", ", stdout); + emitclass(inst->class, inst->arg[1]); + putchar(' '); + emitvalue(inst->arg[0]); + } + putchar(')'); + break; + default: + if (inst->arg[1]) { + fputs(", ", stdout); + emitvalue(inst->arg[1]); + } + } + putchar('\n'); + return instp; +} + +static void +emitjump(struct jump *j) +{ + switch (j->kind) { + case JUMP_NONE: + break; + case JUMP_RET: + fputs("\tret", stdout); + if (j->arg) { + fputc(' ', stdout); + emitvalue(j->arg); + } + putchar('\n'); + break; + case JUMP_JMP: + fputs("\tjmp ", stdout); + emitname(&j->blk[0]->label); + putchar('\n'); + break; + case JUMP_JNZ: + fputs("\tjnz ", stdout); + emitvalue(j->arg); + fputs(", ", stdout); + emitname(&j->blk[0]->label); + fputs(", ", stdout); + emitname(&j->blk[1]->label); + putchar('\n'); + break; + case JUMP_HLT: + fputs("\thlt\n", stdout); + break; + default: + assert(0); + } +} + +void +emitfunc(struct func *f, bool global) +{ + struct block *b; + struct inst **inst, **instend; + struct decl *p; + struct value *v; + + if (f->end->jump.kind == JUMP_NONE) { + v = NULL; + /* implicitly return 0 from main if we reach the end of the + * function */ + if (strcmp(f->name, "main") == 0 && f->type->base == &typeint) + v = mkintconst(0); + funcret(f, v); + } + if (global) + puts("export"); + fputs("function ", stdout); + if (f->type->base != &typevoid) { + emitclass(qbetype(f->type->base).base, f->type->base->value); + putchar(' '); + } + emitname(f->decl->value); + putchar('('); + for (p = f->type->u.func.params, v = f->paramtemps; p; p = p->next, ++v) { + if (p != f->type->u.func.params) + fputs(", ", stdout); + emitclass(qbetype(p->type).base, p->type->value); + putchar(' '); + emitname(v); + } + if (f->type->u.func.isvararg) { + if (f->type->u.func.params) + fputs(", ", stdout); + fputs("...", stdout); + } + puts(") {"); + for (b = f->start; b; b = b->next) { + emitname(&b->label); + putchar('\n'); + if (b->phi.res.kind) { + putchar('\t'); + emitvalue(&b->phi.res); + printf(" =%c phi ", b->phi.class); + emitname(&b->phi.blk[0]->label); + putchar(' '); + emitvalue(b->phi.val[0]); + fputs(", ", stdout); + emitname(&b->phi.blk[1]->label); + putchar(' '); + emitvalue(b->phi.val[1]); + putchar('\n'); + } + instend = (struct inst **)((char *)b->insts.val + b->insts.len); + for (inst = b->insts.val; inst != instend;) + inst = emitinst(inst, instend); + emitjump(&b->jump); + } + puts("}"); +} + +static void +dataitem(struct expr *expr, unsigned long long size) +{ + struct decl *decl; + size_t i, w; + unsigned c; + + switch (expr->kind) { + case EXPRUNARY: + if (expr->op != TBAND) + fatal("not a address expr"); + expr = expr->base; + if (expr->kind != EXPRIDENT) + error(&tok.loc, "initializer is not a constant expression"); + decl = expr->u.ident.decl; + if (decl->kind == DECLOBJECT && decl->u.obj.storage != SDSTATIC) + error(&tok.loc, "initializer is not a constant expression"); + emitname(decl->value); + break; + case EXPRBINARY: + if (expr->op != TADD || expr->u.binary.l->kind != EXPRUNARY + || expr->u.binary.r->kind != EXPRCONST) + error(&tok.loc, "initializer is not a constant expression"); + dataitem(expr->u.binary.l, 0); + fputs(" + ", stdout); + dataitem(expr->u.binary.r, 0); + break; + case EXPRCONST: + if (expr->type->prop & PROPFLOAT) + printf("%c_%.17g", expr->type->size == 4 ? 's' : 'd', expr->u.constant.f); + else + printf("%llu", expr->u.constant.u); + break; + case EXPRSTRING: + w = expr->type->base->size; + if (w == 1) { + fputc('"', stdout); + for (i = 0; i < expr->u.string.size && i < size; ++i) { + c = ((unsigned char *)expr->u.string.data)[i]; + if (isprint(c) && c != '"' && c != '\\') + putchar(c); + else + printf("\\%03o", c); + } + fputc('"', stdout); + } else { + for (i = 0; i < expr->u.string.size && i * w < size; ++i) { + switch (w) { + case 2: + printf("%" PRIuLEAST16 " ", ((uint_least16_t *)expr->u.string.data)[i]); + break; + case 4: + printf("%" PRIuLEAST32 " ", ((uint_least32_t *)expr->u.string.data)[i]); + break; + default: + assert(0); + } + } + } + if (i * w < size) + printf(", z %llu", size - (unsigned long long)i * w); + break; + default: + error(&tok.loc, "initializer is not a constant expression"); + } +} + +void +emitdata(struct decl *d, struct init *init) +{ + struct init *cur; + struct type *t; + unsigned long long offset = 0, start, end, bits = 0; + size_t i; + int align; + + align = d->u.obj.align; + for (cur = init; cur; cur = cur->next) + cur->expr = eval(cur->expr); + if (d->u.obj.storage == SDTHREAD) + fputs("thread ", stdout); + if (d->linkage == LINKEXTERN) + fputs("export ", stdout); + fputs("data ", stdout); + emitname(d->value); + printf(" = align %d { ", align); + + while (init) { + cur = init; + while ((init = init->next) + && init->start * 8 + init->bits.before < cur->end * 8 - cur->bits.after) { + /* + * XXX: currently, if multiple union members are + * initialized, these assertions may not hold + (https:// todo.sr.ht/~mcf/cproc/38) + */ + assert(cur->expr->kind == EXPRSTRING); + assert(init->expr->kind == EXPRCONST); + i = (init->start - cur->start) / cur->expr->type->base->size; + switch (cur->expr->type->base->size) { + case 1: + ((unsigned char *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; + break; + case 2: + ((uint_least16_t *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; + break; + case 4: + ((uint_least32_t *)cur->expr->u.string.data)[i] = init->expr->u.constant.u; + break; + } + } + start = cur->start + cur->bits.before / 8; + end = cur->end - (cur->bits.after + 7) / 8; + if (offset < start && bits) { + printf("b %u, ", (unsigned)bits); /* unfinished byte from previous + * bit-field */ + ++offset; + bits = 0; + } + if (offset < start) + printf("z %llu, ", start - offset); + if (cur->bits.before || cur->bits.after) { + /* little-endian target specific */ + assert(cur->expr->type->prop & PROPINT); + assert(cur->expr->kind == EXPRCONST); + bits |= cur->expr->u.constant.u << cur->bits.before % 8; + for (offset = start; offset < end; ++offset, bits >>= 8) + printf("b %u, ", (unsigned)bits & 0xff); + /* + * clear the upper `after` bits in the last byte, + * or all bits when `after` is 0 (we ended on a + * byte boundary) + */ + bits &= 0x7f >> (cur->bits.after + 7) % 8; + } else { + t = cur->expr->type; + if (t->kind == TYPEARRAY) + t = t->base; + printf("%c ", qbetype(t).data); + dataitem(cur->expr, cur->end - cur->start); + fputs(", ", stdout); + } + offset = end; + } + if (bits) { + printf("b %u, ", (unsigned)bits); + ++offset; + } + assert(offset <= d->type->size); + if (offset < d->type->size) + printf("z %llu ", d->type->size - offset); + puts("}"); +} diff --git a/cmd/dev/cc/scan.c b/cmd/dev/cc/scan.c @@ -0,0 +1,530 @@ +#include <ctype.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +struct buffer { + unsigned char *str; + size_t len, cap; +}; + +struct scanner { + int chr; + bool usebuf; + bool sawspace; + FILE *file; + struct location loc; + struct buffer buf; + struct scanner *next; +}; + +static struct scanner *scanner; + +static void +bufadd(struct buffer *b, int c) +{ + if (b->len >= b->cap) { + b->cap = b->cap ? b->cap * 2 : 1 << 8; + b->str = xreallocarray(b->str, b->cap, 1); + } + b->str[b->len++] = c; +} + +static char * +bufget(struct buffer *b) +{ + char *s; + + bufadd(b, '\0'); + s = xmalloc(b->len); + memcpy(s, b->str, b->len); + b->len = 0; + + return s; +} + +static void +nextchar(struct scanner *s) +{ + int c; + + if (s->usebuf) + bufadd(&s->buf, s->chr); + for (;;) { + s->chr = getc(s->file); + if (s->chr == '\n') { + ++s->loc.line, s->loc.col = 0; + break; + } + ++s->loc.col; + if (s->chr != '\\') + break; + c = getc(s->file); + if (c != '\n') { + ungetc(c, s->file); + break; + } + ++s->loc.line, s->loc.col = 0; + } +} + +static int +op2(struct scanner *s, int t1, int t2) +{ + nextchar(s); + if (s->chr != '=') + return t1; + nextchar(s); + return t2; +} + +static int +op3(struct scanner *s, int t1, int t2, int t3) +{ + int c; + + c = s->chr; + nextchar(s); + if (s->chr == '=') { + nextchar(s); + return t2; + } + if (s->chr != c) + return t1; + nextchar(s); + return t3; +} + +static int +op4(struct scanner *s, int t1, int t2, int t3, int t4) +{ + int c; + + c = s->chr; + nextchar(s); + if (s->chr == '=') { + nextchar(s); + return t2; + } + if (s->chr != c) + return t1; + nextchar(s); + if (s->chr != '=') + return t3; + nextchar(s); + return t4; +} + +static int +ident(struct scanner *s) +{ + int tok; + + s->usebuf = true; + while (isalnum(s->chr) || s->chr == '_') + nextchar(s); + tok = tokenget(s->buf.str, s->buf.len); + s->usebuf = false; + s->buf.len = 0; + return tok; +} + +static int +isodigit(int c) +{ + return (unsigned)c - '0' < 8; +} + +static enum tokenkind +number(struct scanner *s) +{ + bool allowsign = false; + + s->usebuf = true; + for (;;) { + nextchar(s); + switch (s->chr) { + case 'e': + case 'E': + case 'p': + case 'P': + allowsign = true; + break; + case '+': + case '-': + if (!allowsign) + goto done; + break; + case '.': + allowsign = false; + break; + case '\'': + nextchar(s); + --s->buf.len; /* ignore separator */ + /* fallthrough */ + default: + if (!isalnum(s->chr) && s->chr != '_') + goto done; + allowsign = false; + } + } +done: + return TNUMBER; +} + +static void +escape(struct scanner *s) +{ + nextchar(s); + if (s->chr == 'x') { + nextchar(s); + if (!isxdigit(s->chr)) + error(&s->loc, "invalid hexadecimal escape sequence"); + do + nextchar(s); + while (isxdigit(s->chr)); + } else if (isodigit(s->chr)) { + nextchar(s); + if (isodigit(s->chr)) { + nextchar(s); + if (isodigit(s->chr)) + nextchar(s); + } + } else if (strchr("'\"?\\abfnrtv", s->chr)) { + nextchar(s); + } else { + error(&s->loc, "invalid escape sequence"); + } +} + +static enum tokenkind +charconst(struct scanner *s) +{ + s->usebuf = true; + nextchar(s); + for (;;) { + switch (s->chr) { + case '\\': + escape(s); + break; + case '\'': + nextchar(s); + return TCHARCONST; + case '\n': + error(&s->loc, "newline in character constant"); + case EOF: + error(&s->loc, "EOF in character constant"); + default: + nextchar(s); + break; + } + } +} + +static int +stringlit(struct scanner *s) +{ + s->usebuf = true; + nextchar(s); + for (;;) { + switch (s->chr) { + case '\\': + escape(s); + break; + case '"': + nextchar(s); + return TSTRINGLIT; + case '\n': + error(&s->loc, "newline in string literal"); + case EOF: + error(&s->loc, "EOF in string literal"); + default: + nextchar(s); + break; + } + } +} + +static bool +comment(struct scanner *s) +{ + int last; + + switch (s->chr) { + case '/': /* c++-style comment */ + do + nextchar(s); + while (s->chr != '\n' && s->chr != EOF); + break; + case '*': /* c-style comment */ + nextchar(s); + do { + last = s->chr; + nextchar(s); + if (s->chr == EOF) + error(&s->loc, "EOF in comment"); + } while (last != '*' || s->chr != '/'); + nextchar(s); + break; + default: + return false; + } + s->sawspace = true; + return true; +} + +static int +scankind(struct scanner *s, struct location *loc) +{ + enum tokenkind tok; + struct location oldloc; + +again: + *loc = s->loc; + switch (s->chr) { + case ' ': + case '\t': + case '\f': + case '\v': + s->sawspace = true; + nextchar(s); + goto again; + case '!': + return op2(s, TLNOT, TNEQ); + case '"': + return stringlit(s); + case '#': + nextchar(s); + if (s->chr != '#') + return THASH; + nextchar(s); + return THASHHASH; + case '%': + return op2(s, TMOD, TMODASSIGN); + case '&': + return op3(s, TBAND, TBANDASSIGN, TLAND); + case '\'': + return charconst(s); + case '*': + return op2(s, TMUL, TMULASSIGN); + case '+': + return op3(s, TADD, TADDASSIGN, TINC); + case '-': + tok = op3(s, TSUB, TSUBASSIGN, TDEC); + if (tok != TSUB || s->chr != '>') + return tok; + nextchar(s); + return TARROW; + case '/': + tok = op2(s, TDIV, TDIVASSIGN); + if (tok == TDIV && comment(s)) + goto again; + return tok; + case '<': + return op4(s, TLESS, TLEQ, TSHL, TSHLASSIGN); + case '=': + return op2(s, TASSIGN, TEQL); + case '>': + return op4(s, TGREATER, TGEQ, TSHR, TSHRASSIGN); + case '^': + return op2(s, TXOR, TXORASSIGN); + case '|': + return op3(s, TBOR, TBORASSIGN, TLOR); + case '\n': + nextchar(s); + return TNEWLINE; + case '[': + nextchar(s); + return TLBRACK; + case ']': + nextchar(s); + return TRBRACK; + case '(': + nextchar(s); + return TLPAREN; + case ')': + nextchar(s); + return TRPAREN; + case '{': + nextchar(s); + return TLBRACE; + case '}': + nextchar(s); + return TRBRACE; + case '.': + nextchar(s); + if (isdigit(s->chr)) { + bufadd(&s->buf, '.'); + return number(s); + } + if (s->chr != '.') + return TPERIOD; + oldloc = s->loc; + nextchar(s); + if (s->chr != '.') { + ungetc(s->chr, s->file); + s->loc = oldloc; + s->chr = '.'; + return TPERIOD; + } + nextchar(s); + return TELLIPSIS; + case '~': + nextchar(s); + return TBNOT; + case '?': + nextchar(s); + return TQUESTION; + case ':': + nextchar(s); + if (s->chr != ':') + return TCOLON; + nextchar(s); + return TCOLONCOLON; + case ';': + nextchar(s); + return TSEMICOLON; + case ',': + nextchar(s); + return TCOMMA; + case 'L': + case 'U': + case 'u': + s->usebuf = true; + nextchar(s); + if (s->buf.str[0] == 'u' && s->chr == '8') + nextchar(s); + switch (s->chr) { + case '\'': + return charconst(s); + case '"': + return stringlit(s); + } + return ident(s); + case EOF: + return TEOF; + default: + if (isdigit(s->chr)) + return number(s); + if (isalpha(s->chr) || s->chr == '_') + return ident(s); + s->usebuf = true; + nextchar(s); + return TOTHER; + } +} + +void +scanfrom(const char *name, FILE *file) +{ + struct scanner *s; + + s = xmalloc(sizeof(*s)); + s->file = file; + s->buf.str = NULL; + s->buf.len = 0; + s->buf.cap = 0; + s->usebuf = false; + s->loc.file = name; + s->loc.line = 1; + s->loc.col = 0; + s->next = scanner; + if (file) + nextchar(s); + scanner = s; +} + +void +scanopen(void) +{ + if (!scanner->file) { + scanner->file = fopen(scanner->loc.file, "r"); + if (!scanner->file) + fatal("open %s:", scanner->loc.file); + nextchar(scanner); + } +} + +void +scansetloc(struct location loc) +{ + scanner->loc = loc; +} + +char * +scaninclude(bool *is_system) +{ + struct scanner *s = scanner; + int delim; + char *name; + + while (s->chr == ' ' || s->chr == '\t' || s->chr == '\f' || s->chr == '\v') + nextchar(s); + + if (s->chr == '"') { + delim = '"'; + *is_system = false; + } else if (s->chr == '<') { + delim = '>'; + *is_system = true; + } else { + return NULL; + } + + nextchar(s); + s->usebuf = true; + while (s->chr != delim && s->chr != '\n' && s->chr != EOF) { + nextchar(s); + } + s->usebuf = false; + + if (s->chr != delim) { + free(s->buf.str); + s->buf.len = 0; + s->buf.cap = 0; + return NULL; + } + + nextchar(s); + + name = xmalloc(s->buf.len + 1); + memcpy(name, s->buf.str, s->buf.len); + name[s->buf.len] = '\0'; + s->buf.len = 0; + + return name; +} + +static void +scanclose(void) +{ + fclose(scanner->file); + free(scanner->buf.str); + free(scanner); +} + +void +scan(struct token *t) +{ + scanner->sawspace = false; + for (;;) { + t->kind = scankind(scanner, &t->loc); + if (t->kind != TEOF || !scanner->next) + break; + scanclose(); + scanner = scanner->next; + scanopen(); + } + if (scanner->usebuf) { + t->lit = bufget(&scanner->buf); + scanner->usebuf = false; + } else { + t->lit = NULL; + } + t->space = scanner->sawspace; + t->hide = false; +} diff --git a/cmd/dev/cc/scope.c b/cmd/dev/cc/scope.c @@ -0,0 +1,135 @@ +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +struct scope filescope; + +void +scopeinit(void) +{ + static struct decl builtins[] = { + {.name = "__builtin_alloca", .kind = DECLBUILTIN, .u.builtin = BUILTINALLOCA}, + {.name = "__builtin_constant_p", .kind = DECLBUILTIN, .u.builtin = BUILTINCONSTANTP}, + {.name = "__builtin_expect", .kind = DECLBUILTIN, .u.builtin = BUILTINEXPECT}, + {.name = "__builtin_inff", .kind = DECLBUILTIN, .u.builtin = BUILTININFF}, + {.name = "__builtin_nanf", .kind = DECLBUILTIN, .u.builtin = BUILTINNANF}, + {.name = "__builtin_offsetof", .kind = DECLBUILTIN, .u.builtin = BUILTINOFFSETOF}, + {.name = "__builtin_types_compatible_p", + .kind = DECLBUILTIN, + .u.builtin = BUILTINTYPESCOMPATIBLEP}, + {.name = "__builtin_unreachable", .kind = DECLBUILTIN, .u.builtin = BUILTINUNREACHABLE}, + {.name = "__builtin_va_arg", .kind = DECLBUILTIN, .u.builtin = BUILTINVAARG}, + {.name = "__builtin_va_copy", .kind = DECLBUILTIN, .u.builtin = BUILTINVACOPY}, + {.name = "__builtin_va_end", .kind = DECLBUILTIN, .u.builtin = BUILTINVAEND}, + {.name = "__builtin_va_start", .kind = DECLBUILTIN, .u.builtin = BUILTINVASTART}, + {.name = "__builtin_c23_va_start", .kind = DECLBUILTIN, .u.builtin = BUILTINVASTART}, + {.name = "__atomic_load_n", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICLOAD}, + {.name = "__atomic_store_n", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICSTORE}, + {.name = "__atomic_exchange_n", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICEXCHANGE}, + {.name = "__atomic_compare_exchange_n", + .kind = DECLBUILTIN, + .u.builtin = BUILTINATOMICCOMPAREEXCHANGE}, + {.name = "__atomic_fetch_add", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICFETCHADD}, + {.name = "__atomic_fetch_sub", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICFETCHSUB}, + {.name = "__atomic_fetch_and", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICFETCHAND}, + {.name = "__atomic_fetch_or", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICFETCHOR}, + {.name = "__atomic_fetch_xor", .kind = DECLBUILTIN, .u.builtin = BUILTINATOMICFETCHXOR}, + }; + static struct decl valist; + struct decl *d; + + for (d = builtins; d < builtins + countof(builtins); ++d) + scopeputdecl(&filescope, d); + valist.name = "__builtin_va_list"; + valist.kind = DECLTYPE; + valist.type = targ->typevalist; + scopeputdecl(&filescope, &valist); +} + +struct scope * +mkscope(struct scope *parent) +{ + struct scope *s; + + s = xmalloc(sizeof(*s)); + s->decls.len = 0; + s->tags.len = 0; + s->breaklabel = parent->breaklabel; + s->continuelabel = parent->continuelabel; + s->switchcases = parent->switchcases; + s->parent = parent; + + return s; +} + +struct scope * +delscope(struct scope *s) +{ + struct scope *parent = s->parent; + + if (s->decls.len) + mapfree(&s->decls, NULL); + if (s->tags.len) + mapfree(&s->tags, NULL); + free(s); + + return parent; +} + +struct decl * +scopegetdecl(struct scope *s, const char *name, bool recurse) +{ + struct decl *d; + struct mapkey k; + + mapkey(&k, name, strlen(name)); + do { + d = s->decls.len ? mapget(&s->decls, &k, NULL) : NULL; + s = s->parent; + } while (!d && s && recurse); + + return d; +} + +struct type * +scopegettag(struct scope *s, const char *name, bool recurse) +{ + struct type *t; + struct mapkey k; + + mapkey(&k, name, strlen(name)); + do { + t = s->tags.len ? mapget(&s->tags, &k, NULL) : NULL; + s = s->parent; + } while (!t && s && recurse); + + return t; +} + +void +scopeputdecl(struct scope *s, struct decl *d) +{ + struct mapkey k; + size_t i; + + if (!s->decls.len) + mapinit(&s->decls, 32); + mapkey(&k, d->name, strlen(d->name)); + mapput(&s->decls, &k, &i); + s->decls.vals[i].p = d; +} + +void +scopeputtag(struct scope *s, const char *name, struct type *t) +{ + struct mapkey k; + size_t i; + + if (!s->tags.len) + mapinit(&s->tags, 32); + mapkey(&k, name, strlen(name)); + mapput(&s->tags, &k, &i); + s->tags.vals[i].p = t; +} diff --git a/cmd/dev/cc/stmt.c b/cmd/dev/cc/stmt.c @@ -0,0 +1,328 @@ +#include <assert.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +/* 6.8.1 labeled statements */ +static bool +label(struct func *f, struct scope *s) +{ + char *name; + struct gotolabel *g; + struct block *b; + unsigned long long i; + + attr(NULL, 0); + switch (tok.kind) { + case TCASE: + next(); + if (!s->switchcases) + error(&tok.loc, "'case' label must be in switch"); + b = mkblock("switch_case"); + funclabel(f, b); + i = intconstexpr(s, true); + switchcase(s->switchcases, i, b); + expect(TCOLON, "after case expression"); + break; + case TDEFAULT: + next(); + if (!s->switchcases) + error(&tok.loc, "'default' label must be in switch"); + if (s->switchcases->defaultlabel) + error(&tok.loc, "multiple 'default' labels"); + expect(TCOLON, "after 'default'"); + s->switchcases->defaultlabel = mkblock("switch_default"); + funclabel(f, s->switchcases->defaultlabel); + break; + default: + if (tok.kind < TIDENT) + return false; + name = tokenstr(tok.kind); + if (!peek(TCOLON)) + return false; + g = funcgoto(f, name); + g->defined = true; + funclabel(f, g->label); + break; + } + return true; +} + +static void +labelstmt(struct func *f, struct scope *s) +{ + while (label(f, s)) + ; + stmt(f, s); +} + +/* 6.8 statements and blocks */ +void +stmt(struct func *f, struct scope *s) +{ + char *name; + struct expr *e; + struct type *t; + struct value *v; + struct block *b[4]; + struct switchcases swtch; + + attr(NULL, 0); + switch (tok.kind) { + /* 6.8.2 compound statement */ + case TLBRACE: + next(); + s = mkscope(s); + while (tok.kind != TRBRACE) { + if (!label(f, s) && !decl(s, f)) + stmt(f, s); + } + s = delscope(s); + next(); + break; + + /* 6.8.3 expression statement */ + case TSEMICOLON: + next(); + break; + default: + e = expr(s); + v = funcexpr(f, e); + delexpr(e); + expect(TSEMICOLON, "after expression statement"); + break; + + /* 6.8.4 selection statement */ + case TIF: + next(); + s = mkscope(s); + expect(TLPAREN, "after 'if'"); + e = expr(s); + t = e->type; + if (!(t->prop & PROPSCALAR)) + error( + &tok.loc, + "controlling expression of if " + "statement must have scalar type" + ); + b[0] = mkblock("if_true"); + b[1] = mkblock("if_false"); + funcbranch(f, e, b[0], b[1]); + delexpr(e); + expect(TRPAREN, "after expression"); + + funclabel(f, b[0]); + s = mkscope(s); + labelstmt(f, s); + s = delscope(s); + + if (consume(TELSE)) { + b[2] = mkblock("if_join"); + funcjmp(f, b[2]); + funclabel(f, b[1]); + s = mkscope(s); + labelstmt(f, s); + s = delscope(s); + funclabel(f, b[2]); + } else { + funclabel(f, b[1]); + } + s = delscope(s); + break; + case TSWITCH: + next(); + + s = mkscope(s); + expect(TLPAREN, "after 'switch'"); + e = expr(s); + expect(TRPAREN, "after expression"); + + if (!(e->type->prop & PROPINT)) + error( + &tok.loc, + "controlling expression of switch " + "statement must have integer type" + ); + e = exprpromote(e); + + swtch.root = NULL; + swtch.type = e->type; + swtch.defaultlabel = NULL; + + b[0] = mkblock("switch_cond"); + b[1] = mkblock("switch_join"); + + v = funcexpr(f, e); + funcjmp(f, b[0]); + s = mkscope(s); + s->breaklabel = b[1]; + s->switchcases = &swtch; + labelstmt(f, s); + funcjmp(f, b[1]); + + funclabel(f, b[0]); + funcswitch(f, v, &swtch, swtch.defaultlabel ? swtch.defaultlabel : b[1]); + s = delscope(s); + + funclabel(f, b[1]); + s = delscope(s); + break; + + /* 6.8.5 iteration statements */ + case TWHILE: + next(); + s = mkscope(s); + expect(TLPAREN, "after 'while'"); + e = expr(s); + t = e->type; + if (!(t->prop & PROPSCALAR)) + error( + &tok.loc, + "controlling expression of loop must " + "have scalar type" + ); + expect(TRPAREN, "after expression"); + + b[0] = mkblock("while_cond"); + b[1] = mkblock("while_body"); + b[2] = mkblock("while_join"); + + funclabel(f, b[0]); + funcbranch(f, e, b[1], b[2]); + funclabel(f, b[1]); + s = mkscope(s); + s->continuelabel = b[0]; + s->breaklabel = b[2]; + labelstmt(f, s); + s = delscope(s); + funcjmp(f, b[0]); + funclabel(f, b[2]); + s = delscope(s); + break; + case TDO: + next(); + + b[0] = mkblock("do_body"); + b[1] = mkblock("do_cond"); + b[2] = mkblock("do_join"); + + s = mkscope(s); + s = mkscope(s); + s->continuelabel = b[1]; + s->breaklabel = b[2]; + funclabel(f, b[0]); + labelstmt(f, s); + s = delscope(s); + + expect(TWHILE, "after 'do' statement"); + expect(TLPAREN, "after 'while'"); + funclabel(f, b[1]); + e = expr(s); + t = e->type; + if (!(t->prop & PROPSCALAR)) + error( + &tok.loc, + "controlling expression of loop must " + "have scalar type" + ); + expect(TRPAREN, "after expression"); + + funcbranch(f, e, b[0], b[2]); + funclabel(f, b[2]); + s = delscope(s); + expect(TSEMICOLON, "after 'do' statement"); + break; + case TFOR: + next(); + expect(TLPAREN, "after 'for'"); + s = mkscope(s); + if (!decl(s, f)) { + if (tok.kind != TSEMICOLON) { + e = expr(s); + funcexpr(f, e); + delexpr(e); + } + expect(TSEMICOLON, NULL); + } + + b[0] = mkblock("for_cond"); + b[1] = mkblock("for_body"); + b[2] = mkblock("for_cont"); + b[3] = mkblock("for_join"); + + funclabel(f, b[0]); + if (tok.kind != TSEMICOLON) { + e = expr(s); + t = e->type; + if (!(t->prop & PROPSCALAR)) + error( + &tok.loc, + "controlling expression of " + "loop must have scalar type" + ); + funcbranch(f, e, b[1], b[3]); + delexpr(e); + } + expect(TSEMICOLON, NULL); + e = tok.kind == TRPAREN ? NULL : expr(s); + expect(TRPAREN, NULL); + + funclabel(f, b[1]); + s = mkscope(s); + s->breaklabel = b[3]; + s->continuelabel = b[2]; + labelstmt(f, s); + s = delscope(s); + + funclabel(f, b[2]); + if (e) { + funcexpr(f, e); + delexpr(e); + } + funcjmp(f, b[0]); + funclabel(f, b[3]); + s = delscope(s); + break; + + /* 6.8.6 jump statements */ + case TGOTO: + next(); + name = expect(TIDENT, "after 'goto'"); + funcjmp(f, funcgoto(f, name)->label); + expect(TSEMICOLON, "after 'goto' statement"); + break; + case TCONTINUE: + next(); + if (!s->continuelabel) + error(&tok.loc, "'continue' statement must be in loop"); + funcjmp(f, s->continuelabel); + expect(TSEMICOLON, "after 'continue' statement"); + break; + case TBREAK: + next(); + if (!s->breaklabel) + error(&tok.loc, "'break' statement must be in loop or switch"); + funcjmp(f, s->breaklabel); + expect(TSEMICOLON, "after 'break' statement"); + break; + case TRETURN: + next(); + t = functype(f); + if (t->base != &typevoid) { + e = exprassign(expr(s), t->base); + v = funcexpr(f, e); + delexpr(e); + } else { + v = NULL; + } + funcret(f, v); + expect(TSEMICOLON, "after 'return' statement"); + break; + + case T__ASM__: + error(&tok.loc, "inline assembly is not yet supported"); + } +} diff --git a/cmd/dev/cc/targ.c b/cmd/dev/cc/targ.c @@ -0,0 +1,70 @@ +#include <stdbool.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +const struct target *targ; + +static const struct target alltargs[] = { + { + .name = "x86_64-sysv", + .typewchar = &typeint, + .typevalist = + &(struct type){ + .kind = TYPEARRAY, + .align = 8, + .size = 24, + .base = + &(struct type){ + .kind = TYPESTRUCT, + .align = 8, + .size = 24, + }, + }, + .signedchar = 1, + }, + { + .name = "aarch64", + .typevalist = + &(struct type){ + .kind = TYPESTRUCT, + .align = 8, + .size = 32, + .u.structunion.tag = "va_list", + }, + .typewchar = &typeuint, + }, + { + .name = "riscv64", + .typevalist = + &(struct type){ + .kind = TYPEPOINTER, + .prop = PROPSCALAR, + .align = 8, + .size = 8, + .base = &typevoid, + }, + .typewchar = &typeint, + }, +}; + +void +targinit(const char *name) +{ + size_t i; + enum typequal qual; + + if (!name) { + /* TODO: provide a way to set this default */ + targ = &alltargs[0]; + } + for (i = 0; i < countof(alltargs) && !targ; ++i) { + if (strcmp(alltargs[i].name, name) == 0) + targ = &alltargs[i]; + } + if (!targ) + fatal("unknown target '%s'", name); + typechar.u.arith.issigned = targ->signedchar; + qual = QUALNONE; + typeadjvalist = typeadjust(targ->typevalist, &qual); +} diff --git a/cmd/dev/cc/token.c b/cmd/dev/cc/token.c @@ -0,0 +1,191 @@ +#include <assert.h> +#include <ctype.h> +#include <limits.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +struct token tok; +static struct map tokmap; /* maps string to token */ +static struct array tokstr; /* maps token to string */ + +void +tokeninit(void) +{ + static const unsigned char strings[] = +#define TOKEN(t, s) s "\0" +#include "tokens.h" +#undef TOKEN + ; + const unsigned char *s, *e; + struct mapkey k; + size_t l, i; + + mapinit(&tokmap, 1024); + for (s = strings, e = strings + sizeof strings - 1; s != e; s += l + 1) { + l = strlen((char *)s); + if (l) { + mapkey(&k, s, l); + mapput(&tokmap, &k, &i); + tokmap.vals[i].i = tokstr.len / sizeof(void *); + arrayaddptr(&tokstr, (void *)s); + } else { + arrayaddptr(&tokstr, NULL); + } + } +} + +int +tokenget(const void *str, size_t len) +{ + static char *pos, *end; + struct mapkey k; + size_t i; + char *buf; + + mapkey(&k, str, len); + if (mapput(&tokmap, &k, &i)) { + if (len > 8192) + fatal("token is too long"); + if (INT_MAX < tokstr.len / sizeof(void *)) + fatal("too many tokens"); + if (!pos || end - pos < len + 1) { + buf = xmalloc(8192); + pos = buf; + end = buf + 8192; + } + memcpy(pos, str, len); + pos[len] = '\0'; + tokmap.keys[i].str = pos; + tokmap.vals[i].i = tokstr.len / sizeof(void *); + arrayaddptr(&tokstr, pos); + pos += len + 1; + } + return tokmap.vals[i].i; +} + +char * +tokenstr(enum tokenkind kind) +{ + assert(kind < tokstr.len / sizeof(void *)); + return ((void **)tokstr.val)[kind]; +} + +void +tokenprint(const struct token *t, FILE *f) +{ + const char *str; + + if (t->space) + fputc(' ', f); + switch (t->kind) { + case TNUMBER: + case TCHARCONST: + case TSTRINGLIT: + str = t->lit; + break; + case TNEWLINE: + str = "\n"; + break; + case TEOF: + return; + default: + str = tokenstr(t->kind); + } + if (!str) + fatal("cannot print token %d", t->kind); + fputs(str, f); +} + +static void +tokendesc(char *buf, size_t len, enum tokenkind kind, const char *lit) +{ + const char *class; + bool quote = true; + + assert(kind < tokstr.len / sizeof(void *)); + switch (kind) { + case TEOF: + class = "EOF"; + break; + case TNUMBER: + class = "number"; + quote = true; + break; + case TCHARCONST: + class = "character"; + quote = false; + break; + case TSTRINGLIT: + class = "string"; + quote = false; + break; + case TNEWLINE: + class = "newline"; + break; + case TOTHER: + class = NULL; + break; + default: + if (kind >= TIDENT) + class = "identifier", quote = true; + else + class = NULL; + lit = ((void **)tokstr.val)[kind]; + } + if (class && lit) + snprintf(buf, len, quote ? "%s '%s'" : "%s %s", class, lit); + else if (class) + snprintf(buf, len, "%s", class); + else if (kind == TOTHER && !isprint(*(unsigned char *)lit)) + snprintf(buf, len, "<U+%04x>", *(unsigned char *)lit); + else if (lit) + snprintf(buf, len, "'%s'", lit); + else + snprintf(buf, len, "<unknown>"); +} + +char * +tokencheck(const struct token *t, enum tokenkind kind, const char *msg) +{ + char want[64], got[64]; + + if (kind == TPPIDENT || kind == TIDENT) { + if (t->kind < kind) { + strcpy(want, "identifier"); + goto err; + } + return tokenstr(t->kind); + } + if (t->kind != kind && (kind != TIDENT || t->kind < TIDENT)) { + tokendesc(want, sizeof(want), kind, NULL); + err: + tokendesc(got, sizeof(got), t->kind, t->lit); + error(&t->loc, "expected %s %s, saw %s", want, msg, got); + } + return t->lit; +} + +void +diagloc(const struct location *loc) +{ + fprintf(stderr, "%s:%zu:%zu: ", loc->file, loc->line, loc->col); +} + +void +error(const struct location *loc, const char *fmt, ...) +{ + va_list ap; + + diagloc(loc); + fputs("error: ", stderr); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + putc('\n', stderr); + exit(1); +} diff --git a/cmd/dev/cc/tokens.h b/cmd/dev/cc/tokens.h @@ -0,0 +1,152 @@ +TOKEN(TNONE, ) + +TOKEN(TEOF, ) +TOKEN(TNEWLINE, ) +TOKEN(TOTHER, ) + +TOKEN(TNUMBER, ) +TOKEN(TCHARCONST, ) +TOKEN(TSTRINGLIT, ) + +/* punctuators */ +TOKEN(TLBRACK, "[") +TOKEN(TRBRACK, "]") +TOKEN(TLPAREN, "(") +TOKEN(TRPAREN, ")") +TOKEN(TLBRACE, "{") +TOKEN(TRBRACE, "}") +TOKEN(TPERIOD, ".") +TOKEN(TARROW, "->") +TOKEN(TINC, "++") +TOKEN(TDEC, "--") +TOKEN(TBAND, "&") +TOKEN(TMUL, "*") +TOKEN(TADD, "+") +TOKEN(TSUB, "-") +TOKEN(TBNOT, "~") +TOKEN(TLNOT, "!") +TOKEN(TDIV, "/") +TOKEN(TMOD, "%") +TOKEN(TSHL, "<<") +TOKEN(TSHR, ">>") +TOKEN(TLESS, "<") +TOKEN(TGREATER, ">") +TOKEN(TLEQ, "<=") +TOKEN(TGEQ, ">=") +TOKEN(TEQL, "==") +TOKEN(TNEQ, "!=") +TOKEN(TXOR, "^") +TOKEN(TBOR, "|") +TOKEN(TLAND, "&&") +TOKEN(TLOR, "||") +TOKEN(TQUESTION, "?") +TOKEN(TCOLON, ":") +TOKEN(TCOLONCOLON, "::") +TOKEN(TSEMICOLON, ";") +TOKEN(TELLIPSIS, "...") +TOKEN(TASSIGN, "=") +TOKEN(TMULASSIGN, "*=") +TOKEN(TDIVASSIGN, "/=") +TOKEN(TMODASSIGN, "%=") +TOKEN(TADDASSIGN, "+=") +TOKEN(TSUBASSIGN, "-=") +TOKEN(TSHLASSIGN, "<<=") +TOKEN(TSHRASSIGN, ">>=") +TOKEN(TBANDASSIGN, "&=") +TOKEN(TXORASSIGN, "^=") +TOKEN(TBORASSIGN, "|=") +TOKEN(TCOMMA, ",") +TOKEN(THASH, "#") +TOKEN(THASHHASH, "##") + +/* keyword */ +TOKEN(TALIGNAS, "alignas") +TOKEN(TALIGNOF, "alignof") +TOKEN(TAUTO, "auto") +TOKEN(TBOOL, "bool") +TOKEN(TBREAK, "break") +TOKEN(TCASE, "case") +TOKEN(TCHAR, "char") +TOKEN(TCONST, "const") +TOKEN(TCONSTEXPR, "constexpr") +TOKEN(TCONTINUE, "continue") +TOKEN(TDEFAULT, "default") +TOKEN(TDO, "do") +TOKEN(TDOUBLE, "double") +TOKEN(TELSE, "else") +TOKEN(TENUM, "enum") +TOKEN(TEXTERN, "extern") +TOKEN(TFALSE, "false") +TOKEN(TFLOAT, "float") +TOKEN(TFOR, "for") +TOKEN(TGOTO, "goto") +TOKEN(TIF, "if") +TOKEN(TINLINE, "inline") +TOKEN(TINT, "int") +TOKEN(TLONG, "long") +TOKEN(TNULLPTR, "nullptr") +TOKEN(TREGISTER, "register") +TOKEN(TRESTRICT, "restrict") +TOKEN(TRETURN, "return") +TOKEN(TSHORT, "short") +TOKEN(TSIGNED, "signed") +TOKEN(TSIZEOF, "sizeof") +TOKEN(TSTATIC, "static") +TOKEN(TSTATIC_ASSERT, "static_assert") +TOKEN(TSTRUCT, "struct") +TOKEN(TSWITCH, "switch") +TOKEN(TTHREAD_LOCAL, "thread_local") +TOKEN(TTRUE, "true") +TOKEN(TTYPEDEF, "typedef") +TOKEN(TTYPEOF, "typeof") +TOKEN(TTYPEOF_UNQUAL, "typeof_unqual") +TOKEN(TUNION, "union") +TOKEN(TUNSIGNED, "unsigned") +TOKEN(TVOID, "void") +TOKEN(TVOLATILE, "volatile") +TOKEN(TWHILE, "while") +TOKEN(T_ATOMIC, "_Atomic") +TOKEN(T_BITINT, "_BitInt") +TOKEN(T_COMPLEX, "_Complex") +TOKEN(T_DECIMAL128, "_Decimal128") +TOKEN(T_DECIMAL32, "_Decimal32") +TOKEN(T_DECIMAL64, "_Decimal64") +TOKEN(T_GENERIC, "_Generic") +TOKEN(T_INT128, "__int128") +TOKEN(T_IMAGINARY, "_Imaginary") +TOKEN(T_NORETURN, "_Noreturn") +TOKEN(T__ALIGNOF__, "__alignof__") +TOKEN(T__ASM__, "__asm__") +TOKEN(T__ATTRIBUTE__, "__attribute__") + +/* other identifiers */ +TOKEN(TDEFINE, "define") +TOKEN(TELIF, "elif") +TOKEN(TENDIF, "endif") +TOKEN(TERROR, "error") +TOKEN(TIFDEF, "ifdef") +TOKEN(TIFNDEF, "ifndef") +TOKEN(TINCLUDE, "include") +TOKEN(TLINE, "line") +TOKEN(TPRAGMA, "pragma") +TOKEN(TUNDEF, "undef") +TOKEN(TWARNING, "warning") +TOKEN(T__VA_ARGS__, "__VA_ARGS__") + +/* keyword aliases */ +TOKEN(ALIAS_ALIGNAS, "_Alignas") +TOKEN(ALIAS_ALIGNOF, "_Alignof") +TOKEN(ALIAS_BOOL, "_Bool") +TOKEN(ALIAS_STATIC_ASSERT, "_Static_assert") +TOKEN(ALIAS_THREAD_LOCAL, "_Thread_local") + +/* compatibility keyword aliases */ +TOKEN(ALIAS__INLINE, "__inline") /* XXX: what needs this? */ +TOKEN(ALIAS__INLINE__, "__inline__") /* XXX: what needs this? */ +TOKEN(ALIAS__SIGNED, "__signed") /* XXX: what needs this? */ +TOKEN(ALIAS__SIGNED__, "__signed__") /* XXX: what needs this? */ +TOKEN(ALIAS__THREAD, "__thread") +TOKEN(ALIAS__TYPEOF, "__typeof") +TOKEN(ALIAS__TYPEOF__, "__typeof__") +TOKEN(ALIAS__VOLATILE__, "__volatile__") /* XXX: what needs this? */ +TOKEN(ALIAS__ASM, "__asm") diff --git a/cmd/dev/cc/tree.c b/cmd/dev/cc/tree.c @@ -0,0 +1,98 @@ +#include <assert.h> +#include <stdbool.h> +#include <stddef.h> +#include "util.h" + +#define MAXH (sizeof(void *) * 8 * 3 / 2) + +static inline int +height(struct treenode *n) +{ + return n ? n->height : 0; +} + +static int +rot(void **p, struct treenode *x, int dir /* deeper side */) +{ + struct treenode *y = x->child[dir]; + struct treenode *z = y->child[!dir]; + int hx = x->height; + int hz = height(z); + if (hz > height(y->child[dir])) { + /* + * x + * / \ dir z + * a y / \ + * / \ --> x y + * z d /| |\ + * / \ a b c d + * b c + */ + x->child[dir] = z->child[!dir]; + y->child[!dir] = z->child[dir]; + z->child[!dir] = x; + z->child[dir] = y; + x->height = hz; + y->height = hz; + z->height = hz + 1; + } else { + /* + * x y + * / \ / \ + * a y --> x d + * / \ / \ + * z d a z + */ + x->child[dir] = z; + y->child[!dir] = x; + x->height = hz + 1; + y->height = hz + 2; + z = y; + } + *p = z; + return z->height - hx; +} + +/* balance *p, return 0 if height is unchanged */ +static int +balance(void **p) +{ + struct treenode *n = *p; + int h0 = height(n->child[0]); + int h1 = height(n->child[1]); + if (h0 - h1 + 1u < 3u) { + int old = n->height; + n->height = h0 < h1 ? h1 + 1 : h0 + 1; + return n->height - old; + } + return rot(p, n, h0 < h1); +} + +void * +treeinsert(void **root, unsigned long long key, size_t sz) +{ + void **a[MAXH]; + struct treenode *n = *root; + int i = 0; + + a[i++] = root; + while (n) { + if (key == n->key) { + n->new = false; + return n; + } + a[i++] = &n->child[key > n->key]; + n = n->child[key > n->key]; + } + assert(sz > sizeof(*n)); + n = xmalloc(sz); + n->key = key; + n->child[0] = n->child[1] = 0; + n->height = 1; + /* insert new node, rebalance ancestors */ + *a[--i] = n; + while (i && balance(a[--i])) + ; + n->new = true; + return n; +} diff --git a/cmd/dev/cc/type.c b/cmd/dev/cc/type.c @@ -0,0 +1,343 @@ +#include <assert.h> +#include <stdbool.h> +#include <stddef.h> +#include <string.h> +#include "util.h" +#include "cc.h" + +#define INTTYPE(k, n, s, p) \ + { \ + .kind = k, \ + .size = n, \ + .align = n, \ + .u.arith = {.issigned = s, .width = n * 8}, \ + .prop = PROPSCALAR | PROPARITH | PROPREAL | PROPINT | p, \ + } +#define FLTTYPE(k, n) \ + { \ + .kind = k, \ + .size = n, \ + .align = n, \ + .prop = PROPSCALAR | PROPARITH | PROPREAL | PROPFLOAT, \ + } + +struct type typevoid = {.kind = TYPEVOID, .incomplete = true}; + +struct type typebool = INTTYPE(TYPEBOOL, 1, false, 0); + +struct type typechar = INTTYPE(TYPECHAR, 1, true, PROPCHAR); +struct type typeschar = INTTYPE(TYPECHAR, 1, true, PROPCHAR); +struct type typeuchar = INTTYPE(TYPECHAR, 1, false, PROPCHAR); + +struct type typeshort = INTTYPE(TYPESHORT, 2, true, 0); +struct type typeushort = INTTYPE(TYPESHORT, 2, false, 0); + +struct type typeint = INTTYPE(TYPEINT, 4, true, 0); +struct type typeuint = INTTYPE(TYPEINT, 4, false, 0); + +struct type typelong = INTTYPE(TYPELONG, 8, true, 0); +struct type typeulong = INTTYPE(TYPELONG, 8, false, 0); + +struct type typellong = INTTYPE(TYPELLONG, 8, true, 0); +struct type typeullong = INTTYPE(TYPELLONG, 8, false, 0); + +/* unlike every other arithmetic type, this one never lives in a + * single qbe scalar register: qbe has no 128-bit type at all, so a + * value of this type always lives in memory instead, the same way a + * struct does (funcload/funcstore route TYPEINT128 through the same + * address-is-the-value path as TYPESTRUCT/TYPEUNION, see qbe.c). that + * also means it inherits struct/union parameter and return-value + * passing for free, without needing any abi work of its own */ +struct type typeint128 = INTTYPE(TYPEINT128, 16, true, 0); +struct type typeuint128 = INTTYPE(TYPEINT128, 16, false, 0); + +struct type typefloat = FLTTYPE(TYPEFLOAT, 4); +struct type typedouble = FLTTYPE(TYPEDOUBLE, 8); +struct type typeldouble = FLTTYPE(TYPELDOUBLE, 16); + +/* a complex value is its real and imaginary parts back to back, and + * like __int128 always lives in memory rather than a qbe register of + * its own (funcload/funcstore route it the same way, see qbe.c). not + * an arithmetic type in this compiler's own sense (no PROPARITH): it + * never reaches the usual arithmetic conversions expr.c's commonreal + * applies to real operands, +, -, and unary - between two operands of + * the same complex type are special-cased directly instead */ +struct type typefloatcomplex = {.kind = TYPECOMPLEX, .size = 8, .align = 4, .base = &typefloat}; +struct type typedoublecomplex = {.kind = TYPECOMPLEX, .size = 16, .align = 8, .base = &typedouble}; + +struct type typenullptr = {.kind = TYPENULLPTR, .size = 8, .align = 8, .prop = PROPSCALAR}; + +struct type *typeadjvalist; + +struct type * +mktype(enum typekind kind, enum typeprop prop) +{ + struct type *t; + + t = xmalloc(sizeof(*t)); + t->kind = kind; + t->prop = prop; + t->value = NULL; + t->incomplete = false; + + return t; +} + +struct type * +mkpointertype(struct type *base, enum typequal qual) +{ + struct type *t; + + t = mktype(TYPEPOINTER, PROPSCALAR); + t->base = base; + t->qual = qual; + t->size = 8; + t->align = 8; + if (base) + t->prop |= base->prop & PROPVM; + + return t; +} + +struct type * +mkarraytype(struct type *base, enum typequal qual, unsigned long long len) +{ + struct type *t; + + t = mktype(TYPEARRAY, 0); + t->base = base; + t->qual = qual; + t->u.array.length = NULL; + t->u.array.ptrqual = QUALNONE; + t->incomplete = !len; + if (t->base) { + t->align = t->base->align; + t->size = t->base->size * len; /* XXX: overflow? */ + } + + return t; +} + +struct type * +mkbitinttype(int width, bool sign) +{ + struct type *t; + + t = mktype(TYPEBITINT, PROPSCALAR | PROPARITH | PROPREAL | PROPINT); + t->u.arith.issigned = sign; + t->u.arith.width = width; + if (width < 1 + sign || width > 64) + error(&tok.loc, "invalid %s _BitInt width %d", sign ? "signed" : "unsigned", width); + + /* calculate byte size */ + t->size = 1; + while (t->size * 8 < width) + t->size <<= 1; + t->align = t->size; + + return t; +} + +/* + * we define type rank using the number of bits in the type shifted + * left by 4. the least significant 4 bits are used to establish a + * ranking between integer types with the same width (such as long and + * long long on 64-bit platforms) + */ +static int +typerank(struct type *t) +{ + if (t->kind == TYPEENUM) + t = t->base; + assert(t->prop & PROPINT); + switch (t->kind) { + case TYPEBOOL: + return 0; + case TYPECHAR: + return 0x081; + case TYPESHORT: + return 0x101; + case TYPEINT: + return 0x201; + case TYPELONG: + return t->size << 3 + 4 | 0x1; + case TYPELLONG: + return 0x402; + case TYPEBITINT: + return t->u.arith.width << 4; + case TYPEINT128: + return 128 << 4; + } + fatal("internal error; unhandled integer type"); + return -1; +} + +bool +typecompatible(struct type *t1, struct type *t2) +{ + struct decl *p1, *p2; + struct expr *e1, *e2; + + if (t1 == t2) + return true; + if (t1->kind != t2->kind) { + /* + * enum types are compatible with their underlying + * type, but not with each other (unless they are the + * same type) + */ + return t1->kind == TYPEENUM && t2 == t1->base || t2->kind == TYPEENUM && t1 == t2->base; + } + switch (t1->kind) { + case TYPEBITINT: + return t1->u.arith.width == t2->u.arith.width && t1->u.arith.issigned == t2->u.arith.issigned; + case TYPEPOINTER: + goto derived; + case TYPEARRAY: + if (t1->incomplete || t2->incomplete) + goto derived; + e1 = t1->u.array.length; + e2 = t2->u.array.length; + if (e1 && e2 && e1->kind == EXPRCONST && e2->kind == EXPRCONST + && e1->u.constant.u != e2->u.constant.u) + return false; + goto derived; + case TYPEFUNC: + if (t1->u.func.isvararg != t2->u.func.isvararg) + return false; + for (p1 = t1->u.func.params, p2 = t2->u.func.params; p1 && p2; p1 = p1->next, p2 = p2->next) { + if (!typecompatible(p1->type, p2->type)) + return false; + } + if (p1 || p2) + return false; + goto derived; + derived: + return t1->qual == t2->qual && typecompatible(t1->base, t2->base); + } + return false; +} + +bool +typesame(struct type *t1, struct type *t2) +{ + /* XXX: implement */ + return typecompatible(t1, t2); +} + +struct type * +typecomposite(struct type *t1, struct type *t2) +{ + /* XXX: implement 6.2.7 */ + /* XXX: merge with typecompatible? */ + return t1; +} + +struct type * +typepromote(struct type *t, unsigned width) +{ + if (t == &typefloat) + return &typedouble; + if (t->kind == TYPEBITINT) + return t; + if (t->prop & PROPINT && (typerank(t) <= typerank(&typeint) || width <= typeint.size * 8)) { + if (width == -1) + width = t->size * 8; + return width - t->u.arith.issigned < typeint.size * 8 ? &typeint : &typeuint; + } + return t; +} + +struct type * +typecommonreal(struct type *t1, unsigned w1, struct type *t2, unsigned w2) +{ + struct type *tmp; + + assert(t1->prop & PROPREAL && t2->prop & PROPREAL); + if (t1 == &typeldouble || t2 == &typeldouble) + return &typeldouble; + if (t1 == &typedouble || t2 == &typedouble) + return &typedouble; + if (t1 == &typefloat || t2 == &typefloat) + return &typefloat; + t1 = typepromote(t1, w1); + t2 = typepromote(t2, w2); + if (t1 == t2) + return t1; + if (t1->u.arith.issigned == t2->u.arith.issigned) + return typerank(t1) > typerank(t2) ? t1 : t2; + if (t1->u.arith.issigned) { + tmp = t1; + t1 = t2; + t2 = tmp; + } + /* t1 is unsigned and t2 is signed */ + if (typerank(t1) >= typerank(t2)) + return t1; + /* t1 has a lower rank than t2 */ + if (t1->u.arith.width < t2->u.arith.width) + return t2; + switch (t2->kind) { + case TYPEINT: + return &typeuint; + case TYPELONG: + return &typeulong; + case TYPELLONG: + return &typellong; + } + fatal("internal error; could not find common real type"); + return NULL; +} + +/* function parameter type adjustment (C11 6.7.6.3p7) */ +struct type * +typeadjust(struct type *t, enum typequal *tq) +{ + enum typequal ptrqual; + + switch (t->kind) { + case TYPEARRAY: + ptrqual = t->u.array.ptrqual; + t = mkpointertype(t->base, *tq | t->qual); + *tq = ptrqual; + break; + case TYPEFUNC: + assert(*tq == QUALNONE); + t = mkpointertype(t, QUALNONE); + break; + } + + return t; +} + +struct member * +typemember(struct type *t, const char *name, unsigned long long *offset) +{ + struct member *m, *sub; + + assert(t->kind == TYPESTRUCT || t->kind == TYPEUNION); + for (m = t->u.structunion.members; m; m = m->next) { + if (m->name) { + if (strcmp(m->name, name) == 0) { + *offset += m->offset; + return m; + } + } else { + sub = typemember(m->type, name, offset); + if (sub) { + *offset += m->offset; + return sub; + } + } + } + return NULL; +} + +bool +typehasint(struct type *t, unsigned long long i, bool sign) +{ + assert(t->prop & PROPINT); + if (sign && i >= -1ull << 63) + return t->u.arith.issigned && i >= -1ull << (t->size << 3) - 1; + return i <= 0xffffffffffffffffull >> (8 - t->size << 3) + t->u.arith.issigned; +} diff --git a/cmd/dev/cc/utf.c b/cmd/dev/cc/utf.c @@ -0,0 +1,88 @@ +#include <assert.h> +#include <stddef.h> +#include <stdint.h> +#include "utf.h" + +size_t +utf8enc(unsigned char *s, uint_least32_t c) +{ + if (c < 0x80) { + s[0] = c; + return 1; + } + if (c < 0x800) { + s[0] = 0xc0 | c >> 6; + s[1] = 0x80 | c & 0x3f; + return 2; + } + if (c < 0xd800 || c - 0xe000 < 0x2000) { + s[0] = 0xe0 | c >> 12; + s[1] = 0x80 | c >> 6 & 0x3f; + s[2] = 0x80 | c & 0x3f; + return 3; + } + if (c - 0x10000 < 0x100000) { + s[0] = 0xf0 | c >> 18; + s[1] = 0x80 | c >> 12 & 0x3f; + s[2] = 0x80 | c >> 6 & 0x3f; + s[3] = 0x80 | c & 0x3f; + return 4; + } + assert(0); + return 0; +} + +size_t +utf8dec(uint_least32_t *c, const unsigned char *s, size_t n) +{ + size_t i, l; + unsigned char b; + uint_least32_t x; + + b = s[0]; + if (b < 0x80) { + *c = b; + return 1; + } + if ((b & 0xe0) == 0xc0) { + x = b & 0x1f; + l = 2; + } else if ((b & 0xf0) == 0xe0) { + x = b & 0x0f; + l = 3; + } else if ((b & 0xf8) == 0xf0) { + x = b & 0x07; + l = 4; + } else { + return -1; + } + if (n < l) + return -1; + for (i = 1; i < l; ++i) { + b = *++s; + if ((b & 0xc0) != 0x80) + return -1; + x = x << 6 | b & 0x3f; + } + if (x >= 0x110000 || x - 0xd800 < 0x0200) + return -1; + *c = x; + return l; +} + +size_t +utf16enc(uint_least16_t *s, uint_least32_t c) +{ + if (c < 0xd800 || c - 0xe000 < 0x2000) { + s[0] = c; + return 1; + } + c -= 0x10000; + if (c < 0x100000) { + s[0] = 0xd800 | c >> 10 & 0x3ff; + s[1] = 0xdc00 | c & 0x3ff; + return 2; + } + assert(0); + return 0; +} diff --git a/cmd/dev/cc/utf.h b/cmd/dev/cc/utf.h @@ -0,0 +1,3 @@ +size_t utf8enc(unsigned char *, uint_least32_t); +size_t utf8dec(uint_least32_t *, const unsigned char *, size_t); +size_t utf16enc(uint_least16_t *, uint_least32_t); diff --git a/cmd/dev/cc/util.c b/cmd/dev/cc/util.c @@ -0,0 +1,176 @@ +#include <assert.h> +#include <errno.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "util.h" + +char *argv0; + +static void +vwarn(const char *fmt, va_list ap) +{ + fprintf(stderr, "%s: ", argv0); + vfprintf(stderr, fmt, ap); + if (fmt[0] && fmt[strlen(fmt) - 1] == ':') { + fputc(' ', stderr); + perror(NULL); + } else { + fputc('\n', stderr); + } +} + +void +warn(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vwarn(fmt, ap); + va_end(ap); +} + +void +fatal(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vwarn(fmt, ap); + va_end(ap); + exit(1); +} + +void * +reallocarray(void *buf, size_t n, size_t m) +{ + if (n > 0 && SIZE_MAX / n < m) { + errno = ENOMEM; + return NULL; + } + return realloc(buf, n * m); +} + +void * +xreallocarray(void *buf, size_t n, size_t m) +{ + buf = reallocarray(buf, n, m); + if (!buf && n && m) + fatal("reallocarray:"); + + return buf; +} + +void * +xmalloc(size_t len) +{ + void *buf; + + buf = malloc(len); + if (!buf && len) + fatal("malloc:"); + + return buf; +} + +char * +progname(char *name, char *fallback) +{ + char *slash; + + if (!name) + return fallback; + slash = strrchr(name, '/'); + return slash ? slash + 1 : name; +} + +void * +arrayadd(struct array *a, size_t n) +{ + void *v; + + if (a->cap - a->len < n) { + do { + if (a->cap > SIZE_MAX / 2) { + errno = ENOMEM; + fatal("realloc:"); + } + a->cap = a->cap ? a->cap * 2 : 256; + } while (a->cap - a->len < n); + a->val = realloc(a->val, a->cap); + if (!a->val) + fatal("realloc:"); + } + v = (char *)a->val + a->len; + a->len += n; + + return v; +} + +void +arrayaddptr(struct array *a, void *v) +{ + *(void **)arrayadd(a, sizeof(v)) = v; +} + +void * +arraysetptr(struct array *a, size_t i, void *v) +{ + void *prev, **p, **e; + + if (i >= a->len / sizeof v) { + p = arrayadd(a, (i + 1) * sizeof *p - a->len); + e = arraylast(a, sizeof *p); + for (; p != e; ++p) + *p = NULL; + prev = NULL; + } else { + p = (void **)a->val + i; + prev = *p; + } + *p = v; + return prev; +} + +void * +arraygetptr(struct array *a, size_t i) +{ + if (i >= a->len / sizeof(void *)) + return NULL; + return ((void **)a->val)[i]; +} + +void +arrayaddbuf(struct array *a, const void *src, size_t n) +{ + memcpy(arrayadd(a, n), src, n); +} + +void * +arraylast(struct array *a, size_t n) +{ + if (a->len == 0) + return NULL; + assert(n <= a->len); + return (char *)a->val + a->len - n; +} + +void +listinsert(struct list *list, struct list *new) +{ + new->next = list->next; + new->prev = list; + list->next->prev = new; + list->next = new; +} + +void +listremove(struct list *list) +{ + list->next->prev = list->prev; + list->prev->next = list->next; + list->next = list->prev = NULL; +} diff --git a/cmd/dev/cc/util.h b/cmd/dev/cc/util.h @@ -0,0 +1,86 @@ +#include <stdbool.h> +#include <stddef.h> + +#ifndef noreturn +#if __STDC_VERSION__ >= 202311L +#define noreturn [[noreturn]] +#elif __STDC_VERSION__ >= 201112L +#define noreturn _Noreturn +#else +#define noreturn +#endif +#endif + +struct list { + struct list *prev, *next; +}; + +struct array { + void *val; + size_t len, cap; +}; + +struct treenode { + unsigned long long key; + void *child[2]; + int height; + bool new; /* set by treeinsert if this node was newly allocated */ +}; + +extern char *argv0; + +#ifndef countof +#define countof(a) (sizeof(a) / sizeof((a)[0])) +#endif +#define ALIGNDOWN(x, n) ((x) & -(n)) +#define ALIGNUP(x, n) ALIGNDOWN((x) + (n) - 1, n) + +void warn(const char *, ...); +noreturn void fatal(const char *fmt, ...); + +void *reallocarray(void *, size_t, size_t); +void *xreallocarray(void *, size_t, size_t); +void *xmalloc(size_t); + +char *progname(char *, char *); + +void listinsert(struct list *, struct list *); +void listremove(struct list *); +#define listelement(list, type, member) (type *)((char *)list - offsetof(type, member)) + +void *arrayadd(struct array *, size_t); +void arrayaddptr(struct array *, void *); +void *arraysetptr(struct array *, size_t, void *); +void *arraygetptr(struct array *, size_t); +void arrayaddbuf(struct array *, const void *, size_t); +void *arraylast(struct array *, size_t); +#define arrayforeach(a, m) for (m = (a)->val; m != (void *)((char *)(a)->val + (a)->len); ++m) + +/* map */ + +struct map { + size_t len, cap; + struct mapkey *keys; + union mapval *vals; +}; + +struct mapkey { + unsigned long hash; + const void *str; + size_t len; +}; + +union mapval { + void *p; + int i; +}; + +void mapkey(struct mapkey *, const void *, size_t); +void mapinit(struct map *, size_t); +void mapfree(struct map *, void (*)(void *)); +bool mapput(struct map *, struct mapkey *, size_t *); +void *mapget(struct map *, struct mapkey *, size_t *); + +/* tree */ + +void *treeinsert(void **, unsigned long long, size_t); diff --git a/cmd/dev/configure b/cmd/dev/configure @@ -0,0 +1,339 @@ +#!/bin/sh +# aruu dev toolchain configure +# +# generates three headers: +# config.h architecture and platform for as, ld, libtcutil +# cc/config.h driver configuration (crt files, lib paths, defines) +# version.h version string +# +# crt and runtime files are discovered, not assumed from the libc: +# crt1 crti crtn exist everywhere, crtbegin crtend libgcc only with a +# gcc runtime, so the same script works on musl and glibc + +set -u + +fail() { + echo "configure: $*" >&2 + exit 1 +} + +devdir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) + +normpath() { + ( cd "$1" 2>/dev/null && pwd ) || echo "$1" +} + +rootpath() { + case "$1" in + /) printf '%s' / ;; + *) printf '%s' "${1%/}" ;; + esac +} + +host= +target= +sysroot= +gcclibdir= +CC=${CC:-cc} + +for arg; do + case "$arg" in + --host=*) host=${arg#*=} ;; + --target=*) target=${arg#*=} ;; + --sysroot=*) sysroot=${arg#*=} ;; + --with-gcclibdir=*) gcclibdir=${arg#*=} ;; + CC=*) CC=${arg#*=} ;; + *) fail "unknown option: $arg" ;; + esac +done + +# determine host triplet, prefer an explicit --host, then try the c +# compiler, then fall back to uname so the script works without gcc +if [ -z "$host" ]; then + host=$($CC -dumpmachine 2>/dev/null) || true +fi +if [ -z "$host" ]; then + m=$(uname -m) + s=$(uname -s | tr '[:upper:]' '[:lower:]') + case "$s" in + linux) + libc=gnu + [ -f "/lib/ld-musl-$m.so.1" ] && libc=musl + host="$m-pc-linux-$libc" + ;; + *) host="$m-pc-$s" ;; + esac +fi +: "${target:=$host}" + +printf 'host: %s\n' "$host" +printf 'target: %s\n' "$target" + +# map target to architecture constants used by as, ld, libtcutil +case "$target" in +x86_64-*|amd64-*) + tc_arch=1 + machine=EM_X86_64 + ;; +aarch64-*) + tc_arch=2 + machine=EM_AARCH64 + ;; +riscv64-*) + tc_arch=3 + machine=EM_RISCV + ;; +*) fail "unsupported target: $target" ;; +esac + +case "$target" in +*-apple-darwin*) tc_platform=2 ;; +*) tc_platform=1 ;; +esac + +# an explicit sysroot is a search boundary, not a prefix preference +root= +if [ -n "$sysroot" ]; then + root=$(rootpath "$(normpath "$sysroot")") +fi + +# find the libc directory: the first standard path that contains crt1.o +crtdir= +if [ -n "$root" ]; then + for dir in "$root/lib"; do + if [ -f "$dir/crt1.o" ]; then + crtdir=$(normpath "$dir") + break + fi + done +else + printf 'no sysroot: using standalone host runtime paths\n' + for dir in /usr/lib /lib /usr/local/lib; do + if [ -f "$dir/crt1.o" ]; then + crtdir=$(normpath "$dir") + break + fi + done +fi +if [ -z "$crtdir" ]; then + if [ -n "$root" ]; then + fail "cannot find crt1.o inside target sysroot" + fi + fail "cannot find host crt1.o, use --sysroot for an isolated target" +fi +printf 'libc directory: %s\n' "$crtdir" + +# find the gcc runtime directory: glibc systems have one, musl does not, +# and crtbeginT.o is what marks it as usable +if [ -n "$root" ] && [ -n "$gcclibdir" ]; then + if [ "$root" != / ]; then + case "$gcclibdir" in + "$root"/*) ;; + *) fail "--with-gcclibdir escapes --sysroot" ;; + esac + elif [ "${gcclibdir#/}" = "$gcclibdir" ]; then + fail "--with-gcclibdir must name an absolute target-root path" + fi +elif [ -n "$root" ]; then + for dir in "$root"/lib/gcc/*/*/ "$root"/usr/lib/gcc/*/*/; do + if [ -f "${dir}crtbeginT.o" ]; then + gcclibdir=$(normpath "$dir") + break + fi + done +elif [ -z "$gcclibdir" ]; then + for dir in /usr/lib/gcc/*/*/ /usr/local/lib/gcc/*/*/; do + if [ -f "${dir}crtbeginT.o" ]; then + gcclibdir=$(normpath "$dir") + break + fi + done +fi +# validate: only treat gcclibdir as real if crtbeginT.o is there +if [ -z "$gcclibdir" ] || [ ! -f "$gcclibdir/crtbeginT.o" ]; then + gcclibdir= +fi +if [ -n "$gcclibdir" ]; then + printf 'gcc runtime: %s\n' "$gcclibdir" +fi + +# build library search paths +searchpaths=$crtdir +[ -n "$gcclibdir" ] && searchpaths="$searchpaths $gcclibdir" + +linkflags= +for dir in $searchpaths; do + linkflags=$linkflags' "-L", "'$dir'",' +done + +# crt file lists: crt1 crti crtn are standard across libcs, crtbegin and +# crtend come with gcc. libgcc is listed when present and the static +# linker skips unused members, so it is harmless on musl. libc wraps +# libgcc because libgcc_eh needs libc symbols (pthread_cond) and libc +# needs libgcc symbols (unwind) +startfiles='-l", ":crt1.o", "-l", ":crti.o"' +endfiles='-l", "c"' + +if [ -n "$gcclibdir" ] && [ -f "$gcclibdir/crtbeginT.o" ]; then + startfiles=$startfiles', "-l", ":crtbeginT.o"' + + if [ -f "$gcclibdir/libgcc.a" ]; then + endfiles='-l", "c", "-l", "gcc"' + if [ -f "$gcclibdir/libgcc_eh.a" ]; then + endfiles=$endfiles', "-l", "gcc_eh"' + fi + endfiles=$endfiles', "-l", "c"' + fi + + endfiles=$endfiles', "-l", ":crtend.o"' +fi + +endfiles=$endfiles', "-l", ":crtn.o"' + +# fix up leading quote (the string starts with -l, needs ") +startfiles='"'"$startfiles" +endfiles='"'"$endfiles" + +# target-specific defines (architecture, os, data model), not libc-specific: +# the type and feature macros system headers expect from a hosted compiler +defines=' + "-D", "__STDC_ENDIAN_LITTLE__=1234", + "-D", "__STDC_ENDIAN_BIG__=4321", + "-D", "__STDC_ENDIAN_NATIVE__=__STDC_ENDIAN_LITTLE__", + "-D", "__ORDER_LITTLE_ENDIAN__=__STDC_ENDIAN_LITTLE__", + "-D", "__ORDER_BIG_ENDIAN__=__STDC_ENDIAN_BIG__", + "-D", "__BYTE_ORDER__=__STDC_ENDIAN_NATIVE__", + "-D", "__FLT_EVAL_METHOD__=1", + "-D", "__BITINT_MAXWIDTH__=64", +' + +case "$target" in +x86_64-*|amd64-*) + defines=$defines' + "-D", "__x86_64__", + "-D", "__amd64__", + ' + ;; +aarch64-*) + defines=$defines' + "-D", "__aarch64__", + ' + ;; +riscv64-*) + defines=$defines' + "-D", "__riscv", + "-D", "__riscv_i=2001000", + "-D", "__riscv_m=2000000", + "-D", "__riscv_a=2001000", + "-D", "__riscv_f=2002000", + "-D", "__riscv_d=2002000", + "-D", "__riscv_c=2000000", + "-D", "__riscv_xlen=64", + "-D", "__riscv_flen=64", + ' + ;; +esac + +# lp64 data model +defines=$defines' + "-D", "__LP64__", + "-D", "__SIZEOF_LONG__=8", + "-D", "__SIZEOF_POINTER__=8", + "-D", "__SIZEOF_SIZE_T__=8", + "-D", "__SIZEOF_PTRDIFF_T__=8", + + /* standard integer type mappings, needed by system headers */ + "-D", "__SIZE_TYPE__=unsigned long", + "-D", "__PTRDIFF_TYPE__=long", + "-D", "__WCHAR_TYPE__=int", + "-D", "__WINT_TYPE__=unsigned int", + "-D", "__INTMAX_TYPE__=long", + "-D", "__UINTMAX_TYPE__=unsigned long", + + "-D", "__CHAR_BIT__=8", + "-D", "__SCHAR_MAX__=0x7f", + "-D", "__SHRT_MAX__=0x7fff", + "-D", "__INT_MAX__=0x7fffffff", + "-D", "__LONG_MAX__=0x7fffffffffffffffL", + "-D", "__LONG_LONG_MAX__=0x7fffffffffffffffL", +' + +# os defines +case "$target" in +*linux*) + defines=$defines' + "-D", "__linux__", + "-D", "__unix__", + ' + ;; +esac + +if [ -n "$root" ]; then + sysincdirs="$root${ARUU_PATH_INCLUDE:-/include}" +else + sysincdirs="/usr/include /usr/local/include" + case "$target" in + x86_64-*|amd64-*) sysincdirs="$sysincdirs /usr/include/x86_64-linux-gnu" ;; + esac +fi +includeflags= +for dir in $sysincdirs; do + includeflags=$includeflags' "-I", "'$dir'",' + printf 'system include: %s\n' "$dir" +done + +DEFAULT_CPP=$(printf '"%s", ' cpp) +DEFAULT_QBE=$(printf '"%s", ' qbe) +DEFAULT_AS=$(printf '"%s", ' as) +DEFAULT_LD=$(printf '"%s", ' ld) + +# generate config.h +printf 'creating config.h... ' +cat >"$devdir/config.h" <<EOF +/* generated by configure, do not edit */ + +#define TC_ARCH_X64 1 +#define TC_ARCH_AARCH64 2 +#define TC_ARCH_RISCV64 3 + +#define TC_TARGET_ARCH $tc_arch + +#define TC_PLATFORM_POSIX 1 +#define TC_PLATFORM_APPLE 2 + +#define TC_TARGET_PLATFORM $tc_platform + +#define TARGET_POINTER_SIZE 8 + +#define MACHINE_TYPE $machine +EOF +echo done + +# generate cc/config.h +printf 'creating cc/config.h... ' +cat >"$devdir/cc/config.h" <<EOF +/* generated by configure, do not edit */ + +static const char target[] = "$target"; +static const char *const startfiles[] = {$startfiles}; +static const char *const endfiles[] = {$endfiles}; +static const char *const preprocesscmd[] = { + $DEFAULT_CPP"-undef", + $includeflags + "-D", "__STDC_NO_COMPLEX__", + + "-D", "__extension__=", +$defines}; +static const char *const codegencmd[] = {$DEFAULT_QBE}; +static const char *const assemblecmd[] = {$DEFAULT_AS}; +static const char *const linkcmd[] = {$DEFAULT_LD$linkflags}; +EOF +echo done + +# generate version.h +printf 'creating version.h... ' +cat >"$devdir/version.h" <<EOF +/* generated by configure, do not edit */ +#define VERSION "aruu-dev" +EOF +echo done diff --git a/cmd/dev/ld/arch.c b/cmd/dev/ld/arch.c @@ -0,0 +1,27 @@ +/* ld arch dispatch: selects the right relocation backend at runtime + * based on the e_machine field of input object files */ + +#include "ld_arch.h" + +const struct ld_arch_backend * +ld_arch_select(int em_machine) +{ + switch (em_machine) { + case EM_X86_64: + return &ld_arch_x64; + case EM_386: + return &ld_arch_x86; + case EM_ARM: + return &ld_arch_arm; +#ifdef EM_RISCV + case EM_RISCV: + return &ld_arch_riscv; +#endif +#ifdef EM_AARCH64 + case EM_AARCH64: + return &ld_arch_aarch64; +#endif + default: + return NULL; + } +} diff --git a/cmd/dev/ld/arch/aarch64/reloc_aarch64.c b/cmd/dev/ld/arch/aarch64/reloc_aarch64.c @@ -0,0 +1,78 @@ +/* aarch64 relocation handler for the static linker */ + +#include "ld_arch.h" + +void +ld_aarch64_reloc_apply(struct ld_reloc *r) +{ + unsigned long addr; + + switch (r->type) { + case R_AARCH64_NONE: + break; + case R_AARCH64_ABS64: + *r->dst += r->val; + break; + case R_AARCH64_ABS32: + *(unsigned int *)r->dst += r->val; + break; + case R_AARCH64_ABS16: + *(unsigned short *)r->dst += r->val; + break; + case R_AARCH64_PREL64: + *r->dst += r->val - r->addr; + break; + case R_AARCH64_PREL32: + *(unsigned int *)r->dst += r->val - r->addr; + break; + case R_AARCH64_PREL16: + *(unsigned short *)r->dst += r->val - r->addr; + break; + case R_AARCH64_ADR_PREL_PG_HI21: { + /* adrp: page offset, clear low 12 bits */ + long page = (r->val & ~0xfffUL) - (r->addr & ~0xfffUL); + unsigned int *insn = (unsigned int *)r->dst; + *insn = + (*insn & 0x9f00001f) | ((page & 0x3000) << (29 - 12)) | (((page >> 14) & 0x7fff) << 5); + } break; + case R_AARCH64_LDST8_ABS_LO12_NC: + case R_AARCH64_ADD_ABS_LO12_NC: { + unsigned int *insn = (unsigned int *)r->dst; + *insn = (*insn & 0xffc003ff) | ((r->val & 0xfff) << 10); + } break; + case R_AARCH64_LDST16_ABS_LO12_NC: { + unsigned int *insn = (unsigned int *)r->dst; + *insn = (*insn & 0xffc003ff) | (((r->val >> 1) & 0xfff) << 10); + } break; + case R_AARCH64_LDST32_ABS_LO12_NC: { + unsigned int *insn = (unsigned int *)r->dst; + *insn = (*insn & 0xffc003ff) | (((r->val >> 2) & 0xfff) << 10); + } break; + case R_AARCH64_LDST64_ABS_LO12_NC: { + unsigned int *insn = (unsigned int *)r->dst; + *insn = (*insn & 0xffc003ff) | (((r->val >> 3) & 0xfff) << 10); + } break; + case R_AARCH64_JUMP26: + case R_AARCH64_CALL26: { + /* b/bl: 26-bit immediate, word-aligned */ + long off = (r->val - r->addr) >> 2; + unsigned int *insn = (unsigned int *)r->dst; + *insn = (*insn & 0xfc000000) | (off & 0x03ffffff); + } break; + default: + die("ld: unknown aarch64 relocation type"); + } +} + +static int +ld_aarch64_is_got_rel(unsigned int type) +{ + (void)type; + return 0; +} + +const struct ld_arch_backend ld_arch_aarch64 = { + .em_machine = EM_AARCH64, + .reloc_apply = ld_aarch64_reloc_apply, + .is_got_rel = ld_aarch64_is_got_rel, +}; diff --git a/cmd/dev/ld/arch/arm/reloc_arm.c b/cmd/dev/ld/arch/arm/reloc_arm.c @@ -0,0 +1,42 @@ +/* arm (32-bit) relocation handler for the static linker */ + +#include "ld_arch.h" + +void +ld_arm_reloc_apply(struct ld_reloc *r) +{ + unsigned long addr; + + switch (r->type) { + case R_ARM_NONE: + break; + case R_ARM_ABS16: + *(unsigned short *)r->dst += r->val; + break; + case R_ARM_ABS32: + *(unsigned int *)r->dst += r->val; + break; + case R_ARM_REL32: + case R_ARM_PLT32: + *(unsigned int *)r->dst += r->val - r->addr; + break; + case R_ARM_PC24: + *r->dst = (*r->dst & 0xff000000) | ((*r->dst + ((r->val - r->addr) >> 2)) & 0x00ffffff); + break; + default: + die("ld: unknown arm relocation type"); + } +} + +static int +ld_arm_is_got_rel(unsigned int type) +{ + (void)type; + return 0; +} + +const struct ld_arch_backend ld_arch_arm = { + .em_machine = EM_ARM, + .reloc_apply = ld_arm_reloc_apply, + .is_got_rel = ld_arm_is_got_rel, +}; diff --git a/cmd/dev/ld/arch/riscv64/reloc_riscv64.c b/cmd/dev/ld/arch/riscv64/reloc_riscv64.c @@ -0,0 +1,95 @@ +/* riscv relocation handler for the static linker */ + +#include "ld_arch.h" + +void +ld_riscv_reloc_apply(struct ld_reloc *r) +{ + unsigned long addr; + long off; + long hi, lo; + unsigned int *insn; + + switch (r->type) { + case R_RISCV_NONE: + case R_RISCV_RELAX: + break; + case R_RISCV_32: + *(unsigned int *)r->dst += r->val; + break; + case R_RISCV_64: + *r->dst += r->val; + break; + case R_RISCV_BRANCH: + /* conditional branch: b-type encoding */ + off = r->val - r->addr; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0x01fff07f) | (((off >> 12) & 1) << 31) | (((off >> 5) & 0x3f) << 25) + | (((off >> 1) & 0xf) << 8) | (((off >> 11) & 1) << 7); + break; + case R_RISCV_JAL: + /* unconditional jump: j-type encoding */ + off = r->val - r->addr; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0x0000007f) | (((off >> 20) & 1) << 31) | (((off >> 1) & 0x3ff) << 21) + | (((off >> 11) & 1) << 20) | (((off >> 12) & 0xff) << 12); + break; + case R_RISCV_CALL: + case R_RISCV_CALL_PLT: { + /* auipc + jalr pair */ + unsigned int *jalr; + off = r->val - r->addr; + hi = (off + 0x800) >> 12; + lo = off - (hi << 12); + insn = (unsigned int *)r->dst; + jalr = (unsigned int *)(r->dst + 1); + *insn = (*insn & 0xfff) | ((hi & 0xfffff) << 12); + *jalr = (*jalr & 0xfffff) | ((lo << 20) & 0xfff00000); + } break; + case R_RISCV_PCREL_HI20: + case R_RISCV_GOT_HI20: + off = r->val - r->addr; + hi = (off + 0x800) >> 12; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0xfff) | ((hi & 0xfffff) << 12); + break; + case R_RISCV_PCREL_LO12_I: + off = r->val - r->addr; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0xfffff) | ((off & 0xfff) << 20); + break; + case R_RISCV_PCREL_LO12_S: + off = r->val - r->addr; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0x01fff07f) | (((off >> 5) & 0x7f) << 25) | ((off & 0x1f) << 7); + break; + case R_RISCV_HI20: + hi = (r->val + 0x800) >> 12; + insn = (unsigned int *)r->dst; + *insn = (*insn & 0xfff) | ((hi & 0xfffff) << 12); + break; + case R_RISCV_LO12_I: + insn = (unsigned int *)r->dst; + *insn = (*insn & 0xfffff) | ((r->val & 0xfff) << 20); + break; + case R_RISCV_LO12_S: + insn = (unsigned int *)r->dst; + *insn = (*insn & 0x01fff07f) | (((r->val >> 5) & 0x7f) << 25) | ((r->val & 0x1f) << 7); + break; + default: + die("ld: unknown riscv relocation type"); + } +} + +static int +ld_riscv_is_got_rel(unsigned int type) +{ + (void)type; + return 0; +} + +const struct ld_arch_backend ld_arch_riscv = { + .em_machine = EM_RISCV, + .reloc_apply = ld_riscv_reloc_apply, + .is_got_rel = ld_riscv_is_got_rel, +}; diff --git a/cmd/dev/ld/arch/x64/reloc_x64.c b/cmd/dev/ld/arch/x64/reloc_x64.c @@ -0,0 +1,141 @@ +/* x86_64 relocation handler for the static linker */ + +#include "ld_arch.h" + +#include <limits.h> +#include <stdint.h> + +static char * +ld_x64_reloc_name(unsigned int type) +{ + switch (type) { + case R_X86_64_16: + return "R_X86_64_16"; + case R_X86_64_32: + return "R_X86_64_32"; + case R_X86_64_32S: + return "R_X86_64_32S"; + case R_X86_64_PC32: + return "R_X86_64_PC32"; + case R_X86_64_PLT32: + return "R_X86_64_PLT32"; + case R_X86_64_GOTPCREL: + return "R_X86_64_GOTPCREL"; + case R_X86_64_REX_GOTPCRELX: + return "R_X86_64_REX_GOTPCRELX"; + case R_X86_64_GOTPCRELX: + return "R_X86_64_GOTPCRELX"; + case R_X86_64_GOTTPOFF: + return "R_X86_64_GOTTPOFF"; + case R_X86_64_TPOFF32: + return "R_X86_64_TPOFF32"; + default: + return "R_X86_64_UNKNOWN"; + } +} + +static void +ld_x64_check_s16_or_u16(struct ld_reloc *r, unsigned long value) +{ + if (value > USHRT_MAX && value < ULONG_MAX - INT16_MAX) + die_reloc(ld_x64_reloc_name(r->type), value); +} + +static void +ld_x64_check_s32(struct ld_reloc *r, unsigned long value) +{ + if (value > INT32_MAX && value < ULONG_MAX - INT32_MAX) + die_reloc(ld_x64_reloc_name(r->type), value); +} + +static void +ld_x64_check_u32(struct ld_reloc *r, unsigned long value) +{ + if (value > UINT32_MAX) + die_reloc(ld_x64_reloc_name(r->type), value); +} + +static void +ld_x64_write_field(unsigned long *dst, unsigned long value, int size) +{ + memcpy(dst, &value, size); +} + +void +ld_x64_reloc_apply(struct ld_reloc *r) +{ + unsigned long gotaddr, value; + int g; + + switch (r->type) { + case R_X86_64_NONE: + break; + case R_X86_64_16: + value = r->val; + ld_x64_check_s16_or_u16(r, value); + ld_x64_write_field(r->dst, value, sizeof(unsigned short)); + break; + case R_X86_64_32: + ld_x64_check_u32(r, r->val); + ld_x64_write_field(r->dst, r->val, sizeof(unsigned int)); + break; + case R_X86_64_32S: + ld_x64_check_s32(r, r->val); + ld_x64_write_field(r->dst, r->val, sizeof(unsigned int)); + break; + case R_X86_64_64: + *r->dst += r->val; + break; + case R_X86_64_PC64: + *r->dst += r->val - r->addr; + break; + case R_X86_64_PC32: + case R_X86_64_PLT32: + /* plt32 is the same as pc32 for a static linker */ + value = r->val - r->addr; + ld_x64_check_s32(r, value); + ld_x64_write_field(r->dst, value, sizeof(unsigned int)); + break; + case R_X86_64_GOTPCREL: + case R_X86_64_REX_GOTPCRELX: + case R_X86_64_GOTPCRELX: + case R_X86_64_GOTTPOFF: + /* gottpoff loads through a got slot like any gotpcrel form, but + the slot holds a tp-relative offset, not an address. find the + got entry for this symbol, since sym_idx alone is only unique + within one object's symbol table */ + for (g = 0; g < r->oe->ngot; g++) + if (r->oe->got[g].sym_idx == r->sym_idx && r->oe->got[g].obj_idx == r->obj_idx) + break; + if (g == r->oe->ngot) + die("ld: missing got entry for gotpcrel relocation"); + gotaddr = r->oe->got_vaddr + g * sizeof(unsigned long); + /* rip-relative disp32 = G + A - P, the addend corrects for + trailing bytes (immediates) between the disp32 field and the + next instruction that rip actually points at */ + value = gotaddr + r->addend - r->addr; + ld_x64_check_s32(r, value); + ld_x64_write_field(r->dst, value, sizeof(unsigned int)); + break; + case R_X86_64_TPOFF32: + /* tls offset, for static link use symbol value directly */ + ld_x64_check_s32(r, r->val); + ld_x64_write_field(r->dst, r->val, sizeof(unsigned int)); + break; + default: + die("ld: unknown x86_64 relocation type"); + } +} + +static int +ld_x64_is_got_rel(unsigned int type) +{ + return type == R_X86_64_GOTPCREL || type == R_X86_64_REX_GOTPCRELX || type == R_X86_64_GOTPCRELX + || type == R_X86_64_GOTTPOFF; +} + +const struct ld_arch_backend ld_arch_x64 = { + .em_machine = EM_X86_64, + .reloc_apply = ld_x64_reloc_apply, + .is_got_rel = ld_x64_is_got_rel, +}; diff --git a/cmd/dev/ld/arch/x86/reloc_x86.c b/cmd/dev/ld/arch/x86/reloc_x86.c @@ -0,0 +1,37 @@ +/* x86 (i386) relocation handler for the static linker */ + +#include "ld_arch.h" + +void +ld_x86_reloc_apply(struct ld_reloc *r) +{ + switch (r->type) { + case R_386_NONE: + break; + case R_386_16: + *(unsigned short *)r->dst += r->val; + break; + case R_386_32: + *(unsigned int *)r->dst += r->val; + break; + case R_386_PC32: + case R_386_PLT32: + *(unsigned int *)r->dst += r->val - r->addr; + break; + default: + die("ld: unknown i386 relocation type"); + } +} + +static int +ld_x86_is_got_rel(unsigned int type) +{ + (void)type; + return 0; +} + +const struct ld_arch_backend ld_arch_x86 = { + .em_machine = EM_386, + .reloc_apply = ld_x86_reloc_apply, + .is_got_rel = ld_x86_is_got_rel, +}; diff --git a/cmd/dev/ld/ld.c b/cmd/dev/ld/ld.c @@ -0,0 +1,1301 @@ +/* + * ld - static ELF linker + * based on neatld by ali gholami rudi (ISC license) + * + * permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies + */ + +#include "ld.h" +#include "ld_arch.h" + +#include <ctype.h> +#include <fcntl.h> +#include <sys/stat.h> +#include <unistd.h> + +/* config */ +static unsigned long sec_vaddr[3] = {0x400000}; +static unsigned long sec_laddr[3] = {0x400000}; +static int sec_set[3] = {1}; +static int secalign = 16; +static char *entry = "_start"; +static int e_machine; +static int e_flags; +static int nosyms; +static char *libdirs[MAXLIBDIRS]; +static int nlibdirs; +static char *mapfile; + +/* runtime-selected arch backend, set when first object is loaded */ +static const struct ld_arch_backend *ld_arch; + +void +die(char *msg) +{ + fprintf(stderr, "ld: %s\n", msg); + exit(1); +} + +void +die_undef(char *name) +{ + fprintf(stderr, "ld: %s undefined\n", name); + exit(1); +} + +void +die_reloc(char *name, unsigned long value) +{ + fprintf(stderr, "ld: %s value 0x%lx out of range\n", name, value); + exit(1); +} + +void +die_dup(char *name) +{ + fprintf(stderr, "ld: duplicate symbol %s\n", name); + exit(1); +} + +static Elf_Sym * +obj_find(struct obj *obj, char *name) +{ + int i; + for (i = 0; i < obj->nsyms; i++) { + Elf_Sym *sym = &obj->syms[i]; + if (ELF_ST_BIND(sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF) + continue; + if (!strcmp(name, obj->symstr + sym->st_name)) + return sym; + } + return NULL; +} + +static void +obj_init(struct obj *obj, char *mem) +{ + int i; + obj->mem = mem; + obj->ehdr = (void *)mem; + obj->shdr = (void *)(mem + obj->ehdr->e_shoff); + obj->shstr = mem + obj->shdr[obj->ehdr->e_shstrndx].sh_offset; + for (i = 0; i < obj->ehdr->e_shnum; i++) { + if (obj->shdr[i].sh_type != SHT_SYMTAB) + continue; + obj->symstr = mem + obj->shdr[obj->shdr[i].sh_link].sh_offset; + obj->syms = (void *)(mem + obj->shdr[i].sh_offset); + obj->nsyms = obj->shdr[i].sh_size / sizeof(*obj->syms); + } +} + +static void +outelf_init(struct outelf *oe) +{ + memset(oe, 0, sizeof(*oe)); + oe->ehdr.e_ident[0] = 0x7f; + oe->ehdr.e_ident[1] = 'E'; + oe->ehdr.e_ident[2] = 'L'; + oe->ehdr.e_ident[3] = 'F'; + oe->ehdr.e_ident[4] = ELFCLASS; + oe->ehdr.e_ident[5] = ELFDATA2LSB; + oe->ehdr.e_ident[6] = EV_CURRENT; + oe->ehdr.e_type = ET_EXEC; + oe->ehdr.e_version = EV_CURRENT; + oe->ehdr.e_shstrndx = SHN_UNDEF; + oe->ehdr.e_ehsize = sizeof(oe->ehdr); + oe->ehdr.e_phentsize = sizeof(oe->phdr[0]); + oe->ehdr.e_shentsize = sizeof(Elf_Shdr); +} + +struct secmap * +outelf_mapping(struct outelf *oe, Elf_Shdr *shdr) +{ + int i; + for (i = 0; i < oe->nsecs; i++) + if (oe->secs[i].o_shdr == shdr) + return &oe->secs[i]; + return NULL; +} + +static int +outelf_find(struct outelf *oe, char *name, struct obj **sym_obj, Elf_Sym **sym_sym) +{ + int i; + struct obj *strong_obj = NULL; + struct obj *weak_obj = NULL; + Elf_Sym *strong_sym = NULL; + Elf_Sym *weak_sym = NULL; + + /* a strong definition overrides a weak one whatever the link order. + * musl libc.a depends on it (weak default in one member, strong + * implementation in another), so the first match is not enough */ + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + Elf_Sym *sym; + if (!(sym = obj_find(obj, name))) + continue; + if (ELF_ST_BIND(sym->st_info) != STB_WEAK) { + if (strong_obj) + die_dup(name); + strong_obj = obj; + strong_sym = sym; + } else if (!weak_obj) { + weak_obj = obj; + weak_sym = sym; + } + } + if (strong_obj) { + *sym_obj = strong_obj; + *sym_sym = strong_sym; + return 0; + } + if (weak_obj) { + *sym_obj = weak_obj; + *sym_sym = weak_sym; + return 0; + } + return 1; +} + +static unsigned long +bss_addr(struct outelf *oe, Elf_Sym *sym) +{ + int i; + for (i = 0; i < oe->nbss_syms; i++) + if (oe->bss_syms[i].sym == sym) + return oe->bss_vaddr + oe->bss_syms[i].off; + return 0; +} + +/* linker-defined symbols for section boundaries, empty for static + * binaries without constructors */ +static int +is_ldsym(char *name) +{ + return !strcmp(name, "__init_array_start") || !strcmp(name, "__init_array_end") + || !strcmp(name, "__fini_array_start") || !strcmp(name, "__fini_array_end") + || !strcmp(name, "__preinit_array_start") || !strcmp(name, "__preinit_array_end") + || !strcmp(name, "__ehdr_start") || !strcmp(name, "__executable_start"); +} + +static unsigned long +ldsym_val(struct outelf *oe, char *name) +{ + if (!strcmp(name, "__ehdr_start") || !strcmp(name, "__executable_start")) + return sec_vaddr[I_CS]; + return oe->bss_vaddr + oe->bss_len; +} + +static unsigned long +symval(struct outelf *oe, struct obj *obj, Elf_Sym *sym) +{ + struct secmap *sec; + char *name = obj ? obj->symstr + sym->st_name : NULL; + int s_idx, s_off; + + switch (ELF_ST_TYPE(sym->st_info)) { + case STT_SECTION: + if ((sec = outelf_mapping(oe, &obj->shdr[sym->st_shndx]))) { + if (obj->shdr[sym->st_shndx].sh_flags & SHF_TLS) + return sec->vaddr - oe->tls_size; + return sec->vaddr; + } + break; + case STT_NOTYPE: + case STT_OBJECT: + case STT_FUNC: + case STT_TLS: + /* a weak global stays overridable when the sym entry of this relocation + * defines it locally (st_shndx != SHN_UNDEF). musl libc.a has the weak + * default and the strong definition in different members, and every + * reference must bind to the strong one */ + if (name && *name + && (sym->st_shndx == SHN_UNDEF || ELF_ST_BIND(sym->st_info) == STB_WEAK)) { + if (outelf_find(oe, name, &obj, &sym)) { + if (is_ldsym(name)) + return ldsym_val(oe, name); + /* weak undefined symbols resolve to 0 */ + if (ELF_ST_BIND(sym->st_info) == STB_WEAK) + return 0; + else + die_undef(name); + } + } + if (sym->st_shndx == SHN_COMMON) + return bss_addr(oe, sym); + s_idx = sym->st_shndx; + s_off = sym->st_value; + if ((sec = outelf_mapping(oe, &obj->shdr[s_idx]))) { + /* variant ii: a tls symbol address is tp-relative, so return its offset + * from the thread pointer instead of a runtime address */ + if (obj->shdr[s_idx].sh_flags & SHF_TLS) + return sec->vaddr + s_off - oe->tls_size; + return sec->vaddr + s_off; + } + } + return 0; +} + +static unsigned long +outelf_addr(struct outelf *oe, char *name) +{ + struct obj *obj; + Elf_Sym *sym; + + if (is_ldsym(name)) + return ldsym_val(oe, name); + + if (outelf_find(oe, name, &obj, &sym)) + die_undef(name); + return symval(oe, obj, sym); +} + +static void +outelf_got_prescan(struct outelf *oe) +{ + int i, j, k, g; + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + for (j = 0; j < obj->ehdr->e_shnum; j++) { + Elf_Shdr *rs = &obj->shdr[j]; + Elf_Rela *rels; + int nrels; + if (rs->sh_type != SHT_REL_) + continue; + rels = (Elf_Rela *)(obj->mem + rs->sh_offset); + nrels = rs->sh_size / sizeof(*rels); + for (k = 0; k < nrels; k++) { + Elf_Rela *rel = (void *)&rels[k]; + int type = ELF_R_TYPE(rel->r_info); + int sym_idx = ELF_R_SYM(rel->r_info); + if (!ld_arch || !ld_arch->is_got_rel(type)) + continue; + /* sym_idx is unique only within its own object, so obj_idx must match + * too */ + for (g = 0; g < oe->ngot; g++) + if (oe->got[g].sym_idx == sym_idx && oe->got[g].obj_idx == i) + break; + if (g == oe->ngot) { + if (oe->ngot >= MAXGOT) + die("ld: too many got entries"); + oe->got[oe->ngot].sym_idx = sym_idx; + oe->got[oe->ngot].obj_idx = i; + oe->ngot++; + } + } + } + } +} + +static void +outelf_reloc_sec(struct outelf *oe, int o_idx, int s_idx) +{ + struct obj *obj = &oe->objs[o_idx]; + Elf_Shdr *rel_shdr = &obj->shdr[s_idx]; + Elf_Rela *rels = (Elf_Rela *)(obj->mem + obj->shdr[s_idx].sh_offset); + Elf_Shdr *other_shdr = &obj->shdr[rel_shdr->sh_info]; + char *other = obj->mem + other_shdr->sh_offset; + int nrels = rel_shdr->sh_size / sizeof(*rels); + struct secmap *other_sec = outelf_mapping(oe, other_shdr); + int i; + + /* relocations against a section dropped from the output (eh_frame, + * notes, debug info) have nothing to apply to */ + if (!other_sec) + return; + + for (i = 0; i < nrels; i++) { + Elf_Rela *rel = (void *)&rels[i]; + int sym_idx = ELF_R_SYM(rel->r_info); + Elf_Sym *sym = &obj->syms[sym_idx]; + struct ld_reloc r; + r.type = ELF_R_TYPE(rel->r_info); + r.val = symval(oe, obj, sym) + REL_ADDEND(rel); + r.dst = (unsigned long *)(other + rel->r_offset); + r.addr = other_sec->vaddr + rel->r_offset; + r.oe = oe; + r.target_shdr = other_shdr; + r.sym_idx = sym_idx; + r.obj_idx = o_idx; + r.addend = REL_ADDEND(rel); + ld_arch->reloc_apply(&r); + } +} + +static void +outelf_reloc(struct outelf *oe) +{ + int i, j; + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + for (j = 0; j < obj->ehdr->e_shnum; j++) + if (obj->shdr[j].sh_type == SHT_REL_) + outelf_reloc_sec(oe, i, j); + } +} + +static void +alloc_bss(struct outelf *oe, Elf_Sym *sym) +{ + int n = oe->nbss_syms++; + int off = ALIGN(oe->bss_len, MAX(sym->st_value, 4)); + oe->bss_syms[n].sym = sym; + oe->bss_syms[n].off = off; + oe->bss_len = off + sym->st_size; +} + +static void +outelf_bss(struct outelf *oe) +{ + int i, j; + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + for (j = 0; j < obj->nsyms; j++) + if (obj->syms[j].st_shndx == SHN_COMMON) + alloc_bss(oe, &obj->syms[j]); + } +} + +#define SEC_TLS(s) ((s)->sh_flags & SHF_TLS) +#define SEC_CODE(s) (!SEC_TLS(s) && ((s)->sh_flags & SHF_EXECINSTR)) +#define SEC_BSS(s) (!SEC_TLS(s) && (s)->sh_type == SHT_NOBITS) +#define SEC_DATA(s) (!SEC_TLS(s) && !SEC_CODE(s) && !SEC_BSS(s)) +#define SEC_TDATA(s) (SEC_TLS(s) && (s)->sh_type != SHT_NOBITS) +#define SEC_TBSS(s) (SEC_TLS(s) && (s)->sh_type == SHT_NOBITS) + +static int +outelf_str(struct outelf *oe, char *s) +{ + int n = oe->nsymstr; + char *d = oe->symstr + oe->nsymstr; + while (*s) + *d++ = *s++; + *d++ = '\0'; + oe->nsymstr = d - oe->symstr; + return n; +} + +static void +build_symtab(struct outelf *oe) +{ + int i, j; + Elf_Sym *syms = oe->syms; + Elf_Shdr *cs_shdr = &oe->shdr[++oe->nsh]; + Elf_Shdr *ds_shdr = &oe->shdr[++oe->nsh]; + Elf_Shdr *bss_shdr = &oe->shdr[++oe->nsh]; + Elf_Shdr *sym_shdr = &oe->shdr[++oe->nsh]; + Elf_Shdr *str_shdr = &oe->shdr[++oe->nsh]; + int n = 1; + int faddr = oe->shdr_faddr; + + oe->nsh++; + outelf_str(oe, ""); + sym_shdr->sh_name = outelf_str(oe, ".symtab"); + str_shdr->sh_name = outelf_str(oe, ".strtab"); + cs_shdr->sh_name = outelf_str(oe, ".text"); + ds_shdr->sh_name = outelf_str(oe, ".data"); + bss_shdr->sh_name = outelf_str(oe, ".bss"); + + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + for (j = 0; j < obj->nsyms; j++) { + Elf_Sym *sym = &obj->syms[j]; + int type = ELF_ST_TYPE(sym->st_info); + int bind = ELF_ST_BIND(sym->st_info); + char *name = obj->symstr + sym->st_name; + if (!*name || bind == STB_LOCAL || sym->st_shndx == SHN_UNDEF) + continue; + syms[n].st_name = outelf_str(oe, name); + syms[n].st_info = ELF64_ST_INFO(bind, type); + syms[n].st_value = symval(oe, obj, sym); + syms[n].st_size = sym->st_size; + syms[n].st_shndx = SHN_ABS; + n++; + } + } + oe->nsyms = n; + + oe->shdr_faddr = faddr; + faddr += oe->nsh * sizeof(oe->shdr[0]); + oe->syms_faddr = faddr; + faddr += oe->nsyms * sizeof(oe->syms[0]); + oe->symstr_faddr = faddr; + + oe->ehdr.e_shstrndx = str_shdr - oe->shdr; + oe->ehdr.e_shoff = oe->shdr_faddr; + oe->ehdr.e_shnum = oe->nsh; + + str_shdr->sh_type = SHT_STRTAB; + str_shdr->sh_offset = oe->symstr_faddr; + str_shdr->sh_size = oe->nsymstr; + + sym_shdr->sh_type = SHT_SYMTAB; + sym_shdr->sh_entsize = sizeof(oe->syms[0]); + sym_shdr->sh_offset = oe->syms_faddr; + sym_shdr->sh_size = oe->nsyms * sizeof(oe->syms[0]); + sym_shdr->sh_link = str_shdr - oe->shdr; + sym_shdr->sh_info = 0; + + cs_shdr->sh_type = SHT_PROGBITS; + cs_shdr->sh_flags = SHF_ALLOC | SHF_EXECINSTR; + cs_shdr->sh_offset = oe->phdr[I_CS].p_offset; + cs_shdr->sh_addr = oe->phdr[I_CS].p_vaddr; + cs_shdr->sh_addralign = oe->phdr[I_CS].p_align; + cs_shdr->sh_size = oe->phdr[I_CS].p_filesz; + + ds_shdr->sh_type = SHT_PROGBITS; + ds_shdr->sh_flags = SHF_ALLOC | SHF_WRITE; + ds_shdr->sh_offset = oe->phdr[I_DS].p_offset; + ds_shdr->sh_addr = oe->phdr[I_DS].p_vaddr; + ds_shdr->sh_addralign = oe->phdr[I_DS].p_align; + ds_shdr->sh_size = oe->phdr[I_DS].p_filesz; + + bss_shdr->sh_type = SHT_NOBITS; + bss_shdr->sh_flags = SHF_ALLOC | SHF_WRITE; + bss_shdr->sh_offset = oe->phdr[I_BSS].p_offset; + bss_shdr->sh_addr = oe->phdr[I_BSS].p_vaddr; + bss_shdr->sh_addralign = oe->phdr[I_BSS].p_align; + bss_shdr->sh_size = oe->phdr[I_BSS].p_filesz; +} + +static int +secmap_cmp_faddr(const void *a, const void *b) +{ + const struct secmap *const *pa = a, *const *pb = b; + if ((*pa)->faddr < (*pb)->faddr) + return -1; + if ((*pa)->faddr > (*pb)->faddr) + return 1; + return 0; +} + +static void +outelf_write(struct outelf *oe, int fd) +{ + int i, ncode; + long code_end = -1; + struct secmap **code_secs; + + oe->ehdr.e_entry = outelf_addr(oe, entry) - sec_vaddr[I_CS] + sec_laddr[I_CS]; + if (!nosyms) + build_symtab(oe); + oe->ehdr.e_phnum = oe->nph; + oe->ehdr.e_phoff = sizeof(oe->ehdr); + oe->ehdr.e_machine = e_machine; + oe->ehdr.e_flags = e_flags; + + lseek(fd, 0, SEEK_SET); + write(fd, &oe->ehdr, sizeof(oe->ehdr)); + write(fd, &oe->phdr, oe->nph * sizeof(oe->phdr[0])); + + /* link_cs groups sections by name (.init, .fini, the rest), not by + * oe->secs[] order, so the index no longer implies faddr. the gap fill + * below needs true faddr order */ + code_secs = malloc(oe->nsecs * sizeof(*code_secs)); + ncode = 0; + for (i = 0; i < oe->nsecs; i++) + if (SEC_CODE(oe->secs[i].o_shdr)) + code_secs[ncode++] = &oe->secs[i]; + qsort(code_secs, ncode, sizeof(*code_secs), secmap_cmp_faddr); + + for (i = 0; i < ncode; i++) { + struct secmap *sec = code_secs[i]; + char *buf = sec->obj->mem + sec->o_shdr->sh_offset; + int len = sec->o_shdr->sh_size; + /* link_cs aligns code sections but leaves the gap, which reads back as + * zero and decodes as a valid instruction. fill with int3 so a stray + * fall-through traps */ + if (code_end >= 0 && (long)sec->faddr > code_end) { + long gap = sec->faddr - code_end; + unsigned char *pad = malloc(gap); + memset(pad, 0xcc, gap); + lseek(fd, code_end, SEEK_SET); + write(fd, pad, gap); + free(pad); + } + code_end = sec->faddr + len; + lseek(fd, sec->faddr, SEEK_SET); + write(fd, buf, len); + } + free(code_secs); + + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + char *buf = sec->obj->mem + sec->o_shdr->sh_offset; + int len = sec->o_shdr->sh_size; + if (SEC_BSS(sec->o_shdr) || SEC_TBSS(sec->o_shdr) || SEC_CODE(sec->o_shdr)) + continue; + lseek(fd, sec->faddr, SEEK_SET); + write(fd, buf, len); + } + if (oe->ngot > 0) { + unsigned long *gotbuf = malloc(oe->ngot * sizeof(unsigned long)); + int g; + for (g = 0; g < oe->ngot; g++) { + struct obj *go = &oe->objs[oe->got[g].obj_idx]; + Elf_Sym *gs = &go->syms[oe->got[g].sym_idx]; + gotbuf[g] = symval(oe, go, gs); + } + lseek(fd, oe->got_faddr, SEEK_SET); + write(fd, gotbuf, oe->ngot * sizeof(unsigned long)); + free(gotbuf); + } + if (!nosyms) { + lseek(fd, oe->shdr_faddr, SEEK_SET); + write(fd, &oe->shdr, oe->nsh * sizeof(oe->shdr[0])); + lseek(fd, oe->syms_faddr, SEEK_SET); + write(fd, &oe->syms, oe->nsyms * sizeof(oe->syms[0])); + lseek(fd, oe->symstr_faddr, SEEK_SET); + write(fd, &oe->symstr, oe->nsymstr); + } +} + +static void +outelf_add(struct outelf *oe, char *mem) +{ + Elf_Ehdr *ehdr = (void *)mem; + Elf_Shdr *shdr = (void *)(mem + ehdr->e_shoff); + struct obj *obj; + int i; + + if (ehdr->e_type != ET_REL) + return; + e_machine = ehdr->e_machine; + e_flags = ehdr->e_flags; + if (ld_arch == NULL) { + ld_arch = ld_arch_select(e_machine); + if (ld_arch == NULL) + die("ld: unsupported architecture"); + } else if (e_machine != ld_arch->em_machine) { + die("ld: mixed input architectures"); + } + if (oe->nobjs >= MAXOBJS) + die("ld: too many objects"); + obj = &oe->objs[oe->nobjs++]; + obj_init(obj, mem); + for (i = 0; i < obj->nsyms; i++) { + Elf_Sym *sym = &obj->syms[i]; + struct obj *sym_obj; + Elf_Sym *sym_sym; + if (ELF_ST_BIND(sym->st_info) == STB_LOCAL || sym->st_shndx == SHN_UNDEF + || ELF_ST_BIND(sym->st_info) == STB_WEAK) + continue; + outelf_find(oe, obj->symstr + sym->st_name, &sym_obj, &sym_sym); + } + for (i = 0; i < ehdr->e_shnum; i++) { + struct secmap *sec; + if (!(shdr[i].sh_flags & 0x7)) + continue; + if (oe->nsecs >= MAXSECS) + die("ld: too many sections"); + sec = &oe->secs[oe->nsecs++]; + sec->o_shdr = &shdr[i]; + sec->obj = obj; + } +} + +static int +link_cs( + struct outelf *oe, + Elf_Phdr *phdr, + unsigned long faddr, + unsigned long vaddr, + unsigned long laddr, + int len +) +{ + int i, pass; + /* .init/.fini of all objects are fragments of one function (crti.o + * prologue, object parts, crtn.o epilogue) and must be byte-adjacent + * wherever the objects sit in link order. pass 0 lays out every .init, + * pass 1 every .fini, pass 2 the rest */ + for (pass = 0; pass < 3; pass++) { + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + const char *name; + int alignment, is_init, is_fini; + if (!SEC_CODE(sec->o_shdr)) + continue; + name = sec->obj->shstr + sec->o_shdr->sh_name; + is_init = !strcmp(name, ".init"); + is_fini = !strcmp(name, ".fini"); + if ((pass == 0 && !is_init) || (pass == 1 && !is_fini) + || (pass == 2 && (is_init || is_fini))) + continue; + alignment = pass < 2 ? 1 : MAX(sec->o_shdr->sh_addralign, 4); + len = ALIGN(vaddr + len, alignment) - vaddr; + sec->vaddr = vaddr + len; + sec->faddr = faddr + len; + len += sec->o_shdr->sh_size; + } + } + phdr->p_type = PT_LOAD; + phdr->p_flags = PF_R | PF_X; + phdr->p_vaddr = vaddr; + phdr->p_paddr = laddr; + phdr->p_offset = faddr; + phdr->p_filesz = len; + phdr->p_memsz = len; + phdr->p_align = PAGE_SIZE; + return len; +} + +static int +link_ds( + struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr, unsigned long laddr +) +{ + int len = 0; + int i; + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + int alignment = MAX(sec->o_shdr->sh_addralign, 4); + if (!SEC_DATA(sec->o_shdr)) + continue; + len = ALIGN(vaddr + len, alignment) - vaddr; + sec->vaddr = vaddr + len; + sec->faddr = faddr + len; + len += sec->o_shdr->sh_size; + } + len = ALIGN(len, 4); + phdr->p_type = PT_LOAD; + phdr->p_flags = PF_R | PF_W; + phdr->p_align = PAGE_SIZE; + phdr->p_vaddr = vaddr; + phdr->p_paddr = laddr; + phdr->p_filesz = len; + phdr->p_memsz = len; + phdr->p_offset = faddr; + return len; +} + +static int +link_bss(struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr, int len) +{ + int i; + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + int alignment = MAX(sec->o_shdr->sh_addralign, 4); + if (!SEC_BSS(sec->o_shdr)) + continue; + len = ALIGN(vaddr + len, alignment) - vaddr; + sec->vaddr = vaddr + len; + sec->faddr = faddr; + len += sec->o_shdr->sh_size; + } + phdr->p_type = PT_LOAD; + phdr->p_flags = PF_R | PF_W; + phdr->p_vaddr = vaddr; + phdr->p_paddr = vaddr; + phdr->p_offset = faddr; + phdr->p_filesz = 0; + phdr->p_memsz = len; + phdr->p_align = PAGE_SIZE; + return len; +} + +/* merge every .tdata/.tbss into one tls template. variant ii (x86, + * x86-64) puts tls variables below the thread pointer, so a symbol at + * offset off sits at tp - (tls_size - off). tdata comes first (it has + * file bytes), tbss continues the same offset so the template is + * contiguous. returns 0 and adds no phdr when there is no tls section */ +static int +link_tls(struct outelf *oe, Elf_Phdr *phdr, unsigned long faddr, unsigned long vaddr) +{ + int i, len = 0, filesz, align = 1; + + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + int alignment; + if (!SEC_TDATA(sec->o_shdr)) + continue; + alignment = MAX(sec->o_shdr->sh_addralign, 1); + align = MAX(align, alignment); + len = ALIGN(len, alignment); + sec->vaddr = len; + sec->faddr = faddr + len; + len += sec->o_shdr->sh_size; + } + filesz = ALIGN(len, 4); + len = filesz; + + for (i = 0; i < oe->nsecs; i++) { + struct secmap *sec = &oe->secs[i]; + int alignment; + if (!SEC_TBSS(sec->o_shdr)) + continue; + alignment = MAX(sec->o_shdr->sh_addralign, 1); + align = MAX(align, alignment); + len = ALIGN(len, alignment); + sec->vaddr = len; + len += sec->o_shdr->sh_size; + } + if (len == 0) + return 0; + + len = ALIGN(len, align); + + phdr->p_type = PT_TLS; + phdr->p_flags = PF_R; + phdr->p_vaddr = vaddr; + phdr->p_paddr = vaddr; + phdr->p_offset = faddr; + phdr->p_filesz = filesz; + phdr->p_memsz = len; + phdr->p_align = align; + + oe->tls_size = len; + oe->tls_filesz = filesz; + return len; +} + +static void +outelf_link(struct outelf *oe) +{ + unsigned long faddr, vaddr, laddr; + int len, has_tls; + + len = ALIGN(sizeof(oe->ehdr) + MAXPHDRS * sizeof(oe->phdr[0]), secalign); + faddr = len & ~PAGE_MASK; + vaddr = sec_vaddr[I_CS]; + laddr = sec_laddr[I_CS]; + len = link_cs(oe, &oe->phdr[0], faddr, vaddr, laddr, len & PAGE_MASK); + + len = ALIGN(faddr + len, secalign) - faddr; + faddr += len; + vaddr = sec_set[I_DS] ? sec_vaddr[I_DS] | (faddr & PAGE_MASK) : vaddr + PAGE_SIZE + len; + laddr = sec_set[I_DS] ? sec_laddr[I_DS] | (faddr & PAGE_MASK) : laddr + PAGE_SIZE + len; + len = link_ds(oe, &oe->phdr[1], faddr, vaddr, laddr); + + outelf_got_prescan(oe); + + oe->got_vaddr = vaddr + len; + oe->got_faddr = faddr + len; + len += oe->ngot * sizeof(unsigned long); + len = ALIGN(len, 4); + + /* tls template follows the got inside the data segment. its tbss tail + * has no file bytes, like bss, so it grows p_memsz but not p_filesz */ + has_tls = link_tls(oe, &oe->phdr[3], faddr + len, vaddr + len) != 0; + oe->phdr[1].p_filesz = ALIGN(len + oe->tls_filesz, 4); + len = ALIGN(len + oe->tls_size, 4); + oe->phdr[1].p_memsz = len; + + len = ALIGN(faddr + len, secalign) - faddr; + faddr += len; + vaddr = sec_set[I_BSS] ? sec_vaddr[I_BSS] | (faddr & PAGE_MASK) : vaddr + PAGE_SIZE + len; + outelf_bss(oe); + oe->bss_vaddr = vaddr; + len = link_bss(oe, &oe->phdr[2], faddr, vaddr, oe->bss_len); + + oe->nph = has_tls ? 4 : 3; + oe->shdr_faddr = faddr; + outelf_reloc(oe); +} + +/* archive (.a) handling */ +struct arhdr { + char ar_name[16]; + char ar_date[12]; + char ar_uid[6]; + char ar_gid[6]; + char ar_mode[8]; + char ar_size[10]; + char ar_fmag[2]; +}; + +static int +get_be32(unsigned char *s) +{ + return s[3] | (s[2] << 8) | (s[1] << 16) | (s[0] << 24); +} + +static int +sym_undef(struct outelf *oe, char *name) +{ + int i, j; + int undef = 0; + for (i = 0; i < oe->nobjs; i++) { + struct obj *obj = &oe->objs[i]; + for (j = 0; j < obj->nsyms; j++) { + Elf_Sym *sym = &obj->syms[j]; + if (ELF_ST_BIND(sym->st_info) == STB_LOCAL) + continue; + if (strcmp(name, obj->symstr + sym->st_name)) + continue; + if (sym->st_shndx != SHN_UNDEF) + return 0; + undef = 1; + } + } + return undef; +} + +static int +outelf_ar_link(struct outelf *oe, char *ar, int base) +{ + char *ar_index; + char *ar_name; + int nsyms = get_be32((void *)ar); + int added = 0; + int i; + + ar_index = ar + 4; + ar_name = ar_index + nsyms * 4; + for (i = 0; i < nsyms; i++) { + int off = get_be32((void *)(ar_index + i * 4)) + sizeof(struct arhdr); + char *member = ar - base + off; + int j; + + if (!sym_undef(oe, ar_name)) + goto next; + + for (j = 0; j < oe->nobjs; j++) + if (oe->objs[j].mem == member) + goto next; + + outelf_add(oe, member); + added++; + next: + ar_name = strchr(ar_name, '\0') + 1; + } + return added; +} + +static void +outelf_archive(struct outelf *oe, char *ar) +{ + char *beg = ar; + + ar += 8; + for (;;) { + struct arhdr *hdr = (void *)ar; + char *name = hdr->ar_name; + int size; + + ar += sizeof(*hdr); + hdr->ar_size[sizeof(hdr->ar_size) - 1] = '\0'; + size = atoi(hdr->ar_size); + size = (size + 1) & ~1; + + if (name[0] == '/' && name[1] == ' ') { + while (outelf_ar_link(oe, ar, ar - beg)) + ; + return; + } + if (name[0] == '/' && name[1] == '/' && name[2] == ' ') + outelf_add(oe, ar); + ar += size; + } +} + +/* find the archive symbol index for multi-pass linking */ +static char * +ar_symtab(char *ar) +{ + ar += 8; + for (;;) { + struct arhdr *hdr = (void *)ar; + char *name = hdr->ar_name; + int size; + + ar += sizeof(*hdr); + hdr->ar_size[sizeof(hdr->ar_size) - 1] = '\0'; + size = atoi(hdr->ar_size); + size = (size + 1) & ~1; + + if (name[0] == '/' && name[1] == ' ') + return ar; + ar += size; + } +} + +/* multi-pass archive resolution: iterate over all archives until no + * new objects are pulled in. handles circular deps between libc and + * libgcc */ +static char *ar_mems[MAXFILES]; +static int nar_mems; + +static void +resolve_archives(struct outelf *oe) +{ + int i, changed; + + do { + changed = 0; + for (i = 0; i < nar_mems; i++) { + char *symtab = ar_symtab(ar_mems[i]); + while (outelf_ar_link(oe, symtab, symtab - ar_mems[i])) + changed = 1; + } + } while (changed); +} + +/* file I/O */ +static long +filesize(int fd) +{ + struct stat st; + if (fstat(fd, &st) < 0) + return -1; + return st.st_size; +} + +static char * +fileread(char *path) +{ + int fd = open(path, O_RDONLY); + long size; + char *buf; + ssize_t nread; + + if (fd < 0) + return NULL; + size = filesize(fd); + if (size <= 0) { + close(fd); + return NULL; + } + buf = malloc((size_t)size); + if (!buf) { + close(fd); + return NULL; + } + nread = read(fd, buf, (size_t)size); + close(fd); + if (nread != (ssize_t)size) { + free(buf); + return NULL; + } + return buf; +} + +static int +is_ar(char *path) +{ + int len = strlen(path); + return len > 2 && path[len - 2] == '.' && path[len - 1] == 'a'; +} + +static int +lib_find(char *path, char *lib) +{ + struct stat st; + int i; + + if (lib[0] == ':') { + lib++; + for (i = 0; i < nlibdirs; i++) { + sprintf(path, "%s/%s", libdirs[i], lib); + if (!stat(path, &st)) + return 0; + } + return 1; + } + + for (i = 0; i < nlibdirs; i++) { + sprintf(path, "%s/lib%s.a", libdirs[i], lib); + if (!stat(path, &st)) + return 0; + } + return 1; +} + +static unsigned long +hexnum(char *s) +{ + unsigned long n = 0; + if (s[0] == '0' && s[1] == 'x') + s += 2; + for (; isdigit(*s) || isalpha(*s); s++) { + n <<= 4; + n |= isdigit(*s) ? *s - '0' : tolower(*s) - 'a' + 10; + } + return n; +} + +static void +set_addr(int sec, char *arg) +{ + int idx = I_CS; + char *sep = strchr(arg, ':'); + + if (sec == 'd') + idx = I_DS; + if (sec == 'b') + idx = I_BSS; + sec_vaddr[idx] = hexnum(arg); + sec_laddr[idx] = sep ? hexnum(sep + 1) : sec_vaddr[idx]; + sec_set[idx] = 1; +} + +static void +usage(void) +{ + fprintf( + stderr, + "usage: ld [-static] [-o outfile] [-e entry] [-L dir] [-l lib]\n" + " [-Ttext addr] [-Tdata addr] [-Tbss addr] [-Map file]\n" + " [-s] [-p] [-h name] objfile ...\n" + ); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + char out[PATHLEN] = "a.out"; + static struct outelf oe; + char *mem[MAXFILES]; + int nmem = 0; + int fd; + int i = 0; + + if (argc < 2) + usage(); + outelf_init(&oe); + + while (++i < argc) { + if (argv[i][0] != '-') { + mem[nmem++] = fileread(argv[i]); + if (!mem[nmem - 1]) + die("ld: cannot open object"); + if (is_ar(argv[i])) { + ar_mems[nar_mems++] = mem[nmem - 1]; + outelf_archive(&oe, mem[nmem - 1]); + } else + outelf_add(&oe, mem[nmem - 1]); + continue; + } + + if (argv[i][1] == 'l' && argv[i][2] == '\0') { + char path[PATHLEN]; + if (i + 1 >= argc) + die("ld: -l missing argument"); + if (lib_find(path, argv[++i])) + die("ld: cannot find library"); + mem[nmem] = fileread(path); + if (!mem[nmem]) + die("ld: cannot read library"); + nmem++; + if (is_ar(path)) { + ar_mems[nar_mems++] = mem[nmem - 1]; + outelf_archive(&oe, mem[nmem - 1]); + } else + outelf_add(&oe, mem[nmem - 1]); + continue; + } + + if (argv[i][1] == 'l' && argv[i][2] != '\0') { + char path[PATHLEN]; + if (lib_find(path, argv[i] + 2)) + die("ld: cannot find library"); + mem[nmem] = fileread(path); + if (!mem[nmem]) + die("ld: cannot read library"); + nmem++; + if (is_ar(path)) { + ar_mems[nar_mems++] = mem[nmem - 1]; + outelf_archive(&oe, mem[nmem - 1]); + } else + outelf_add(&oe, mem[nmem - 1]); + continue; + } + + if (argv[i][1] == 'L' && argv[i][2] == '\0') { + if (i + 1 >= argc) + die("ld: -L missing argument"); + if (nlibdirs >= MAXLIBDIRS) + die("ld: too many library dirs"); + libdirs[nlibdirs++] = argv[++i]; + continue; + } + + if (argv[i][1] == 'L' && argv[i][2] != '\0') { + if (nlibdirs >= MAXLIBDIRS) + die("ld: too many library dirs"); + libdirs[nlibdirs++] = argv[i] + 2; + continue; + } + + if (argv[i][1] == 'o' && argv[i][2] == '\0') { + if (i + 1 >= argc) + die("ld: -o missing argument"); + strcpy(out, argv[++i]); + continue; + } + if (argv[i][1] == 'o') { + strcpy(out, argv[i] + 2); + continue; + } + + if ((argv[i][1] == 's' || argv[i][1] == 'S') && argv[i][2] == '\0') { + nosyms = 1; + continue; + } + + if (argv[i][1] == 'g' && argv[i][2] == '\0') + continue; + + if (argv[i][1] == 'e' && argv[i][2] == '\0') { + if (i + 1 >= argc) + die("ld: -e missing argument"); + entry = argv[++i]; + continue; + } + if (argv[i][1] == 'e') { + entry = argv[i] + 2; + continue; + } + + if (argv[i][1] == 'p' && argv[i][2] == '\0') { + secalign = PAGE_SIZE; + continue; + } + + /* -ttext/-tdata/-tbss: set segment base addresses */ + if (!strncmp(argv[i], "-Ttext", 6)) { + char *arg = argv[i][6] ? (argv[i][6] == '=' ? argv[i] + 7 : argv[i] + 6) : argv[++i]; + set_addr('c', arg); + continue; + } + if (!strncmp(argv[i], "-Tdata", 6)) { + char *arg = argv[i][6] ? (argv[i][6] == '=' ? argv[i] + 7 : argv[i] + 6) : argv[++i]; + set_addr('d', arg); + continue; + } + if (!strncmp(argv[i], "-Tbss", 5)) { + char *arg = argv[i][5] ? (argv[i][5] == '=' ? argv[i] + 6 : argv[i] + 5) : argv[++i]; + set_addr('b', arg); + continue; + } + + /* -T linker script: tolerate (not yet supported) */ + if (argv[i][1] == 'T' && argv[i][2] == '\0') { + if (i + 1 < argc) + ++i; + continue; + } + + /* -map file: write link map */ + if (!strncmp(argv[i], "-Map", 4)) { + mapfile = argv[i][4] ? (argv[i][4] == '=' ? argv[i] + 5 : argv[i] + 4) : argv[++i]; + continue; + } + + /* -m: neatld section address or GNU emulation mode */ + if (argv[i][1] == 'm') { + /* -melf_x86_64: emulation, tolerate */ + if (argv[i][2] == 'e') + continue; + /* -m c=addr or -mc=addr: section address */ + if (argv[i][2] == '\0') { + if (i + 1 < argc) { + char *a = argv[i + 1]; + /* elf_* is emulation not section */ + if (a[0] == 'e') { + ++i; + continue; + } + set_addr(a[0], a[2] == '=' ? a + 3 : a + 1); + ++i; + } + continue; + } + { + char sec = argv[i][2]; + char *arg = argv[i][3] == '=' ? argv[i] + 4 : (argv[i][3] ? argv[i] + 3 : argv[++i]); + set_addr(sec, arg); + } + continue; + } + + /* -z takes one argument: -z now, -z relro, etc */ + if (argv[i][1] == 'z') { + if (argv[i][2] == '\0' && i + 1 < argc) + ++i; + continue; + } + + /* -h name / -soname name: shared lib internal name, tolerate */ + if (argv[i][1] == 'h' && argv[i][2] == '\0') { + if (i + 1 < argc) + ++i; + continue; + } + if (!strncmp(argv[i] + 1, "soname", 6)) { + if (argv[i][7] == '\0' && i + 1 < argc) + ++i; + continue; + } + + /* -u sym: force undefined symbol, tolerate */ + if (argv[i][1] == 'u' && argv[i][2] == '\0') { + if (i + 1 < argc) + ++i; + continue; + } + + /* -defsym sym=val: tolerate */ + if (!strncmp(argv[i] + 1, "defsym", 6)) { + if (argv[i][7] == '\0' && i + 1 < argc) + ++i; + continue; + } + + /* -r / --relocatable: partial linking, tolerate for now */ + if (argv[i][1] == 'r' && argv[i][2] == '\0') + continue; + + /* -n / -N: nmagic, tolerate */ + if ((argv[i][1] == 'n' || argv[i][1] == 'N') && argv[i][2] == '\0') + continue; + + /* -static / -bstatic: already static, no-op */ + if (!strcmp(argv[i] + 1, "static") || !strcmp(argv[i] + 1, "Bstatic")) + continue; + + /* -shared / -bdynamic: static only, tolerate */ + if (!strcmp(argv[i] + 1, "shared") || !strcmp(argv[i] + 1, "Bdynamic")) + continue; + + /* -pie / -no-pie / -fno-pie: tolerate */ + if (!strcmp(argv[i] + 1, "pie") || !strcmp(argv[i] + 1, "no-pie") + || !strcmp(argv[i] + 1, "fno-pie") || !strcmp(argv[i] + 1, "fpie")) + continue; + + if (argv[i][1] == 'v' && argv[i][2] == '\0') { + printf("ld (aruu-dev)\n"); + return 0; + } + + if (!strcmp(argv[i], "--version")) { + printf("ld (aruu-dev)\n"); + return 0; + } + + if (!strcmp(argv[i], "--help")) + usage(); + + /* long options: tolerate (--build-id, --hash-style, etc) */ + if (argv[i][1] == '-') + continue; + + /* unknown single-char option: warn but continue */ + fprintf(stderr, "ld: unknown option: %s\n", argv[i]); + } + + resolve_archives(&oe); + outelf_link(&oe); + fd = open(out, O_WRONLY | O_TRUNC | O_CREAT, 0755); + if (fd < 0) + die("ld: failed to create output"); + outelf_write(&oe, fd); + close(fd); + + for (i = 0; i < nmem; i++) + free(mem[i]); + return 0; +} diff --git a/cmd/dev/ld/ld.h b/cmd/dev/ld/ld.h @@ -0,0 +1,139 @@ +/* ld: shared types and declarations for the static linker + * included by ld.c and per-arch relocation handlers */ + +#ifndef LD_LD_H +#define LD_LD_H + +#include <elf.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* section order: text, data, bss */ +#define I_CS 0 +#define I_DS 1 +#define I_BSS 2 + +#define MAXSECS (1 << 13) +#define MAXOBJS (1 << 11) +#define MAXSYMS (1 << 16) +#define MAXSYMSTR (1 << 20) +#define PAGE_SIZE (1 << 12) +#define PAGE_MASK (PAGE_SIZE - 1) +#define MAXFILES (1 << 10) +#define MAXPHDRS 4 +#define MAXLIBDIRS 32 +#define PATHLEN 256 +#define MAXGOT (1 << 16) + +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1)) + +/* 64-bit ELF by default, switch to 32-bit on __i386__ */ +#ifdef __x86_64__ +#define ELFCLASS ELFCLASS64 +#define Elf_Ehdr Elf64_Ehdr +#define Elf_Phdr Elf64_Phdr +#define Elf_Shdr Elf64_Shdr +#define Elf_Sym Elf64_Sym +#define Elf_Rela Elf64_Rela +#define SHT_REL_ SHT_RELA +#define REL_ADDEND(r) ((r)->r_addend) +#define ELF_ST_BIND ELF64_ST_BIND +#define ELF_ST_TYPE ELF64_ST_TYPE +#define ELF_R_SYM ELF64_R_SYM +#define ELF_R_TYPE ELF64_R_TYPE +#define ELF_ST_INFO ELF64_ST_INFO +#else +#define ELFCLASS ELFCLASS32 +#define Elf_Ehdr Elf32_Ehdr +#define Elf_Phdr Elf32_Phdr +#define Elf_Shdr Elf32_Shdr +#define Elf_Sym Elf32_Sym +#define Elf_Rela Elf32_Rel +#define SHT_REL_ SHT_REL +#define REL_ADDEND(r) (0) +#define ELF_ST_BIND ELF32_ST_BIND +#define ELF_ST_TYPE ELF32_ST_TYPE +#define ELF_R_SYM ELF32_R_SYM +#define ELF_R_TYPE ELF32_R_TYPE +#define ELF_ST_INFO ELF32_ST_INFO +#endif + +struct obj { + char *mem; + Elf_Ehdr *ehdr; + Elf_Shdr *shdr; + Elf_Sym *syms; + int nsyms; + char *symstr; + char *shstr; +}; + +struct secmap { + Elf_Shdr *o_shdr; + struct obj *obj; + unsigned long vaddr; + unsigned long faddr; +}; + +struct bss_sym { + Elf_Sym *sym; + int off; +}; + +struct got_entry { + int sym_idx; + int obj_idx; +}; + +struct outelf { + Elf_Ehdr ehdr; + Elf_Phdr phdr[MAXPHDRS]; + int nph; + struct secmap secs[MAXSECS]; + int nsecs; + struct obj objs[MAXOBJS]; + int nobjs; + + unsigned long code_addr; + + struct bss_sym bss_syms[MAXSYMS]; + int nbss_syms; + unsigned long bss_vaddr; + int bss_len; + + /* got: one entry per GOTPCREL/GOTTPOFF relocation. the entry stores + * the resolved symbol address (or, for a tls symbol, its tp-relative + * offset). the relocation displacement points here */ + struct got_entry got[MAXGOT]; + int ngot; + unsigned long got_vaddr; + unsigned long got_faddr; + + /* tls template: .tdata/.tbss from every object, merged into one + * block. a tls section's secmap.vaddr holds its offset from the + * start of this block (0-based), not a runtime address, since tls + * variables are addressed tp-relative, not absolutely */ + unsigned long tls_size; + unsigned long tls_filesz; + + Elf_Shdr shdr[MAXSECS]; + int nsh; + char symstr[MAXSYMSTR]; + Elf_Sym syms[MAXSYMS]; + int nsyms; + int nsymstr; + unsigned long shdr_faddr; + unsigned long syms_faddr; + unsigned long symstr_faddr; +}; + +void die(char *msg); +void die_undef(char *name); +void die_reloc(char *name, unsigned long value); +void die_dup(char *name); + +struct secmap *outelf_mapping(struct outelf *oe, Elf_Shdr *shdr); + +#endif /* LD_LD_H */ diff --git a/cmd/dev/ld/ld_arch.h b/cmd/dev/ld/ld_arch.h @@ -0,0 +1,48 @@ +/* ld arch dispatch: per-architecture relocation handlers + * the linker discovers the target arch from input object e_machine + * and selects the matching backend at runtime */ + +#ifndef LD_LD_ARCH_H +#define LD_LD_ARCH_H + +#include "ld.h" + +/* a single relocation to apply. all fields are set by the core + * relocation loop before calling the arch handler */ +struct ld_reloc { + unsigned int type; /* ELF relocation type (R_* constant) */ + unsigned long val; /* resolved symbol value + addend */ + unsigned long *dst; /* pointer to target bytes in section data */ + unsigned long addr; /* virtual address of the relocation site */ + struct outelf *oe; /* linker state for GOT lookups */ + Elf_Shdr *target_shdr; /* section header of section being patched */ + int sym_idx; /* symbol index in source object */ + int obj_idx; /* index of source object in oe->objs */ + long addend; /* raw rela addend, unmixed with symval */ +}; + +/* per-arch relocation backend */ +struct ld_arch_backend { + int em_machine; /* EM_* constant */ + /* apply a single relocation. modifies *dst in place */ + void (*reloc_apply)(struct ld_reloc *r); + /* check if a relocation type requires a got entry */ + int (*is_got_rel)(unsigned int type); +}; + +/* select the arch backend matching the given e_machine + * returns NULL for unsupported arches */ +const struct ld_arch_backend *ld_arch_select(int em_machine); + +/* per-arch backend definitions, one per arch source file */ +extern const struct ld_arch_backend ld_arch_x64; +extern const struct ld_arch_backend ld_arch_x86; +extern const struct ld_arch_backend ld_arch_arm; +#ifdef EM_RISCV +extern const struct ld_arch_backend ld_arch_riscv; +#endif +#ifdef EM_AARCH64 +extern const struct ld_arch_backend ld_arch_aarch64; +#endif + +#endif /* LD_LD_ARCH_H */ diff --git a/cmd/dev/ninqu/expand.c b/cmd/dev/ninqu/expand.c @@ -269,15 +269,12 @@ expand_rule(const char *name) int j; int r_literal = rule_is_literal(r); - /* run a codegen producer before globbing only when its own - * output feeds this rules glob, so a step like POSIX_BC_C - * (produces cmd/posix/bc.c) finishes before glob_all() looks - * for cmd/posix/bc.c. anything else in extra_deps (a library to - * link, a header some other rule includes) never needs to run - * here, expand_rule() on it just registers its instances so - * the resolve_input_token() pass in finalize_inst() can wire up - * dep_rule_names for backend scheduling. skipped in - * summary mode since -S must not execute */ + /* run a codegen producer before globbing only when its output feeds + * this rule's glob, so POSIX_BC_C (produces cmd/posix/bc.c) finishes + * before glob_all() looks for it. other extra_deps (libraries, + * headers) just get registered by expand_rule() so finalize_inst() + * can wire up dep_rule_names. skipped in summary mode: -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]); diff --git a/cmd/dev/ninqu/ninja.c b/cmd/dev/ninqu/ninja.c @@ -4,11 +4,9 @@ #include <stdlib.h> #include <string.h> -/* ninjas own tokenizer treats '$', ':' and ' ' as special outside - * of a rules variables, so any path used in a build statement - * (outputs, inputs, deps) needs those three escaped with a leading - * '$'. this is a different escaping pass from shell quoting below, - * it runs on ninjas file syntax, not on the command it configures */ +/* ninja treats '$', ':' and ' ' as special in a build statement path + * (outputs, inputs, deps), so escape them with a leading '$'. this is + * ninja file syntax, separate from the shell quoting below */ static char * ninja_path_escape(const char *s) { @@ -25,12 +23,10 @@ ninja_path_escape(const char *s) return out; } -/* ninqus argv is already fully expanded ($(VAR) substitution - * happened at parse time), so the ninja rules command is a plain - * literal string, never $in/$out. write one argv word as a single - * shell-quoted token: close/escape/reopen for an embedded quote, - * and double any '$' so ninjas own preprocessing pass on the - * "command" value hands the shell back exactly one '$' */ +/* argv is fully expanded at parse time, so the ninja command is a + * plain literal, never $in/$out. write one word as a single shell + * quoted token, and double each '$' so ninja preprocessing hands the + * shell exactly one */ static void fprint_shell_word_plain(FILE *f, const char *s) { @@ -46,23 +42,12 @@ fprint_shell_word_plain(FILE *f, const char *s) fputc('\'', f); } -/* ninja reads a "command = ..." value to the end of the physical - * line: a literal newline byte terminates the statement, and $\n is - * a continuation that strips the newline rather than preserving it, - * so neither lets a real newline survive inside the value. POSIX - * single quotes cannot help either, there is no escape processing - * inside them, so a backslash-n written between quotes stays two - * literal characters, not a newline, once the shell reads it back - * - * the fix is to not carry the newline in quoted text at all: emit - * a command substitution that runs the word through `printf '%b'`, - * whose %b directive is posix-specified to expand backslash escapes - * (including \n) in its argument at runtime. the argument to printf - * is itself single-quoted using the same rules as the plain case, - * plus doubling any backslash so it survives as data rather than - * being read as an escape by the quoting layer itself, and the `$(` - * that opens the substitution needs its own `$` doubled so ninjas - * pass just picks it out unmodified for the shell to see */ +/* ninja ends a "command = ..." value at the physical line end and $\n + * strips the newline, and \n inside posix single quotes stays two + * characters. so emit a command substitution running the word through + * `printf '%b'`, which expands escapes at run time. the argument is + * single-quoted with backslashes doubled, and the `$` of the opening + * `$(` is doubled so ninja leaves it for the shell */ static void fprint_shell_word(FILE *f, const char *s) { @@ -101,16 +86,12 @@ fprint_shell_word(FILE *f, const char *s) fputs("')\"", f); } -/* an instance with no (out) has no on-disk path of its own (a - * (phony) rule, or a pure grouping rule). ninja still needs a - * target name to hang a build statement off, so one is made up - * from the rule name and instance index. it is never a real file, - * so ninja will always find it missing and re-run it, the same - * "always stale" behaviour inst_stale() gives phony instances in - * the internal engine. the name is a single flat path component - * (no '/'), so ninja never mkdir -p's a directory for it: ninja - * only creates the parent directory of a build outputs path, and a - * name with no slash has no parent beyond the working directory */ +/* an instance with no (out) has no on-disk path (a phony or pure + * grouping rule), but ninja needs a target name for its build + * statement, so one is made from the rule name and instance index. + * it never exists as a file, so ninja always re-runs it, matching the + * "always stale" behaviour inst_stale() gives phony instances. the + * name has no '/', so ninja never creates a parent directory for it */ static const char * inst_target(struct Inst *inst, int idx, char *buf, size_t bufsz) { @@ -120,15 +101,12 @@ inst_target(struct Inst *inst, int idx, char *buf, size_t bufsz) return buf; } -/* does this instance look like "cc ... -c ... -o foo.o"? if so its - * a real compile step and ninja can track its header dependencies - * precisely via a gcc-style depfile instead of only the coarse - * order-only edges dep_inst gives every instance. matched by - * basename so whatever CC the manifest actually resolved (gcc, - * clang, a cross compiler under some path) is what gets the extra - * flags, nothing here hardcodes a specific compiler binary; the - * check is on -c and a .o output, not on the compiler name meaning - * anything beyond "probably understands -MMD -MF" */ +/* does this instance look like "cc ... -c ... -o foo.o"? if so it is a + * real compile step, and ninja can track header dependencies through + * a gcc-style depfile instead of only the coarse order-only edges + * dep_inst gives. the check is on -c and a .o output, not the + * compiler name, so any CC the manifest resolved works as long as it + * understands -MMD -MF */ static int is_cc_compile(struct Inst *inst) { @@ -211,28 +189,19 @@ emit_command(FILE *f, struct Inst *inst) } } -/* write every instance currently in insts[] (the same closure the - * internal engine would have built, wanted targets plus their - * transitive deps) out as a build.ninja. one rule per instance - * (ninqu already resolved everything to a literal command line, so - * there is no shared rule template to factor out), one build - * statement per instance. dep_inst edges become order-only ("||"): - * inst_stale() never consults dep_inst for staleness either, only - * (in)/(stale_extra), so mirroring that as a plain (not order-only) - * prerequisite list is what makes ninjas own mtime check agree - * with ninqus +/* write every instance in insts[] (wanted targets plus their + * transitive deps) out as a build.ninja: one rule and one build + * statement per instance, since ninqu already resolved each to a + * literal command line. dep_inst edges become order-only ("||"), + * because inst_stale() only consults (in)/(stale_extra), so this + * keeps ninja's mtime check in agreement with ninqu's * - * ninja only knows build outputs, never ninqus rule/group/meta - * names, so `ninja LIBUTIL` (what the makefile forwards $@ as) has - * nothing to resolve against on its own. wanted carries the literal - * command-line words ninqu itself was invoked with, one phony alias - * per word makes that name buildable too. when more than one target - * was requested in the same invocation every alias points at the - * whole combined closure rather than just its own slice, since - * insts[] no longer remembers which instance came from which wanted - * name, thats fine for the makefiles own use (always one target - * per invocation), just slightly conservative for a multi-target - * `ninqu -G ninja a b` run */ + * ninja only knows build outputs, not ninqu's rule/group/meta names, + * so `ninja LIBUTIL` has nothing to resolve. wanted holds the words + * ninqu was invoked with, and one phony alias per word makes each + * buildable. with several targets in one invocation every alias + * points at the whole combined closure, which is slightly + * conservative but fine for the makefile's one-target use */ void emit_ninja(const char *path, struct StrList *wanted) { diff --git a/cmd/extra/blkid.c b/cmd/extra/blkid.c @@ -6,6 +6,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <unistd.h> static char *oflag = "full"; @@ -79,8 +80,8 @@ do_blkid(const char *path) // ?man blkid: print block device attributes // ?man arguments: [device ...] -// ?man blkid locates and prints attributes (such as uuid, volume label, and -// filesystem type) ?man of block devices or partition images +// ?man blkid locates and prints attributes (such as uuid, volume label, and filesystem type) +// ?man of block devices or partition images int main(int argc, char *argv[]) { diff --git a/cmd/extra/dc.c b/cmd/extra/dc.c @@ -2,6 +2,7 @@ #include "arg.h" #include "util.h" +#include "wexec.h" #include <assert.h> #include <ctype.h> @@ -1652,11 +1653,9 @@ string(char *dst, int *np) switch (ch) { case '\0': - /* the read above already stepped input->s one past this - * buffer's own terminator; moreinput()'s own fast path - * dereferences input->s directly on the assumption it is - * always in bounds, so it has to be backed up first or that - * check reads one byte past the allocation */ + /* the read above stepped input->s past the buffer terminator. back it + * up first, moreinput() assumes input->s is in bounds and would read a + * byte past the allocation */ --input->s; if (!moreinput()) exit(0); @@ -1962,10 +1961,9 @@ printbytes(void) freeval(v); } -/* bc's own spawn() repurposes fd 0 as the read end of the pipe - * carrying its generated code, and dups the real, original stdin to - * fd 3 first so this command still has somewhere real to read from; - * standalone dc (fd 3 never opened) falls back to its own real stdin */ +/* bc spawn() makes fd 0 the read end of the pipe with the generated + * code and dups the original stdin to fd 3 first. standalone dc has no + * fd 3 and falls back to stdin */ static FILE * readsrc(void) { @@ -2113,7 +2111,7 @@ eval(void) ch = NE; break; default: - system(input->s - 1); + wsystem(input->s - 1); goto discard; } case '>': @@ -2122,10 +2120,8 @@ eval(void) relational(ch); break; case '?': - /* real dc executes the line as commands rather than pushing it - * as a string: bc's own read() relies on exactly this, since a - * bare number is already a complete, valid command that pushes - * itself */ + /* real dc runs the line as commands instead of pushing a string. bc + * read() depends on it, a bare number is a command that pushes itself */ s = NULL; if (getline(&s, &siz, readsrc()) > 0) { addinput(NULL, s); diff --git a/cmd/extra/install.c b/cmd/extra/install.c @@ -169,7 +169,7 @@ install_one(const char *src, const char *dst) // ?man arguments: source ... dest // ?man install copies each source to dest, or into dest when dest is a // ?man directory or -t is given, then applies mode/owner/group; with -// ?man -d, every argument is a directory to create instead +// ?man with -d, every argument is a directory to create instead int main(int argc, char *argv[]) { diff --git a/cmd/extra/pgrep.c b/cmd/extra/pgrep.c @@ -38,9 +38,9 @@ static struct hit *hits; static size_t nhits, hitscap; static int count; -// newest/oldest are mutually exclusive with each other and with -// printing every match as it is found, so they buffer every match -// instead of streaming it: 0 means "print as found" +/* newest/oldest are mutually exclusive with each other and with + * printing every match as it is found, so they buffer every match + * instead of streaming it: 0 means "print as found" */ enum { PGREP_NONE = 0, PGREP_NEWEST, PGREP_OLDEST }; static int select_mode; diff --git a/cmd/extra/sync.c b/cmd/extra/sync.c @@ -1,4 +1,8 @@ /* see LICENSE file for copyright and license details */ +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include <unistd.h> #include "arg.h" @@ -6,9 +10,10 @@ // ?man sync: flush disk cache // ?man synopsis: -// ?man The sync utility invokes sync(2) to flush all unwritten changes to disk -// this is usually done before shutting down, rebooting or halting. ?man ## SEE -// ALSO ?man fsync(2), sync(2) +// ?man The sync utility invokes sync(2) to flush all unwritten changes to disk. this is usually done +// ?man before shutting down, rebooting or halting. +// ?man ## SEE ALSO +// ?man fsync(2), sync(2) static void usage(void) diff --git a/cmd/extra/yap/in_all.h b/cmd/extra/yap/in_all.h @@ -1,9 +1,11 @@ #ifndef IN_ALL_H #define IN_ALL_H +#if FEATURE_YAP_EXT #ifndef _DEFAULT_SOURCE #define _DEFAULT_SOURCE #endif +#endif #include <errno.h> #include <fcntl.h> diff --git a/cmd/extra/yap/main.c b/cmd/extra/yap/main.c @@ -8,7 +8,9 @@ #include "output.h" #include "process.h" #include "prompt.h" +#include "paths.h" #include "term.h" +#include "wexec.h" int nopipe; char *progname; @@ -45,7 +47,7 @@ main(int argc, char **argv) } if (no_tty) { *--av = "cat"; - execve("/bin/cat", av, (char *const[]){NULL}); + wexecve_self(ARUU_PATH_BIN "/cat", av, (char *const[]){NULL}); } else processfiles(argc - (av - argv), av); (void)quit(); diff --git a/cmd/linux/ctrlaltdel.c b/cmd/linux/ctrlaltdel.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_SYSCALL +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/syscall.h> #include <stdio.h> diff --git a/cmd/linux/depmod.c b/cmd/linux/depmod.c @@ -264,8 +264,6 @@ usage(void) // ?man depmod: generate modules.dep and map files // ?man arguments: version // ?man depmod generates modules.dep containing dependency information for -// modprobe ?man // ?man -n: dry run print results to stdout instead of writing -// files ?man // ?man -b basedir: use basedir as prefix for module directories int main(int argc, char *argv[]) { diff --git a/cmd/linux/hwclock.c b/cmd/linux/hwclock.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_TIME +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/time.h> diff --git a/cmd/linux/insmod.c b/cmd/linux/insmod.c @@ -1,4 +1,9 @@ +#if FEATURE_LINUX_SYSCALL +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/stat.h> #include <sys/syscall.h> diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -1,4 +1,9 @@ +#if FEATURE_LINUX_SYSCALL +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include "arg.h" #include "fs.h" #include "paths.h" @@ -542,10 +547,11 @@ usage(void) // ?man modprobe: add or remove modules from the Linux kernel // ?man arguments: module [symbol=value ...] // ?man modprobe loads or removes kernel modules from the running system -// ?man It reads modules.dep, modules.alias, and modules.symbols from the -// appropriate ?man /lib/modules/release directory to resolve module names and -// dependencies, ?man loading prerequisites first. ?man without -r, modprobe -// loads the named module (and any required dependencies) ?man into the kernel +// ?man It reads modules.dep, modules.alias, and modules.symbols from the appropriate +// ?man /lib/modules/release directory to resolve module names and dependencies, +// ?man loading prerequisites first. +// ?man without -r, modprobe loads the named module (and any required dependencies) +// ?man into the kernel int main(int argc, char *argv[]) { @@ -556,63 +562,49 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -a: specify a option case 'a': - // ?man -a: Load all modules named on the command line (rather - // than stopping after the first) + // ?man -a: Load all modules named on the command line (rather than stopping after the first) aflag = 1; break; - // ?man -r: specify r option case 'r': - // ?man -r: Remove the named modules from the kernel - // dependencies are not automatically removed + // ?man -r: Remove the named modules from the kernel dependencies are not automatically + // ?man removed rflag = 1; break; - // ?man -q: specify q option case 'q': // ?man -q: Quiet mode. Suppress error messages qflag = 1; break; - // ?man -v: specify v option case 'v': // ?man -v: Verbose mode. Print each action taken vflag = 1; break; - // ?man -l: specify l option case 'l': - // ?man -l: List available modules matching the optional - // _pattern_ (a fnmatch(3) glob) + // ?man -l: List available modules matching the optional _pattern_ (a fnmatch(3) glob) lflag = 1; break; #if FEATURE_MODPROBE_SHOW_DEPENDS - // ?man -D: specify D option case 'D': - // ?man -D: Print the sequence of insmod commands that would be - // used to load the module, without actually loading anything + // ?man -D: Print the sequence of insmod commands that would be used to load the module, + // ?man without actually loading anything Dflag = 1; break; #endif #if FEATURE_MODPROBE_BLACKLIST - // ?man -b: specify b option case 'b': - // ?man -b: Skip modules listed as blacklist in - // /etc/modprobe.d/ + // ?man -b: Skip modules listed as blacklist in /etc/modprobe.d/ bflag = 1; break; #endif #if FEATURE_MODPROBE_SYSLOG - // ?man -s: specify s option case 's': - // ?man -s: Log messages to syslog(3) (facility LOG_DAEMON) - // instead of standard error + // ?man -s: Log messages to syslog(3) (facility LOG_DAEMON) instead of standard error sflag = 1; break; #endif #if FEATURE_MODPROBE_DIR_OVERRIDE - // ?man -d:file: specify d option case 'd': - // ?man -d dir: Use dir as the base directory for module files - // instead of /lib/modules/release + // ?man -d:dir: use dir as the base directory for module files instead of /lib/modules/release strlist_append(&moddirs, EARGF(usage())); break; #endif diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_MOUNT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/mount.h> #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/linux/pivot_root.c b/cmd/linux/pivot_root.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_SYSCALL +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/syscall.h> #include <stdio.h> diff --git a/cmd/linux/readahead.c b/cmd/linux/readahead.c @@ -1,5 +1,13 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_READAHEAD +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <fcntl.h> #include <limits.h> #include <stdio.h> diff --git a/cmd/linux/rmmod.c b/cmd/linux/rmmod.c @@ -1,4 +1,9 @@ +#if FEATURE_LINUX_SYSCALL +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/syscall.h> #include <fcntl.h> @@ -19,8 +24,8 @@ usage(void) // ?man rmmod: remove a module from the Linux kernel // ?man arguments: module... // ?man rmmod removes a kernel module from the running kernel -// ?man // ?man -f: force removal of a module even if it is busy or in use -// ?man // ?man -w: wait for the module to become unused before removing +// ?man -f: force removal of a module even if it is busy or in use +// ?man -w: wait for the module to become unused before removing int main(int argc, char *argv[]) { diff --git a/cmd/linux/switch_root.c b/cmd/linux/switch_root.c @@ -1,5 +1,13 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_SWITCH_ROOT_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 700 +#endif +#endif #include <sys/mount.h> #include <sys/stat.h> #include <sys/vfs.h> @@ -13,6 +21,7 @@ #include <unistd.h> #include "util.h" +#include "wexec.h" #define RAMFS_MAGIC 0x858458f6 /* some random number */ #define TMPFS_MAGIC 0x01021994 @@ -131,7 +140,7 @@ main(int argc, char *argv[]) } /* execute init */ - execv(argv[1], argv); + wexecv_self(argv[1], argv); eprintf("can't execute '%s':", argv[1]); return 1; } diff --git a/cmd/linux/unshare.c b/cmd/linux/unshare.c @@ -1,5 +1,9 @@ /* see LICENSE file for copyright and license details */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + #include <sched.h> #include <stdio.h> #include <stdlib.h> diff --git a/cmd/net/host.c b/cmd/net/host.c @@ -12,6 +12,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> diff --git a/cmd/net/httpd.c b/cmd/net/httpd.c @@ -1,5 +1,9 @@ /* see LICENSE file for copyright and license details */ +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include "arg.h" #include "util.h" @@ -13,6 +17,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/net/ifconfig.c b/cmd/net/ifconfig.c @@ -1,23 +1,13 @@ /* see LICENSE file for copyright and license details */ #include <arpa/inet.h> -#include <ctype.h> -#include <errno.h> -#include <net/if.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <sys/ioctl.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <unistd.h> +#include "net.h" #include "util.h" -int net_get_interfaces(struct NetInterface **, int *); -int net_get_stats(const char *, struct NetStats *); -int net_set_txqueuelen(const char *, int); - static void usage(void) { @@ -41,7 +31,7 @@ display_interface(const struct NetInterface *iface) iface->mac[4], iface->mac[5] ); - } else if (iface->flags & IFF_LOOPBACK) { + } else if (iface->flags & NET_IF_LOOPBACK) { printf("Local Loopback\n"); } else { printf("UNSPEC\n"); @@ -60,25 +50,25 @@ display_interface(const struct NetInterface *iface) } printf(" "); - if (iface->flags & IFF_UP) + if (iface->flags & NET_IF_UP) printf("UP "); - if (iface->flags & IFF_BROADCAST) + if (iface->flags & NET_IF_BROADCAST) printf("BROADCAST "); - if (iface->flags & IFF_DEBUG) + if (iface->flags & NET_IF_DEBUG) printf("DEBUG "); - if (iface->flags & IFF_LOOPBACK) + if (iface->flags & NET_IF_LOOPBACK) printf("LOOPBACK "); - if (iface->flags & IFF_POINTOPOINT) + if (iface->flags & NET_IF_POINTOPOINT) printf("POINTOPOINT "); - if (iface->flags & IFF_RUNNING) + if (iface->flags & NET_IF_RUNNING) printf("RUNNING "); - if (iface->flags & IFF_NOARP) + if (iface->flags & NET_IF_NOARP) printf("NOARP "); - if (iface->flags & IFF_PROMISC) + if (iface->flags & NET_IF_PROMISC) printf("PROMISC "); - if (iface->flags & IFF_ALLMULTI) + if (iface->flags & NET_IF_ALLMULTI) printf("ALLMULTI "); - if (iface->flags & IFF_MULTICAST) + if (iface->flags & NET_IF_MULTICAST) printf("MULTICAST "); printf(" MTU:%d Metric:%d\n", iface->mtu, iface->metric); @@ -114,7 +104,7 @@ list_interfaces(int all) eprintf("net_get_interfaces:"); for (i = 0; i < count; i++) { - if (all || (ifaces[i].flags & IFF_UP)) { + if (all || (ifaces[i].flags & NET_IF_UP)) { display_interface(&ifaces[i]); } } @@ -129,17 +119,13 @@ main(int argc, char *argv[]) { struct NetInterface *ifaces = NULL; const struct NetInterface *iface = NULL; - struct ifreq ifr; - struct sockaddr_in *sin; char *name; char *arg; char *slash; int aflag = 0; - int sock = -1; int i = 1; int prefix; int count = 0; - unsigned int mask; ARGBEGIN { @@ -177,68 +163,40 @@ main(int argc, char *argv[]) return 0; } - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - eprintf("socket:"); - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - while (i < argc) { arg = argv[i]; if (strcmp(arg, "up") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_UP | NET_IF_RUNNING, 1) < 0) + eprintf("net_set_flags up:"); i++; } else if (strcmp(arg, "down") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags &= ~IFF_UP; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_UP, 0) < 0) + eprintf("net_set_flags down:"); i++; } else if (strcmp(arg, "netmask") == 0) { if (i + 1 >= argc) eprintf("netmask needs an address\n"); - sin = (struct sockaddr_in *)&ifr.ifr_netmask; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, argv[i + 1], &sin->sin_addr) <= 0) - eprintf("invalid address: %s\n", argv[i + 1]); - if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) - eprintf("ioctl SIOCSIFNETMASK:"); + if (net_set_mask(name, argv[i + 1]) < 0) + eprintf("net_set_mask:"); i += 2; } else if (strcmp(arg, "broadcast") == 0) { if (i + 1 >= argc) eprintf("broadcast needs an address\n"); - sin = (struct sockaddr_in *)&ifr.ifr_broadaddr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, argv[i + 1], &sin->sin_addr) <= 0) - eprintf("invalid address: %s\n", argv[i + 1]); - if (ioctl(sock, SIOCSIFBRDADDR, &ifr) < 0) - eprintf("ioctl SIOCSIFBRDADDR:"); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_BROADCAST; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_broadcast(name, argv[i + 1]) < 0) + eprintf("net_set_broadcast:"); i += 2; } else if (strcmp(arg, "mtu") == 0) { if (i + 1 >= argc) eprintf("mtu needs a value\n"); - ifr.ifr_mtu = atoi(argv[i + 1]); - if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) - eprintf("ioctl SIOCSIFMTU:"); + if (net_set_mtu(name, atoi(argv[i + 1])) < 0) + eprintf("net_set_mtu:"); i += 2; } else if (strcmp(arg, "metric") == 0) { if (i + 1 >= argc) eprintf("metric needs a value\n"); - ifr.ifr_metric = atoi(argv[i + 1]); - if (ioctl(sock, SIOCSIFMETRIC, &ifr) < 0) - eprintf("ioctl SIOCSIFMETRIC:"); + if (net_set_metric(name, atoi(argv[i + 1])) < 0) + eprintf("net_set_metric:"); i += 2; } else if (strcmp(arg, "txqueuelen") == 0) { if (i + 1 >= argc) @@ -249,116 +207,55 @@ main(int argc, char *argv[]) } else if (strcmp(arg, "dstaddr") == 0 || strcmp(arg, "pointopoint") == 0) { if (i + 1 >= argc) eprintf("%s needs an address\n", arg); - sin = (struct sockaddr_in *)&ifr.ifr_dstaddr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, argv[i + 1], &sin->sin_addr) <= 0) - eprintf("invalid address: %s\n", argv[i + 1]); - if (ioctl(sock, SIOCSIFDSTADDR, &ifr) < 0) - eprintf("ioctl SIOCSIFDSTADDR:"); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_POINTOPOINT; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_dstaddr(name, argv[i + 1]) < 0) + eprintf("net_set_dstaddr:"); i += 2; } else if (strcmp(arg, "arp") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags &= ~IFF_NOARP; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_NOARP, 0) < 0) + eprintf("net_set_flags arp:"); i++; } else if (strcmp(arg, "-arp") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_NOARP; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_NOARP, 1) < 0) + eprintf("net_set_flags -arp:"); i++; } else if (strcmp(arg, "promisc") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_PROMISC; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_PROMISC, 1) < 0) + eprintf("net_set_flags promisc:"); i++; } else if (strcmp(arg, "-promisc") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags &= ~IFF_PROMISC; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_PROMISC, 0) < 0) + eprintf("net_set_flags -promisc:"); i++; } else if (strcmp(arg, "allmulti") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_ALLMULTI; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_ALLMULTI, 1) < 0) + eprintf("net_set_flags allmulti:"); i++; } else if (strcmp(arg, "-allmulti") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags &= ~IFF_ALLMULTI; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_ALLMULTI, 0) < 0) + eprintf("net_set_flags -allmulti:"); i++; } else if (strcmp(arg, "multicast") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_MULTICAST; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_MULTICAST, 1) < 0) + eprintf("net_set_flags multicast:"); i++; } else if (strcmp(arg, "-multicast") == 0) { - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags &= ~IFF_MULTICAST; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); + if (net_set_flags(name, NET_IF_MULTICAST, 0) < 0) + eprintf("net_set_flags -multicast:"); i++; } else { - sin = (struct sockaddr_in *)&ifr.ifr_addr; - sin->sin_family = AF_INET; - slash = strchr(arg, '/'); - prefix = -1; + slash = strchr(arg, '/'); + prefix = -1; if (slash) { *slash = '\0'; prefix = atoi(slash + 1); } - if (inet_pton(AF_INET, arg, &sin->sin_addr) <= 0) { - eprintf( - "unknown action or invalid address: " - "%s\n", - arg - ); - } - if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) - eprintf("ioctl SIOCSIFADDR:"); - - if (prefix >= 0) { - mask = 0; - if (prefix > 0) - mask = htonl(~0U << (32 - prefix)); - sin = (struct sockaddr_in *)&ifr.ifr_netmask; - sin->sin_family = AF_INET; - sin->sin_addr.s_addr = mask; - if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) - eprintf("ioctl SIOCSIFNETMASK:"); - } - - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCGIFFLAGS:"); - ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) - eprintf("ioctl SIOCSIFFLAGS:"); - + if (net_add_addr(name, arg, prefix) < 0) + eprintf("net_add_addr:"); i++; } } free(ifaces); - close(sock); if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) return 1; diff --git a/cmd/net/ip.c b/cmd/net/ip.c @@ -1,49 +1,21 @@ /* see LICENSE file for copyright and license details */ #include <arpa/inet.h> -#include <ctype.h> -#include <errno.h> -#include <net/if.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <sys/socket.h> -#include <sys/types.h> -#include <unistd.h> +#include "net.h" #include "util.h" -#if FEATURE_IP_ROUTE_ADD_DEL -static void -prefix_to_mask(int prefix, char *mask_str, size_t mask_str_len) -{ - unsigned long mask; - struct in_addr addr; - - if (prefix < 0) - prefix = 32; - if (prefix > 32) - eprintf("invalid prefix: %d\n", prefix); - - if (prefix == 0) { - mask = 0; - } else { - mask = 0xffffffffUL << (32 - prefix); - } - addr.s_addr = htonl(mask); - strlcpy(mask_str, inet_ntoa(addr), mask_str_len); -} -#endif - static void usage(void) { eprintf("usage: %s [addr | link | route] [args...]\n", argv0); } -/* real ip(8) and BusyBox's own ip applet both accept any unambiguous - * prefix of an object name (ip a, ip li, ip ro, ...), not just the - * full word: obj matches full whenever it is a real, non-empty prefix */ +/* like ip(8) and busybox, accept any unambiguous prefix of an object + * name (ip a, ip li, ip ro), not only the full word */ static int is_object(const char *obj, const char *full) { @@ -75,13 +47,13 @@ static void print_link_iface(const struct NetInterface *iface) { printf("%d: %s: mtu %d ", iface->metric, iface->name, iface->mtu); - if (iface->flags & IFF_UP) + if (iface->flags & NET_IF_UP) printf("UP "); - if (iface->flags & IFF_LOOPBACK) + if (iface->flags & NET_IF_LOOPBACK) printf("LOOPBACK "); - if (iface->flags & IFF_POINTOPOINT) + if (iface->flags & NET_IF_POINTOPOINT) printf("POINTOPOINT "); - if (iface->flags & IFF_RUNNING) + if (iface->flags & NET_IF_RUNNING) printf("RUNNING "); printf("\n"); if (iface->has_mac) { @@ -210,7 +182,7 @@ do_link(int argc, char *argv[]) struct NetInterface *ifaces = NULL; char *cmd, *dev, *mac_str; int count = 0; - int i, mtu; + int i, mtu, qlen, set; unsigned char mac[6]; if (argc == 0) @@ -245,10 +217,10 @@ do_link(int argc, char *argv[]) dev = argv[1]; for (i = 2; i < argc; i++) { if (strcmp(argv[i], "up") == 0) { - if (net_set_flags(dev, IFF_UP, 1) < 0) + if (net_set_flags(dev, NET_IF_UP, 1) < 0) eprintf("net_set_flags up:"); } else if (strcmp(argv[i], "down") == 0) { - if (net_set_flags(dev, IFF_UP, 0) < 0) + if (net_set_flags(dev, NET_IF_UP, 0) < 0) eprintf("net_set_flags down:"); } else if (strcmp(argv[i], "mtu") == 0 && i + 1 < argc) { mtu = atoi(argv[i + 1]); @@ -262,41 +234,33 @@ do_link(int argc, char *argv[]) eprintf("net_set_mac:"); i++; #if FEATURE_IP_LINK_SET -#ifdef IFF_NOARP } else if (strcmp(argv[i], "arp") == 0 && i + 1 < argc) { - int set = (strcmp(argv[i + 1], "off") == 0); - if (net_set_flags(dev, IFF_NOARP, set) < 0) + set = (strcmp(argv[i + 1], "off") == 0); + if (net_set_flags(dev, NET_IF_NOARP, set) < 0) eprintf("net_set_flags arp:"); i++; -#endif -#ifdef IFF_MULTICAST } else if (strcmp(argv[i], "multicast") == 0 && i + 1 < argc) { - int set = (strcmp(argv[i + 1], "on") == 0); - if (net_set_flags(dev, IFF_MULTICAST, set) < 0) + set = (strcmp(argv[i + 1], "on") == 0); + if (net_set_flags(dev, NET_IF_MULTICAST, set) < 0) eprintf("net_set_flags multicast:"); i++; -#endif -#ifdef IFF_ALLMULTI } else if (strcmp(argv[i], "allmulticast") == 0 && i + 1 < argc) { - int set = (strcmp(argv[i + 1], "on") == 0); - if (net_set_flags(dev, IFF_ALLMULTI, set) < 0) + set = (strcmp(argv[i + 1], "on") == 0); + if (net_set_flags(dev, NET_IF_ALLMULTI, set) < 0) eprintf("net_set_flags allmulticast:"); i++; -#endif -#ifdef IFF_PROMISC } else if (strcmp(argv[i], "promisc") == 0 && i + 1 < argc) { - int set = (strcmp(argv[i + 1], "on") == 0); - if (net_set_flags(dev, IFF_PROMISC, set) < 0) + set = (strcmp(argv[i + 1], "on") == 0); + if (net_set_flags(dev, NET_IF_PROMISC, set) < 0) eprintf("net_set_flags promisc:"); i++; -#endif } else if (strcmp(argv[i], "name") == 0 && i + 1 < argc) { if (net_set_name(dev, argv[i + 1]) < 0) eprintf("net_set_name:"); dev = argv[i + 1]; i++; } else if (strcmp(argv[i], "txqueuelen") == 0 && i + 1 < argc) { - int qlen = atoi(argv[i + 1]); + qlen = atoi(argv[i + 1]); if (net_set_txqueuelen(dev, qlen) < 0) eprintf("net_set_txqueuelen:"); i++; @@ -316,7 +280,6 @@ do_route(int argc, char *argv[]) char *cmd, *dst, *slash; const char *gateway = NULL, *dev = NULL; int prefix_len = -1, metric = -1, i; - char mask_str[32]; if (argc == 0) cmd = "show"; @@ -346,8 +309,8 @@ do_route(int argc, char *argv[]) } else if (strcmp(dst, "default") == 0) { prefix_len = 0; } - - prefix_to_mask(prefix_len, mask_str, sizeof(mask_str)); + if (prefix_len > 32) + eprintf("invalid prefix: %d\n", prefix_len); for (i = 2; i < argc; i++) { if (strcmp(argv[i], "via") == 0 && i + 1 < argc) { @@ -363,10 +326,10 @@ do_route(int argc, char *argv[]) } if (strcmp(cmd, "add") == 0) { - if (net_add_route(dst, gateway, mask_str, dev, metric) < 0) + if (net_add_route(dst, gateway, dev, prefix_len, metric) < 0) eprintf("net_add_route:"); } else { - if (net_del_route(dst, gateway, mask_str, dev, metric) < 0) + if (net_del_route(dst, gateway, dev, prefix_len, metric) < 0) eprintf("net_del_route:"); } return 0; @@ -393,11 +356,12 @@ do_route(int argc, char *argv[]) // ?man flush all addresses from interface // ?man ### link [show | list [dev <device>]] // ?man show interface link states -// ?man ### link set <interface> [up | down | mtu <mtu> | address <mac> | arp -// on|off | multicast on|off | allmulticast on|off | promisc on|off | name -// <newname> | txqueuelen <qlen>] ?man configure interface settings ?man ### -// route [show | list] ?man show routing table ?man ### route add <prefix> [via -// <gateway>] [dev <device>] [metric <metric>] ?man add route to routing table +// ?man ### link set <interface> [up | down | mtu <mtu> | address <mac> | arp on|off | multicast on|off | allmulticast on|off | promisc on|off | name <newname> | txqueuelen <qlen>] +// ?man configure interface settings +// ?man ### route [show | list] +// ?man show routing table +// ?man ### route add <prefix> [via <gateway>] [dev <device>] [metric <metric>] +// ?man add route to routing table // ?man ### route del <prefix> [via <gateway>] [dev <device>] [metric <metric>] // ?man delete route from routing table int diff --git a/cmd/net/ping.c b/cmd/net/ping.c @@ -1,5 +1,11 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_NET_IOCTL +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include "arg.h" #include "util.h" diff --git a/cmd/net/sdhcp.c b/cmd/net/sdhcp.c @@ -1,5 +1,11 @@ /* sdhcp: simple DHCP client, ported from git.2f30.org/sdhcp */ /* see LICENSE file for copyright and license details */ +#if FEATURE_NET_IOCTL +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include "arg.h" #include "util.h" #include "wexec.h" @@ -405,7 +411,8 @@ calctimeout(int n, struct itimerspec *ts) static void run(void) { - int forked = 0, t; + int forked = 0, t; + pid_t pid; struct itimerspec timeout = {0}; uint32_t renewaltime, rebindingtime, lease; @@ -460,7 +467,10 @@ Bound: acceptlease(); puts("Bound. Network configured."); if (!fflag && !forked) { - if (fork()) + pid = fork(); + if (pid < 0) + eprintf("fork:"); + if (pid > 0) exit(0); forked = 1; } diff --git a/cmd/net/wget.c b/cmd/net/wget.c @@ -1,5 +1,9 @@ /* see license file for copyright and license details */ +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include "arg.h" #include "tls.h" #include "util.h" @@ -14,8 +18,10 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <sys/socket.h> #include <sys/stat.h> +#include <sys/time.h> #include <sys/types.h> #include <unistd.h> @@ -462,7 +468,7 @@ main(int argc, char *argv[]) post_len = st.st_size; } - /* wgets own -t: 0 means retry forever */ + /* -t 0 means retry forever */ max_tries = tries == 0 ? INT_MAX : tries; while (!tls_sock) { diff --git a/cmd/posix/awk/main.c b/cmd/posix/awk/main.c @@ -25,6 +25,11 @@ const char *version = "version 20260426"; #define DEBUG +#if FEATURE_AWK_RANDOM +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include "awk.h" #include <ctype.h> #include <locale.h> diff --git a/cmd/posix/awk/run.c b/cmd/posix/awk/run.c @@ -27,8 +27,15 @@ #endif #define DEBUG +#if FEATURE_AWK_RANDOM +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include "awk.h" #include "awkgram.tab.h" +#include "wexec.h" + #include <ctype.h> #include <fcntl.h> #include <limits.h> @@ -2180,7 +2187,6 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ char *buf; Node *nextarg; FILE *fp; - int status = 0; int estatus = 0; t = ptoi(a[0]); @@ -2224,20 +2230,7 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ break; case FSYSTEM: fflush(stdout); /* in case something is buffered already */ - estatus = status = system(getsval(x)); - if (status != -1) { - if (WIFEXITED(status)) { - estatus = WEXITSTATUS(status); - } else if (WIFSIGNALED(status)) { - estatus = WTERMSIG(status) + 256; -#ifdef WCOREDUMP - if (WCOREDUMP(status)) - estatus += 256; -#endif - } else /* something else?!? */ - estatus = 0; - } - /* else estatus was set to -1 */ + estatus = wsystem(getsval(x)); u = estatus; break; case FRAND: @@ -2391,7 +2384,7 @@ openfile(int a, const char *us, bool *pnewflag) *pnewflag = false; return files[i].fp; } - if (a == FFLUSH) /* didn't find it, so dont create it! */ + if (a == FFLUSH) /* didnt find it, so dont create it! */ return NULL; for (i = 0; i < nfiles; i++) if (files[i].fp == NULL) @@ -2421,9 +2414,9 @@ openfile(int a, const char *us, bool *pnewflag) fp = fopen(s, "a"); m = GT; /* so can mix > and >> */ } else if (a == '|') { /* output pipe */ - fp = popen(s, "w"); + fp = wpopen(s, NULL, "w"); } else if (a == LE) { /* input pipe */ - fp = popen(s, "r"); + fp = wpopen(s, NULL, "r"); } else if (a == LT) { /* getline <file */ fp = strcmp(s, "-") == 0 ? stdin : fopen(s, "r"); /* "-" is stdin */ } else /* cant happen */ @@ -2475,7 +2468,7 @@ closefile(Node **a, int n) if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) stat = freopen("/dev/null", "r+", files[i].fp) == NULL; else if (files[i].mode == '|' || files[i].mode == LE) - stat = pclose(files[i].fp) == -1; + stat = wpclose(files[i].fp) == -1; else stat = fclose(files[i].fp) == EOF; if (stat) @@ -2511,7 +2504,7 @@ closeall(void) if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) continue; if (files[i].mode == '|' || files[i].mode == LE) - stat = pclose(files[i].fp) == -1; + stat = wpclose(files[i].fp) == -1; else stat = fclose(files[i].fp) == EOF; if (stat) diff --git a/cmd/posix/bc.y b/cmd/posix/bc.y @@ -1,4 +1,9 @@ %{ +#if FEATURE_BC_ASCII +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <libgen.h> #include <unistd.h> @@ -13,6 +18,7 @@ #include "arg.h" #include "util.h" +#include "wexec.h" #define DIGITS "0123456789ABCDEF" #define NESTED_MAX 32 @@ -66,7 +72,7 @@ static char *dcprog = "dc"; %union { char *str; - char id[16]; // matches dc's own REGSIZ: an extended register name's cap + char id[16]; // dc REGSIZ: cap on an extended register name Macro *macro; } @@ -154,20 +160,14 @@ stat : exprstat | for '(' expr ';' rel ';' expr ')' optnl stat {$$ = forcode($1, $3, $5, $7, $10);} ; -// real scripts routinely put a while/if/for's own body on the next -// line instead of right after the condition; nothing else in this -// grammar needs a newline here, since a body wrapped in { } already -// goes through statlst, which handles its own internal newlines +// a while/if/for body may start on the next line. a { } body goes +// through statlst, which handles its own newlines optnl : | optnl '\n' ; -// print takes a comma-separated list of any length, mixing strings -// and expressions freely: real scripts (the kernel's own timeconst.bc -// generator among them) routinely print three or more at once. no -// item here ever gets an automatic trailing newline of its own, -// matching real bc: whatever newlines appear come from the items -// themselves +// print takes any number of strings and expressions, mixed. no item +// gets an implicit trailing newline, as in real bc prlst : pritem | prlst ',' pritem {$$ = code("%s%s", $1, $3);} ; @@ -310,11 +310,8 @@ err: eprintf("writing to dc:"); } -// grows the shared code buffer geometrically to fit at least 'need' -// bytes: a single generated dc macro (an if/else body, a print list, -// a deeply nested function) has no fixed upper bound, unlike the -// stdio-buffering constant BUFSIZ this buffer borrowed its original -// size from +// grow the code buffer geometrically to fit need bytes. a generated dc +// macro has no fixed upper bound, unlike BUFSIZ static void growbuff(size_t need) { @@ -538,9 +535,8 @@ whilecode(Macro *d, char *cmp, char *body) return s; } -// the trailing relational operator on a cond's own generated code -// (see the rel grammar rule) is always one of these six forms; an -// else branch runs on whichever of them means "the opposite happened" +// the trailing relational op (see rel) is one of these six, else runs +// on the opposite one static char * invertrel(char *cmp) { @@ -579,10 +575,9 @@ invertrel(char *cmp) return s; } -// an else branch's own stored body needs a register distinct from the -// then branch's d->id: nested caps how high d->id itself ever goes, -// so offsetting by it lands on a register no other nesting level, and -// no ordinary (single-letter or, under -i, named) variable, ever uses +// an else body needs a register distinct from the then branch d->id. +// nested bounds d->id, so offsetting by it never collides with another +// nesting level or a named variable static char * ifcode(Macro *d, char *cmp, char *body, char *ebody) { @@ -713,10 +708,8 @@ iden(int ch) if (p->str) return p->token; - // strict POSIX bc only ever names a variable/function with a - // single lowercase letter; every real bc script in the wild - // (the kernel's own timeconst.bc among them) freely uses - // multi-character names anyway, same as GNU bc's own default + // posix bc names variables and functions with one lowercase letter, + // but real scripts use longer names, as GNU bc does #if !FEATURE_BC_MULTICHAR if (!sflag) yyerror("invalid keyword"); @@ -788,11 +781,9 @@ string(int ch) if ((ch = getc(filep)) == '"') break; #if FEATURE_BC_ESCAPES - // strict POSIX bc has no escape sequences in a string at - // all; every real script (again, the kernel's own scripts - // among them) assumes GNU bc's \n/\t/etc, since dc's own - // string reader passes a literal byte straight through - // with nothing left to turn it into a real newline later + // posix bc has no string escapes, but scripts assume GNU \n \t etc, + // and dc passes a literal byte through with nothing to turn it into a + // newline later if (ch == '\\') { switch (ch = getc(filep)) { case 'a': @@ -817,9 +808,7 @@ string(int ch) ch = '\v'; break; case 'q': - // GNU bc's own escape for a literal double - // quote, needed since a bc string's own - // delimiter is " with no other way in + // GNU escape for a literal double quote, the only way into a bc string ch = '"'; break; case '\\': @@ -963,10 +952,9 @@ static void spawn(void) { int fds[2]; - // dc only accepts the extended, multi-character register - // syntax bc.y's own ftn()/var()/ary() emit for a non-single- - // letter name (see iden() above) when told -i: whenever this - // build can produce that syntax at all, dc always needs it + // dc needs the extended register syntax from ftn()/var()/ary() (see + // iden()) for any name that is not one letter, so pass -i whenever + // this build can emit it #if FEATURE_BC_MULTICHAR char *par = "-i"; #else @@ -974,14 +962,10 @@ spawn(void) #endif char errmsg[] = "bc:error execing dc\n"; - // fd 0 is about to become the read end of the code pipe below, - // but dc's own "?" (bc's read()) needs the real, original stdin: - // stash it on a fixed fd dc knows to check, or read() would read - // straight out of this project's own generated dc code instead - // of whatever the user actually piped in. this has to happen - // before pipe() claims its own two fds, or dup2 here could - // clobber one of them (fd 3 is often the next one pipe() itself - // would have picked) + // fd 0 becomes the read end of the code pipe below, but dc ? (bc + // read()) needs the original stdin. stash it on fd 3, which dc checks, + // or read() would consume the generated code. do it before pipe() so + // dup2 cant clobber one of its fds dup2(0, 3); if (pipe(fds) < 0) @@ -1002,9 +986,9 @@ spawn(void) dup(fds[0]); close(fds[0]); close(fds[1]); - execlp(dcprog, "dc", par, (char *) NULL); + wexecvp_self(dcprog, (char *const[]){"dc", par, NULL}); - /* it shouldn't happen */ + /* it shouldnt happen */ write(3, errmsg, sizeof(errmsg)-1); _Exit(2); } @@ -1093,11 +1077,8 @@ main(int argc, char *argv[]) if (lflag) bc(PREFIX "/share/misc/bc.library"); - // stdin is only the script source when no file was given at all: - // a real file argument alongside piped stdin data (the kernel's - // own "echo $HZ | bc -q file.bc" being the standing example) means - // that data is meant for read(), not for bc itself to parse as - // more of the program + // stdin is the script only when no file was given. with a file plus + // piped data (echo $HZ | bc -q file.bc) the data is for read() if (!*argv) { bc(NULL); } else { diff --git a/cmd/posix/cal.c b/cmd/posix/cal.c @@ -160,7 +160,7 @@ drawcal(size_t year, int month, size_t ncols, size_t nmons, int fday) static void usage(void) { -#ifdef FEATURE_CAL_EXT +#if FEATURE_CAL_EXT eprintf( "usage: %s [-1 | -3 | -y | -n num] " "[-s | -m | -f num] [-c num] [[month] year]\n", @@ -189,7 +189,7 @@ main(int argc, char *argv[]) if (!isatty(STDOUT_FILENO)) ltime = NULL; /* dont highlight today's date */ -#ifdef FEATURE_CAL_EXT +#if FEATURE_CAL_EXT ncols = 3; nmons = 0; #else @@ -199,7 +199,7 @@ main(int argc, char *argv[]) ARGBEGIN { -#ifdef FEATURE_CAL_EXT +#if FEATURE_CAL_EXT // ?man -1: specify option flag case '1': nmons = 1; @@ -247,7 +247,7 @@ main(int argc, char *argv[]) } ARGEND -#ifdef FEATURE_CAL_EXT +#if FEATURE_CAL_EXT if (nmons == 0) { if (argc == 1) { month = 1; diff --git a/cmd/posix/cat.c b/cmd/posix/cat.c @@ -23,10 +23,8 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -u: specify u option case 'u': - // ?man -u: ignored; accepted for posix compatibility; output is - // always unbuffered + // ?man -u: ignored; accepted for posix compatibility; output is always unbuffered break; default: usage(); @@ -61,8 +59,11 @@ main(int argc, char *argv[]) // ?man // ?man ## Exit status // ?man - // ?man cat exits 0 on success, and >0 if an error occurs reading any - // file ?man or writing to standard output ?man ?man ## see also ?man + // ?man cat exits 0 on success, and >0 if an error occurs reading any file + // ?man or writing to standard output + // ?man + // ?man ## see also + // ?man // ?man cp(1), dd(1) // ?man diff --git a/cmd/posix/df.c b/cmd/posix/df.c @@ -1,14 +1,12 @@ /* see LICENSE file for copyright and license details */ -#include <sys/statvfs.h> +#include "filesystem.h" +#include "util.h" -#include <mntent.h> +#include <errno.h> #include <stdio.h> -#include <stdlib.h> #include <string.h> -#include "util.h" - static long blksize = 512; static int aflag = 0; static int hflag = 0; @@ -67,17 +65,17 @@ print_human( static int mnt_show(const char *fsname, const char *dir) { - struct statvfs s; - unsigned long long total, used, avail; - int capacity = 0; - int bs; + struct FilesystemStatus status; + unsigned long long total, used, avail; + int capacity = 0; + int bs; - if (statvfs(dir, &s) < 0) + if (fs_get_status(dir, &status) < 0) return -1; - bs = s.f_frsize / blksize; - total = s.f_blocks * bs; - avail = s.f_bfree * bs; + bs = status.block_size / blksize; + total = status.total_blocks * bs; + avail = status.free_blocks * bs; used = total - avail; if (used + avail) { @@ -105,9 +103,10 @@ usage(void) int main(int argc, char *argv[]) { - struct mntent *me = NULL; - FILE *fp; - int ret = 0; + struct FilesystemMount *mounts = NULL; + size_t count; + size_t i; + int ret = 0; ARGBEGIN { @@ -128,9 +127,11 @@ main(int argc, char *argv[]) break; // ?man -s: silent mode or print summary case 's': + eprintf("-s is not supported\n"); + break; // ?man -i: interactive mode or prompt for confirmation case 'i': - eprintf("not implemented\n"); + eprintf("-i is not supported\n"); break; default: usage(); @@ -149,17 +150,18 @@ main(int argc, char *argv[]) blksize ); - fp = setmntent("/proc/mounts", "r"); - if (!fp) - eprintf("setmntent %s:", "/proc/mounts"); - while ((me = getmntent(fp)) != NULL) { - if (aflag == 0) - if (strcmp(me->mnt_type, "rootfs") == 0) - continue; - if (mnt_show(me->mnt_fsname, me->mnt_dir) < 0) + if (fs_get_mounts(&mounts, &count) < 0) { + if (errno == ENOTSUP) + eprintf("filesystem mount table is not supported\n"); + eprintf("cannot read filesystem mount table:"); + } + for (i = 0; i < count; i++) { + if (aflag == 0 && strcmp(mounts[i].type, "rootfs") == 0) + continue; + if (mnt_show(mounts[i].source, mounts[i].path) < 0) ret = 1; } - endmntent(fp); + fs_free_mounts(mounts, count); return ret; } diff --git a/cmd/posix/diff.c b/cmd/posix/diff.c @@ -1,4 +1,9 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_DIFF_EXT +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include "paths.h" #include "util.h" #include "wexec.h" @@ -404,13 +409,7 @@ stop_pr(struct Pr *pr) // ?man diff: differential file and directory comparator // ?man arguments: file1 file2 -// ?man synopsis: [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] [--brief] -// [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] -// [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] -// [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] -// [--normal] [--rcs] [--show-c-function] [--starting-file] -// [--speed-large-files] [--strip-trailing-cr] [--tabsize number] [--text] [-I -// pattern] [-F pattern] [-L label] file1 file2 +// ?man synopsis: [-aBbdipTtw] [-c|-e|-f|-n|-q|-u|-y] [-A algo] [--brief] [--color=when] [--changed-group-format GFMT] [--ed] [--expand-tabs] [--forward-ed] [--ignore-all-space] [--ignore-case] [--ignore-space-change] [--initial-tab] [--minimal] [--no-dereference] [--no-ignore-file-name-case] [--normal] [--rcs] [--show-c-function] [--starting-file] [--speed-large-files] [--strip-trailing-cr] [--tabsize number] [--text] [-I pattern] [-F pattern] [-L label] file1 file2 int main(int argc, char **argv) { diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c @@ -1328,7 +1328,6 @@ repeat: goto print; case 'l': case 'n': - // ?man -p: preserve file attributes case 'p': back(cmd); chkprint(1); @@ -1387,7 +1386,6 @@ repeat: error("nothing to undo"); undo(); break; - // ?man -s: silent mode or print summary case 's': deflines(curln, curln); c = input(); diff --git a/cmd/posix/env.c b/cmd/posix/env.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_ENV_PUTENV +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <errno.h> #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_CASEFOLD +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include "config.h" #include "util.h" #include "wexec.h" @@ -1022,13 +1027,13 @@ parse(int argc, char **argv) default: /* this expression can be simplified, but i decided copy * the verbage from the wikipedia page in order to more - * clearly explain what's going on */ + * clearly explain whats going on */ while (top-- > stack && ((tok->u.oinfo->lassoc && tok->u.oinfo->prec <= (*top)->u.oinfo->prec) || (!tok->u.oinfo->lassoc && tok->u.oinfo->prec < (*top)->u.oinfo->prec))) *out++ = **top; - /* top now points to either an operator we didn't pop, + /* top now points to either an operator we didnt pop, * or stack[-1] either way we need to increment it * before using it, then increment again so the stack * works */ diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c @@ -15,6 +15,15 @@ static void addpattern(const char *); static void addpatternfile(FILE *); static int grep(FILE *, const char *); +// true if argv0's own basename is exactly name, ignoring any path prefix +static int +invoked_as(const char *name) +{ + const char *base = strrchr(argv0, '/'); + base = base ? base + 1 : argv0; + return strcmp(base, name) == 0; +} + static int Eflag; static int Fflag; static int Hflag; @@ -266,25 +275,28 @@ main(int argc, char *argv[]) SLIST_INIT(&phead); + // egrep/fgrep: legacy invocation names many upstream scripts still + // assume exist as their own commands rather than as grep -E/-F + if (invoked_as("egrep")) { + Eflag = 1; + flags |= REG_EXTENDED; + } else if (invoked_as("fgrep")) { + Fflag = 1; + } + ARGBEGIN { #if FEATURE_GREP_CONTEXT - // ?man -A:num: specify A option + // ?man -A:num: print num lines of trailing context after each match case 'A': - // ?man -A num: print num lines of trailing context after each - // match Aflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -B:num: specify B option + // ?man -B:num: print num lines of leading context before each match case 'B': - // ?man -B num: print num lines of leading context before each - // match Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; - // ?man -C:num: specify C option + // ?man -C:num: print num lines of context before and after each match case 'C': - // ?man -C num: print num lines of context before and after each - // match; equivalent to -A num -B num Aflag = Bflag = estrtonum(EARGF(usage()), 0, LONG_MAX); break; // ?man ARGNUM: specify RGNUM option @@ -293,37 +305,30 @@ main(int argc, char *argv[]) break; #endif #if FEATURE_GREP_MAX_COUNT - // ?man -m:num: specify m option + // ?man -m:num: stop reading a file after num matching lines case 'm': - // ?man -m num: stop reading a file after num matching lines mval = estrtonum(EARGF(usage()), 0, LONG_MAX); break; #endif - // ?man -E: specify E option case 'E': // ?man -E: interpret pattern as an extended regular expression Eflag = 1; Fflag = 0; flags |= REG_EXTENDED; break; - // ?man -F: specify F option case 'F': - // ?man -F: interpret pattern as a list of fixed strings - // separated by newlines + // ?man -F: interpret pattern as a list of fixed strings separated by newlines Fflag = 1; Eflag = 0; flags &= ~REG_EXTENDED; break; - // ?man -H: specify H option case 'H': // ?man -H: always print the file name with matching lines Hflag = 1; hflag = 0; break; - // ?man -e:file: specify e option + // ?man -e:file: specify a pattern to match; may be given multiple times case 'e': - // ?man -e pattern: specify a pattern to match; may be given - // multiple times arg = EARGF(usage()); if (!(fp = fmemopen(arg, strlen(arg) + 1, "r"))) eprintf("fmemopen:"); @@ -331,9 +336,8 @@ main(int argc, char *argv[]) efshut(fp, arg); eflag = 1; break; - // ?man -f:file: specify f option + // ?man -f:file: read patterns from file, one per line case 'f': - // ?man -f file: read patterns from file, one per line arg = EARGF(usage()); fp = fopen(arg, "r"); if (!fp) @@ -342,56 +346,41 @@ main(int argc, char *argv[]) efshut(fp, arg); fflag = 1; break; - // ?man -h: specify h option case 'h': // ?man -h: never print file names with matching lines hflag = 1; Hflag = 0; break; - // ?man -c: specify c option case 'c': // ?man -c: print only a count of matching lines per file /* FALLTHROUGH */ - // ?man -l: specify l option case 'l': - // ?man -l: print only the names of files with at least one - // matching line + // ?man -l: print only the names of files with at least one matching line /* FALLTHROUGH */ - // ?man -n: specify n option case 'n': - // ?man -n: prefix each matching line with its line number - // within its file + // ?man -n: prefix each matching line with its line number within its file /* FALLTHROUGH */ - // ?man -q: specify q option case 'q': - // ?man -q: quiet mode; exit immediately with status 0 on first - // match and write nothing + // ?man -q: quiet mode; exit immediately with status 0 on first match and write nothing mode = ARGC(); break; - // ?man -i: specify i option case 'i': // ?man -i: perform case-insensitive matching flags |= REG_ICASE; iflag = 1; break; - // ?man -s: specify s option case 's': - // ?man -s: suppress error messages about nonexistent or - // unreadable files + // ?man -s: suppress error messages about nonexistent or unreadable files sflag = 1; break; - // ?man -v: specify v option case 'v': - // ?man -v: invert the sense of matching to select non-matching - // lines + // ?man -v: invert the sense of matching to select non-matching lines vflag = 1; break; - // ?man -w: specify w option case 'w': // ?man -w: match only whole words wflag = 1; break; - // ?man -x: specify x option case 'x': // ?man -x: match only whole lines xflag = 1; diff --git a/cmd/posix/id.c b/cmd/posix/id.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_ID_GROUPLIST +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/types.h> #include <ctype.h> diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LN_RELATIVE +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/stat.h> #include <errno.h> @@ -130,8 +135,7 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -f: force creation of links by removing existing destination - // files + // ?man -f: force creation of links by removing existing destination files case 'f': fflag = 1; break; @@ -144,8 +148,8 @@ main(int argc, char *argv[]) flags &= ~AT_SYMLINK_FOLLOW; break; #if FEATURE_LN_RELATIVE - // ?man -r: with -s, store the target as a path relative to name's - // own directory instead of copying it as given + // ?man -r: with -s, store the target as a path relative to name's own directory instead of + // ?man copying it as given case 'r': rflag = 1; sflag = 1; @@ -156,9 +160,8 @@ main(int argc, char *argv[]) sflag = 1; break; #if FEATURE_LN_NO_TARGET_DIR - // ?man -T: treat name as a regular file, never as a directory to - // place the link into, even if a file of that name is currently - // a directory + // ?man -T: treat name as a regular file, never as a directory to place the link into, even if a + // ?man file of that name is currently a directory case 'T': Tflag = 1; break; @@ -232,10 +235,9 @@ main(int argc, char *argv[]) #if FEATURE_LN_RELATIVE if (rflag) { - /* targetdir only names the real destination directory when name - * was defaulted from target's own basename (the dir-argument - * form); an explicit name may itself carry a directory prefix - * (ln -r target dir/name), which then names it instead */ + /* targetdir is the real destination dir only when name defaulted from + * the basename of target. an explicit name may carry a dir prefix + * (ln -r target dir/name), which then names the destination */ char dirbuf[PATH_MAX]; const char *fromdir = targetdir; diff --git a/cmd/posix/logger.c b/cmd/posix/logger.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LOGGER_SYSLOG +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <stdio.h> #include <stdlib.h> #include <string.h> diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c @@ -1,5 +1,10 @@ /* see license file for copyright and license details */ +#if FEATURE_LS_COLOR +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/stat.h> #include <sys/types.h> #ifndef major @@ -417,11 +422,9 @@ entcmp(const void *va, const void *vb) const struct entry *a = va, *b = vb; switch (sort) { - // ?man -S: sort by file size case 'S': cmp = b->size - a->size; break; - // ?man -t: sort by modification time case 't': if (!(cmp = b->t.tv_sec - a->t.tv_sec)) cmp = b->t.tv_nsec - a->t.tv_nsec; @@ -725,7 +728,7 @@ main(int argc, char *argv[]) // ?man --: specify - option case '-': #if FEATURE_LS_COLOR - // ?man --color [when]: control coloring + // ?man --color:when: control coloring if (strncmp(argv[0], "-color", 6) == 0) { char *val = NULL; if (argv[0][6] == '=') { diff --git a/cmd/posix/nl.c b/cmd/posix/nl.c @@ -71,7 +71,6 @@ nl(const char *fname, FILE *fp) if (line.data[0] != '\n') donumber = 1; break; - // ?man -p: preserve file attributes case 'p': if (!regexec(preg + section, line.data, 0, NULL, 0)) donumber = 1; diff --git a/cmd/posix/od.c b/cmd/posix/od.c @@ -62,7 +62,6 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) }; switch (format) { - // ?man -a: print or show all entries case 'a': c = *s & ~128; /* clear high bit as required by standard */ if (c < LEN(namedict) || c == 127) { @@ -71,7 +70,6 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) printf(" %3c", c); } break; - // ?man -c: print count or perform stdout action case 'c': if (strchr("\a\b\t\n\v\f\r\0", *s)) { printf(" %3s", escdict[*s]); @@ -94,13 +92,9 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) } } /* x/o print a fixed-width, zero-padded field: 2 hex digits per - * byte, or ceil(8*len/3) octal digits, the exact digit count - * needed for len bytes' worth of bits, not the old 4*len-1 - * estimate (right for octal/decimal at len==1 only by - * coincidence, and short for hex at every len). d/u stay right- - * justified with spaces at that same estimate, same as every - * other od: an oversized width there is just extra leading - * whitespace, harmless under a space fill */ + * byte, or ceil(8*len/3) octal digits. d/u stay right-justified + * with spaces at the older estimate, where an oversized width + * only adds leading whitespace */ fmt[2] = (format == 'x' || format == 'o') ? '0' : ' '; fmt[6] = format; switch (format) { @@ -292,19 +286,13 @@ main(int argc, char *argv[]) s = EARGF(usage()); for (; *s; s++) { switch (*s) { - // ?man -a: print or show all entries case 'a': - // ?man -c: print count or perform stdout action case 'c': addtype(*s, 1); break; - // ?man -d: specify directory case 'd': - // ?man -o: specify output file case 'o': - // ?man -u: unbuffered output case 'u': - // ?man -x: hex format or match whole lines case 'x': fmt_char = *s; if (isdigit((unsigned char)*(s + 1))) { @@ -312,22 +300,18 @@ main(int argc, char *argv[]) s = end - 1; } else { switch (*(s + 1)) { - // ?man -C: specify option flag case 'C': len = sizeof(char); s++; break; - // ?man -S: specify option flag case 'S': len = sizeof(short); s++; break; - // ?man -I: specify option flag case 'I': len = sizeof(int); s++; break; - // ?man -L: specify option flag case 'L': len = sizeof(long); s++; diff --git a/cmd/posix/patch.c b/cmd/posix/patch.c @@ -1,4 +1,9 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_PATCH_EXT +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include "paths.h" #include "util.h" #include "wexec.h" diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c @@ -856,12 +856,10 @@ readpax(struct bufio *f, struct header *h) case 'g': readexthdr(f, &globexthdr, h->size); break; - // ?man -x: hex format or match whole lines - case 'x': + case 'x': readexthdr(f, &exthdr, h->size); break; - // ?man -L: specify option flag - case 'L': + case 'L': if ((exthdr.delete | opt.delete) & PATH) break; readgnuhdr(f, &exthdr.pathbuf, h->size); @@ -2179,12 +2177,10 @@ parsereplstr(char *str) case 'g': r->global = 1; break; - // ?man -p: preserve file attributes case 'p': r->print = 1; break; - // ?man -s: silent mode or print summary - case 's': + case 's': r->symlink = 0; break; case 'S': @@ -2464,8 +2460,7 @@ main(int argc, char *argv[]) ARGBEGIN { - // ?man -a: print or show all entries - case 'a': + case 'a': aflag = 1; break; // ?man -b:str: specify block size or base directory @@ -2520,8 +2515,7 @@ main(int argc, char *argv[]) case 'o': parseopts(EARGF(usage())); break; - // ?man -p:str: preserve file attributes - case 'p': + case 'p': for (arg = EARGF(usage()); *arg; ++arg) { switch (*arg) { // ?man -a: print or show all entries @@ -2536,11 +2530,10 @@ main(int argc, char *argv[]) case 'm': preserve &= ~MTIME; break; - // ?man -o: specify output file - case 'o': + case 'o': preserve |= UID | GID; break; - // ?man -p: preserve file attributes + // ?man -p:str: preserve file attributes case 'p': preserve |= MODE; break; diff --git a/cmd/posix/readlink.c b/cmd/posix/readlink.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_READLINK_REALPATH +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <limits.h> #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c @@ -9,6 +9,11 @@ * POSIX says dont flush on n when out of input, but GNU and busybox do */ +#if FEATURE_SED_ASCII +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include "config.h" #include "utf.h" #include "util.h" @@ -851,7 +856,7 @@ free_acir_arg(Cmd *c) * whitespace, closing braces, etc. and can be limited to 8 bytes * * i allow a semicolon or closing brace to terminate a label name, its not - * POSIX compliant, but its useful and every sed version i've tried to date + * POSIX compliant, but its useful and every sed version i have tried to date * does the same * * FIXME: POSIX dictates that leading whitespace is ignored but trailing @@ -1148,7 +1153,7 @@ run(void) leprintf("extra {"); /* genbuf has already been initialized, patt will be in new_line - * (or we'll halt) */ + * (or we will halt) */ stracpy(&hold, ""); insert_labels(); @@ -1226,7 +1231,7 @@ next_file(void) if (!strcmp(*files, "-")) { file = stdin; } else if (!(file = fopen(*files, "r"))) { - /* warn this file didn't open, but move on to next */ + /* warn this file didnt open, but move on to next */ weprintf("fopen %s:", *files); ret = 1; } @@ -1591,7 +1596,7 @@ cmd_s(Cmd *c) leprintf("this shouldn't be possible"); break; case '\0': - /* we're at the end, back up one so the + /* we are at the end, back up one so the * ++p will put us on the null byte to * break out of the loop */ --p; diff --git a/cmd/posix/sh/error.h b/cmd/posix/sh/error.h @@ -103,7 +103,10 @@ void errorwithstatus(int, const char *, ...) __printf0like(2, 3) __dead2; * so we use _setjmp instead */ +#if FEATURE_SH_LONGJMP +void _longjmp(jmp_buf, int); #undef setjmp #define setjmp(jmploc) _setjmp(jmploc) #undef longjmp #define longjmp(jmploc, val) _longjmp(jmploc, val) +#endif diff --git a/cmd/posix/sh/expand.c b/cmd/posix/sh/expand.c @@ -36,6 +36,14 @@ * SUCH DAMAGE */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <dirent.h> #include <errno.h> #include <inttypes.h> @@ -1078,7 +1086,7 @@ expmeta(char *enddir, char *name, struct arglist *arglist) } } } - if (metaflag == 0) { /* we've reached the end of the file name */ + if (metaflag == 0) { /* we have reached the end of the file name */ if (enddir != expdir) metaflag++; for (p = name;; p++) { diff --git a/cmd/posix/sh/input.c b/cmd/posix/sh/input.c @@ -32,6 +32,14 @@ * SUCH DAMAGE */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <errno.h> #include <fcntl.h> #include <stdio.h> /* defines BUFSIZ */ diff --git a/cmd/posix/sh/jobs.c b/cmd/posix/sh/jobs.c @@ -32,6 +32,14 @@ * SUCH DAMAGE */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <errno.h> #include <fcntl.h> #include <signal.h> diff --git a/cmd/posix/sh/miscbltin.c b/cmd/posix/sh/miscbltin.c @@ -36,6 +36,14 @@ * miscellaneous builtins */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/resource.h> #include <sys/stat.h> #include <sys/time.h> @@ -289,7 +297,7 @@ readcmd(int argc __unused, char **argv __unused) } sigprocmask(SIG_SETMASK, &oset, NULL); /* - * if there's nothing ready, return an error + * if theres nothing ready, return an error */ if (status <= 0) { while (*ap != NULL) diff --git a/cmd/posix/sh/output.c b/cmd/posix/sh/output.c @@ -42,6 +42,14 @@ * output of the command via a pipe */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <errno.h> #include <stdarg.h> #include <stdio.h> /* defines BUFSIZ */ diff --git a/cmd/posix/sh/parser.c b/cmd/posix/sh/parser.c @@ -32,6 +32,14 @@ * SUCH DAMAGE */ +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <pwd.h> #include <stdio.h> #include <stdlib.h> diff --git a/cmd/posix/sh/sh_cdefs.h b/cmd/posix/sh/sh_cdefs.h @@ -14,6 +14,15 @@ #ifndef SH_CDEFS_H #define SH_CDEFS_H +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif + #ifndef __dead2 #define __dead2 __attribute__((__noreturn__)) #endif diff --git a/cmd/posix/sh/test.c b/cmd/posix/sh/test.c @@ -42,6 +42,14 @@ #endif #endif +#if FEATURE_SH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif +#endif #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c @@ -298,27 +298,21 @@ parse_flags(char **s, int *flags, int bflag) { while (isalpha((int)**s)) { switch (*((*s)++)) { - // ?man -b: specify block size or base directory case 'b': *flags |= bflag; break; - // ?man -d: specify directory case 'd': *flags |= MOD_D; break; - // ?man -f: force the operation case 'f': *flags |= MOD_F; break; - // ?man -i: interactive mode or prompt for confirmation case 'i': *flags |= MOD_I; break; - // ?man -n: print line numbers or counts case 'n': *flags |= MOD_N; break; - // ?man -r: operate recursively case 'r': *flags |= MOD_R; break; diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c @@ -27,14 +27,12 @@ dropinit(int fd, const char *fname, size_t count) count--; /* numbering starts at 1 */ while (count && (n = read(fd, buf, sizeof(buf))) > 0) { switch (mode) { - // ?man -n: print line numbers or counts case 'n': /* lines */ for (p = buf; count && n > 0; p++, n--) { if (*p == '\n') count--; } break; - // ?man -c: print count or perform stdout action case 'c': /* bytes */ if (count > (size_t)n) { count -= n; @@ -44,7 +42,6 @@ dropinit(int fd, const char *fname, size_t count) count = 0; } break; - // ?man -m: specify mode or limit case 'm': /* runes */ for (p = buf; count && n > 0; p += nr, n -= nr, count--) { nr = charntorune(&r, p, n); @@ -106,7 +103,6 @@ taketail(int fd, const char *fname, size_t count) break; len += n; switch (mode) { - // ?man -n: print line numbers or counts case 'n': /* lines */ /* ignore the last character; if it is a newline, it * ends the last line */ @@ -120,11 +116,9 @@ taketail(int fd, const char *fname, size_t count) } } break; - // ?man -c: print count or perform stdout action case 'c': /* bytes */ p = count < len ? buf + len - count : buf; break; - // ?man -m: specify mode or limit case 'm': /* runes */ for (p = buf + len - 1, left = count; p >= buf; p--) { /* skip utf-8 continuation bytes */ diff --git a/cmd/posix/test.c b/cmd/posix/test.c @@ -1,5 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_FILE_MODE_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <sys/stat.h> #include <ctype.h> diff --git a/cmd/posix/touch.c b/cmd/posix/touch.c @@ -1,5 +1,13 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_TOUCH_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 700 +#endif +#endif #include <sys/stat.h> #include <errno.h> diff --git a/cmd/pseudo/chroot.c b/cmd/pseudo/chroot.c @@ -1,5 +1,14 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_CHROOT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif +#endif + #include <errno.h> #include <stdlib.h> #include <unistd.h> @@ -35,8 +44,12 @@ main(int argc, char *argv[]) if ((aux = getenv("SHELL"))) shell[0] = aux; +#if FEATURE_CHROOT if (chroot(argv[0]) < 0) eprintf("chroot %s:", argv[0]); +#else + eprintf("chroot: not supported\n"); +#endif if (chdir("/") < 0) eprintf("chdir:"); diff --git a/cmd/pseudo/cron.c b/cmd/pseudo/cron.c @@ -1,5 +1,11 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LOGGER_SYSLOG || FEATURE_CRON_DAEMON +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include <sys/types.h> #include <sys/wait.h> @@ -56,9 +62,11 @@ loginfo(const char *fmt, ...) { va_list ap; va_start(ap, fmt); +#if FEATURE_LOGGER_SYSLOG if (nflag == 0) vsyslog(LOG_INFO, fmt, ap); else +#endif vfprintf(stdout, fmt, ap); fflush(stdout); va_end(ap); @@ -69,9 +77,11 @@ logwarn(const char *fmt, ...) { va_list ap; va_start(ap, fmt); +#if FEATURE_LOGGER_SYSLOG if (nflag == 0) vsyslog(LOG_WARNING, fmt, ap); else +#endif vfprintf(stderr, fmt, ap); va_end(ap); } @@ -81,9 +91,11 @@ logerr(const char *fmt, ...) { va_list ap; va_start(ap, fmt); +#if FEATURE_LOGGER_SYSLOG if (nflag == 0) vsyslog(LOG_ERR, fmt, ap); else +#endif vfprintf(stderr, fmt, ap); va_end(ap); } @@ -524,11 +536,17 @@ main(int argc, char *argv[]) usage(); if (nflag == 0) { +#if FEATURE_LOGGER_SYSLOG openlog(argv[0], LOG_CONS | LOG_PID, LOG_CRON); +#endif +#if FEATURE_CRON_DAEMON if (daemon(1, 0) < 0) { logerr("error: failed to daemonize %s\n", strerror(errno)); return 1; } +#else + eprintf("cron: daemon support not built\n"); +#endif if ((fp = fopen(pidfile, "w"))) { fprintf(fp, "%d\n", getpid()); fclose(fp); @@ -577,8 +595,10 @@ main(int argc, char *argv[]) } } +#if FEATURE_LOGGER_SYSLOG if (nflag == 0) closelog(); +#endif return 0; } diff --git a/cmd/pseudo/dmesg.c b/cmd/pseudo/dmesg.c @@ -5,12 +5,9 @@ #include <string.h> #include <unistd.h> +#include "sysinfo.h" #include "util.h" -ssize_t get_dmesg(char *, size_t); -int clear_dmesg(void); -int set_console_level(int); - static void dmesg_show(const void *buf, size_t n) { diff --git a/cmd/pseudo/free.c b/cmd/pseudo/free.c @@ -3,10 +3,9 @@ #include <stdio.h> #include <stdlib.h> +#include "sysinfo.h" #include "util.h" -int get_meminfo(struct MemInfo *); - static unsigned int mem_unit = 1; static unsigned int unit_shift; diff --git a/cmd/pseudo/getty.c b/cmd/pseudo/getty.c @@ -1,5 +1,11 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_GTTY_VHANGUP +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> @@ -75,7 +81,11 @@ main(int argc, char *argv[]) /* steal the controlling terminal if necessary */ if (ioctl(fd, TIOCSCTTY, (void *)1) != 0) weprintf("TIOCSCTTY: could not set controlling tty\n"); +#if FEATURE_GTTY_VHANGUP vhangup(); +#else + eprintf("getty: vhangup support not built\n"); +#endif close(fd); fd = open(tty, O_RDWR); diff --git a/cmd/pseudo/halt.c b/cmd/pseudo/halt.c @@ -1,5 +1,14 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_LINUX_SYSCALL +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif +#endif + #include <sys/syscall.h> #include <stdio.h> @@ -41,7 +50,11 @@ main(int argc, char *argv[]) if (argc > 0) usage(); +#if FEATURE_LINUX_SYSCALL sync(); +#else + eprintf("halt: support not built\n"); +#endif if (pflag && rflag) usage(); @@ -51,7 +64,9 @@ main(int argc, char *argv[]) if (rflag) cmd = LINUX_REBOOT_CMD_RESTART; +#if FEATURE_LINUX_SYSCALL if (syscall(__NR_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, NULL) < 0) eprintf("reboot:"); +#endif return 0; } diff --git a/cmd/pseudo/hostname.c b/cmd/pseudo/hostname.c @@ -1,5 +1,11 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_HOSTNAME_SET +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include <stdio.h> #include <string.h> #include <unistd.h> @@ -32,8 +38,12 @@ main(int argc, char *argv[]) eprintf("gethostname:"); puts(host); } else if (argc == 1) { +#if FEATURE_HOSTNAME_SET if (sethostname(argv[0], strlen(argv[0])) < 0) eprintf("sethostname:"); +#else + eprintf("hostname: setting not supported\n"); +#endif } else { usage(); } diff --git a/cmd/pseudo/install.c b/cmd/pseudo/install.c @@ -1,214 +0,0 @@ -/* see LICENSE file for copyright and license details */ - -#include <dirent.h> -#include <errno.h> -#include <fcntl.h> -#include <grp.h> -#include <pwd.h> -#include <stdlib.h> -#include <string.h> -#include <sys/stat.h> -#include <sys/wait.h> -#include <unistd.h> - -#include "util.h" - -static int Dflag = 0; -static gid_t group; -static uid_t owner; -static mode_t mode = 0755; - -static void -make_dir(char *dir, int was_missing) -{ - if (!mkdir(dir, was_missing ? 0755 : mode)) { - if (!was_missing && (lchown(dir, owner, group) < 0)) - eprintf("lchmod %s:", dir); - } else if (errno != EEXIST) { - eprintf("mkdir %s:", dir); - } -} - -static void -make_dirs(char *dir, int was_missing) -{ - char *p; - for (p = strchr(dir + (dir[0] == '/'), '/'); p; p = strchr(p + 1, '/')) { - *p = '\0'; - make_dir(dir, was_missing); - *p = '/'; - } - make_dir(dir, was_missing); -} - -static int -install(const char *s1, const char *s2, int depth) -{ - int f1, f2; - - (void)depth; - - if ((f1 = open(s1, O_RDONLY)) < 0) - eprintf("open %s:", s1); - if ((f2 = creat(s2, 0600)) < 0) { - if (unlink(s2) < 0 && errno != ENOENT) - eprintf("unlink %s:", s2); - if ((f2 = creat(s2, 0600)) < 0) - eprintf("creat %s:", s2); - } - if (concat(f1, s1, f2, s2) < 0) - goto fail; - if (fchmod(f2, mode) < 0) { - weprintf("fchmod %s:", s2); - goto fail; - } - if (fchown(f2, owner, group) < 0) { - weprintf("fchown %s:", s2); - goto fail; - } - - close(f1); - close(f2); - - return 0; - -fail: - unlink(s2); - exit(1); -} - -static void -usage(void) -{ - eprintf( - "usage: %s [-g group] [-o owner] [-m mode] (-d dir ... | [-D] " - "(-t dest source ... | source ... dest))\n", - argv0 - ); -} - -// ?man install: copy files and set attributes -// ?man arguments: (-d dir ... | (-t dest source ... | source ... dest)) -// ?man copy files and set their permissions and ownership -int -main(int argc, char *argv[]) -{ - int dflag = 0; - char *gflag = 0; - char *oflag = 0; - char *mflag = 0; - char *tflag = 0; - struct group *gr; - struct passwd *pw; - struct stat st; - char *p; - - ARGBEGIN - { - // ?man -c: print count or perform stdout action - case 'c': - /* no-op for compatibility */ - break; - // ?man -d: specify directory - case 'd': - dflag = 1; - break; - // ?man -D: specify option flag - case 'D': - Dflag = 1; - break; - // ?man -s: silent mode or print summary - case 's': - /* no-op for compatibility */ - break; - // ?man -g:str: specify option flag - case 'g': - gflag = EARGF(usage()); - break; - // ?man -o:str: specify output file - case 'o': - oflag = EARGF(usage()); - break; - // ?man -m:str: specify mode or limit - case 'm': - mflag = EARGF(usage()); - break; - // ?man -t:str: sort or specify timestamp - case 't': - tflag = EARGF(usage()); - break; - default: - usage(); - } - ARGEND - - if (argc < 1 + (!tflag & !dflag) || dflag & (Dflag | !!tflag)) - usage(); - - if (gflag) { - errno = 0; - gr = getgrnam(gflag); - if (gr) { - group = gr->gr_gid; - } else { - if (errno) - eprintf("getgrnam %s:", gflag); - group = estrtonum(gflag, 0, UINT_MAX); - } - } else { - group = getgid(); - } - - if (oflag) { - errno = 0; - pw = getpwnam(oflag); - if (pw) { - owner = pw->pw_uid; - } else { - if (errno) - eprintf("getpwnam %s:", oflag); - owner = estrtonum(oflag, 0, UINT_MAX); - } - } else { - owner = getuid(); - } - - if (mflag) - mode = parsemode(mflag, mode, 0); - - if (dflag) { - for (; *argv; argc--, argv++) - make_dirs(*argv, 0); - return 0; - } - - if (tflag) { - argv = memmove(argv - 1, argv, argc * sizeof(*argv)); - argv[argc++] = tflag; - } - if (tflag || argc > 2) { - if (stat(argv[argc - 1], &st) < 0) { - if ((errno == ENOENT) && Dflag) { - make_dirs(argv[argc - 1], 1); - } else { - eprintf("stat %s:", argv[argc - 1]); - } - } else if (!S_ISDIR(st.st_mode)) { - eprintf("%s: not a directory\n", argv[argc - 1]); - } - } - if (stat(argv[argc - 1], &st) < 0) { - if (errno != ENOENT) - eprintf("stat %s:", argv[argc - 1]); - if (tflag || Dflag || argc > 2) { - if ((p = strrchr(argv[argc - 1], '/')) != NULL) { - *p = '\0'; - make_dirs(argv[argc - 1], 1); - *p = '/'; - } - } - } - enmasse(argc, argv, install); - - return 0; -} diff --git a/cmd/pseudo/killall5.c b/cmd/pseudo/killall5.c @@ -6,6 +6,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <strings.h> #include <unistd.h> #include "proc.h" diff --git a/cmd/pseudo/seq.c b/cmd/pseudo/seq.c @@ -59,7 +59,6 @@ format: fmt++; switch (*fmt) { - // ?man -f: force the operation case 'f': case 'F': case 'g': diff --git a/cmd/pseudo/sponge.c b/cmd/pseudo/sponge.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) { char tmp[] = "/tmp/sponge-XXXXXX"; - int fd, tmpfd; + int fd, tmpfd, ret = 0; ARGBEGIN { @@ -33,16 +33,28 @@ main(int argc, char *argv[]) if ((tmpfd = mkstemp(tmp)) < 0) eprintf("mkstemp:"); - unlink(tmp); - if (concat(0, "<stdin>", tmpfd, "<tmpfile>") < 0) + if (unlink(tmp) < 0) + eprintf("unlink %s:", tmp); + if (concat(0, "<stdin>", tmpfd, "<tmpfile>") < 0) { + if (close(tmpfd) < 0) + weprintf("close tmpfile:"); return 1; + } if (lseek(tmpfd, 0, SEEK_SET) < 0) eprintf("lseek:"); if ((fd = creat(argv[0], 0666)) < 0) eprintf("creat %s:", argv[0]); if (concat(tmpfd, "<tmpfile>", fd, argv[0]) < 0) - return 1; + ret = 1; + if (close(tmpfd) < 0) { + weprintf("close tmpfile:"); + ret = 1; + } + if (close(fd) < 0) { + weprintf("close %s:", argv[0]); + ret = 1; + } - return 0; + return ret; } diff --git a/cmd/pseudo/stat.c b/cmd/pseudo/stat.c @@ -1,5 +1,9 @@ +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include "config.h" #include "util.h" @@ -55,8 +59,7 @@ print_custom(const char *file, struct stat *st, const char *fmt) case 'n': putchar('\n'); break; - // ?man -t: sort or specify timestamp - case 't': + case 't': putchar('\t'); break; case 'r': @@ -65,7 +68,6 @@ print_custom(const char *file, struct stat *st, const char *fmt) case 'b': putchar('\b'); break; - // ?man -f: force the operation case 'f': putchar('\f'); break; @@ -183,8 +185,7 @@ print_custom(const char *file, struct stat *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long long)st->st_size); break; - // ?man -t: sort or specify timestamp - case 't': + case 't': fmt_spec[fmt_len++] = 'x'; fmt_spec[fmt_len] = '\0'; printf(fmt_spec, major(st->st_rdev)); @@ -313,8 +314,7 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt) case 'n': putchar('\n'); break; - // ?man -t: sort or specify timestamp - case 't': + case 't': putchar('\t'); break; case 'r': @@ -323,7 +323,6 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt) case 'b': putchar('\b'); break; - // ?man -f: force the operation case 'f': putchar('\f'); break; @@ -377,8 +376,7 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long long)st->f_blocks); break; - // ?man -c: print count or perform stdout action - case 'c': + case 'c': fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'd'; @@ -392,7 +390,6 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long long)st->f_ffree); break; - // ?man -f: force the operation case 'f': fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'l'; @@ -434,8 +431,7 @@ print_fs_custom(const char *file, struct statfs *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long)st->f_frsize ? (long)st->f_frsize : (long)st->f_bsize); break; - // ?man -t: sort or specify timestamp - case 't': + case 't': fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'x'; fmt_spec[fmt_len] = '\0'; @@ -544,13 +540,11 @@ main(int argc, char *argv[]) fn = stat; fnname = "stat"; break; - // ?man -t: sort or specify timestamp - case 't': + case 't': showstat = show_stat_terse; break; #if FEATURE_STAT_FILESYSTEM - // ?man -f: force the operation - case 'f': + case 'f': fflag = 1; break; #endif diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -1,5 +1,11 @@ +#if FEATURE_MKNOD +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include "config.h" #include "fs.h" #include "utf.h" @@ -526,6 +532,7 @@ unarchive(char *fname, ssize_t l, char b[BLKSIZ]) break; case CHARDEV: case BLOCKDEV: +#if FEATURE_MKNOD if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') eprintf("strtol %s: invalid mode\n", h->mode); if ((major = strtol(h->major, &p, 8)) < 0 || *p != '\0') @@ -535,12 +542,19 @@ unarchive(char *fname, ssize_t l, char b[BLKSIZ]) type = (h->type == CHARDEV) ? S_IFCHR : S_IFBLK; if (mknod(fname, type | mode, makedev(major, minor)) < 0) eprintf("mknod %s:", fname); +#else + eprintf("tar: device extraction not supported\n"); +#endif break; case FIFO: +#if FEATURE_MKNOD if ((mode = strtol(h->mode, &p, 8)) < 0 || *p != '\0') eprintf("strtol %s: invalid mode\n", h->mode); if (mknod(fname, S_IFIFO | mode, 0) < 0) eprintf("mknod %s:", fname); +#else + eprintf("tar: fifo extraction not supported\n"); +#endif break; default: eprintf("unsupported tar-filetype %c\n", h->type); @@ -838,8 +852,8 @@ usage(void) // ?man tar: tape archiver // ?man arguments: [x | t | -x | -t] [file ...] -// ?man tar [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] [-T file] [-X file] -// path ... [-f file] ?man manipulate tape archive files +// ?man tar [c | -c] [-C dir] [-J | -Z | -a | -j | -z] [-h] [-T file] [-X file] path ... [-f file] +// ?man manipulate tape archive files int main(int argc, char *argv[]) { @@ -1021,7 +1035,6 @@ main(int argc, char *argv[]) switch (mode) { #if FEATURE_TAR_CREATE - // ?man -c: create a new archive case 'c': if (!argc && !files_from_cnt) usage(); @@ -1049,9 +1062,7 @@ main(int argc, char *argv[]) #endif break; #endif - // ?man -t: list the contents of an archive case 't': - // ?man -x: extract files from an archive case 'x': tarfd = 0; if (file && *file != '-') { diff --git a/cmd/pseudo/uptime.c b/cmd/pseudo/uptime.c @@ -7,11 +7,9 @@ #include <utmpx.h> #include "config.h" +#include "sysinfo.h" #include "util.h" -int get_uptime(long *); -int get_loads(double *); - static void usage(void) { diff --git a/cmd/pseudo/watch.c b/cmd/pseudo/watch.c @@ -3,6 +3,7 @@ #include <errno.h> #include <stdio.h> #include <stdlib.h> +#include <time.h> #include <unistd.h> #include "util.h" @@ -20,10 +21,10 @@ usage(void) int main(int argc, char *argv[]) { - char cmd[BUFSIZ]; - char *end; - useconds_t interval = 2 * 1E6; - float period; + char cmd[BUFSIZ]; + char *end; + struct timespec interval = { .tv_sec = 2, .tv_nsec = 0 }; + float period; int i; ARGBEGIN @@ -38,7 +39,8 @@ main(int argc, char *argv[]) eprintf("invalid interval\n"); if (period < 0) period = 0.1f; - interval = period * 1E6; + interval.tv_sec = period; + interval.tv_nsec = (period - interval.tv_sec) * 1E9; break; default: usage(); @@ -61,7 +63,7 @@ main(int argc, char *argv[]) printf("\x1b[2J\x1b[H"); /* clear */ fflush(NULL); wsystem(cmd); - usleep(interval); + nanosleep(&interval, NULL); } return 0; } diff --git a/cmd/xsi/login.c b/cmd/xsi/login.c @@ -1,5 +1,9 @@ /* see LICENSE file for copyright and license details */ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif + #include "config.h" #include "passwd.h" #include "util.h" diff --git a/cmd/xsi/mknod.c b/cmd/xsi/mknod.c @@ -1,4 +1,10 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_MKNOD +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif + #include <sys/stat.h> #include <sys/types.h> diff --git a/cmd/xsi/mkpasswd.c b/cmd/xsi/mkpasswd.c @@ -1,4 +1,11 @@ /* see LICENSE file for copyright and license details */ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include "passwd.h" #include "util.h" diff --git a/cmd/xsi/passwd.c b/cmd/xsi/passwd.c @@ -1,4 +1,11 @@ /* see LICENSE file for copyright and license details */ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 500 +#endif + #include "passwd.h" #include "util.h" diff --git a/cmd/xsi/su.c b/cmd/xsi/su.c @@ -1,4 +1,8 @@ /* see LICENSE file for copyright and license details */ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif + #include "passwd.h" #include "util.h" #include "wexec.h" diff --git a/ninqu.rules b/ninqu.rules @@ -1,27 +1,25 @@ -; genconfig.sh config produces four files from build.cfg in one -; invocation: config.set (read by ninqu), config.kv (read by mkman), -; nofork_list.h (included by wexec.c), and features.h (-included -; into every compile). only CONFIG_SET actually runs the script; -; NOFORK_LIST_H and FEATURES_H depend on its output instead of -; re-running genconfig.sh themselves, so ninja never schedules two -; invocations of the same script concurrently. running it twice in -; parallel raced both invocations' truncate-then-append writes to -; the same files, byte-interleaving their output into invalid C -; +; each generated file has one rule and one target, so parallel +; generators never write through another target's side effects + (rule CONFIG_SET (out "scripts/mk/config.set") (dep "build.cfg" "scripts/genconfig.sh") - (exec sh scripts/genconfig.sh config)) + (exec sh scripts/genconfig.sh config-set)) + +(rule CONFIG_KV + (out "scripts/mk/config.kv") + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh config-kv)) (rule NOFORK_LIST_H (out "shared/libutil/nofork_list.h") - (dep "scripts/mk/config.set") - (exec true)) + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh nofork-list-h)) (rule FEATURES_H (out "scripts/mk/features.h") - (dep "scripts/mk/config.set") - (exec true)) + (dep "build.cfg" "scripts/genconfig.sh") + (exec sh scripts/genconfig.sh features-h)) (set-file "scripts/mk/config.set") @@ -29,7 +27,7 @@ ; (rule LIBUTF_OBJ (glob "shared/libutf/*.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libutf $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -42,13 +40,29 @@ (rule LIBUTIL_OBJ (glob "shared/libutil/*.c") - (dep $(MATCH)) - (after NOFORK_LIST_H FEATURES_H) + (skip "filesystem_linux.c" "filesystem_other.c" + "net_linux.c" "net_other.c" + "sysinfo_linux.c" "sysinfo_other.c") + (dep $(MATCH) FEATURES_H) + (after NOFORK_LIST_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS_LIBUTIL) -Ishared/libutil $(CFLAGS) -c -o $(OUT) $(MATCH))) + (rule LIBUTIL_OS_OBJ + (glob "shared/libutil/filesystem_linux.c" + "shared/libutil/filesystem_other.c" + "shared/libutil/net_linux.c" + "shared/libutil/net_other.c" + "shared/libutil/sysinfo_linux.c" + "shared/libutil/sysinfo_other.c") + (dep $(MATCH) "shared/filesystem.h" "shared/net.h" + "shared/sysinfo.h" FEATURES_H) + (after NOFORK_LIST_H) + (out "shared/libutil/$(BASESTEM).o") + (exec $(CC) $(CPPFLAGS_LIBUTIL) -Ishared -Ishared/libutil $(CFLAGS) -c -o $(OUT) $(MATCH))) + (rule LIBUTIL - (dep LIBUTIL_OBJ) + (dep LIBUTIL_OBJ LIBUTIL_OS_OBJ) (out "shared/libutil/libutil.a") (description "allocation, error reporting, and string helpers shared by every tool") (feature core-lib) @@ -56,7 +70,7 @@ (rule LIBREDLINE_OBJ (glob "shared/libredline/*.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libredline $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -69,7 +83,7 @@ (rule LIBBLAKE3_OBJ (glob "shared/libblake3/*.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libblake3 $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -122,7 +136,7 @@ (rule $(NAME) (glob "cmd/$(CATEGORY)/*.c") (gate build_$(CATEGORY)_$(IDENT)) - (dep $(MATCH) LIBUTIL LIBUTF LIBBLAKE3) + (dep $(MATCH) FEATURES_H LIBUTIL LIBUTF LIBBLAKE3) (after $(EXTRA_AFTER)) (out $(STEM)) (description $(DESC)) @@ -177,7 +191,7 @@ (out "cmd/dev/config.h") (dep "cmd/dev/configure") (phony) - (exec sh cmd/dev/configure)) + (exec sh cmd/dev/configure --target=$(MICE_TARGET_TRIPLE) --sysroot=$(MICE_TARGET_SYSROOT))) (group codegen GETCONF_H POSIX_BC_C POSIX_AWK_C POSIX_SH_C DEVCONF) @@ -188,7 +202,7 @@ (rule POSIX_BC_OBJ (glob "cmd/posix/bc.c") (gate build_posix_bc) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_BC_C) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -204,7 +218,7 @@ (glob "cmd/posix/awk/*.c") (gate build_posix_awk) (skip "maketab.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_AWK_C) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -220,7 +234,7 @@ (glob "cmd/posix/sh/*.c") (gate build_posix_sh) (skip "mknodes.c" "mksyntax.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_SH_C) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -235,7 +249,7 @@ (rule POSIX_MAKE_OBJ (glob "cmd/posix/make/*.c") (gate build_posix_make) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -249,7 +263,7 @@ (rule EXTRA_YAP_OBJ (glob "cmd/extra/yap/*.c") (gate build_extra_yap) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -272,7 +286,8 @@ (glob "cmd/dev/ar/*.c") (gate build_dev_ar) (skip "tinyar.c") - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/ar $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -288,14 +303,16 @@ (rule TCUTIL_OBJ (glob "shared/libtcutil/*.c" "shared/libtcutil/elf/*.c" "shared/libtcutil/ar/*.c") (gate build_dev_cc) - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libtcutil -Ishared/libtcutil/elf -Ishared/libtcutil/ar -Icmd/dev $(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)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Ishared/libtcutil -Ishared/libtcutil/elf -Ishared/libtcutil/ar -Icmd/dev -Icmd/dev/as -Icmd/dev/as/arch/x64 -Ishared $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -308,7 +325,8 @@ (rule LD_OBJ (glob "cmd/dev/ld/*.c" "cmd/dev/ld/arch/*/*.c") (gate build_dev_ld) - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/ld $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -323,14 +341,16 @@ (rule CCPOOL_OBJ (glob "cmd/dev/cc/*.c") (gate build_dev_cc) - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (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)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -342,7 +362,8 @@ (rule UTIL_OBJ (glob "cmd/dev/cc/util.c") (gate build_dev_cc) - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -355,7 +376,8 @@ (rule CPP_OBJ (glob "cmd/dev/cc/cpp.c") (gate build_dev_cc) - (dep $(MATCH)) + (after DEVCONF) + (dep $(MATCH) FEATURES_H) (out "$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -365,12 +387,19 @@ (out "cmd/dev/cc/cpp") (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) + ; driver.c's own quoted #include "config.h" needs cmd/dev/config.h + ; (DEVCONF's own output), not shared/config.h, MICE's unrelated + ; project-wide one that $(CPPFLAGS)'s own -Ishared would otherwise + ; win on: -Icmd/dev goes first, ahead of $(CPPFLAGS), so it wins the + ; search. (after DEVCONF) orders the generation itself first, or + ; parallel execution can compile driver.c before config.h exists (rule CCDRV_OBJ (glob "cmd/dev/cc/driver.c") (gate build_dev_cc) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) + (after DEVCONF) (out "$(STEM).o") - (exec $(CC) $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) + (exec $(CC) -Icmd/dev $(CPPFLAGS) -Icmd/dev/cc $(CFLAGS) -c -o $(OUT) $(MATCH))) (rule CCDRV (gate build_dev_cc) @@ -378,18 +407,28 @@ (out "cmd/dev/cc/cc") (exec $(CC) -static -o $(OUT) $(IN) $(LDFLAGS))) - ; like BOX_OBJ: rename main and hide other globals so ninqu can link - ; into aruu-box. it is still not reentrant, so it stays out of - ; NOFORK_LIST + ; ninqu is multiple translation units sharing globals (rules, insts, + ; and so on), unlike the single-file tools BOX_OBJ handles: combine + ; its objects first, like POSIX_BC_BOX/POSIX_AWK_BOX/POSIX_SH_BOX/ + ; POSIX_MAKE_BOX/EXTRA_YAP_BOX do for their own multi-file tools, so + ; --keep-global-symbol only strips main across the combined object + ; instead of hiding every cross-file global before linking even + ; happens. 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)") + (dep $(MATCH) FEATURES_H) + (after LIBUTIL LIBUTF LIBREDLINE NOFORK_LIST_H GETCONF_H) + (out ".box/parts/$(STEM).o") + (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) + + (rule NINQU_BOX + (gate build_dev_ninqu) + (dep NINQU_BOX_OBJ) + (out ".box/cmd/dev/ninqu.o") + (description "ninqu's objects combined into one relocatable object, main renamed for the box dispatch table") + (shell "$(LD) -r -o $(OUT) $(IN) && $(OBJCOPY) --redefine-sym main=ninqu_main $(OUT) && $(OBJCOPY) --keep-global-symbol=ninqu_main $(OUT)") (group box)) (group dev lib DEVCONF AR AS LD CC1 CPP CCDRV) @@ -405,7 +444,7 @@ (rule MAN_MDOC (glob "cmd/**/*.c") (mark "?man") - (dep (after MKMAN)) + (dep CONFIG_KV (after MKMAN)) (out "man/man$(SEC_OF:$(DIR))/$(BASESTEM).$(SEC_OF:$(DIR))") (exec scripts/mkman/mkman -fmt mdoc -config scripts/mk/config.kv $(MATCH)) (redirect)) @@ -413,13 +452,14 @@ (rule MAN_TXT (glob "cmd/**/*.c") (mark "?man") - (dep (after MKMAN)) + (dep CONFIG_KV (after MKMAN)) (out "man/man$(SEC_OF:$(DIR))/$(BASESTEM).$(SEC_OF:$(DIR)).txt") (exec scripts/mkman/mkman -fmt txt -config scripts/mk/config.kv $(MATCH)) (redirect)) (map SEC_OF (cmd/posix 1) + (cmd/posix/make 1) (cmd/linux 8) (cmd/net 8) (cmd/xsi 1) @@ -470,8 +510,11 @@ (phony) (after ALL_BINS LIBUTIL MAN_MDOC MAN_TXT) (shell " - d=\"${DESTDIR:-}$(PREFIX)\" - m=\"${DESTDIR:-}$(MANPREFIX)\" + [ -n \"${DESTDIR:-}\" ] || { printf 'install requires DESTDIR\n' >&2; exit 1; } + case \"$(PREFIX)\" in /usr|/usr/*|usr|usr/*) printf 'ARUU cannot install into usr\n' >&2; exit 1 ;; esac + case \"$DESTDIR\" in /usr|/usr/*) printf 'ARUU cannot install into usr\n' >&2; exit 1 ;; esac + d=\"$DESTDIR$(PREFIX)\" + m=\"$DESTDIR$(MANPREFIX)\" mkdir -p \"$d/bin\" \"$m/man1\" \"$m/man8\" \"$d/lib\" \"$d/include/aruu\" find cmd -type f ! -name '*.*' -perm -100 | while read -r bin; do @@ -490,7 +533,8 @@ printf ' INSTALL %s/lib/libaruu.a\n' '$(PREFIX)' cp shared/libutil/libutil.a \"$d/lib/libaruu.a\" chmod 644 \"$d/lib/libaruu.a\" - for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h; do + for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h \ + shared/filesystem.h shared/net.h shared/sysinfo.h; do printf ' INSTALL %s/include/aruu/%s\n' '$(PREFIX)' \"${h##*/}\" cp \"$h\" \"$d/include/aruu/${h##*/}\" chmod 644 \"$d/include/aruu/${h##*/}\" @@ -508,8 +552,11 @@ POSIX_BC POSIX_AWK POSIX_SH POSIX_MAKE EXTRA_YAP LIBUTIL MAN_MDOC MAN_TXT) (shell " - d=\"${DESTDIR:-}$(PREFIX)\" - m=\"${DESTDIR:-}$(MANPREFIX)\" + [ -n \"${DESTDIR:-}\" ] || { printf 'install-base requires DESTDIR\n' >&2; exit 1; } + case \"$(PREFIX)\" in /usr|/usr/*|usr|usr/*) printf 'ARUU cannot install into usr\n' >&2; exit 1 ;; esac + case \"$DESTDIR\" in /usr|/usr/*) printf 'ARUU cannot install into usr\n' >&2; exit 1 ;; esac + d=\"$DESTDIR$(PREFIX)\" + m=\"$DESTDIR$(MANPREFIX)\" mkdir -p \"$d/bin\" \"$m/man1\" \"$m/man8\" \"$d/lib\" \"$d/include/aruu\" find cmd -type f ! -name '*.*' -perm -100 ! -path 'cmd/dev/*' | while read -r bin; do @@ -528,7 +575,8 @@ printf ' INSTALL %s/lib/libaruu.a\n' '$(PREFIX)' cp shared/libutil/libutil.a \"$d/lib/libaruu.a\" chmod 644 \"$d/lib/libaruu.a\" - for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h; do + for h in shared/util.h shared/wexec.h shared/arg.h shared/compat.h \ + shared/filesystem.h shared/net.h shared/sysinfo.h; do printf ' INSTALL %s/include/aruu/%s\n' '$(PREFIX)' \"${h##*/}\" cp \"$h\" \"$d/include/aruu/${h##*/}\" chmod 644 \"$d/include/aruu/${h##*/}\" @@ -541,26 +589,31 @@ (rule REMOVE (phony) (shell " + [ -n \"${DESTDIR:-}\" ] || { printf 'remove requires DESTDIR\n' >&2; exit 1; } + case \"$(PREFIX)\" in /usr|/usr/*|usr|usr/*) printf 'ARUU cannot remove from usr\n' >&2; exit 1 ;; esac + case \"$DESTDIR\" in /usr|/usr/*) printf 'ARUU cannot remove from usr\n' >&2; exit 1 ;; esac + d=\"$DESTDIR$(PREFIX)\" + m=\"$DESTDIR$(MANPREFIX)\" 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\" + rm -f \"$d/bin/$name\" done find man/man1 man/man8 -type f -name '*.[18]' 2>/dev/null | while read -r f; do sec=${f%/*}; sec=${sec##*/} name=${f##*/} printf ' REMOVE %s/%s/%s\n' '$(MANPREFIX)' \"$sec\" \"$name\" - rm -f \"$(MANPREFIX)/$sec/$name\" + rm -f \"$m/$sec/$name\" done printf ' REMOVE %s/lib/libaruu.a\n' '$(PREFIX)' - rm -f \"$(PREFIX)/lib/libaruu.a\" - for h in util.h wexec.h arg.h compat.h; do + rm -f \"$d/lib/libaruu.a\" + for h in util.h wexec.h arg.h compat.h filesystem.h net.h sysinfo.h; do printf ' REMOVE %s/include/aruu/%s\n' '$(PREFIX)' \"$h\" - rm -f \"$(PREFIX)/include/aruu/$h\" + rm -f \"$d/include/aruu/$h\" done - rmdir \"$(PREFIX)/include/aruu\" 2>/dev/null || : + rmdir \"$d/include/aruu\" 2>/dev/null || : ")) (group remove REMOVE) @@ -634,8 +687,8 @@ (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) + (dep $(MATCH) FEATURES_H) + (after LIBUTIL LIBUTF LIBREDLINE NOFORK_LIST_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)") @@ -652,7 +705,7 @@ (rule POSIX_BC_BOX_OBJ (glob "cmd/posix/bc.c") (gate build_posix_bc) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_BC_C) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -669,7 +722,7 @@ (glob "cmd/posix/awk/*.c") (gate build_posix_awk) (skip "maketab.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_AWK_C) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) -Icmd/posix/awk $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -686,7 +739,7 @@ (glob "cmd/posix/sh/*.c") (gate build_posix_sh) (skip "mknodes.c" "mksyntax.c") - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (after POSIX_SH_C) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) -DSHELL -Icmd/posix/sh $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -702,7 +755,7 @@ (rule POSIX_MAKE_BOX_OBJ (glob "cmd/posix/make/*.c") (gate build_posix_make) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -717,7 +770,7 @@ (rule EXTRA_YAP_BOX_OBJ (glob "cmd/extra/yap/*.c") (gate build_extra_yap) - (dep $(MATCH)) + (dep $(MATCH) FEATURES_H) (out ".box/parts/$(STEM).o") (exec $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $(OUT) $(MATCH))) @@ -734,7 +787,7 @@ ; 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) + (dep BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX) (out ".box/aruu-box.c") (description "dispatch table and main() for aruu-box, generated from the enabled tool list") (exec scripts/genbox.sh $(IN)) @@ -748,8 +801,13 @@ ; disabled. genconfig.sh exports BOX_EXTRA_LIBS as "-ltinfo" or an empty string ; based on whether yap is enabled ; + ; libblake3 is the same story as libm: b3sum needs it, EXTRA_LIBS only + ; applies to PERFILE's own standalone link line, box has no per-tool + ; equivalent, so LIBBLAKE3 goes in BOX's own dep list unconditionally + ; instead, same as LIBUTIL/LIBUTF/LIBREDLINE + ; (rule BOX - (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX_OBJ LIBUTIL LIBUTF LIBREDLINE) + (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX LIBUTIL LIBUTF LIBREDLINE LIBBLAKE3) (out "aruu-box") (description "single multi-call binary, one dispatch table for every enabled tool") (shell "$(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) $(BOX_EXTRA_LIBS)") diff --git a/scripts/genbox.sh b/scripts/genbox.sh @@ -1,9 +1,8 @@ #!/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 +# given the BOX_OBJ output paths (".box/cmd/<category>/<tool>.o") on +# argv, print the c source of the dispatch table and main() on stdout # set -e @@ -12,11 +11,9 @@ set -e 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 +# derive category, tool and c symbol from one BOX_OBJ output path. the +# transform (tr '.-' '__', append _main) must match the BOX_OBJ objcopy +# step, see the CATEGORY_OF comment in ninqu.rules path_category() { rest=${1#.box/cmd/} printf "%s\n" "${rest%%/*}" @@ -45,8 +42,8 @@ cat << 'HEAD' HEAD -# extern decls, in the order ninqu passed the objects in (BOX_OBJ's -# own glob order, one category at a time) +# extern decls, in the order ninqu passed the objects in (BOX_OBJ glob +# order, one category at a time) for obj in "$@"; do sym=$(path_symbol "$obj") echo "int ${sym}(int, char **);" @@ -78,6 +75,10 @@ for category in $categories; do if [ "$tool" = "test" ]; then printf '\t{ "[", %s, "%s" },\n' "$sym" "$category" fi + if [ "$tool" = "grep" ]; then + printf '\t{ "egrep", %s, "%s" },\n' "$sym" "$category" + printf '\t{ "fgrep", %s, "%s" },\n' "$sym" "$category" + fi done done @@ -141,6 +142,7 @@ main(int argc, char *argv[]) { struct Cmd *c; char *s; + int dash; argv0 = argv[0]; @@ -170,10 +172,18 @@ main(int argc, char *argv[]) else s = argv[0]; } + /* login exec's a shell with a '-' prefixed to argv[0]; match the + applet without it, and leave argv[0] alone so the applet can + still see it was invoked as a login shell */ + dash = (*s == '-'); + if (dash) + s++; + for (c = cmds; c->name; c++) { if (strcmp(c->name, s) == 0) { argv0 = (char *)c->name; - argv[0] = (char *)c->name; + if (!dash) + argv[0] = (char *)c->name; return c->fn(argc, argv); } } diff --git a/scripts/genconfig.sh b/scripts/genconfig.sh @@ -9,11 +9,9 @@ # (gate ...) in ninqu.rules only ever checks # the lowercase form # -# scripts/mk/config.kv shell-quoted KEY="VAL" format. sourced by -# read via the -config flag by scripts/mkman -# nothing in the ninqu build itself sources -# this file: genbox.sh takes its input on argv -# only, see the BOX section of ninqu.rules +# scripts/mk/config.kv strictly quoted KEY="VAL" format, read by +# mkman through its -config flag. nothing in the ninqu build itself +# sources this file: genbox.sh takes its input on argv only # # shared/libutil/nofork_list.h # wexec.c includes this at compile time @@ -169,56 +167,52 @@ clean() { # (KEY=VAL) since ninqu's (set-file) takes the rest of the line # verbatim -config() { - mkdir -p scripts/mk +config_check() { + case "${cppflags_common}" in + *-D_POSIX_C_SOURCE=200809L*) ;; + *) printf 'genconfig: missing POSIX 2008 baseline\n' >&2; return 1 ;; + esac + case "${cppflags_common}" in + *-D_DEFAULT_SOURCE*|*-D_GNU_SOURCE*|*-D_NETBSD_SOURCE*|*-D_BSD_SOURCE*|*-D_XOPEN_SOURCE*) + printf 'genconfig: non-POSIX feature-test macro leaked into CPPFLAGS\n' >&2 + return 1 + ;; + esac + for f in ${features}; do + eval "val=\$$f" + case "${val}" in + 0|1) ;; + *) printf 'genconfig: %s must be 0 or 1, got %s\n' "${f}" "${val}" >&2; return 1 ;; + esac + done +} + +config_resolve() { + VERSION=${VERSION:-0} + PREFIX=${PREFIX:-} + MANPREFIX=${MANPREFIX:-/share/man} + RANLIB=${RANLIB:-ranlib} + AR=${AR:-ar} + ARFLAGS=${ARFLAGS:-rc} + CC=${CC:-cc} + CFLAGS=${CFLAGS:--std=c99 -Wall -Wextra -pedantic} + OBJCOPY=${OBJCOPY:-objcopy} + LD=${LD:-ld} + LDFLAGS_TLS=${LDFLAGS_TLS:-} + LDLIBS_TLS=${LDLIBS_TLS:-} + CPPFLAGS_TLS=${CPPFLAGS_TLS:-} + NINJA_TRY=${NINJA_TRY:-samu,ninja} + LDFLAGS="${LDFLAGS:-} ${LDFLAGS_TLS}" + LDLIBS="${LDLIBS:-} ${LDLIBS_TLS}" - 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:-}" - - # for when ninqu builds itself, otherwise it wont have this value - emit NINJA_TRY "${NINJA_TRY:-samu,ninja}" - - # these seven are only consulted per-tool below (build_category_tool, - # build_category_$(basestem)) 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}" + eval "${g}=\${${g}:-0}" done - # 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 + config_build_tools="" for category in posix xsi net pseudo extra linux dev; do [ -d "cmd/$category" ] || continue - u_category=$(echo "$category" | tr '[:lower:]' '[:upper:]') - + u_category=$(printf '%s' "$category" | tr '[:lower:]' '[:upper:]') tools="" for d in "cmd/$category"/*; do [ -d "$d" ] && tools="$tools ${d##*/}" @@ -233,81 +227,166 @@ config() { esac tools="$tools $b" done - - tools=$(echo "$tools" | tr ' ' '\n' | sort -u | grep -v '^$' || true) - - for b in $tools; do - u_tool=$(echo "$b" | tr 'a-z-' 'A-Z_') + tools=$(printf '%s\n' ${tools} | sort -u | grep -v '^$' || true) + for b in ${tools}; do + u_tool=$(printf '%s' "$b" | tr 'a-z-' 'A-Z_') var_name="BUILD_${u_category}_${u_tool}" - - # if [ "$category" = "dev" ] && [ "$u_tool" = "AS" ]; then - # var_name="build_dev_cc" - # fi - - eval "has_override=\${$var_name+yes}" - if [ "$has_override" = "yes" ]; then - eval "val=\${$var_name}" + eval "has_override=\${${var_name}+yes}" + if [ "$has_override" = yes ]; then + eval "val=\${${var_name}}" else eval "val=\$BUILD_${u_category}" fi - - echo "${var_name}=\"${val}\"" >> "${kv_file}" - lk=$(echo "$var_name" | tr '[:upper:]' '[:lower:]') - echo "${lk}=${val}" >> "${set_file}" + config_build_tools="${config_build_tools} ${var_name}=${val}" done done - # 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}" - + [ "${BUILD_EXTRA_YAP:-0}" != 0 ] && box_extra_libs=-ltinfo + config_build_tools="${config_build_tools} 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 - # 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" + cppflags_common="-DPREFIX=\"${PREFIX}\" -D_POSIX_C_SOURCE=200809L -D_FILE_OFFSET_BITS=64 -include scripts/mk/features.h ${CPPFLAGS_TLS}" + config_check +} + +config_kv_quote() { + escaped=$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g') + printf '"%s"' "$escaped" +} + +config_kv() { + config_resolve + mkdir -p scripts/mk + tmp="scripts/mk/config.kv.tmp.$$" { - echo "/* autogenerated by genconfig.sh, do not edit */" - for f in $features; do - eval "fval=\$$f" - echo "# define ${f} ${fval}" + emit_kv() { + printf '%s=' "$1" + config_kv_quote "$2" + printf '\n' + } + + emit_kv VERSION "${VERSION}" + emit_kv PREFIX "${PREFIX}" + emit_kv MANPREFIX "${MANPREFIX}" + emit_kv RANLIB "${RANLIB}" + emit_kv AR "${AR}" + emit_kv ARFLAGS "${ARFLAGS}" + emit_kv CC "${CC}" + emit_kv CFLAGS "${CFLAGS}" + emit_kv LDFLAGS "${LDFLAGS}" + emit_kv LDLIBS "${LDLIBS}" + emit_kv OBJCOPY "${OBJCOPY}" + emit_kv LD "${LD}" + emit_kv CPPFLAGS_TLS "${CPPFLAGS_TLS}" + emit_kv LDFLAGS_TLS "${LDFLAGS_TLS}" + emit_kv LDLIBS_TLS "${LDLIBS_TLS}" + emit_kv NINJA_TRY "${NINJA_TRY}" + + for g in BUILD_POSIX BUILD_XSI BUILD_NET BUILD_PSEUDO BUILD_EXTRA BUILD_LINUX BUILD_DEV; do + eval "val=\$$g" + emit_kv "$g" "$val" 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}" + for entry in ${config_build_tools}; do + emit_kv "${entry%%=*}" "${entry#*=}" + done + for f in ${features}; do + eval "val=\$$f" + emit_kv "$f" "$val" + done + emit_kv CPPFLAGS "-Ishared ${cppflags_common}" + emit_kv CPPFLAGS_LIBUTIL "${cppflags_common}" + } > "${tmp}" + mv "${tmp}" scripts/mk/config.kv +} + +config_set() { + config_resolve + mkdir -p scripts/mk + tmp="scripts/mk/config.set.tmp.$$" + { + emit_set() { + case "$2" in + *' +'*) printf 'genconfig: %s contains a newline\n' "$1" >&2; return 1 ;; + esac + printf '%s=%s\n' "$1" "$2" + } + + emit_set VERSION "${VERSION}" + emit_set PREFIX "${PREFIX}" + emit_set MANPREFIX "${MANPREFIX}" + emit_set RANLIB "${RANLIB}" + emit_set AR "${AR}" + emit_set ARFLAGS "${ARFLAGS}" + emit_set CC "${CC}" + emit_set CFLAGS "${CFLAGS}" + emit_set LDFLAGS "${LDFLAGS}" + emit_set LDLIBS "${LDLIBS}" + emit_set OBJCOPY "${OBJCOPY}" + emit_set LD "${LD}" + emit_set CPPFLAGS_TLS "${CPPFLAGS_TLS}" + emit_set LDFLAGS_TLS "${LDFLAGS_TLS}" + emit_set LDLIBS_TLS "${LDLIBS_TLS}" + emit_set NINJA_TRY "${NINJA_TRY}" + + for g in BUILD_POSIX BUILD_XSI BUILD_NET BUILD_PSEUDO BUILD_EXTRA BUILD_LINUX BUILD_DEV; do + eval "val=\$$g" + emit_set "$g" "$val" + done + for entry in ${config_build_tools}; do + entry_name="${entry%%=*}" + entry_value="${entry#*=}" + emit_set "${entry_name}" "${entry_value}" + entry_lower=$(printf '%s' "${entry_name}" | tr '[:upper:]' '[:lower:]') + emit_set "${entry_lower}" "${entry_value}" + done + for f in ${features}; do + eval "val=\$$f" + emit_set "$f" "$val" + feature_lower=$(printf '%s' "$f" | tr '[:upper:]' '[:lower:]') + emit_set "$feature_lower" "$val" + done + emit_set CPPFLAGS "-Ishared ${cppflags_common}" + emit_set CPPFLAGS_LIBUTIL "${cppflags_common}" + } > "${tmp}" + mv "${tmp}" scripts/mk/config.set +} + +features_h() { + config_resolve + mkdir -p scripts/mk + tmp="scripts/mk/features.h.tmp.$$" + { + printf '/* generated by genconfig.sh */\n' + for f in ${features}; do + eval "val=\$$f" + printf '#define %s %s\n' "$f" "$val" + done + } > "${tmp}" + mv "${tmp}" scripts/mk/features.h +} + +nofork_list_h() { + config_resolve + tmp="shared/libutil/nofork_list.h.tmp.$$" + { + printf '/* generated by genconfig.sh */\n' + printf 'static const char *nofork_list[] = {\n' + for app in ${NOFORK_LIST:-}; do + printf ' "%s",\n' "$app" + done + printf ' NULL\n' + printf '};\n' + } > "${tmp}" + mv "${tmp}" shared/libutil/nofork_list.h +} + +config() { + config_set + config_kv + features_h + nofork_list_h } case "$target" in @@ -321,11 +400,16 @@ case "$target" in gen_awk gen_sh ;; - config) config ;; - clean) clean ;; + config) config ;; + config-set) config_set ;; + config-kv) config_kv ;; + features-h) features_h ;; + nofork-list-h) nofork_list_h ;; + config-check) config_resolve ;; + clean) clean ;; *) printf "genconfig: unknown target: %s\n" "$target" >&2 - printf "usage: %s (config|getconf|bc|awk|sh|all|clean)\n" "$0" >&2 + printf "usage: %s (config|config-set|config-kv|features-h|nofork-list-h|config-check|getconf|bc|awk|sh|all|clean)\n" "$0" >&2 exit 1 ;; esac diff --git a/scripts/mkman/main.go b/scripts/mkman/main.go @@ -2,17 +2,24 @@ package main import ( "bufio" + "bytes" "flag" "fmt" + "io" "os" "path/filepath" + "regexp" + "strconv" "strings" "time" ) -// parse config.kv variables and values +// config holds strict key-value records from config.kv type Config map[string]string +var configKeyPattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`) +var featureNamePattern = regexp.MustCompile(`^FEATURE_[A-Z][A-Z0-9_]*$`) + func parseConfigKv(path string) (Config, error) { f, err := os.Open(path) if err != nil { @@ -22,21 +29,35 @@ func parseConfigKv(path string) (Config, error) { cfg := make(Config) sc := bufio.NewScanner(f) + lineNo := 0 for sc.Scan() { + lineNo++ line := strings.TrimSpace(sc.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } + eq := strings.IndexByte(line, '=') if eq < 0 { - continue + return nil, fmt.Errorf("line %d: missing =", lineNo) + } + key := strings.TrimSpace(line[:eq]) + if !configKeyPattern.MatchString(key) { + return nil, fmt.Errorf("line %d: invalid key %q", lineNo, key) } - k := strings.TrimSpace(line[:eq]) - v := strings.TrimSpace(line[eq+1:]) - if len(v) >= 2 && ((v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'')) { - v = v[1 : len(v)-1] + if strings.HasPrefix(key, "FEATURE") && !featureNamePattern.MatchString(key) { + return nil, fmt.Errorf("line %d: invalid feature name %q", lineNo, key) + } + if _, ok := cfg[key]; ok { + return nil, fmt.Errorf("line %d: duplicate key %q", lineNo, key) + } + + raw := strings.TrimSpace(line[eq+1:]) + value, err := strconv.Unquote(raw) + if err != nil { + return nil, fmt.Errorf("line %d: invalid quoted value for %s: %w", lineNo, key, err) } - cfg[k] = v + cfg[key] = value } if err := sc.Err(); err != nil { return nil, err @@ -51,8 +72,9 @@ func (cfg Config) isEnabled(key string) bool { // preprocessor condition stack for nested feature blocks type ifFrame struct { - active bool - seen bool + active bool + seen bool + elseSeen bool } type ifStack struct { @@ -94,94 +116,148 @@ func (s *ifStack) top() *ifFrame { return &s.frames[len(s.frames)-1] } -// parse and evaluate preprocessor feature conditions -func evalCondition(expr string, cfg Config) bool { +var conditionPattern = regexp.MustCompile(`^(?:(!?)defined\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)|(!?)([A-Za-z_][A-Za-z0-9_]*)(?:\s*(==|!=)\s*([01]))?)$`) + +func validateConditionalName(name string) error { + if strings.HasPrefix(name, "FEATURE") && !featureNamePattern.MatchString(name) { + return fmt.Errorf("invalid feature name %q", name) + } + return nil +} + +func evalCondition(expr string, cfg Config) (bool, error) { expr = strings.TrimSpace(expr) - if strings.HasPrefix(expr, "defined(") && strings.HasSuffix(expr, ")") { - key := expr[8 : len(expr)-1] - _, ok := cfg[key] - return ok + alternatives := strings.Split(expr, "||") + result := false + for _, alternative := range alternatives { + terms := strings.Split(alternative, "&&") + termResult := true + for _, term := range terms { + value, err := evalConditionAtom(term, cfg) + if err != nil { + return false, err + } + termResult = termResult && value + } + result = result || termResult } - if strings.HasPrefix(expr, "!defined(") && strings.HasSuffix(expr, ")") { - key := expr[9 : len(expr)-1] - _, ok := cfg[key] - return !ok + return result, nil +} + +func evalConditionAtom(expr string, cfg Config) (bool, error) { + match := conditionPattern.FindStringSubmatch(strings.TrimSpace(expr)) + if match == nil { + return false, fmt.Errorf("unsupported preprocessor condition %q", expr) + } + + not := match[1] != "" + definedName := match[2] + plainNot := match[3] != "" + plainName := match[4] + operator := match[5] + value := match[6] + + if definedName != "" { + if err := validateConditionalName(definedName); err != nil { + return false, err + } + _, ok := cfg[definedName] + return ok != not, nil } - if idx := strings.Index(expr, "=="); idx >= 0 { - lhs := strings.TrimSpace(expr[:idx]) - rhs := strings.TrimSpace(expr[idx+2:]) - return cfg[lhs] == rhs + if err := validateConditionalName(plainName); err != nil { + return false, err } - if idx := strings.Index(expr, "!="); idx >= 0 { - lhs := strings.TrimSpace(expr[:idx]) - rhs := strings.TrimSpace(expr[idx+2:]) - return cfg[lhs] != rhs + if operator == "" { + return cfg[plainName] == "1" != plainNot, nil } - if strings.HasPrefix(expr, "!") { - key := strings.TrimSpace(expr[1:]) - return cfg[key] != "1" + result := cfg[plainName] == value + if operator == "!=" { + result = !result } - return cfg[expr] == "1" + return result, nil } // section inference from file path func inferSection(path string) int { - clean := filepath.ToSlash(path) - switch { - case strings.Contains(clean, "/linux/"), - strings.Contains(clean, "/net/"), - strings.Contains(clean, "/xsi/"): - return 8 - case strings.Contains(clean, "/posix/"), - strings.Contains(clean, "/pseudo/"), - strings.Contains(clean, "/extra/"), - strings.Contains(clean, "/dev/"): + parts := strings.Split(filepath.ToSlash(path), "/") + if len(parts) < 3 { return 1 + } + switch parts[1] { + case "linux", "net", "xsi": + return 8 default: return 1 } } -// a renderer turns a parsed page into one output format on os.stdout +func validateSourcePath(path string) error { + if filepath.IsAbs(path) || filepath.Clean(path) != path || strings.Contains(path, "\\") { + return fmt.Errorf("source path must be a clean relative path") + } + base := filepath.Base(path) + if filepath.Ext(base) != ".c" || !manNamePattern.MatchString(strings.TrimSuffix(base, ".c")) { + return fmt.Errorf("invalid generated path %q", path) + } + return nil +} + +// a renderer turns a parsed page into one output format type Renderer interface { Render() error } -func newRenderer(format string, page *Page) (Renderer, error) { +func newRenderer(format string, page *Page, w io.Writer) (Renderer, error) { switch strings.ToLower(format) { case "", "mdoc": - return NewMdocRenderer(page, os.Stdout), nil + return NewMdocRenderer(page, w), nil case "txt": - return NewTxtRenderer(page, os.Stdout), nil + return NewTxtRenderer(page, w), nil default: return nil, fmt.Errorf("unknown format %q (want mdoc or txt)", format) } } -// main entry point and flags definition func main() { - configPath := flag.String("config", "scripts/mk/config.kv", "path to config.kv") - sectionFlag := flag.Int("section", 0, "man section override (0 = infer from path)") - dateFlag := flag.String("date", "", "date string for TH line (default: current month/year)") - formatFlag := flag.String("fmt", "mdoc", "output format: mdoc or txt") - flag.Parse() + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + flags := flag.NewFlagSet("mkman", flag.ContinueOnError) + flags.SetOutput(stderr) + configPath := flags.String("config", "scripts/mk/config.kv", "path to config.kv") + sectionFlag := flags.Int("section", 0, "man section override (0 = infer from path)") + dateFlag := flags.String("date", "", "date string for TH line (default: current month/year)") + formatFlag := flags.String("fmt", "mdoc", "output format: mdoc or txt") + outputPath := flags.String("out", "", "write output to this path instead of standard output") + if err := flags.Parse(args); err != nil { + return 1 + } - if flag.NArg() < 1 { - fmt.Fprintf(os.Stderr, "usage: mkman [-config scripts/mk/config.kv] [-section N] [-fmt mdoc|txt] file.c\n") - os.Exit(1) + if flags.NArg() != 1 { + fmt.Fprintln(stderr, "usage: mkman [-config scripts/mk/config.kv] [-section N] [-fmt mdoc|txt] [-out file] file.c") + return 1 + } + cfile := flags.Arg(0) + if err := validateSourcePath(cfile); err != nil { + fmt.Fprintf(stderr, "mkman: %v\n", err) + return 1 } - cfile := flag.Arg(0) cfg, err := parseConfigKv(*configPath) if err != nil { - fmt.Fprintf(os.Stderr, "mkman: config: %v\n", err) - os.Exit(1) + fmt.Fprintf(stderr, "mkman: config: %v\n", err) + return 1 } section := *sectionFlag if section == 0 { section = inferSection(cfile) } + if section != 1 && section != 8 { + fmt.Fprintf(stderr, "mkman: invalid man section %d\n", section) + return 1 + } date := *dateFlag if date == "" { @@ -190,22 +266,50 @@ func main() { page, err := ParsePage(cfile, cfg, section, date) if err != nil { - fmt.Fprintf(os.Stderr, "mkman: scan: %v\n", err) - os.Exit(1) + fmt.Fprintf(stderr, "mkman: scan: %v\n", err) + return 1 } - if page == nil { - fmt.Fprintf(os.Stderr, "mkman: %s: no ?man comments found\n", cfile) - os.Exit(0) + fmt.Fprintf(stderr, "mkman: %s: no ?man comments found\n", cfile) + return 0 } - r, err := newRenderer(*formatFlag, page) + var output bytes.Buffer + renderer, err := newRenderer(*formatFlag, page, &output) if err != nil { - fmt.Fprintf(os.Stderr, "mkman: %v\n", err) - os.Exit(1) + fmt.Fprintf(stderr, "mkman: %v\n", err) + return 1 + } + if err := renderer.Render(); err != nil { + fmt.Fprintf(stderr, "mkman: render: %v\n", err) + return 1 + } + + outProvided := false + flags.Visit(func(f *flag.Flag) { + if f.Name == "out" { + outProvided = true + } + }) + if outProvided { + if strings.TrimSpace(*outputPath) == "" { + fmt.Fprintln(stderr, "mkman: output path must not be empty") + return 1 + } + if err := os.WriteFile(*outputPath, output.Bytes(), 0666); err != nil { + fmt.Fprintf(stderr, "mkman: write %s: %v\n", *outputPath, err) + return 1 + } + return 0 + } + + n, err := stdout.Write(output.Bytes()) + if err == nil && n != output.Len() { + err = io.ErrShortWrite } - if err := r.Render(); err != nil { - fmt.Fprintf(os.Stderr, "mkman: render: %v\n", err) - os.Exit(1) + if err != nil { + fmt.Fprintf(stderr, "mkman: write stdout: %v\n", err) + return 1 } + return 0 } diff --git a/scripts/mkman/mdoc.go b/scripts/mkman/mdoc.go @@ -8,30 +8,38 @@ import ( type MdocRenderer struct { page *Page - w io.Writer + w *trackingWriter } func NewMdocRenderer(page *Page, w io.Writer) *MdocRenderer { - return &MdocRenderer{page: page, w: w} + return &MdocRenderer{page: page, w: newTrackingWriter(w)} } func (r *MdocRenderer) Render() error { - if err := r.page.validate(); err != nil { return err; } + if err := r.page.validate(); err != nil { + return err + } fmt.Fprintf(r.w, ".Dd %s\n", troffEscape(r.page.Date)) fmt.Fprintf(r.w, ".Dt %s %d\n", strings.ToUpper(r.page.Name), r.page.Section) fmt.Fprintf(r.w, ".Os %s\n", "aruu") r.renderName() - if len(r.page.Synopsis) != 0 { r.renderSynopsis(); } - if len(r.page.Description) != 0 { r.renderDescription(); } - if len(r.page.Options) != 0 { r.renderOptions(); } + if len(r.page.Synopsis) != 0 { + r.renderSynopsis() + } + if len(r.page.Description) != 0 { + r.renderDescription() + } + if len(r.page.Options) != 0 { + r.renderOptions() + } for _, section := range r.page.Sections { r.renderSection(section.Title, section.Blocks) } - return nil + return r.w.err } func (r *MdocRenderer) renderName() { @@ -114,11 +122,15 @@ func renderSynopsisPhrase(items []SynopsisItem, topLevel bool) string { func renderMacro(name, body string, topLevel bool) string { if body == "" { - if topLevel { return "." + name; } + if topLevel { + return "." + name + } return name } - if topLevel { return "." + name + " " + body; } + if topLevel { + return "." + name + " " + body + } return name + " " + body } @@ -245,4 +257,4 @@ func trailingSpace(inline Inline) bool { } } -func isSpaceByte(b byte) bool { return b == ' ' || b == '\t' || b == '\n'; } +func isSpaceByte(b byte) bool { return b == ' ' || b == '\t' || b == '\n' } diff --git a/scripts/mkman/mkman_test.go b/scripts/mkman/mkman_test.go @@ -0,0 +1,379 @@ +package main + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestParseConfigKv(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.kv") + content := "NAME=\"a \\\"quoted\\\" path\\\\name\"\nEMPTY=\"\"\nFEATURE_A=\"1\"\n" + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + cfg, err := parseConfigKv(path) + if err != nil { + t.Fatal(err) + } + if cfg["NAME"] != "a \"quoted\" path\\name" || cfg["EMPTY"] != "" { + t.Fatalf("unexpected config: %#v", cfg) + } +} + +func TestParseConfigKvRejectsMalformedRecords(t *testing.T) { + tests := []struct { + name string + content string + }{ + {"missing separator", "NAME\n"}, + {"invalid key", "name=\"x\"\n"}, + {"unquoted value", "NAME=x\n"}, + {"duplicate key", "NAME=\"x\"\nNAME=\"y\"\n"}, + {"invalid feature name", "FEATUREbad=\"1\"\n"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.kv") + if err := os.WriteFile(path, []byte(test.content), 0600); err != nil { + t.Fatal(err) + } + if _, err := parseConfigKv(path); err == nil { + t.Fatal("parseConfigKv accepted malformed input") + } + }) + } +} + +func TestEvalConditionCompatibility(t *testing.T) { + cfg := Config{"FEATURE_A": "1", "FEATURE_B": "0"} + for _, test := range []struct { + expr string + want bool + }{ + {"FEATURE_A", true}, + {"!FEATURE_B", true}, + {"FEATURE_B == 0", true}, + {"defined(FEATURE_A)", true}, + {"!defined(FEATURE_C)", true}, + {"defined(_DEFAULT_SOURCE)", false}, + {"FEATURE_A && FEATURE_B", false}, + {"FEATURE_A || FEATURE_B", true}, + } { + got, err := evalCondition(test.expr, cfg) + if err != nil { + t.Fatalf("evalCondition(%q): %v", test.expr, err) + } + if got != test.want { + t.Errorf("evalCondition(%q) = %v, want %v", test.expr, got, test.want) + } + } +} + +func TestParsePageRejectionClasses(t *testing.T) { + tests := []struct { + name string + content string + }{ + { + name: "malformed command metadata", + content: "// ?man cmd:\n", + }, + { + name: "unsupported conditional", + content: "// ?man cmd: summary\n#if (FEATURE_A)\n// ?man -a: use a\n#endif\n", + }, + { + name: "invalid feature name", + content: "// ?man cmd: summary\n#ifdef FEATUREbad\n// ?man -a: use a\n#endif\n", + }, + { + name: "duplicate option", + content: "// ?man cmd: summary\n// ?man -a: first\n// ?man -a: second\n", + }, + { + name: "empty type suffix", + content: "// ?man cmd: summary\n// ?man -a:: use a\n", + }, + { + name: "invalid type suffix", + content: "// ?man cmd: summary\n// ?man -a:bad/type: use a\n", + }, + { + name: "malformed group", + content: "// ?man cmd: summary\n// ?man -a{1bad}: use a\n// ?man -b: use b\n", + }, + { + name: "misplaced group", + content: "// ?man cmd: summary\n// ?man -a{x}y: use a\n// ?man -b: use b\n", + }, + { + name: "singleton group", + content: "// ?man cmd: summary\n// ?man -a{choice}: use a\n", + }, + { + name: "mixed required group", + content: "// ?man cmd: summary\n// ?man -a{choice}!: use a\n// ?man -b{choice}: use b\n", + }, + { + name: "unclosed synopsis group", + content: "// ?man cmd: summary\n// ?man synopsis: [-a\n", + }, + { + name: "mismatched synopsis group", + content: "// ?man cmd: summary\n// ?man synopsis: [-a}\n", + }, + { + name: "empty synopsis group", + content: "// ?man cmd: summary\n// ?man synopsis: []\n", + }, + { + name: "misplaced synopsis pipe", + content: "// ?man cmd: summary\n// ?man synopsis: -a || -b\n", + }, + { + name: "synopsis without colon", + content: "// ?man cmd: summary\n// ?man synopsis\n", + }, + { + name: "empty arguments", + content: "// ?man cmd: summary\n// ?man arguments:\n", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if _, err := parseSource(t, test.content, Config{"FEATURE_A": "1"}); err == nil { + t.Fatal("ParsePage accepted malformed metadata") + } + }) + } +} + +func TestParseOptionCompatibility(t *testing.T) { + for _, line := range []string{ + "-a: use a", + "-a:str: use a", + "-?: use question", + "--color:when: use color", + "-a{mode}!: use mode a", + "-a:str{mode}!: use mode a", + } { + if _, err := parseOption(line); err != nil { + t.Errorf("parseOption(%q): %v", line, err) + } + } +} + +func TestParseSynopsisCompatibility(t *testing.T) { + for _, raw := range []string{ + "[-a] file ...", + "(-f | -u) mountpoint", + "| -l num", + "+format | mmddHHMM[[CC]yy]", + "[-aBbdipTtw] [-c|-e|-f]", + "[x | t | -x | -t] [file ...]", + } { + if _, err := parseSynopsis(raw, false); err != nil { + t.Errorf("parseSynopsis(%q): %v", raw, err) + } + } +} + +func TestExplicitEmptySynopsisCompatibility(t *testing.T) { + page, err := parseSource(t, "// ?man sync: flush disk cache\n// ?man synopsis:\n// ?man flush pending writes\n", Config{}) + if err != nil { + t.Fatal(err) + } + if len(page.Synopsis) != 0 { + t.Fatalf("empty explicit synopsis produced %d forms", len(page.Synopsis)) + } +} + +func TestValidateSourcePath(t *testing.T) { + for _, path := range []string{"cmd/posix/cat.c", "cmd/nac/main.c", "ports/pkgtools/dtr/main.c"} { + if err := validateSourcePath(path); err != nil { + t.Errorf("validateSourcePath(%q): %v", path, err) + } + } + for _, path := range []string{"cmd/posix/../cat.c", "cmd/posix/cat"} { + if err := validateSourcePath(path); err == nil { + t.Errorf("validateSourcePath accepted %q", path) + } + } +} + +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { + return 0, errors.New("write failed") +} + +type shortWriter struct{} + +func (shortWriter) Write(p []byte) (int, error) { + return len(p) - 1, nil +} + +func TestRenderWriteFailure(t *testing.T) { + page := &Page{Name: "cat", Summary: "concatenate files", Section: 1, Date: "January 2, 2006"} + for _, writer := range []io.Writer{failingWriter{}, shortWriter{}} { + if err := NewMdocRenderer(page, writer).Render(); err == nil { + t.Fatal("mdoc renderer accepted a failed write") + } + if err := NewTxtRenderer(page, writer).Render(); err == nil { + t.Fatal("text renderer accepted a failed write") + } + } +} + +func TestRunRejectionsAndOutput(t *testing.T) { + dir := t.TempDir() + sourceDir := filepath.Join(dir, "cmd", "posix") + if err := os.MkdirAll(sourceDir, 0700); err != nil { + t.Fatal(err) + } + source := filepath.Join(sourceDir, "bad.c") + if err := os.WriteFile(source, []byte("// ?man bad:\n"), 0600); err != nil { + t.Fatal(err) + } + config := filepath.Join(dir, "config.kv") + if err := os.WriteFile(config, []byte("FEATURE_A=\"1\"\n"), 0600); err != nil { + t.Fatal(err) + } + + oldwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + if err := os.Chdir(dir); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.Chdir(oldwd); err != nil { + t.Errorf("restore working directory: %v", err) + } + }) + + validSource := "// ?man bad: reject bad input\n// ?man synopsis: [file ...]\n" + for _, test := range []struct { + name string + source string + args []string + want string + }{ + { + name: "malformed metadata", + source: "// ?man bad:\n", + args: []string{"-config", config, "cmd/posix/bad.c"}, + want: "malformed command metadata", + }, + { + name: "empty output path", + source: validSource, + args: []string{"-config", config, "-out", "", "cmd/posix/bad.c"}, + want: "output path must not be empty", + }, + { + name: "output write failure", + source: validSource, + args: []string{"-config", config, "-out", ".", "cmd/posix/bad.c"}, + want: "write .", + }, + } { + t.Run(test.name, func(t *testing.T) { + if err := os.WriteFile(source, []byte(test.source), 0600); err != nil { + t.Fatal(err) + } + var stdout bytes.Buffer + var stderr bytes.Buffer + if status := run(test.args, &stdout, &stderr); status == 0 { + t.Fatal("run accepted malformed input") + } + if !strings.Contains(stderr.String(), test.want) { + t.Fatalf("stderr %q does not contain %q", stderr.String(), test.want) + } + }) + } + + if err := os.WriteFile(source, []byte("// ?man bad: reject bad input\n// ?man synopsis: [file ...]\n"), 0600); err != nil { + t.Fatal(err) + } + out := filepath.Join(dir, "bad.1") + var stdout bytes.Buffer + var stderr bytes.Buffer + if status := run([]string{"-config", config, "-out", out, "cmd/posix/bad.c"}, &stdout, &stderr); status != 0 { + t.Fatalf("run failed: %s", stderr.String()) + } + if stdout.Len() != 0 { + t.Fatalf("run wrote to standard output: %q", stdout.String()) + } + written, err := os.ReadFile(out) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(written, []byte(".Dt BAD 1\n")) { + t.Fatalf("unexpected output:\n%s", written) + } + + var shortOutput shortWriter + stderr.Reset() + if status := run([]string{"-config", config, "cmd/posix/bad.c"}, &shortOutput, &stderr); status == 0 { + t.Fatal("run accepted a short standard-output write") + } + if !strings.Contains(stderr.String(), "write stdout: short write") { + t.Fatalf("unclear standard-output write error: %s", stderr.String()) + } +} + +func TestRenderCompatibility(t *testing.T) { + page, err := parseSource(t, `// ?man cat: concatenate files +// ?man arguments: [-abt] [file ...] +// ?man concatenate FILE to standard output +// ?man -a: answer all +// ?man -b:str: ignore expanded tabs +`, Config{}) + if err != nil { + t.Fatal(err) + } + page.Date = "January 2, 2006" + + var mdoc bytes.Buffer + if err := NewMdocRenderer(page, &mdoc).Render(); err != nil { + t.Fatal(err) + } + wantMdoc := ".Dd January 2, 2006\n.Dt CAT 1\n.Os aruu\n.Sh NAME\n.Nm cat\n.Nd concatenate files\n.Sh SYNOPSIS\n.Nm cat\n.Op Fl a\n.Op Fl b Ar str\n.Op Fl a Fl b Fl t\n.Op Ar file ...\n.Sh DESCRIPTION\n.Pp\n.No concatenate FILE to standard output\n.Sh OPTIONS\n.Bl -tag -width Ds\n.It Fl a\n.Pp\n.No answer all\n.It Fl b Ar str\n.Pp\n.No ignore expanded tabs\n.El\n" + if mdoc.String() != wantMdoc { + t.Fatalf("mdoc output changed:\n%s", mdoc.String()) + } + + var text bytes.Buffer + if err := NewTxtRenderer(page, &text).Render(); err != nil { + t.Fatal(err) + } + wantText := "NAME\n cat - concatenate files\n\nSYNOPSIS\n cat [-a] [-b str] [-a -b -t] [file ...]\n\nDESCRIPTION\n\n concatenate FILE to standard output\n\nOPTIONS\n -a\n\n answer all\n\n -b str\n\n ignore expanded tabs\n" + if text.String() != wantText { + t.Fatalf("text output changed:\n%s", text.String()) + } +} + +func parseSource(t *testing.T, content string, cfg Config) (*Page, error) { + t.Helper() + path := filepath.Join(t.TempDir(), "source.c") + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + page, err := ParsePage(path, cfg, 1, "January 2, 2006") + if err != nil { + return nil, err + } + if page == nil { + return nil, fmt.Errorf("ParsePage returned no page") + } + return page, nil +} diff --git a/scripts/mkman/page.go b/scripts/mkman/page.go @@ -1,5 +1,28 @@ package main +import "io" + +type trackingWriter struct { + w io.Writer + err error +} + +func newTrackingWriter(w io.Writer) *trackingWriter { + return &trackingWriter{w: w} +} + +func (w *trackingWriter) Write(p []byte) (int, error) { + if w.err != nil { + return 0, w.err + } + n, err := w.w.Write(p) + if err == nil && n != len(p) { + err = io.ErrShortWrite + } + w.err = err + return n, err +} + type Page struct { Name string Summary string diff --git a/scripts/mkman/parse.go b/scripts/mkman/parse.go @@ -10,20 +10,110 @@ import ( ) var xrefPattern = regexp.MustCompile(`^\s*([A-Za-z0-9][A-Za-z0-9+_.-]*)\((\d+[A-Za-z]*)\)\s*$`) -var groupPattern = regexp.MustCompile(`\{([A-Za-z0-9_-]+)\}`) +var groupPattern = regexp.MustCompile(`\{[A-Za-z][A-Za-z0-9_-]*\}`) +var macroNamePattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) +var manNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9+_.-]*$`) func parseNameSummary(line string) (string, string, bool) { line = strings.TrimSpace(line) - if idx := strings.Index(line, ":"); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true + idx := strings.IndexByte(line, ':') + if idx < 0 { + return "", "", false } - if idx := strings.Index(line, " \\- "); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+4:]), true + return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+1:]), true +} + +func parseConditional(directive string, cfg Config, stack *ifStack, lineNo int) error { + name := directive + if fields := strings.Fields(directive); len(fields) != 0 { + name = fields[0] } - if idx := strings.Index(line, " - "); idx >= 0 { - return strings.TrimSpace(line[:idx]), strings.TrimSpace(line[idx+3:]), true + + switch name { + case "if", "ifdef", "ifndef", "elif", "else", "endif": + default: + if strings.HasPrefix(name, "if") || strings.HasPrefix(name, "elif") || + strings.HasPrefix(name, "else") || strings.HasPrefix(name, "endif") { + return fmt.Errorf("line %d: unsupported preprocessor conditional %q", lineNo, directive) + } + return nil } - return "", "", false + + switch name { + case "if": + if !strings.HasPrefix(directive, "if ") { + return fmt.Errorf("line %d: malformed #if directive", lineNo) + } + result, err := evalCondition(strings.TrimSpace(directive[3:]), cfg) + if err != nil { + return fmt.Errorf("line %d: %w", lineNo, err) + } + pa := stack.parentActive() + stack.push(pa && result, result) + case "ifdef", "ifndef": + prefix := name + " " + if !strings.HasPrefix(directive, prefix) { + return fmt.Errorf("line %d: malformed #%s directive", lineNo, name) + } + key := strings.TrimSpace(directive[len(prefix):]) + if !macroNamePattern.MatchString(key) { + return fmt.Errorf("line %d: invalid macro name %q", lineNo, key) + } + if err := validateConditionalName(key); err != nil { + return fmt.Errorf("line %d: %w", lineNo, err) + } + _, defined := cfg[key] + result := defined + if name == "ifndef" { + result = !result + } + pa := stack.parentActive() + stack.push(pa && result, result) + case "else": + if directive != "else" { + return fmt.Errorf("line %d: malformed #else directive", lineNo) + } + top := stack.top() + if top == nil { + return fmt.Errorf("line %d: #else without #if", lineNo) + } + if top.elseSeen { + return fmt.Errorf("line %d: duplicate #else", lineNo) + } + pa := stack.parentActive() + top.active = pa && !top.seen + top.seen = true + top.elseSeen = true + case "elif": + if !strings.HasPrefix(directive, "elif ") { + return fmt.Errorf("line %d: malformed #elif directive", lineNo) + } + top := stack.top() + if top == nil { + return fmt.Errorf("line %d: #elif without #if", lineNo) + } + if top.elseSeen { + return fmt.Errorf("line %d: #elif after #else", lineNo) + } + result, err := evalCondition(strings.TrimSpace(directive[5:]), cfg) + if err != nil { + return fmt.Errorf("line %d: %w", lineNo, err) + } + pa := stack.parentActive() + top.active = pa && !top.seen && result + if result { + top.seen = true + } + case "endif": + if directive != "endif" { + return fmt.Errorf("line %d: malformed #endif directive", lineNo) + } + if stack.top() == nil { + return fmt.Errorf("line %d: #endif without #if", lineNo) + } + stack.pop() + } + return nil } func extractManLines(path string, cfg Config) ([]string, error) { @@ -38,7 +128,9 @@ func extractManLines(path string, cfg Config) ([]string, error) { sc.Buffer(make([]byte, 1<<20), 1<<20) inBlockComment := false + lineNo := 0 for sc.Scan() { + lineNo++ line := sc.Text() trimmed := strings.TrimSpace(line) @@ -75,40 +167,8 @@ func extractManLines(path string, cfg Config) ([]string, error) { } directive = strings.TrimSpace(directive) - switch { - case strings.HasPrefix(directive, "ifdef "): - key := strings.TrimSpace(directive[6:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && defined, defined) - case strings.HasPrefix(directive, "ifndef "): - key := strings.TrimSpace(directive[7:]) - _, defined := cfg[key] - pa := stack.parentActive() - stack.push(pa && !defined, !defined) - case strings.HasPrefix(directive, "if "): - expr := strings.TrimSpace(directive[3:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - stack.push(pa && result, result) - case directive == "else": - if top := stack.top(); top != nil { - pa := stack.parentActive() - top.active = pa && !top.seen - top.seen = true - } - case strings.HasPrefix(directive, "elif "): - if top := stack.top(); top != nil { - expr := strings.TrimSpace(directive[5:]) - result := evalCondition(expr, cfg) - pa := stack.parentActive() - top.active = pa && !top.seen && result - if result { - top.seen = true - } - } - case directive == "endif": - stack.pop() + if err := parseConditional(directive, cfg, stack, lineNo); err != nil { + return nil, err } continue } @@ -137,6 +197,12 @@ func extractManLines(path string, cfg Config) ([]string, error) { if err := sc.Err(); err != nil { return nil, err } + if inBlockComment { + return nil, fmt.Errorf("unterminated man comment") + } + if len(stack.frames) != 0 { + return nil, fmt.Errorf("unterminated preprocessor conditional") + } return lines, nil } @@ -165,7 +231,7 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) var fallbackArgs string var rawOptions []rawOption var currentOption *rawOption - optionIndex := make(map[string]int) + optionNames := make(map[string]bool) for _, raw := range lines { line := strings.TrimSpace(raw) @@ -182,6 +248,9 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) if page.Name == "" && !strings.HasPrefix(line, "-") && !strings.HasPrefix(line, "#") { if name, summary, ok := parseNameSummary(line); ok { + if !manNamePattern.MatchString(name) || summary == "" { + return nil, fmt.Errorf("malformed command metadata %q", line) + } page.Name = name page.Summary = summary sawContent = true @@ -190,18 +259,28 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) } lower := strings.ToLower(line) + if lower == "synopsis" || lower == "arguments" { + return nil, fmt.Errorf("invalid synopsis metadata %q", line) + } switch { case strings.HasPrefix(lower, "synopsis:"): currentOption = nil form := strings.TrimSpace(line[len("synopsis:"):]) if form != "" { - page.Synopsis = append(page.Synopsis, parseSynopsis(form, true)) + synopsis, err := parseSynopsis(form, true) + if err != nil { + return nil, fmt.Errorf("invalid synopsis metadata: %w", err) + } + page.Synopsis = append(page.Synopsis, synopsis) } sawContent = true continue case strings.HasPrefix(lower, "arguments:"): currentOption = nil fallbackArgs = strings.TrimSpace(line[len("arguments:"):]) + if fallbackArgs == "" { + return nil, fmt.Errorf("invalid synopsis metadata: empty arguments") + } sawContent = true continue case strings.HasPrefix(line, "## "): @@ -214,7 +293,16 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) } if currentSection == nil { - if opt, ok := parseOption(line); ok { + if strings.HasPrefix(line, "-") { + opt, err := parseOption(line) + if err != nil { + return nil, err + } + name := optionIdentity(opt) + if optionNames[name] { + return nil, fmt.Errorf("duplicate option %q", name) + } + optionNames[name] = true rawOptions = append(rawOptions, rawOption{ Option: opt, Lines: []string{opt.Desc}, @@ -235,19 +323,53 @@ func ParsePage(path string, cfg Config, section int, date string) (*Page, error) sawContent = true } - if !sawContent || page.Name == "" { + if !sawContent { return nil, nil } + if page.Name == "" { + return nil, fmt.Errorf("first man comment must be NAME: SUMMARY") + } + + groupMembers := make(map[string]int) + groupRequired := make(map[string]int) + for _, raw := range rawOptions { + option := raw.Option + if option.Group == "" { + continue + } + groupMembers[option.Group]++ + required := 0 + if option.Required { + required = 1 + } + if groupRequired[option.Group] != 0 && groupRequired[option.Group] != required { + groupRequired[option.Group] = -1 + } else if groupRequired[option.Group] == 0 { + groupRequired[option.Group] = required + } + } + for name, count := range groupMembers { + if count < 2 { + return nil, fmt.Errorf("mutual exclusion group %q has one option", name) + } + if groupRequired[name] < 0 { + return nil, fmt.Errorf("mutual exclusion group %q mixes required and optional options", name) + } + } // explicit synopsis forms are authoritative. for simple pages we can produce // a synopsis from the parsed option specs plus the arguments line for _, raw := range rawOptions { raw.Option.Body = parseBlocks(raw.Lines, "") - addOption(page, optionIndex, raw.Option) + page.Options = append(page.Options, raw.Option) } if len(page.Synopsis) == 0 && fallbackArgs != "" { - page.Synopsis = append(page.Synopsis, synthesizeSynopsis(page.Options, fallbackArgs)) + synopsis, err := synthesizeSynopsis(page.Options, fallbackArgs) + if err != nil { + return nil, fmt.Errorf("invalid synopsis metadata: %w", err) + } + page.Synopsis = append(page.Synopsis, synopsis) } page.Description = parseBlocks(descriptionLines, "") @@ -272,79 +394,111 @@ type rawOption struct { Lines []string } -func parseOption(line string) (Option, bool) { - if !strings.HasPrefix(line, "-") { - return Option{}, false - } +var optionFlagPattern = regexp.MustCompile(`^(?:--|--?[A-Za-z0-9?][A-Za-z0-9?-]*)$`) +var optionTypePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]*$`) +func parseOption(line string) (Option, error) { parts := strings.Split(line, ":") if len(parts) < 2 { - return Option{}, false + return Option{}, fmt.Errorf("malformed option %q: missing type separator", line) + } + + if len(parts) > 2 && strings.TrimSpace(parts[1]) == "" { + return Option{}, fmt.Errorf("malformed option %q: empty type", line) } specParts := []string{strings.TrimSpace(parts[0])} - i := 1 - for i < len(parts)-1 { - part := strings.TrimSpace(parts[i]) + descriptionAt := 1 + for descriptionAt < len(parts)-1 { + part := strings.TrimSpace(parts[descriptionAt]) if !looksLikeOptionArg(part) { break } specParts = append(specParts, part) - i++ + descriptionAt++ + } + if len(specParts) > 2 { + return Option{}, fmt.Errorf("malformed option %q: expected at most one type", line) } - desc := strings.TrimSpace(strings.Join(parts[i:], ":")) - flag, typ, group, required := splitOptionSpec(strings.Join(specParts, ":")) - if flag == "" { - return Option{}, false + description := strings.TrimSpace(strings.Join(parts[descriptionAt:], ":")) + spec := strings.Join(specParts, ":") + flag, typ, group, required, err := splitOptionSpec(spec) + if err != nil { + return Option{}, fmt.Errorf("malformed option %q: %w", line, err) + } + if !optionFlagPattern.MatchString(flag) { + return Option{}, fmt.Errorf("malformed option %q: invalid flag", line) + } + if typ != "" && !optionTypePattern.MatchString(typ) { + return Option{}, fmt.Errorf("malformed option %q: invalid type %q", line, typ) } rawSpec := flag if typ != "" { rawSpec += " " + typ } - spec := normalizeOptionSpec(rawSpec) - desc = stripRepeatedSpec(spec, desc) - if spec == "" || desc == "" { - return Option{}, false + normalized := normalizeOptionSpec(rawSpec) + description = stripRepeatedSpec(normalized, description) + if description == "" { + return Option{}, fmt.Errorf("malformed option %q: missing description", line) + } + items, err := parseSynopsis(normalized, false) + if err != nil { + return Option{}, fmt.Errorf("malformed option %q: %w", line, err) + } + if len(items.Items) == 0 { + return Option{}, fmt.Errorf("malformed option %q: empty synopsis", line) } return Option{ - Spec: parseSynopsis(spec, false).Items, - Desc: desc, - Key: synopsisKey(spec) + "\x00" + group, + Spec: items.Items, + Desc: description, + Key: synopsisKey(normalized) + "\x00" + group, Group: group, Required: required, - }, true + }, nil } -// splitoptionspec peels the required marker (!) and the mutual exclusion -// group marker ({name}) off a raw option spec, leaving the bare flag and -// its optional colon-delimited type suffix -func splitOptionSpec(raw string) (flag, typ, group string, required bool) { +func splitOptionSpec(raw string) (flag, typ, group string, required bool, err error) { raw = strings.TrimSpace(raw) + if strings.Count(raw, "!") > 1 { + return "", "", "", false, fmt.Errorf("duplicate required marker") + } if strings.HasSuffix(raw, "!") { required = true - raw = raw[:len(raw)-1] + raw = strings.TrimSpace(raw[:len(raw)-1]) + } else if strings.Contains(raw, "!") { + return "", "", "", false, fmt.Errorf("misplaced required marker") } - if m := groupPattern.FindStringSubmatchIndex(raw); m != nil { - group = raw[m[2]:m[3]] - raw = raw[:m[0]] + raw[m[1]:] + + matches := groupPattern.FindAllStringIndex(raw, -1) + if strings.ContainsAny(raw, "{}") { + if len(matches) != 1 { + return "", "", "", false, fmt.Errorf("invalid mutual exclusion group") + } + start, end := matches[0][0], matches[0][1] + if start == 0 || (end != len(raw) && !strings.HasPrefix(raw[end:], ":")) { + return "", "", "", false, fmt.Errorf("misplaced mutual exclusion group") + } + group = raw[start+1 : end-1] + raw = raw[:start] + raw[end:] } - if idx := strings.Index(raw, ":"); idx >= 0 { - flag = raw[:idx] - typ = raw[idx+1:] + + if strings.Count(raw, ":") > 1 { + return "", "", "", false, fmt.Errorf("more than one type suffix") + } + if idx := strings.IndexByte(raw, ':'); idx >= 0 { + flag = strings.TrimSpace(raw[:idx]) + typ = strings.TrimSpace(raw[idx+1:]) } else { - flag = raw + flag = strings.TrimSpace(raw) } - return flag, typ, group, required + return flag, typ, group, required, nil } func looksLikeOptionArg(s string) bool { - if s == "" { - return false - } - return !strings.ContainsAny(s, " \t") + return s != "" && !strings.ContainsAny(s, " \t") } func normalizeOptionSpec(spec string) string { @@ -384,49 +538,14 @@ func stripRepeatedSpec(spec, desc string) string { return desc } -func addOption(page *Page, index map[string]int, opt Option) { - if idx, ok := index[opt.Key]; ok { - if betterOptionDesc(opt.Desc, page.Options[idx].Desc) { - page.Options[idx].Desc = opt.Desc - page.Options[idx].Spec = opt.Spec - page.Options[idx].Body = opt.Body - } - return - } - - primary := optionPrimaryFlag(opt) - if primary != "" { - for idx, existing := range page.Options { - if optionPrimaryFlag(existing) != primary { - continue - } - if betterOptionDesc(opt.Desc, existing.Desc) { - page.Options[idx].Desc = opt.Desc - page.Options[idx].Spec = opt.Spec - page.Options[idx].Body = opt.Body - delete(index, existing.Key) - index[opt.Key] = idx - } - return +func optionIdentity(opt Option) string { + parts := make([]string, 0, len(opt.Spec)) + for _, item := range opt.Spec { + if item.Kind == SynFlag { + parts = append(parts, item.Text) } } - - index[opt.Key] = len(page.Options) - page.Options = append(page.Options, opt) -} - -func betterOptionDesc(newDesc, oldDesc string) bool { - return optionDescScore(newDesc) > optionDescScore(oldDesc) -} - -func optionDescScore(desc string) int { - desc = strings.TrimSpace(desc) - score := len(desc) - lower := strings.ToLower(desc) - if strings.HasPrefix(lower, "specify ") && strings.HasSuffix(lower, " option") { - score -= 1000 - } - return score + return strings.Join(parts, "\x00") } func optionPrimaryFlag(opt Option) string { @@ -554,8 +673,8 @@ func parseSubsections(lines []string, title string) ([]Block, bool) { lines = lines[1:] } blocks = append(blocks, Block{ - Kind: BlockSubsection, - Title: subtitle, + Kind: BlockSubsection, + Title: subtitle, Blocks: parseBlocks(body, subtitle), }) } @@ -746,7 +865,7 @@ func classifyInlineLiteral(s string) Inline { return Inline{Kind: InlineLiteral, Text: s} } -func synthesizeSynopsis(options []Option, args string) SynopsisForm { +func synthesizeSynopsis(options []Option, args string) (SynopsisForm, error) { type unit struct { sortKey string items []SynopsisItem @@ -816,8 +935,12 @@ func synthesizeSynopsis(options []Option, args string) SynopsisForm { for _, u := range units { items = append(items, u.items...) } - items = append(items, parseSynopsis(args, false).Items...) - return SynopsisForm{Items: items} + argsSynopsis, err := parseSynopsis(args, false) + if err != nil { + return SynopsisForm{}, err + } + items = append(items, argsSynopsis.Items...) + return SynopsisForm{Items: items}, nil } func optionSortKey(opt Option) string { @@ -875,10 +998,22 @@ func parseXRefs(s string) ([]XRef, bool) { return refs, len(refs) != 0 } -func parseSynopsis(raw string, explicit bool) SynopsisForm { +func parseSynopsis(raw string, explicit bool) (SynopsisForm, error) { tokens := tokenizeSynopsis(raw) - items, _ := parseSynopsisSeq(tokens, 0, explicit, true) - return SynopsisForm{Items: items} + if len(tokens) == 0 { + return SynopsisForm{}, nil + } + items, next, closer, err := parseSynopsisSeq(tokens, 0, explicit, true) + if err != nil { + return SynopsisForm{}, err + } + if closer != "" { + return SynopsisForm{}, fmt.Errorf("unexpected %q", closer) + } + if next != len(tokens) { + return SynopsisForm{}, fmt.Errorf("unclosed %q", tokens[next]) + } + return SynopsisForm{Items: items}, nil } func tokenizeSynopsis(raw string) []string { @@ -907,43 +1042,84 @@ func tokenizeSynopsis(raw string) []string { return tokens } -func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) ([]SynopsisItem, int) { +func parseSynopsisSeq(tokens []string, start int, explicit bool, topLevel bool) ([]SynopsisItem, int, string, error) { var items []SynopsisItem seenNonFlag := false for i := start; i < len(tokens); i++ { switch tokens[i] { case "]", "}": - return items, i - case "[": - children, end := parseSynopsisSeq(tokens, i+1, explicit, false) - items = append(items, SynopsisItem{Kind: SynOptional, Children: children}) - i = end - case "{": - children, end := parseSynopsisSeq(tokens, i+1, explicit, false) - items = append(items, SynopsisItem{Kind: SynRequiredGroup, Children: children}) - i = end + if len(items) == 0 { + return nil, i, tokens[i], fmt.Errorf("empty group") + } + return items, i, tokens[i], nil + case "[", "{": + open := tokens[i] + children, next, closer, err := parseSynopsisSeq(tokens, i+1, explicit, false) + if err != nil { + return nil, next, closer, err + } + if closer == "" { + return nil, next, closer, fmt.Errorf("unclosed %q", open) + } + expected := "]" + kind := SynOptional + if open == "{" { + expected = "}" + kind = SynRequiredGroup + } + if closer != expected { + return nil, next, closer, fmt.Errorf("mismatched %q and %q", open, closer) + } + items = append(items, SynopsisItem{Kind: kind, Children: children}) + i = next case "|": + if i+1 >= len(tokens) || tokens[i+1] == "|" || tokens[i+1] == "]" || tokens[i+1] == "}" { + return nil, i, "", fmt.Errorf("misplaced |") + } + if i != start { + previous := tokens[i-1] + if previous == "|" || previous == "[" || previous == "{" { + return nil, i, "", fmt.Errorf("misplaced |") + } + } else if !topLevel { + return nil, i, "", fmt.Errorf("misplaced |") + } items = append(items, SynopsisItem{Kind: SynPipe, Text: "|"}) default: + if err := validateSynopsisToken(tokens[i]); err != nil { + return nil, i, "", err + } if flags, ok := splitGroupedFlags(tokens[i]); ok { items = append(items, flags...) continue } kind := classifySynopsisToken(tokens, i, explicit, topLevel, seenNonFlag) - text := tokens[i] - if text == "..." && len(items) != 0 { + if tokens[i] == "..." { + if len(items) == 0 { + return nil, i, "", fmt.Errorf("misplaced ...") + } items[len(items)-1].Text += " ..." continue } - items = append(items, SynopsisItem{Kind: kind, Text: text}) + items = append(items, SynopsisItem{Kind: kind, Text: tokens[i]}) if kind != SynFlag && kind != SynPipe { seenNonFlag = true } } } - return items, len(tokens) + return items, len(tokens), "", nil +} + +func validateSynopsisToken(token string) error { + if strings.HasPrefix(token, "<") && (!strings.HasSuffix(token, ">") || token == "<>") { + return fmt.Errorf("malformed angle placeholder %q", token) + } + if strings.HasSuffix(token, ">") && !strings.HasPrefix(token, "<") { + return fmt.Errorf("malformed angle placeholder %q", token) + } + return nil } func splitGroupedFlags(tok string) ([]SynopsisItem, bool) { diff --git a/scripts/mkman/txt.go b/scripts/mkman/txt.go @@ -17,12 +17,12 @@ const ( type TxtRenderer struct { page *Page - w io.Writer + w *trackingWriter wrote bool } func NewTxtRenderer(page *Page, w io.Writer) *TxtRenderer { - return &TxtRenderer{page: page, w: w} + return &TxtRenderer{page: page, w: newTrackingWriter(w)} } func (r *TxtRenderer) Render() error { @@ -51,7 +51,7 @@ func (r *TxtRenderer) Render() error { r.renderBlock(block, txtIndent) } } - return nil + return r.w.err } // heading prints a flush-left section title, with a blank line above diff --git a/shared/filesystem.h b/shared/filesystem.h @@ -0,0 +1,22 @@ +#ifndef FILESYSTEM_H +#define FILESYSTEM_H + +#include <stddef.h> + +struct FilesystemStatus { + unsigned long long block_size; + unsigned long long total_blocks; + unsigned long long free_blocks; +}; + +struct FilesystemMount { + char *source; + char *type; + char *path; +}; + +int fs_get_status(const char *, struct FilesystemStatus *); +int fs_get_mounts(struct FilesystemMount **, size_t *); +void fs_free_mounts(struct FilesystemMount *, size_t); + +#endif diff --git a/shared/libredline/redline.c b/shared/libredline/redline.c @@ -12,6 +12,9 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#if FEATURE_CASEFOLD +#include <strings.h> +#endif #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> @@ -309,7 +312,11 @@ isUnsupportedTerm(void) if (term == NULL) return 0; for (i = 0; unsupported[i]; i++) { +#if FEATURE_CASEFOLD if (strcasecmp(term, unsupported[i]) == 0) +#else + if (strcmp(term, unsupported[i]) == 0) +#endif return 1; } return 0; diff --git a/shared/libtcutil/tcutil.h b/shared/libtcutil/tcutil.h @@ -50,7 +50,7 @@ int is_file(const char *path); ssize_t getline_chomp(char **lineptr, size_t *n, FILE *stream); ssize_t getline_cont(char **lineptr, size_t *n, FILE *stream, int *plineno); -/* memory: toolchain-local, same contract as aruu emalloc/ecalloc/erealloc +/* memory: toolchain-local, same behavior as aruu emalloc/ecalloc/erealloc * kept separate so the toolchain can build standalone without libutil */ void *malloc_or_die(size_t size); void *calloc_or_die(size_t size); diff --git a/shared/libutil/cp.c b/shared/libutil/cp.c @@ -1,4 +1,9 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_MKNOD +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <dirent.h> #include <errno.h> #include <fcntl.h> diff --git a/shared/libutil/filesystem_linux.c b/shared/libutil/filesystem_linux.c @@ -0,0 +1,69 @@ +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#if defined(__linux__) +#include "../filesystem.h" +#include "../paths.h" +#include "../util.h" + +#include <mntent.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/statvfs.h> + +int +fs_get_status(const char *path, struct FilesystemStatus *status) +{ + struct statvfs s; + + memset(status, 0, sizeof(*status)); + if (statvfs(path, &s) < 0) + return -1; + status->block_size = s.f_frsize; + status->total_blocks = s.f_blocks; + status->free_blocks = s.f_bfree; + return 0; +} + +int +fs_get_mounts(struct FilesystemMount **mounts, size_t *count) +{ + struct FilesystemMount *list = NULL; + struct mntent *me; + FILE *fp; + size_t n = 0; + + *mounts = NULL; + *count = 0; + fp = setmntent(ARUU_LINUX_PATH_PROC_MOUNTS, "r"); + if (!fp) + return -1; + + while ((me = getmntent(fp)) != NULL) { + list = erealloc(list, (n + 1) * sizeof(*list)); + list[n].source = estrdup(me->mnt_fsname); + list[n].type = estrdup(me->mnt_type); + list[n].path = estrdup(me->mnt_dir); + n++; + } + endmntent(fp); + + *mounts = list; + *count = n; + return 0; +} + +void +fs_free_mounts(struct FilesystemMount *mounts, size_t count) +{ + size_t i; + + for (i = 0; i < count; i++) { + free(mounts[i].source); + free(mounts[i].type); + free(mounts[i].path); + } + free(mounts); +} +#endif diff --git a/shared/libutil/filesystem_other.c b/shared/libutil/filesystem_other.c @@ -0,0 +1,31 @@ +#include "../filesystem.h" + +#include <errno.h> +#include <string.h> + +#if !defined(__linux__) || defined(ARUU_FORCE_OTHER) +int +fs_get_status(const char *path, struct FilesystemStatus *status) +{ + (void)path; + memset(status, 0, sizeof(*status)); + errno = ENOTSUP; + return -1; +} + +int +fs_get_mounts(struct FilesystemMount **mounts, size_t *count) +{ + *mounts = NULL; + *count = 0; + errno = ENOTSUP; + return -1; +} + +void +fs_free_mounts(struct FilesystemMount *mounts, size_t count) +{ + (void)mounts; + (void)count; +} +#endif diff --git a/shared/libutil/mode.c b/shared/libutil/mode.c @@ -1,4 +1,9 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_FILE_MODE_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include <stdlib.h> #include <string.h> #include <sys/stat.h> diff --git a/shared/libutil/net.c b/shared/libutil/net.c @@ -1,395 +1,21 @@ -#include "../paths.h" +#include "../net.h" #include "../util.h" #include <arpa/inet.h> -#include <ctype.h> -#include <errno.h> -#include <ifaddrs.h> -#include <net/if.h> -#include <net/route.h> #include <stdio.h> #include <stdlib.h> -#include <string.h> -#include <sys/ioctl.h> -#include <sys/socket.h> -#include <unistd.h> - -#ifdef __linux__ -#include <netpacket/packet.h> -#else -#include <net/if_dl.h> -#include <sys/sysctl.h> -#endif - -static void -get_mtu_metric(const char *name, int *mtu, int *metric) -{ - struct ifreq ifr; - int sock; - - *mtu = 0; - *metric = 0; - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0) - *mtu = ifr.ifr_mtu; - if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0) - *metric = ifr.ifr_metric; - close(sock); -} - -int -net_get_interfaces(struct NetInterface **ifaces, int *count) -{ - struct ifaddrs *ifaddr, *ifa; - struct NetInterface *list = NULL; - struct NetInterface *iface; - int found_count = 0; - int i; - - if (getifaddrs(&ifaddr) < 0) - return -1; - - for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { - iface = NULL; - for (i = 0; i < found_count; i++) { - if (strcmp(list[i].name, ifa->ifa_name) == 0) { - iface = &list[i]; - break; - } - } - if (!iface) { - list = reallocarray(list, found_count + 1, sizeof(*list)); - if (!list) { - freeifaddrs(ifaddr); - return -1; - } - iface = &list[found_count]; - memset(iface, 0, sizeof(*iface)); - strlcpy(iface->name, ifa->ifa_name, sizeof(iface->name)); - iface->flags = ifa->ifa_flags; - get_mtu_metric(iface->name, &iface->mtu, &iface->metric); - found_count++; - } - - if (!ifa->ifa_addr) - continue; - - if (ifa->ifa_addr->sa_family == AF_INET) { - memcpy(&iface->ipv4_addr, ifa->ifa_addr, sizeof(struct sockaddr_in)); - iface->has_ipv4 = 1; - if (ifa->ifa_netmask) - memcpy(&iface->ipv4_mask, ifa->ifa_netmask, sizeof(struct sockaddr_in)); - if (ifa->ifa_dstaddr) - memcpy(&iface->ipv4_brd, ifa->ifa_dstaddr, sizeof(struct sockaddr_in)); - } else if (ifa->ifa_addr->sa_family == AF_INET6) { - memcpy(&iface->ipv6_addr, ifa->ifa_addr, sizeof(struct sockaddr_in6)); - iface->has_ipv6 = 1; - /* scope id could be set here from sin6_scope_id */ - } -#ifdef __linux__ - else if (ifa->ifa_addr->sa_family == AF_PACKET) { - struct sockaddr_ll *sll = (struct sockaddr_ll *)ifa->ifa_addr; - if (sll->sll_halen == 6) { - memcpy(iface->mac, sll->sll_addr, 6); - iface->has_mac = 1; - } - } -#else - else if (ifa->ifa_addr->sa_family == AF_LINK) { - struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr; - if (sdl->sdl_alen == 6) { - memcpy(iface->mac, LLADDR(sdl), 6); - iface->has_mac = 1; - } - } -#endif - } - - freeifaddrs(ifaddr); - *ifaces = list; - *count = found_count; - return 0; -} - -#ifdef __linux__ -int -net_get_stats(const char *ifname, struct NetStats *stats) -{ - FILE *fp; - char line[256]; - char *p, *name; - int found = 0; - - memset(stats, 0, sizeof(*stats)); - fp = fopen(ARUU_LINUX_PATH_PROC "/net/dev", "r"); - if (!fp) - return -1; - - while (fgets(line, sizeof(line), fp)) { - p = strchr(line, ':'); - if (p) { - *p = '\0'; - name = line; - while (isspace(*name)) - name++; - if (strcmp(name, ifname) == 0) { - if (sscanf( - p + 1, - "%llu %llu %llu %llu %*u %*u %*u " - "%*u %llu %llu %llu %llu", - &stats->rx_bytes, - &stats->rx_packets, - &stats->rx_errs, - &stats->rx_drop, - &stats->tx_bytes, - &stats->tx_packets, - &stats->tx_errs, - &stats->tx_drop - ) - == 8) { - found = 1; - } - break; - } - } - } - fclose(fp); - return found ? 0 : -1; -} -#else -int -net_get_stats(const char *ifname, struct NetStats *stats) -{ - struct ifaddrs *ifaddr, *ifa; - int found = 0; - - memset(stats, 0, sizeof(*stats)); - if (getifaddrs(&ifaddr) < 0) - return -1; - - for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { - if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_LINK - && strcmp(ifa->ifa_name, ifname) == 0) { - struct if_data *ifd = (struct if_data *)ifa->ifa_data; - if (ifd) { - stats->rx_bytes = ifd->ifi_ibytes; - stats->rx_packets = ifd->ifi_ipackets; - stats->rx_errs = ifd->ifi_ierrors; - stats->rx_drop = ifd->ifi_iqdrops; - stats->tx_bytes = ifd->ifi_obytes; - stats->tx_packets = ifd->ifi_opackets; - stats->tx_errs = ifd->ifi_oerrors; - stats->tx_drop = 0; - found = 1; - break; - } - } - } - freeifaddrs(ifaddr); - return found ? 0 : -1; -} -#endif - -#ifdef __linux__ -int -net_set_txqueuelen(const char *name, int qlen) -{ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_qlen = qlen; - if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; -} -#else -int -net_set_txqueuelen(const char *name, int qlen) -{ - (void)name; - (void)qlen; - return -1; -} -#endif - -int -net_set_flags(const char *name, unsigned int flags, int set) -{ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { - close(sock); - return -1; - } - if (set) - ifr.ifr_flags |= flags; - else - ifr.ifr_flags &= ~flags; - if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; -} - -int -net_set_mtu(const char *name, int mtu) -{ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_mtu = mtu; - if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; -} - -int -net_set_mac(const char *name, const unsigned char *mac) -{ -#ifdef __linux__ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - ifr.ifr_hwaddr.sa_family = 1; - memcpy(ifr.ifr_hwaddr.sa_data, mac, 6); - if (ioctl(sock, SIOCSIFHWADDR, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; -#else - (void)name; - (void)mac; - return -1; -#endif -} - -int -net_add_addr(const char *name, const char *addr, int prefix) -{ - struct ifreq ifr; - struct sockaddr_in *sin; - int sock; - unsigned int mask; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - - sin = (struct sockaddr_in *)&ifr.ifr_addr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - - if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) { - close(sock); - return -1; - } - - if (prefix >= 0) { - mask = 0; - if (prefix > 0) - mask = htonl(~0U << (32 - prefix)); - sin = (struct sockaddr_in *)&ifr.ifr_netmask; - sin->sin_family = AF_INET; - sin->sin_addr.s_addr = mask; - if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) { - close(sock); - return -1; - } - } - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) { - ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - ioctl(sock, SIOCSIFFLAGS, &ifr); - } - - close(sock); - return 0; -} - -int -net_del_addr(const char *name, const char *addr, int prefix) -{ - struct ifreq ifr; - struct sockaddr_in *sin; - int sock; - - (void)prefix; - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - - sin = (struct sockaddr_in *)&ifr.ifr_addr; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - - if (ioctl(sock, SIOCDIFADDR, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); - return 0; -} int net_show_routes(void) { -#ifdef __linux__ - FILE *fp; - char line[256]; - char iface[16], dest[16], gateway[16], mask[16]; - unsigned int d, g, m, flags, metric; + struct NetRoute *routes = NULL; + char dest[NET_ROUTE_ADDRSTRLEN]; + char gateway[NET_ROUTE_ADDRSTRLEN]; + char mask[NET_ROUTE_ADDRSTRLEN]; + int count = 0; + int i; - fp = fopen(ARUU_LINUX_PATH_PROC "/net/route", "r"); - if (!fp) + if (net_get_routes(&routes, &count) < 0) return -1; printf( @@ -401,190 +27,20 @@ net_show_routes(void) "Flags", "Metric" ); - if (fgets(line, sizeof(line), fp)) { - while (fgets(line, sizeof(line), fp)) { - if (sscanf(line, "%15s %x %x %x %*u %*u %u %x", iface, &d, &g, &m, &metric, &flags) == 6) { - struct in_addr dest_addr, gw_addr, mask_addr; - dest_addr.s_addr = d; - gw_addr.s_addr = g; - mask_addr.s_addr = m; - strlcpy(dest, inet_ntoa(dest_addr), sizeof(dest)); - strlcpy(gateway, inet_ntoa(gw_addr), sizeof(gateway)); - strlcpy(mask, inet_ntoa(mask_addr), sizeof(mask)); - printf("%-10s %-15s %-15s %-15s 0x%04X %-6u\n", iface, dest, gateway, mask, flags, metric); - } - } - } - fclose(fp); - return 0; -#else - printf("route listing not implemented on this OS\n"); - return 0; -#endif -} - -int -net_add_route(const char *dst, const char *gateway, const char *mask, const char *dev, int metric) -{ - struct rtentry rt; - struct sockaddr_in *sin; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&rt, 0, sizeof(rt)); - - sin = (struct sockaddr_in *)&rt.rt_dst; - sin->sin_family = AF_INET; - if (strcmp(dst, "default") == 0) { - sin->sin_addr.s_addr = INADDR_ANY; - } else { - if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - if (gateway) { - sin = (struct sockaddr_in *)&rt.rt_gateway; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - rt.rt_flags |= RTF_GATEWAY; - } - - if (mask) { - sin = (struct sockaddr_in *)&rt.rt_genmask; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - rt.rt_flags |= RTF_UP; - if (dev) - rt.rt_dev = (char *)dev; - if (metric >= 0) - rt.rt_metric = metric + 1; - - if (ioctl(sock, SIOCADDRT, &rt) < 0) { - close(sock); - return -1; - } - - close(sock); - return 0; -} - -int -net_del_route(const char *dst, const char *gateway, const char *mask, const char *dev, int metric) -{ - struct rtentry rt; - struct sockaddr_in *sin; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - - memset(&rt, 0, sizeof(rt)); - - sin = (struct sockaddr_in *)&rt.rt_dst; - sin->sin_family = AF_INET; - if (strcmp(dst, "default") == 0) { - sin->sin_addr.s_addr = INADDR_ANY; - } else { - if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - if (gateway) { - sin = (struct sockaddr_in *)&rt.rt_gateway; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - rt.rt_flags |= RTF_GATEWAY; - } - - if (mask) { - sin = (struct sockaddr_in *)&rt.rt_genmask; - sin->sin_family = AF_INET; - if (inet_pton(AF_INET, mask, &sin->sin_addr) <= 0) { - close(sock); - return -1; - } - } - - rt.rt_flags |= RTF_UP; - if (dev) - rt.rt_dev = (char *)dev; - if (metric >= 0) - rt.rt_metric = metric + 1; - - if (ioctl(sock, SIOCDELRT, &rt) < 0) { - close(sock); - return -1; - } - - close(sock); - return 0; -} - -int -net_flush_addrs(const char *dev) -{ - struct NetInterface *ifaces = NULL; - int count = 0, i, r = 0; - - if (net_get_interfaces(&ifaces, &count) < 0) - return -1; - for (i = 0; i < count; i++) { - if (strcmp(ifaces[i].name, dev) == 0) { - if (ifaces[i].has_ipv4) { - char addr_str[16]; - struct sockaddr_in *sin = &ifaces[i].ipv4_addr; - inet_ntop(AF_INET, &sin->sin_addr, addr_str, sizeof(addr_str)); - if (net_del_addr(dev, addr_str, -1) < 0) - r = -1; - } - } - } - free(ifaces); - return r; -} - -int -net_set_name(const char *name, const char *newname) -{ -#ifdef __linux__ - struct ifreq ifr; - int sock; - - sock = socket(AF_INET, SOCK_DGRAM, 0); - if (sock < 0) - return -1; - memset(&ifr, 0, sizeof(ifr)); - strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); - strlcpy(ifr.ifr_newname, newname, sizeof(ifr.ifr_newname)); - if (ioctl(sock, SIOCSIFNAME, &ifr) < 0) { - close(sock); - return -1; - } - close(sock); + strlcpy(dest, inet_ntoa(routes[i].destination), sizeof(dest)); + strlcpy(gateway, inet_ntoa(routes[i].gateway), sizeof(gateway)); + strlcpy(mask, inet_ntoa(routes[i].mask), sizeof(mask)); + printf( + "%-10s %-15s %-15s %-15s 0x%04X %-6u\n", + routes[i].interface, + dest, + gateway, + mask, + routes[i].flags, + routes[i].metric + ); + } + free(routes); return 0; -#else - (void)name; - (void)newname; - return -1; -#endif } diff --git a/shared/libutil/net_linux.c b/shared/libutil/net_linux.c @@ -0,0 +1,663 @@ +#if defined(__linux__) +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#include "../net.h" +#include "../paths.h" +#include "../util.h" + +#include <arpa/inet.h> +#include <ctype.h> +#include <errno.h> +#include <ifaddrs.h> +#include <net/if.h> +#include <net/route.h> +#include <netpacket/packet.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/ioctl.h> +#include <sys/socket.h> +#include <unistd.h> + +static unsigned int +interface_flags_to_linux(unsigned int flags) +{ + unsigned int linux_flags = 0; + + if (flags & NET_IF_UP) + linux_flags |= IFF_UP; + if (flags & NET_IF_BROADCAST) + linux_flags |= IFF_BROADCAST; + if (flags & NET_IF_DEBUG) + linux_flags |= IFF_DEBUG; + if (flags & NET_IF_LOOPBACK) + linux_flags |= IFF_LOOPBACK; + if (flags & NET_IF_POINTOPOINT) + linux_flags |= IFF_POINTOPOINT; + if (flags & NET_IF_RUNNING) + linux_flags |= IFF_RUNNING; + if (flags & NET_IF_NOARP) + linux_flags |= IFF_NOARP; + if (flags & NET_IF_PROMISC) + linux_flags |= IFF_PROMISC; + if (flags & NET_IF_ALLMULTI) + linux_flags |= IFF_ALLMULTI; + if (flags & NET_IF_MULTICAST) + linux_flags |= IFF_MULTICAST; + return linux_flags; +} + +static unsigned int +interface_flags_from_linux(unsigned int linux_flags) +{ + unsigned int flags = 0; + + if (linux_flags & IFF_UP) + flags |= NET_IF_UP; + if (linux_flags & IFF_BROADCAST) + flags |= NET_IF_BROADCAST; + if (linux_flags & IFF_DEBUG) + flags |= NET_IF_DEBUG; + if (linux_flags & IFF_LOOPBACK) + flags |= NET_IF_LOOPBACK; + if (linux_flags & IFF_POINTOPOINT) + flags |= NET_IF_POINTOPOINT; + if (linux_flags & IFF_RUNNING) + flags |= NET_IF_RUNNING; + if (linux_flags & IFF_NOARP) + flags |= NET_IF_NOARP; + if (linux_flags & IFF_PROMISC) + flags |= NET_IF_PROMISC; + if (linux_flags & IFF_ALLMULTI) + flags |= NET_IF_ALLMULTI; + if (linux_flags & IFF_MULTICAST) + flags |= NET_IF_MULTICAST; + return flags; +} + +static void +get_mtu_metric(const char *name, int *mtu, int *metric) +{ + struct ifreq ifr; + int sock; + + *mtu = 0; + *metric = 0; + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFMTU, &ifr) >= 0) + *mtu = ifr.ifr_mtu; + if (ioctl(sock, SIOCGIFMETRIC, &ifr) >= 0) + *metric = ifr.ifr_metric; + close(sock); +} + +int +net_get_interfaces(struct NetInterface **ifaces, int *count) +{ + struct ifaddrs *ifaddr, *ifa; + struct sockaddr_ll *sll; + struct NetInterface *list = NULL; + struct NetInterface *iface; + int found_count = 0; + int i; + + if (getifaddrs(&ifaddr) < 0) + return -1; + + for (ifa = ifaddr; ifa; ifa = ifa->ifa_next) { + iface = NULL; + for (i = 0; i < found_count; i++) { + if (strcmp(list[i].name, ifa->ifa_name) == 0) { + iface = &list[i]; + break; + } + } + if (!iface) { + list = reallocarray(list, found_count + 1, sizeof(*list)); + if (!list) { + freeifaddrs(ifaddr); + return -1; + } + iface = &list[found_count]; + memset(iface, 0, sizeof(*iface)); + strlcpy(iface->name, ifa->ifa_name, sizeof(iface->name)); + iface->flags = interface_flags_from_linux(ifa->ifa_flags); + get_mtu_metric(iface->name, &iface->mtu, &iface->metric); + found_count++; + } + + if (!ifa->ifa_addr) + continue; + + if (ifa->ifa_addr->sa_family == AF_INET) { + memcpy(&iface->ipv4_addr, ifa->ifa_addr, sizeof(struct sockaddr_in)); + iface->has_ipv4 = 1; + if (ifa->ifa_netmask) + memcpy(&iface->ipv4_mask, ifa->ifa_netmask, sizeof(struct sockaddr_in)); + if (ifa->ifa_dstaddr) + memcpy(&iface->ipv4_brd, ifa->ifa_dstaddr, sizeof(struct sockaddr_in)); + } else if (ifa->ifa_addr->sa_family == AF_INET6) { + memcpy(&iface->ipv6_addr, ifa->ifa_addr, sizeof(struct sockaddr_in6)); + iface->has_ipv6 = 1; + } else if (ifa->ifa_addr->sa_family == AF_PACKET) { + sll = (struct sockaddr_ll *)ifa->ifa_addr; + if (sll->sll_halen == 6) { + memcpy(iface->mac, sll->sll_addr, 6); + iface->has_mac = 1; + } + } + } + + freeifaddrs(ifaddr); + *ifaces = list; + *count = found_count; + return 0; +} + +int +net_get_stats(const char *ifname, struct NetStats *stats) +{ + FILE *fp; + char line[256]; + char *p, *name; + int found = 0; + + memset(stats, 0, sizeof(*stats)); + fp = fopen(ARUU_LINUX_PATH_PROC "/net/dev", "r"); + if (!fp) + return -1; + + while (fgets(line, sizeof(line), fp)) { + p = strchr(line, ':'); + if (p) { + *p = '\0'; + name = line; + while (isspace(*name)) + name++; + if (strcmp(name, ifname) == 0) { + if (sscanf( + p + 1, + "%llu %llu %llu %llu %*u %*u %*u " + "%*u %llu %llu %llu %llu", + &stats->rx_bytes, + &stats->rx_packets, + &stats->rx_errs, + &stats->rx_drop, + &stats->tx_bytes, + &stats->tx_packets, + &stats->tx_errs, + &stats->tx_drop + ) + == 8) { + found = 1; + } + break; + } + } + } + fclose(fp); + return found ? 0 : -1; +} + +int +net_set_txqueuelen(const char *name, int qlen) +{ + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_qlen = qlen; + if (ioctl(sock, SIOCSIFTXQLEN, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_set_flags(const char *name, unsigned int flags, int set) +{ + struct ifreq ifr; + unsigned int linux_flags; + int sock; + + linux_flags = interface_flags_to_linux(flags); + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + if (set) + ifr.ifr_flags |= linux_flags; + else + ifr.ifr_flags &= ~linux_flags; + if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_set_mtu(const char *name, int mtu) +{ + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_mtu = mtu; + if (ioctl(sock, SIOCSIFMTU, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_set_metric(const char *name, int metric) +{ + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_metric = metric; + if (ioctl(sock, SIOCSIFMETRIC, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_set_mac(const char *name, const unsigned char *mac) +{ + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + ifr.ifr_hwaddr.sa_family = 1; + memcpy(ifr.ifr_hwaddr.sa_data, mac, 6); + if (ioctl(sock, SIOCSIFHWADDR, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +enum InterfaceAddress { + INTERFACE_ADDRESS_MASK, + INTERFACE_ADDRESS_BROADCAST, + INTERFACE_ADDRESS_DESTINATION, +}; + +static struct sockaddr_in * +interface_address(struct ifreq *ifr, enum InterfaceAddress type) +{ + switch (type) { + case INTERFACE_ADDRESS_MASK: + return (struct sockaddr_in *)&ifr->ifr_netmask; + case INTERFACE_ADDRESS_BROADCAST: + return (struct sockaddr_in *)&ifr->ifr_broadaddr; + case INTERFACE_ADDRESS_DESTINATION: + return (struct sockaddr_in *)&ifr->ifr_dstaddr; + } + return NULL; +} + +static int +set_interface_address( + const char *name, + const char *addr, + enum InterfaceAddress type, + unsigned long request, + unsigned int flags +) +{ + struct ifreq ifr; + struct sockaddr_in *sin; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + sin = interface_address(&ifr, type); + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + if (ioctl(sock, request, &ifr) < 0) { + close(sock); + return -1; + } + if (flags) { + if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + ifr.ifr_flags |= interface_flags_to_linux(flags); + if (ioctl(sock, SIOCSIFFLAGS, &ifr) < 0) { + close(sock); + return -1; + } + } + close(sock); + return 0; +} + +int +net_set_mask(const char *name, const char *mask) +{ + return set_interface_address(name, mask, INTERFACE_ADDRESS_MASK, SIOCSIFNETMASK, 0); +} + +int +net_set_broadcast(const char *name, const char *broadcast) +{ + return set_interface_address( + name, broadcast, INTERFACE_ADDRESS_BROADCAST, SIOCSIFBRDADDR, NET_IF_BROADCAST + ); +} + +int +net_set_dstaddr(const char *name, const char *dstaddr) +{ + return set_interface_address( + name, dstaddr, INTERFACE_ADDRESS_DESTINATION, SIOCSIFDSTADDR, NET_IF_POINTOPOINT + ); +} + +int +net_add_addr(const char *name, const char *addr, int prefix) +{ + struct ifreq ifr; + struct sockaddr_in *sin; + int sock; + unsigned int mask; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + + sin = (struct sockaddr_in *)&ifr.ifr_addr; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + + if (ioctl(sock, SIOCSIFADDR, &ifr) < 0) { + close(sock); + return -1; + } + + if (prefix >= 0) { + mask = 0; + if (prefix > 0) + mask = htonl(~0U << (32 - prefix)); + sin = (struct sockaddr_in *)&ifr.ifr_netmask; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = mask; + if (ioctl(sock, SIOCSIFNETMASK, &ifr) < 0) { + close(sock); + return -1; + } + } + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + if (ioctl(sock, SIOCGIFFLAGS, &ifr) >= 0) { + ifr.ifr_flags |= IFF_UP | IFF_RUNNING; + ioctl(sock, SIOCSIFFLAGS, &ifr); + } + + close(sock); + return 0; +} + +int +net_del_addr(const char *name, const char *addr, int prefix) +{ + struct ifreq ifr; + struct sockaddr_in *sin; + int sock; + + (void)prefix; + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + + sin = (struct sockaddr_in *)&ifr.ifr_addr; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, addr, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + + if (ioctl(sock, SIOCDIFADDR, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_get_routes(struct NetRoute **routes, int *count) +{ + FILE *fp; + char line[256]; + char iface[NET_IFNAME_MAX]; + unsigned int d, g, flags, metric, m; + struct in_addr dest_addr, gw_addr, mask_addr; + struct NetRoute *list = NULL; + struct NetRoute *route; + int found_count = 0; + + *routes = NULL; + *count = 0; + fp = fopen(ARUU_LINUX_PATH_PROC "/net/route", "r"); + if (!fp) + return -1; + + if (fgets(line, sizeof(line), fp)) { + while (fgets(line, sizeof(line), fp)) { + if (sscanf(line, "%15s %x %x %x %*u %*u %u %x", iface, &d, &g, &flags, &metric, &m) != 6) + continue; + route = reallocarray(list, found_count + 1, sizeof(*route)); + if (!route) { + free(list); + fclose(fp); + return -1; + } + list = route; + route = &list[found_count]; + dest_addr.s_addr = d; + gw_addr.s_addr = g; + mask_addr.s_addr = m; + strlcpy(route->interface, iface, sizeof(route->interface)); + route->destination.s_addr = dest_addr.s_addr; + route->gateway.s_addr = gw_addr.s_addr; + route->mask.s_addr = mask_addr.s_addr; + route->flags = flags; + route->metric = metric; + found_count++; + } + } + fclose(fp); + *routes = list; + *count = found_count; + return 0; +} + +static int +route_prefix_to_mask(int prefix, struct in_addr *mask) +{ + if (prefix > 32) { + errno = EINVAL; + return -1; + } + if (prefix < 0) + prefix = 32; + mask->s_addr = 0; + if (prefix > 0) + mask->s_addr = htonl(~0U << (32 - prefix)); + return 0; +} + +static int +change_route( + const char *dst, + const char *gateway, + const char *dev, + int prefix, + int metric, + unsigned long request +) +{ + struct rtentry rt; + struct sockaddr_in *sin; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&rt, 0, sizeof(rt)); + + sin = (struct sockaddr_in *)&rt.rt_dst; + sin->sin_family = AF_INET; + if (strcmp(dst, "default") == 0) { + sin->sin_addr.s_addr = INADDR_ANY; + } else { + if (inet_pton(AF_INET, dst, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + } + + if (gateway) { + sin = (struct sockaddr_in *)&rt.rt_gateway; + sin->sin_family = AF_INET; + if (inet_pton(AF_INET, gateway, &sin->sin_addr) <= 0) { + close(sock); + return -1; + } + rt.rt_flags |= RTF_GATEWAY; + } + + sin = (struct sockaddr_in *)&rt.rt_genmask; + sin->sin_family = AF_INET; + if (route_prefix_to_mask(prefix, &sin->sin_addr) < 0) { + close(sock); + return -1; + } + + rt.rt_flags |= RTF_UP; + if (dev) + rt.rt_dev = (char *)dev; + if (metric >= 0) + rt.rt_metric = metric + 1; + + if (ioctl(sock, request, &rt) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} + +int +net_add_route(const char *dst, const char *gateway, const char *dev, int prefix, int metric) +{ + return change_route(dst, gateway, dev, prefix, metric, SIOCADDRT); +} + +int +net_del_route(const char *dst, const char *gateway, const char *dev, int prefix, int metric) +{ + return change_route(dst, gateway, dev, prefix, metric, SIOCDELRT); +} + +int +net_flush_addrs(const char *dev) +{ + struct NetInterface *ifaces = NULL; + struct sockaddr_in *sin; + char addr_str[16]; + int count = 0, i, r = 0; + + if (net_get_interfaces(&ifaces, &count) < 0) + return -1; + + for (i = 0; i < count; i++) { + if (strcmp(ifaces[i].name, dev) == 0) { + if (ifaces[i].has_ipv4) { + sin = &ifaces[i].ipv4_addr; + inet_ntop(AF_INET, &sin->sin_addr, addr_str, sizeof(addr_str)); + if (net_del_addr(dev, addr_str, -1) < 0) + r = -1; + } + } + } + free(ifaces); + return r; +} + +int +net_set_name(const char *name, const char *newname) +{ + struct ifreq ifr; + int sock; + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) + return -1; + memset(&ifr, 0, sizeof(ifr)); + strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name)); + strlcpy(ifr.ifr_newname, newname, sizeof(ifr.ifr_newname)); + if (ioctl(sock, SIOCSIFNAME, &ifr) < 0) { + close(sock); + return -1; + } + close(sock); + return 0; +} +#endif diff --git a/shared/libutil/net_other.c b/shared/libutil/net_other.c @@ -0,0 +1,174 @@ +#include "../net.h" + +#include <errno.h> +#include <stddef.h> + +#if !defined(__linux__) || defined(ARUU_FORCE_OTHER) +int +net_get_interfaces(struct NetInterface **ifaces, int *count) +{ + *ifaces = NULL; + *count = 0; + errno = ENOTSUP; + return -1; +} + +int +net_get_routes(struct NetRoute **routes, int *count) +{ + *routes = NULL; + *count = 0; + errno = ENOTSUP; + return -1; +} + +int +net_show_routes(void) +{ + errno = ENOTSUP; + return -1; +} + +int +net_get_stats(const char *ifname, struct NetStats *stats) +{ + (void)ifname; + (void)stats; + errno = ENOTSUP; + return -1; +} + +int +net_set_flags(const char *name, unsigned int flags, int set) +{ + (void)name; + (void)flags; + (void)set; + errno = ENOTSUP; + return -1; +} + +int +net_set_mtu(const char *name, int mtu) +{ + (void)name; + (void)mtu; + errno = ENOTSUP; + return -1; +} + +int +net_set_metric(const char *name, int metric) +{ + (void)name; + (void)metric; + errno = ENOTSUP; + return -1; +} + +int +net_set_mac(const char *name, const unsigned char *mac) +{ + (void)name; + (void)mac; + errno = ENOTSUP; + return -1; +} + +int +net_set_mask(const char *name, const char *mask) +{ + (void)name; + (void)mask; + errno = ENOTSUP; + return -1; +} + +int +net_set_broadcast(const char *name, const char *broadcast) +{ + (void)name; + (void)broadcast; + errno = ENOTSUP; + return -1; +} + +int +net_set_dstaddr(const char *name, const char *dstaddr) +{ + (void)name; + (void)dstaddr; + errno = ENOTSUP; + return -1; +} + +int +net_add_addr(const char *name, const char *addr, int prefix) +{ + (void)name; + (void)addr; + (void)prefix; + errno = ENOTSUP; + return -1; +} + +int +net_del_addr(const char *name, const char *addr, int prefix) +{ + (void)name; + (void)addr; + (void)prefix; + errno = ENOTSUP; + return -1; +} + +int +net_add_route(const char *dst, const char *gateway, const char *dev, int prefix, int metric) +{ + (void)dst; + (void)gateway; + (void)dev; + (void)prefix; + (void)metric; + errno = ENOTSUP; + return -1; +} + +int +net_del_route(const char *dst, const char *gateway, const char *dev, int prefix, int metric) +{ + (void)dst; + (void)gateway; + (void)dev; + (void)prefix; + (void)metric; + errno = ENOTSUP; + return -1; +} + +int +net_flush_addrs(const char *dev) +{ + (void)dev; + errno = ENOTSUP; + return -1; +} + +int +net_set_txqueuelen(const char *name, int qlen) +{ + (void)name; + (void)qlen; + errno = ENOTSUP; + return -1; +} + +int +net_set_name(const char *name, const char *newname) +{ + (void)name; + (void)newname; + errno = ENOTSUP; + return -1; +} +#endif diff --git a/shared/libutil/passwd.c b/shared/libutil/passwd.c @@ -1,4 +1,9 @@ /* see LICENSE file for copyright and license details */ +#if FEATURE_PASSWD_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif #include "../passwd.h" #include "../paths.h" #include "../text.h" @@ -78,11 +83,10 @@ pw_check(const struct passwd *pw, const char *pass) weprintf("denied\n"); return -1; } - /* same empty-hash fast path as above, re-checked here: stored was - * just reassigned from the shadow entry's own field, and an empty - * shadow hash means "passwordless account", not "match nothing" - * (falling through to crypt() with an empty salt does the latter, - * since crypt("", "") is never itself the empty string) */ + /* same empty-hash path as above, redone because stored was just + * reassigned from the shadow entry. an empty shadow hash means a + * passwordless account, while crypt() with an empty salt would match + * nothing */ if (stored[0] == '\0') { if (pass[0] == '\0') return 1; @@ -370,19 +374,37 @@ static int update_master_passwd(const char *name, const char *newhash) { int r; - pid_t pid; + pid_t pid, wr; int st; r = update_passwd_file(ARUU_BSD_PATH_MASTER_PASSWD, name, newhash); if (r != 0) return r; pid = fork(); + if (pid < 0) { + weprintf("fork:"); + return -1; + } if (pid == 0) { execl(ARUU_BSD_PATH_PWD_MKDB, "pwd_mkdb", "-p", NULL); + weprintf("exec %s:", ARUU_BSD_PATH_PWD_MKDB); _exit(127); } - if (pid > 0) - waitpid(pid, &st, 0); + do { + wr = waitpid(pid, &st, 0); + } while (wr < 0 && errno == EINTR); + if (wr < 0) { + weprintf("waitpid:"); + return -1; + } + if (!WIFEXITED(st)) { + weprintf("pwd_mkdb did not exit normally\n"); + return -1; + } + if (WEXITSTATUS(st) != 0) { + weprintf("pwd_mkdb exited with status %d\n", WEXITSTATUS(st)); + return -1; + } return 0; } #endif diff --git a/shared/libutil/sysinfo.c b/shared/libutil/sysinfo.c @@ -1,147 +1,16 @@ -#include "../util.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <time.h> -#include <unistd.h> - -#ifdef __linux__ -#include <sys/sysinfo.h> -#else -#include <sys/sysctl.h> -#include <sys/time.h> -#endif - -int -get_uptime(long *uptime_secs) -{ -#ifdef __linux__ - struct sysinfo info; - - if (sysinfo(&info) < 0) - return -1; - *uptime_secs = info.uptime; - return 0; -#else - struct timeval boottime; - size_t len = sizeof(boottime); - int mib[2] = {CTL_KERN, KERN_BOOTTIME}; - time_t now; - - if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0) - return -1; - time(&now); - *uptime_secs = (long)(now - boottime.tv_sec); - return 0; +#if FEATURE_SYSINFO_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE #endif -} - -int -get_loads(double loads[3]) -{ - if (getloadavg(loads, 3) != 3) - return -1; - return 0; -} - -int -get_meminfo(struct MemInfo *mi) -{ - memset(mi, 0, sizeof(*mi)); -#ifdef __linux__ - struct sysinfo info; - unsigned long long unit; - - if (sysinfo(&info) < 0) - return -1; - unit = info.mem_unit ? info.mem_unit : 1; - mi->total = info.totalram * unit; - mi->free = info.freeram * unit; - mi->shared = info.sharedram * unit; - mi->buffers = info.bufferram * unit; - mi->cached = 0; - mi->totalswap = info.totalswap * unit; - mi->freeswap = info.freeswap * unit; - return 0; -#else - int mib[2]; - size_t len; - unsigned long physmem = 0; - unsigned int page_size = 4096; - unsigned int free_pages = 0; - - mib[0] = CTL_HW; - mib[1] = HW_PHYSMEM; - len = sizeof(physmem); - if (sysctl(mib, 2, &physmem, &len, NULL, 0) < 0) - return -1; - mi->total = physmem; - - mib[0] = CTL_HW; - mib[1] = HW_PAGESIZE; - len = sizeof(page_size); - sysctl(mib, 2, &page_size, &len, NULL, 0); - - len = sizeof(free_pages); - if (sysctlbyname("vm.stats.vm.v_free_count", &free_pages, &len, NULL, 0) >= 0) { - mi->free = (unsigned long long)free_pages * page_size; - } else { - mi->free = mi->total / 4; - } - return 0; #endif -} - -#ifdef __linux__ -#include <sys/klog.h> -ssize_t -get_dmesg(char *buf, size_t len) -{ - if (!buf && len == 0) - return klogctl(10, NULL, 0); - return klogctl(3, buf, len); -} +#include "../sysinfo.h" -int -clear_dmesg(void) -{ - if (klogctl(5, NULL, 0) < 0) - return -1; - return 0; -} +#include <stdlib.h> int -set_console_level(int level) +get_loads(double *loads) { - if (klogctl(8, NULL, level) < 0) + if (getloadavg(loads, 3) != 3) return -1; return 0; } -#else -ssize_t -get_dmesg(char *buf, size_t len) -{ - int mib[2]; - size_t needed = len; - - mib[0] = CTL_KERN; - mib[1] = KERN_MSGBUF; - if (sysctl(mib, 2, buf, &needed, NULL, 0) < 0) - return -1; - return (ssize_t)needed; -} - -int -clear_dmesg(void) -{ - return -1; -} - -int -set_console_level(int level) -{ - (void)level; - return -1; -} -#endif diff --git a/shared/libutil/sysinfo_linux.c b/shared/libutil/sysinfo_linux.c @@ -0,0 +1,67 @@ +#if FEATURE_SYSINFO_EXT +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#endif +#if defined(__linux__) +#include "../sysinfo.h" + +#include <string.h> +#include <sys/klog.h> +#include <sys/sysinfo.h> + +int +get_uptime(long *uptime_secs) +{ + struct sysinfo info; + + if (sysinfo(&info) < 0) + return -1; + *uptime_secs = info.uptime; + return 0; +} + +int +get_meminfo(struct MemInfo *mi) +{ + struct sysinfo info; + unsigned long long unit; + + memset(mi, 0, sizeof(*mi)); + if (sysinfo(&info) < 0) + return -1; + unit = info.mem_unit ? info.mem_unit : 1; + mi->total = info.totalram * unit; + mi->free = info.freeram * unit; + mi->shared = info.sharedram * unit; + mi->buffers = info.bufferram * unit; + mi->cached = 0; + mi->totalswap = info.totalswap * unit; + mi->freeswap = info.freeswap * unit; + return 0; +} + +ssize_t +get_dmesg(char *buf, size_t len) +{ + if (!buf && len == 0) + return klogctl(10, NULL, 0); + return klogctl(3, buf, len); +} + +int +clear_dmesg(void) +{ + if (klogctl(5, NULL, 0) < 0) + return -1; + return 0; +} + +int +set_console_level(int level) +{ + if (klogctl(8, NULL, level) < 0) + return -1; + return 0; +} +#endif diff --git a/shared/libutil/sysinfo_other.c b/shared/libutil/sysinfo_other.c @@ -0,0 +1,46 @@ +#include "../sysinfo.h" + +#include <errno.h> +#include <string.h> + +#if !defined(__linux__) || defined(ARUU_FORCE_OTHER) +int +get_uptime(long *uptime_secs) +{ + (void)uptime_secs; + errno = ENOTSUP; + return -1; +} + +int +get_meminfo(struct MemInfo *mi) +{ + memset(mi, 0, sizeof(*mi)); + errno = ENOTSUP; + return -1; +} + +ssize_t +get_dmesg(char *buf, size_t len) +{ + (void)buf; + (void)len; + errno = ENOTSUP; + return -1; +} + +int +clear_dmesg(void) +{ + errno = ENOTSUP; + return -1; +} + +int +set_console_level(int level) +{ + (void)level; + errno = ENOTSUP; + return -1; +} +#endif diff --git a/shared/libutil/tls.c b/shared/libutil/tls.c @@ -27,11 +27,14 @@ struct x509_noverify_ctx { br_x509_minimal_context minimal; }; +struct TlsTrustStore; + struct TlsSocket { int fd; int is_tls; br_ssl_client_context sc; struct x509_noverify_ctx x509_noverify; + struct TlsTrustStore *tas; unsigned char iobuf[BR_SSL_BUFSIZE_BIDI]; br_sslio_context ioc; }; @@ -138,6 +141,21 @@ sock_write(void *ctx, const unsigned char *buf, size_t len) } } +struct TlsTrustStore { + br_x509_trust_anchor *v; + size_t num; + size_t cap; +}; + +struct PemDecoder { + unsigned char *data; + size_t len; + size_t cap; + unsigned int value; + size_t quantum; + size_t padding; +}; + static int b64_decode_char(char c) { @@ -151,26 +169,99 @@ b64_decode_char(char c) return 62; if (c == '/') return 63; + if (c == '=') + return -2; return -1; } -static size_t -b64_decode(const char *src, size_t src_len, unsigned char *dst) +static int +b64_decoder_flush(struct PemDecoder *dec) { - size_t i, j = 0; - int val = 0, valb = -8; - for (i = 0; i < src_len; i++) { - int c = b64_decode_char(src[i]); - if (c >= 0) { - val = (val << 6) | c; - valb += 6; - if (valb >= 0) { - dst[j++] = (val >> valb) & 0xFF; - valb -= 8; - } + size_t i, n; + + if (dec->quantum != 4) + return -1; + n = 3 - dec->padding; + for (i = 0; i < n; i++) { + if (dec->len == dec->cap) { + size_t cap = dec->cap ? dec->cap * 2 : 1024; + if (cap < dec->cap) + return -1; + dec->data = erealloc(dec->data, cap); + dec->cap = cap; } + dec->data[dec->len++] = (dec->value >> (16 - i * 8)) & 0xFF; + } + dec->value = 0; + dec->quantum = 0; + dec->padding = 0; + return 0; +} + +static int +b64_decoder_push(struct PemDecoder *dec, char c) +{ + int value = b64_decode_char(c); + + if (value == -2) { + if ((!dec->padding && dec->quantum < 2) || (dec->padding && dec->quantum != 3)) + return -1; + dec->value <<= 6; + dec->padding++; + dec->quantum++; + } else { + if (value < 0 || dec->padding) + return -1; + dec->value = (dec->value << 6) | (unsigned int)value; + dec->quantum++; + } + if (dec->quantum == 4) + return b64_decoder_flush(dec); + return 0; +} + +static int +b64_decoder_push_line(struct PemDecoder *dec, const char *line, size_t len) +{ + size_t i; + + for (i = 0; i < len; i++) { + if (b64_decoder_push(dec, line[i]) < 0) + return -1; + } + return 0; +} + +static int +b64_decoder_finish(const struct PemDecoder *dec) +{ + return dec->quantum == 0 ? 0 : -1; +} + +static void +trust_anchor_free(br_x509_trust_anchor *ta) +{ + free(ta->dn.data); + if (ta->pkey.key_type == BR_KEYTYPE_RSA) { + free(ta->pkey.key.rsa.n); + free(ta->pkey.key.rsa.e); + } else if (ta->pkey.key_type == BR_KEYTYPE_EC) { + free(ta->pkey.key.ec.q); } - return j; + memset(ta, 0, sizeof(*ta)); +} + +static void +trust_store_free(struct TlsTrustStore *tas) +{ + size_t i; + + if (!tas) + return; + for (i = 0; i < tas->num; i++) + trust_anchor_free(&tas->v[i]); + free(tas->v); + memset(tas, 0, sizeof(*tas)); } static int @@ -180,6 +271,7 @@ decode_cert_der(const unsigned char *der, size_t der_len, br_x509_trust_anchor * struct dn_accum accum = {NULL, 0, 0}; const br_x509_pkey *pk; + memset(ta, 0, sizeof(*ta)); br_x509_decoder_init(&dc, append_dn_callback, &accum); br_x509_decoder_push(&dc, der, der_len); if (br_x509_decoder_last_error(&dc) != 0) { @@ -210,76 +302,170 @@ decode_cert_der(const unsigned char *der, size_t der_len, br_x509_trust_anchor * ta->pkey.key.ec.q = emalloc(pk->key.ec.qlen); memcpy(ta->pkey.key.ec.q, pk->key.ec.q, pk->key.ec.qlen); } else { - free(accum.data); + trust_anchor_free(ta); return 0; } return 1; } -static br_x509_trust_anchor *tas = NULL; -static size_t tas_num = 0; +static int +trust_store_append(struct TlsTrustStore *tas, const br_x509_trust_anchor *ta) +{ + if (tas->num == tas->cap) { + size_t cap = tas->cap ? tas->cap * 2 : 8; + if (cap < tas->cap) + return -1; + tas->v = ereallocarray(tas->v, cap, sizeof(*tas->v)); + tas->cap = cap; + } + tas->v[tas->num++] = *ta; + return 0; +} + +static int +line_is(const char *line, size_t len, const char *text) +{ + return strlen(text) == len && memcmp(line, text, len) == 0; +} + +static int +load_ca_certs_file(const char *path, struct TlsTrustStore *tas) +{ + static const char begin[] = "-----BEGIN CERTIFICATE-----"; + static const char end[] = "-----END CERTIFICATE-----"; + FILE *fp; + char *line = NULL; + size_t line_cap = 0, line_len, line_no = 0, cert_num = 0; + ssize_t nread; + int in_cert = 0, failed = 0; + struct PemDecoder dec = {0}; + + fp = fopen(path, "r"); + if (!fp) + return 0; + while ((nread = getline(&line, &line_cap, fp)) >= 0) { + line_no++; + line_len = (size_t)nread; + while (line_len > 0 && (line[line_len - 1] == '\r' || line[line_len - 1] == '\n')) + line_len--; + if (in_cert && memchr(line, '\0', line_len) != NULL) { + weprintf("%s:%zu: invalid base64 in CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + if (line_is(line, line_len, begin)) { + if (in_cert) { + weprintf("%s:%zu: malformed PEM in CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + cert_num++; + in_cert = 1; + continue; + } + if (line_is(line, line_len, end)) { + br_x509_trust_anchor ta; + if (!in_cert) { + weprintf("%s:%zu: unexpected CA certificate end\n", path, line_no); + failed = 1; + break; + } + if (b64_decoder_finish(&dec) < 0 || dec.len == 0) { + weprintf("%s:%zu: invalid base64 in CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + if (!decode_cert_der(dec.data, dec.len, &ta)) { + weprintf("%s:%zu: malformed CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + if (trust_store_append(tas, &ta) < 0) { + trust_anchor_free(&ta); + weprintf("%s:%zu: cannot store CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + free(dec.data); + memset(&dec, 0, sizeof(dec)); + in_cert = 0; + continue; + } + if (in_cert && b64_decoder_push_line(&dec, line, line_len) < 0) { + weprintf("%s:%zu: invalid base64 in CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + break; + } + } + if (!failed && ferror(fp)) { + weprintf("%s:%zu: cannot read CA certificates\n", path, line_no + 1); + failed = 1; + } + if (!failed && in_cert) { + weprintf("%s:%zu: unterminated CA certificate %zu\n", path, line_no, cert_num); + failed = 1; + } + if (fclose(fp) != 0 && !failed) { + weprintf("%s: cannot close CA certificates\n", path); + failed = 1; + } + free(line); + free(dec.data); + if (failed) { + trust_store_free(tas); + return -1; + } + return 1; +} static void -load_ca_certs(void) +warn_no_ca_certs(void) +{ + weprintf( + "no CA certificates found, TLS verification will " + "fail\n" + ); +} + +static int +load_ca_certs(struct TlsTrustStore *tas) { static const char *ca_paths[] = { ARUU_PATH_ETC "/ssl/certs/ca-certificates.crt", ARUU_PATH_ETC "/ssl/cert.pem", ARUU_PATH_ETC "/pki/tls/certs/ca-bundle.crt", }; - FILE *fp = NULL; size_t i; - char line[512]; - struct { - char *data; - size_t len; - size_t cap; - } pem = {NULL, 0, 0}; - int in_cert = 0; + int r; for (i = 0; i < LEN(ca_paths); i++) { - if ((fp = fopen(ca_paths[i], "r"))) - break; - } - if (!fp) { - weprintf( - "no CA certificates found, TLS verification will " - "fail\n" - ); - return; - } - - while (fgets(line, sizeof(line), fp)) { - if (strncmp(line, "-----BEGIN CERTIFICATE-----", 27) == 0) { - in_cert = 1; - pem.len = 0; - } else if (strncmp(line, "-----END CERTIFICATE-----", 25) == 0) { - if (in_cert) { - unsigned char *der = emalloc(pem.len); - size_t der_len = b64_decode(pem.data, pem.len, der); - br_x509_trust_anchor ta; - if (decode_cert_der(der, der_len, &ta)) { - tas = ereallocarray(tas, tas_num + 1, sizeof(*tas)); - tas[tas_num++] = ta; - } - free(der); - in_cert = 0; - } - } else if (in_cert) { - size_t llen = strlen(line); - while (llen > 0 && (line[llen - 1] == '\r' || line[llen - 1] == '\n')) - llen--; - if (pem.len + llen > pem.cap) { - pem.cap = pem.len + llen + 1024; - pem.data = erealloc(pem.data, pem.cap); - } - memcpy(pem.data + pem.len, line, llen); - pem.len += llen; + r = load_ca_certs_file(ca_paths[i], tas); + if (r >= 0) { + if (r == 0) + warn_no_ca_certs(); + return 1; } } - free(pem.data); - fclose(fp); + warn_no_ca_certs(); + return 1; +} + +static int +sigpipe_ignore(struct sigaction *old) +{ + struct sigaction sa; + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = SIG_IGN; + return sigaction(SIGPIPE, &sa, old); +} + +static int +sigpipe_restore(const struct sigaction *old) +{ + return sigaction(SIGPIPE, old, NULL); } + #else struct TlsSocket { int fd; @@ -295,10 +481,13 @@ tlss_connect(int fd, const char *host, int check_cert, int is_tls) s = emalloc(sizeof(*s)); s->fd = fd; s->is_tls = is_tls; +#if FEATURE_USE_BEARSSL + s->tas = NULL; +#endif if (!is_tls) return s; -#if !FEATURE_USE_LIBTLS && !FEATURE_USE_BEARSSL && !FEATURE_USE_OPENSSL +#if !FEATURE_USE_LIBTLS && !FEATURE_USE_BEARSSL (void)host; (void)check_cert; #endif @@ -342,15 +531,18 @@ tlss_connect(int fd, const char *host, int check_cert, int is_tls) } #elif FEATURE_USE_BEARSSL { - signal(SIGPIPE, SIG_IGN); + struct sigaction old_sigpipe; + int r; if (check_cert) { - static int ca_loaded = 0; - if (!ca_loaded) { - load_ca_certs(); - ca_loaded = 1; + s->tas = emalloc(sizeof(*s->tas)); + if (!load_ca_certs(s->tas)) { + weprintf("cannot load CA certificates\n"); + free(s->tas); + free(s); + return NULL; } - br_ssl_client_init_full(&s->sc, &s->x509_noverify.minimal, tas, tas_num); + br_ssl_client_init_full(&s->sc, &s->x509_noverify.minimal, s->tas->v, s->tas->num); } else { br_ssl_client_init_full(&s->sc, &s->x509_noverify.minimal, NULL, 0); s->x509_noverify.vtable = &x509_noverify_vtable; @@ -361,8 +553,22 @@ tlss_connect(int fd, const char *host, int check_cert, int is_tls) br_ssl_client_reset(&s->sc, host, 0); br_sslio_init(&s->ioc, &s->sc.eng, sock_read, &s->fd, sock_write, &s->fd); - if (br_sslio_flush(&s->ioc) < 0) { + if (sigpipe_ignore(&old_sigpipe) < 0) { + weprintf("cannot suppress SIGPIPE for TLS handshake\n"); + trust_store_free(s->tas); + free(s->tas); + free(s); + return NULL; + } + r = br_sslio_flush(&s->ioc); + if (sigpipe_restore(&old_sigpipe) < 0) { + weprintf("cannot restore SIGPIPE after TLS handshake\n"); + r = -1; + } + if (r < 0) { weprintf("TLS handshake failed with %s\n", host); + trust_store_free(s->tas); + free(s->tas); free(s); return NULL; } @@ -424,12 +630,25 @@ tlss_write(struct TlsSocket *s, const void *buf, size_t len) } #elif FEATURE_USE_BEARSSL { - int r = br_sslio_write_all(&s->ioc, buf, len); - if (r < 0) + struct sigaction old_sigpipe; + int r; + + if (sigpipe_ignore(&old_sigpipe) < 0) { + weprintf("cannot suppress SIGPIPE for TLS write\n"); return -1; - if (br_sslio_flush(&s->ioc) < 0) + } + r = br_sslio_write_all(&s->ioc, buf, len); + if (r < 0) + r = -1; + else if (br_sslio_flush(&s->ioc) < 0) + r = -1; + else + r = 0; + if (sigpipe_restore(&old_sigpipe) < 0) { + weprintf("cannot restore SIGPIPE after TLS write\n"); return -1; - return len; + } + return r < 0 ? -1 : (ssize_t)len; } #else return -1; @@ -444,10 +663,79 @@ tlss_close(struct TlsSocket *s, int close_fd) tls_close(s->ctx); tls_free(s->ctx); #elif FEATURE_USE_BEARSSL - br_sslio_close(&s->ioc); + { + struct sigaction old_sigpipe; + + if (sigpipe_ignore(&old_sigpipe) < 0) { + weprintf("cannot suppress SIGPIPE for TLS teardown\n"); + } else { + br_sslio_close(&s->ioc); + if (sigpipe_restore(&old_sigpipe) < 0) + weprintf("cannot restore SIGPIPE after TLS teardown\n"); + } + } + trust_store_free(s->tas); + free(s->tas); #endif } if (close_fd) close(s->fd); free(s); } + +#if FEATURE_USE_BEARSSL && defined(ARUU_TLS_TESTING) +int +tlss_test_b64_decode( + const char *src, size_t src_len, unsigned char *dst, size_t dst_cap, size_t *dst_len +) +{ + struct PemDecoder dec = {0}; + size_t i; + + for (i = 0; i < src_len; i++) { + if (b64_decoder_push(&dec, src[i]) < 0) + break; + } + if (i == src_len && b64_decoder_finish(&dec) == 0 && dec.len <= dst_cap) { + memcpy(dst, dec.data, dec.len); + *dst_len = dec.len; + free(dec.data); + return 0; + } + free(dec.data); + return -1; +} + +int +tlss_test_load_ca_certs(const char *path) +{ + struct TlsTrustStore tas = {0}; + int num; + + if (load_ca_certs_file(path, &tas) != 1) + return -1; + num = (int)tas.num; + trust_store_free(&tas); + return num; +} + +int +tlss_test_sigpipe_setup(void) +{ + struct sigaction old_sigpipe; + + if (sigpipe_ignore(&old_sigpipe) < 0) + return -1; + return sigpipe_restore(&old_sigpipe); +} + +int +tlss_test_sigpipe_teardown(void) +{ + struct sigaction old_sigpipe; + + if (sigpipe_ignore(&old_sigpipe) < 0) + return -1; + return sigpipe_restore(&old_sigpipe); +} +#endif diff --git a/shared/libutil/wexec.c b/shared/libutil/wexec.c @@ -13,6 +13,8 @@ #include <sys/wait.h> #include <unistd.h> +extern char **environ; + #define MAX_BUILTINS 256 #define MAX_POPEN 32 @@ -644,6 +646,46 @@ wexecv_self(const char *path, char *const *argv) exit((errno == ENOENT) ? 127 : 126); } +void +wexecve_self(const char *path, char *const *argv, char *const *envp) +{ +#if FEATURE_NOEXEC + { + const char *base = strrchr(path, '/'); + base = base ? base + 1 : path; + if (wexec_get_noexec() && wexec_is_builtin(base)) { + struct sigaction sa; + char **oldenv; + int i, ret; + + for (i = 1; i < NSIG; i++) { + if (sigaction(i, NULL, &sa) == 0) { + if (sa.sa_handler != SIG_IGN && sa.sa_handler != SIG_DFL) { + sa.sa_handler = SIG_DFL; + sa.sa_flags = 0; + sigemptyset(&sa.sa_mask); + sigaction(i, &sa, NULL); + } + } + } + + oldenv = environ; + environ = (char **)envp; + fflush(stdout); + fflush(stderr); + ret = wexec_call_builtin(base, argv); + environ = oldenv; + fflush(stdout); + fflush(stderr); + exit(ret); + } + } +#endif + execve(path, argv, envp); + weprintf("execve %s:", path); + exit((errno == ENOENT) ? 127 : 126); +} + void(exit)(int); void diff --git a/shared/net.h b/shared/net.h @@ -0,0 +1,78 @@ +#ifndef NET_H +#define NET_H + +#include <netinet/in.h> + +#define NET_IFNAME_MAX 16 +#define NET_ROUTE_ADDRSTRLEN 16 + +enum NetInterfaceFlag { + NET_IF_UP = 0x00000001, + NET_IF_BROADCAST = 0x00000002, + NET_IF_DEBUG = 0x00000004, + NET_IF_LOOPBACK = 0x00000008, + NET_IF_POINTOPOINT = 0x00000010, + NET_IF_RUNNING = 0x00000020, + NET_IF_NOARP = 0x00000040, + NET_IF_PROMISC = 0x00000080, + NET_IF_ALLMULTI = 0x00000100, + NET_IF_MULTICAST = 0x00000200, +}; + +struct NetStats { + unsigned long long rx_bytes; + unsigned long long rx_packets; + unsigned long long rx_errs; + unsigned long long rx_drop; + unsigned long long tx_bytes; + unsigned long long tx_packets; + unsigned long long tx_errs; + unsigned long long tx_drop; +}; + +struct NetInterface { + char name[NET_IFNAME_MAX]; + unsigned int flags; + int mtu; + int metric; + unsigned char mac[6]; + int has_mac; + struct sockaddr_in ipv4_addr; + int has_ipv4; + struct sockaddr_in ipv4_mask; + struct sockaddr_in ipv4_brd; + struct sockaddr_in6 ipv6_addr; + int has_ipv6; + unsigned int ipv6_scope; + unsigned int ipv6_prefix; +}; + +struct NetRoute { + char interface[NET_IFNAME_MAX]; + struct in_addr destination; + struct in_addr gateway; + struct in_addr mask; + unsigned int flags; + unsigned int metric; +}; + +int net_get_interfaces(struct NetInterface **, int *); +int net_get_routes(struct NetRoute **, int *); +int net_show_routes(void); +int net_get_stats(const char *, struct NetStats *); +int net_set_flags(const char *, unsigned int, int); +int net_set_mtu(const char *, int); +int net_set_metric(const char *, int); +int net_set_mac(const char *, const unsigned char *); +int net_set_mask(const char *, const char *); +int net_set_broadcast(const char *, const char *); +int net_set_dstaddr(const char *, const char *); +int net_add_addr(const char *, const char *, int); +int net_del_addr(const char *, const char *, int); +int net_add_route(const char *, const char *, const char *, int, int); +int net_del_route(const char *, const char *, const char *, int, int); +int net_flush_addrs(const char *); +int net_set_txqueuelen(const char *, int); +int net_set_name(const char *, const char *); + +#endif diff --git a/shared/paths.h b/shared/paths.h @@ -33,6 +33,10 @@ #define ARUU_PATH_TMP "/tmp" #endif +#ifndef ARUU_PATH_INCLUDE +#define ARUU_PATH_INCLUDE "/include" +#endif + #ifndef ARUU_PATH_BIN #define ARUU_PATH_BIN "/bin" #endif @@ -74,7 +78,9 @@ #if defined(__linux__) #define ARUU_LINUX_PATH_PROC "/proc" #define ARUU_LINUX_PATH_SYS "/sys" +#ifndef ARUU_LINUX_PATH_PROC_MOUNTS #define ARUU_LINUX_PATH_PROC_MOUNTS ARUU_LINUX_PATH_PROC "/mounts" +#endif #define ARUU_LINUX_PATH_PROC_PARTITIONS ARUU_LINUX_PATH_PROC "/partitions" #define ARUU_LINUX_PATH_PROC_MEMINFO ARUU_LINUX_PATH_PROC "/meminfo" #define ARUU_LINUX_PATH_PROC_LOADAVG ARUU_LINUX_PATH_PROC "/loadavg" diff --git a/shared/sysinfo.h b/shared/sysinfo.h @@ -0,0 +1,24 @@ +#ifndef SYSINFO_H +#define SYSINFO_H + +#include <stddef.h> +#include <sys/types.h> + +struct MemInfo { + unsigned long long total; + unsigned long long free; + unsigned long long shared; + unsigned long long buffers; + unsigned long long cached; + unsigned long long totalswap; + unsigned long long freeswap; +}; + +int get_uptime(long *); +int get_loads(double *); +int get_meminfo(struct MemInfo *); +ssize_t get_dmesg(char *, size_t); +int clear_dmesg(void); +int set_console_level(int); + +#endif diff --git a/shared/tls.h b/shared/tls.h @@ -18,4 +18,13 @@ ssize_t tlss_write(struct TlsSocket *s, const void *buf, size_t len); /* closes the tls connection and optionally closes the socket fd */ void tlss_close(struct TlsSocket *s, int close_fd); +#ifdef ARUU_TLS_TESTING +int tlss_test_b64_decode( + const char *src, size_t src_len, unsigned char *dst, size_t dst_cap, size_t *dst_len +); +int tlss_test_load_ca_certs(const char *path); +int tlss_test_sigpipe_setup(void); +int tlss_test_sigpipe_teardown(void); +#endif + #endif /* tls_h_ */ diff --git a/shared/util.h b/shared/util.h @@ -12,6 +12,8 @@ #include "arg.h" #include "compat.h" +#include "net.h" +#include "sysinfo.h" #define UTF8_POINT(c) (((c) & 0xc0) != 0x80) @@ -112,69 +114,6 @@ void recurse_dir(const char *, void (*)(const char *)); void devtotty(int, int *, int *); int ttytostr(int, int, char *, size_t); -#include <netinet/in.h> -#include <sys/socket.h> - -#ifndef IFNAMSIZ -#define IFNAMSIZ 16 -#endif - -struct NetStats { - unsigned long long rx_bytes; - unsigned long long rx_packets; - unsigned long long rx_errs; - unsigned long long rx_drop; - unsigned long long tx_bytes; - unsigned long long tx_packets; - unsigned long long tx_errs; - unsigned long long tx_drop; -}; - -struct NetInterface { - char name[IFNAMSIZ]; - unsigned int flags; - int mtu; - int metric; - unsigned char mac[6]; - int has_mac; - - /* ipv4 addresses */ - struct sockaddr_in ipv4_addr; - int has_ipv4; - struct sockaddr_in ipv4_mask; - struct sockaddr_in ipv4_brd; - - /* ipv6 addresses */ - struct sockaddr_in6 ipv6_addr; - int has_ipv6; - unsigned int ipv6_scope; - unsigned int ipv6_prefix; -}; - -struct MemInfo { - unsigned long long total; - unsigned long long free; - unsigned long long shared; - unsigned long long buffers; - unsigned long long cached; - unsigned long long totalswap; - unsigned long long freeswap; -}; - -int net_get_interfaces(struct NetInterface **, int *); -int net_get_stats(const char *, struct NetStats *); -int net_set_flags(const char *, unsigned int, int); -int net_set_mtu(const char *, int); -int net_set_mac(const char *, const unsigned char *); -int net_add_addr(const char *, const char *, int); -int net_del_addr(const char *, const char *, int); -int net_show_routes(void); -int net_add_route(const char *, const char *, const char *, const char *, int); -int net_del_route(const char *, const char *, const char *, const char *, int); -int net_flush_addrs(const char *); -int net_set_txqueuelen(const char *, int); -int net_set_name(const char *, const char *); - #if FEATURE_NOEXEC || FEATURE_NOFORK #include "wexec.h" #define exit(code) wexec_exit(code) diff --git a/shared/wexec.h b/shared/wexec.h @@ -46,6 +46,7 @@ int wsystem(const char *cmd); void wexecvp_self(const char *name, char *const *argv) __attribute__((noreturn)); void wexecv_self(const char *path, char *const *argv) __attribute__((noreturn)); +void wexecve_self(const char *path, char *const *argv, char *const *envp) __attribute__((noreturn)); int wpopen_track(FILE *fp, pid_t pid); pid_t wpopen_untrack(FILE *fp);