#  hate-no-d
#
#  Native platforms are auto-detected from uname. Cross targets are selected explicitly:
#      make
#      make PLATFORM=Android ANDROID_NDK=/opt/android-ndk
#      make PLATFORM=Android ANDROID_NDK=... ANDROID_ABI=armeabi-v7a ANDROID_API=21
#      make PLATFORM=iOS IOS_ARCH=arm64 IOS_MIN=12.0
#      make PLATFORM=Windows WIN_ARCH=x86_64        (cross build with mingw-w64)
#
#  Targets:
#      make            the CLI (hate-no-d, or hate-no-d.exe / libluajit.a on iOS)
#      make lib        libhate-no-d.a, for embedding into another program
#      make help       every target and option

# luajit requires GNU Make (use `gmake` on FreeBSD/OpenBSD/NetBSD).
ifndef .FEATURES
	$(error This build requires GNU Make -- on BSD use 'gmake')
endif

.DEFAULT_GOAL := all

LUAJIT_DIR  := submodules/luajit
LUAJIT_SRC  := $(LUAJIT_DIR)/src
LUAJIT_AR   := $(LUAJIT_SRC)/libluajit.a
OBJ         := hate-no-d.o
BIN         := hate-no-d
LIB         := libhate-no-d.a

# Everything that goes into $(LIB) besides LuaJIT itself. Empty today: the only
# C in the tree is the CLI driver, and its main() belongs to the executable an
# embedder already has, not to a library (a -all_load/--whole-archive link would
# collide). Runtime modules added later get listed here, e.g.
#     LIB_OBJS += hnod.o
# and are merged into the archive automatically -- that is why the archive has
# a name of its own instead of just being LuaJIT's.
LIB_OBJS    :=

# Archiver used to merge $(LIB). Cross toolchains ship their own; Apple has no
# `ar -M`, so those targets use libtool instead (see the $(LIB) rule).
AR ?= ar

LUAJIT_XCFLAGS := -DLUAJIT_ENABLE_LUA52COMPAT
LUAJIT_EXTRA   :=

# Platform detection. PLATFORM= always wins over uname.
PLATFORM ?= $(shell uname -s)

ifeq ($(PLATFORM),Linux)
  OS_KIND := linux
else ifeq ($(PLATFORM),Android)
  OS_KIND := android
else ifeq ($(PLATFORM),Darwin)
  OS_KIND := macos
else ifeq ($(PLATFORM),iOS)
  OS_KIND := ios
else ifeq ($(PLATFORM),Windows)
  OS_KIND := windows
else ifneq (,$(filter $(PLATFORM),FreeBSD OpenBSD NetBSD DragonFly GNU/kFreeBSD))
  OS_KIND := bsd
else
  OS_KIND := posix
endif

# Linux (ELF)
ifeq ($(OS_KIND),linux)
  EXPORT_LDFLAGS := -Wl,-E
  PLAT_LIBS      := -lm -ldl
  LINK_TARGET    := $(BIN)
endif

# BSD (ELF or Mach-O, dlopen lives in libc)
ifeq ($(OS_KIND),bsd)
  EXPORT_LDFLAGS := -Wl,-E
  PLAT_LIBS      := -lm
  LINK_TARGET    := $(BIN)
endif

# Generic POSIX fallback (Solaris/illumos, AIX, Haiku, ...).
# Note: Solaris ld's -E is NOT --export-dynamic, so it is deliberately off.
ifeq ($(OS_KIND),posix)
  EXPORT_LDFLAGS :=
  PLAT_LIBS      := -lm
  LINK_TARGET    := $(BIN)
endif

