#!/bin/sh
# SPDX-License-Identifier: BSD-2-Clause
# The C compiler for XNU/wasm user space: clang for arm64 Mach-O against the
# musl sysroot (scripts/ulibc.py); links static executables (ld64.lld, then
# scripts/macho-static.py, as ld64.lld has no -static).
#   xnu-cc [cc options] files...      (like cc; -c/-S/-E only compile)
set -e
here=$(cd "$(dirname "$0")" && pwd)
root=$(dirname "$here")
LLVM=${LLVM:-/opt/homebrew/opt/llvm/bin}
LD64=${LD64:-$(command -v ld64.lld 2>/dev/null || echo /opt/homebrew/opt/lld/bin/ld64.lld)}
SYSROOT=${XNU_SYSROOT:-$root/build/userland/sysroot}
RES=$("$LLVM/clang" -print-resource-dir)
CC="$LLVM/clang --target=arm64-apple-macos11 -nostdinc -isystem $SYSROOT/include -isystem $RES/include
 -U__APPLE__ -U__MACH__ -D__xnu_unkernel__ -fno-stack-protector -fno-stack-check
 -Wno-unused-command-line-argument -mno-outline-atomics"

link=1
out=a.out
for a in "$@"; do
	case "$a" in
	-c|-S|-E|-M|-MM|-print-*|--version|-v|-dumpversion|-dumpmachine) link=0 ;;
	esac
done
if [ $link = 0 ]; then
	case " $* " in
	*" -dumpmachine "*) echo aarch64-apple-darwin; exit 0 ;;
	esac
	exec $CC "$@"
fi

# split compile inputs from link options; compile sources to temporaries
tmp=$(mktemp -d "${TMPDIR:-/tmp}/xnu-cc.XXXXXX")
trap 'rm -rf "$tmp"' EXIT
objs=
libs=
cflags=
n=0
while [ $# -gt 0 ]; do
	a=$1; shift
	case "$a" in
	-o) out=$1; shift ;;
	-o*) out=${a#-o} ;;
	*.c|*.s|*.S|*.cc|*.cpp)
		n=$((n + 1)); o="$tmp/$n.o"
		$CC $cflags -c "$a" -o "$o"
		objs="$objs $o" ;;
	*.o|*.a)
		# a thin archive from xnu-ld (ld -r): all of it, as ld -r would
		if [ "$(head -c 7 "$a" 2>/dev/null)" = "!<thin>" ]; then
			objs="$objs -force_load $a"
		else
			objs="$objs $a"
		fi ;;
	-l*) libs="$libs $a" ;;
	-L*) libs="$libs $a" ;;
	-Wl,*)
		# GNU ld options that ld64 does not have
		case "$a" in
		-Wl,--sort-section,*|-Wl,-Map,*|-Wl,-z,*|-Wl,-soname,*|-Wl,--version-script,*) ;;
		*)
			for o in $(echo "${a#-Wl,}" | tr ',' ' '); do
				case "$o" in
				--gc-sections|--sort-common|--start-group|--end-group|--warn-common|--verbose|\
				--as-needed|--no-as-needed|-O1|-O2|--hash-style=*|--build-id*|-E|--export-dynamic|\
				--no-undefined|-static|-Bstatic|-Bdynamic|--whole-archive|--no-whole-archive) ;;
				*) libs="$libs $o" ;;
				esac
			done ;;
		esac ;;
	-static|-s|-rdynamic|-pthread|-shared|-pie|-no-pie|-nostdlib|-static-libgcc) ;;
	*) cflags="$cflags $a" ;;
	esac
done
rt=$SYSROOT/lib/libclang_rt.builtins.a
[ -f "$rt" ] || rt=$RES/lib/darwin/libclang_rt.osx.a
[ -f "$rt" ] || rt=
"$LD64" -arch arm64 -platform_version macos 11.0 11.0 -e _start -headerpad 0x400 \
	-dead_strip -o "$tmp/out.dyn" "$SYSROOT/lib/crt1.o" $objs -L"$SYSROOT/lib" $libs -lc $rt
python3 "$here/macho-static.py" "$tmp/out.dyn" "$out"
chmod +x "$out"