# Windows (PE, cross-compiled from a POSIX host with mingw-w64)
#
# Native builds use build.bat.
#
# 64-bit targets build on any 64-bit host. i686 also needs a 32-bit host
# compiler, because LuaJIT's buildvm runs natively and its pointer size must
# match the target:
#   make PLATFORM=Windows WIN_ARCH=i686 HOST_CC="gcc -m32"
#
# No export table: ffi.C resolves through msvcrt/kernel32 handles on Windows,
# unlike ELF where the Lua API has to be exported with -Wl,-E.
ifeq ($(OS_KIND),windows)
  WIN_ARCH ?= x86_64

  ifeq ($(filter $(WIN_ARCH),x86_64 i686),)
    $(error WIN_ARCH must be x86_64 or i686)
  endif

  CC          := $(WIN_ARCH)-w64-mingw32-gcc
  AR          := $(WIN_ARCH)-w64-mingw32-ar
  HOST_CC     ?= gcc
  PLAT_LIBS   := -lm
  BIN         := $(BIN).exe
  LINK_TARGET := $(BIN)

  # LuaJIT derives HOST_CC from CC, so label both to the sub-make: otherwise
  # the host tools (minilua, buildvm) are compiled with the cross compiler.
  LUAJIT_EXTRA := "CC=$(CC)" "HOST_CC=$(HOST_CC)" TARGET_SYS=Windows
endif

# macOS (Mach-O)
#
# ld64 exports main-executable globals by default; -export_dynamic only stops
# -dead_strip / LTO from discarding the Lua API. GC64 is mandatory on arm64.
# JIT under the hardened runtime needs MAP_JIT, which is compiled in only when
# the deployment target is >= 11.0.
ifeq ($(OS_KIND),macos)
  ifeq ($(origin CC),default)
    CC := clang
  endif
  MACOSX_DEPLOYMENT_TARGET ?= 11.0
  export MACOSX_DEPLOYMENT_TARGET

  EXPORT_LDFLAGS := -Wl,-export_dynamic
  PLAT_LIBS      := -lm
  LINK_TARGET    := $(BIN)

  # MAP_JIT path: needed for the hardened runtime (and therefore notarization).
  # Requires MACOSX_DEPLOYMENT_TARGET >= 11.0 or LuaJIT compiles it back out.
  MACOSX_HRT ?= 1
  ifeq ($(MACOSX_HRT),1)
    LUAJIT_XCFLAGS += -DLUAJIT_ENABLE_OSX_HRT
  endif
endif

# Android (ELF, cross-compiled with the NDK)
#
# 64-bit ABIs build on any 64-bit host. armeabi-v7a additionally needs a
# 32-bit host compiler:  make ... HOST_CC="gcc -m32"
ifeq ($(OS_KIND),android)
  ANDROID_NDK ?= $(ANDROID_NDK_HOME)
  ANDROID_API ?= 21
  ANDROID_ABI ?= arm64-v8a

  ifeq ($(strip $(ANDROID_NDK)),)
    $(error PLATFORM=Android requires ANDROID_NDK (or ANDROID_NDK_HOME) to be set)
  endif

  ifeq ($(ANDROID_ABI),arm64-v8a)
    ANDROID_TRIPLET := aarch64-linux-android
  else ifeq ($(ANDROID_ABI),armeabi-v7a)
    ANDROID_TRIPLET := armv7a-linux-androideabi
  else ifeq ($(ANDROID_ABI),x86_64)
    ANDROID_TRIPLET := x86_64-linux-android
  else ifeq ($(ANDROID_ABI),x86)
    ANDROID_TRIPLET := i686-linux-android
  else
    $(error ANDROID_ABI must be one of: arm64-v8a, armeabi-v7a, x86_64, x86)
  endif

  ifeq ($(shell uname -s),Darwin)
    ANDROID_HOST_TAG ?= darwin-x86_64
  else
    ANDROID_HOST_TAG ?= linux-x86_64
  endif

  ANDROID_BIN := $(ANDROID_NDK)/toolchains/llvm/prebuilt/$(ANDROID_HOST_TAG)/bin
  ANDROID_CC  := $(ANDROID_BIN)/$(ANDROID_TRIPLET)$(ANDROID_API)-clang

  CC             := $(ANDROID_CC)
  AR             := $(ANDROID_BIN)/llvm-ar
  EXPORT_LDFLAGS := -Wl,-E
  PLAT_LIBS      := -lm
  LINK_TARGET    := $(BIN)

  LUAJIT_EXTRA := CROSS=$(ANDROID_BIN)/$(ANDROID_TRIPLET)- STATIC_CC=$(ANDROID_CC) TARGET_LD=$(ANDROID_CC) "TARGET_AR=$(ANDROID_BIN)/llvm-ar rcus" TARGET_STRIP=$(ANDROID_BIN)/llvm-strip
endif

# iOS (Mach-O, ARM64 only)
#
# There is no runnable binary: link libluajit.a into your Xcode app target.
# The JIT is compiled out by LuaJIT itself (no runtime code generation is
# allowed on iOS), so you get the fast interpreter only.
ifeq ($(OS_KIND),ios)
  IOS_SDK  ?= $(shell xcrun --sdk iphoneos --show-sdk-path 2>/dev/null)
  IOS_CC   ?= $(shell xcrun --sdk iphoneos --find clang 2>/dev/null)
  IOS_ARCH ?= arm64
  IOS_MIN  ?= 12.0

  ifeq ($(strip $(IOS_SDK)),)
    $(error PLATFORM=iOS requires Xcode/xcrun on the build host)
  endif

  IOS_FLAGS := -arch $(IOS_ARCH) -isysroot $(IOS_SDK) -mios-version-min=$(IOS_MIN)

  CC             := $(IOS_CC)
  EXPORT_LDFLAGS :=
  PLAT_LIBS      :=
  LINK_TARGET    := $(LUAJIT_AR)

  # DEFAULT_CC keeps the host toolchain (minilua/buildvm) native; CROSS
  # switches only the target objects to the iOS SDK.
  LUAJIT_EXTRA := DEFAULT_CC=clang CROSS=$(dir $(IOS_CC)) TARGET_SYS=iOS "TARGET_FLAGS=$(IOS_FLAGS)"
endif

ifndef LINK_TARGET
	$(error Unsupported platform '$(PLATFORM)')
endif

# Compiler / linker flags
CFLAGS   ?= -O2 -Wall
CPPFLAGS += -I$(LUAJIT_SRC)

# LuaJIT: static archive only, built through the upstream GNU Makefile.
LUAJIT_MAKE_ARGS := BUILDMODE=static XCFLAGS="$(LUAJIT_XCFLAGS)" $(LUAJIT_EXTRA)

$(LUAJIT_AR):
	$(MAKE) -C $(LUAJIT_SRC) $(LUAJIT_MAKE_ARGS) "LJCORE_O=ljamalg.o" libluajit.a

# Targets
help:
	@echo "hate-no-d -- LuaJIT-based Lua runtime"
	@echo ""
	@echo "Targets:"
	@echo "  make [all]          CLI for the auto-detected platform (hate-no-d,"
	@echo "                      hate-no-d.exe, or libluajit.a on iOS)"
	@echo "  make lib            libhate-no-d.a: LuaJIT plus LIB_OBJS, for embedding"
	@echo "  make luajit         LuaJIT static archive only"
	@echo "  make print-config   resolved configuration for the current target"
	@echo "  make clean          remove build artifacts, LuaJIT's included"
	@echo "  make help           this text"
	@echo ""
	@echo "Options (pass as VAR=value):"
	@echo "  PLATFORM=           Linux | Android | Darwin | iOS | Windows | a BSD"
	@echo "                      (default: uname -s)"
	@echo "  WIN_ARCH=           x86_64 | i686                          [Windows]"
	@echo "  ANDROID_NDK=        NDK root, or export ANDROID_NDK_HOME   [Android]"
	@echo "  ANDROID_ABI=        arm64-v8a | armeabi-v7a | x86_64 | x86 [Android]"
	@echo "  ANDROID_API=        target API level, default 21           [Android]"
	@echo "  IOS_ARCH= IOS_MIN=  arm64 / 12.0                           [iOS]"
	@echo "  IOS_SDK= IOS_CC=    Xcode paths, default from xcrun        [iOS]"
	@echo "  MACOSX_HRT=         hardened-runtime JIT, default 1        [macOS]"
	@echo "  MACOSX_DEPLOYMENT_TARGET=   default 11.0                   [macOS]"
	@echo "  HOST_CC=            host compiler for minilua/buildvm; needed"
	@echo "                      when the target is 32-bit and the host is not"
	@echo "  CFLAGS=             default -O2 -Wall"
	@echo "  LDFLAGS=            extra linker flags"
	@echo "  LIB_OBJS=           extra objects merged into libhate-no-d.a"
	@echo "  AR=                 archiver used to merge libhate-no-d.a"

all: $(LINK_TARGET)

$(OBJ): hate-no-d.c
	$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ hate-no-d.c

$(BIN): $(OBJ) $(LUAJIT_AR)
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(OBJ) \
	    $(LUAJIT_AR) $(EXPORT_LDFLAGS) $(LDFLAGS) $(PLAT_LIBS)

luajit: $(LUAJIT_AR)

# Static library for embedding: $(LIB_OBJS) plus LuaJIT, merged into one archive
# so a host program links a single file, and modules added to $(LIB_OBJS) later
# join it without the host's link line changing.
lib: $(LIB)

# Apple's ar (cctools) has no MRI script mode, so archives are merged with
# libtool there. Everywhere else GNU ar, binutils ar and llvm-ar all parse MRI
# scripts (ADDMOD for objects, ADDLIB for another archive).
APPLE := $(filter macos ios,$(OS_KIND))

$(LIB): $(LIB_OBJS) $(LUAJIT_AR)
ifeq ($(APPLE),)
	@rm -f $@ $@.mri
	@{ echo "CREATE $@"; \
	   for o in $(LIB_OBJS); do echo "ADDMOD $$o"; done; \
	   echo "ADDLIB $(LUAJIT_AR)"; \
	   echo "SAVE"; echo "END"; } > $@.mri
	$(AR) -M < $@.mri
	@rm -f $@.mri
else
	@rm -f $@
	libtool -static -o $@ $(LIB_OBJS) $(LUAJIT_AR)
endif
	@echo "lib: built $@ ($$($(AR) t $@ | wc -l | tr -d ' ') members)"

# Show the resolved configuration for the current (or selected) platform.
# Useful for checking a cross build before committing to it.
print-config:
	@echo "PLATFORM                 = $(PLATFORM)"
	@echo "OS_KIND                  = $(OS_KIND)"
	@echo "CC / AR                  = $(CC) / $(AR)"
	@echo "CFLAGS                   = $(CFLAGS)"
	@echo "CPPFLAGS                 = $(CPPFLAGS)"
	@echo "EXPORT_LDFLAGS           = $(EXPORT_LDFLAGS)"
	@echo "PLAT_LIBS                = $(PLAT_LIBS)"
	@echo "LINK_TARGET              = $(LINK_TARGET)"
	@echo "OBJ / LIB                = $(OBJ) / $(LIB) [$(LIB_OBJS)]"
	@echo "LUAJIT_MAKE_ARGS         = $(LUAJIT_MAKE_ARGS)"
	@echo "MACOSX_DEPLOYMENT_TARGET = $(MACOSX_DEPLOYMENT_TARGET) (HRT=$(MACOSX_HRT))"
	@echo "ANDROID_ABI / API        = $(ANDROID_ABI) / $(ANDROID_API)"
	@echo "IOS_ARCH / MIN           = $(IOS_ARCH) / $(IOS_MIN)"
	@echo "WIN_ARCH                 = $(WIN_ARCH) (HOST_CC=$(HOST_CC))"

clean:
	$(MAKE) -C $(LUAJIT_DIR) clean
	rm -f $(BIN) $(OBJ) $(LIB) $(LIB).mri

.PHONY: all clean luajit print-config lib help
