# This makefile embeds an application compiled to WASM into a native C program.
# The WASM module will be loaded by the WASM runtime.

# Paths
WAMR_ROOT     := /opt/wamr
WAMRC         := /opt/wamr-wamrc/wamrc
IWASM         := /opt/wamr-iwasm/iwasm
WAMRC_LIB     := /opt/wamr-libvmlib
IWASM_LIB     := /opt/wamr-libiwasm

WASI_ROOT     := /opt/wasi-sdk
WASI_CC       := $(WASI_ROOT)/bin/clang
WASI_CFLAGS   := --target=wasm32-wasi \
		 --sysroot=$(WASI_ROOT)/share/wasi-sysroot \
		 -O0 -g -Wall

# Embedding
EMBED_CC      := gcc
EMBED_INCL    := -I$(WAMR_ROOT)/core/iwasm/include \
                 -I$(WAMR_ROOT)/core/iwasm/common \
		 -I$(WAMR_ROOT)/core/shared/platform/linux \
		 -I$(WAMR_ROOT)/core/shared/utils \
		 -I$(WAMR_ROOT)/core/shared/utils/uncommon
EMBED_SOURCES := $(WAMR_ROOT)/core/shared/utils/uncommon/bh_read_file.c # Not used when reading from buffer
EMBED_CFLAGS  := -O0 -g -Wall $(EMBED_INCL)
AOT_LDFLAGS   := -Wl,-rpath,$(WAMRC_LIB)
AOT_LDLIBS    := -L$(WAMRC_LIB) -lvmlib -lm
INTER_LDFLAGS := -Wl,-rpath,$(IWASM_LIB)
INTER_LDLIBS  := -L$(IWASM_LIB) -liwasm -lm
XXD           := busybox xxd

# Files
SRCS          := $(wildcard *.c)
WASMS         := $(SRCS:.c=.wasm)
CWASMS        := $(SRCS:.c=_wasm.c)
AOTS          := $(SRCS:.c=.aot)
OBJS          := $(SRCS:.c=.o)
DEPS          := $(SRCS:.c=.d)
HOSTS         := $(SRCS:.c=_host.elf)


.PHONY: all build-wasms build-aots build-cwasms build-hosts clean

all: build-wasms build-aots build-cwasms build-hosts

# Compile to wasm bytecode using wasi-sdk
build-wasms: $(WASMS)

%.wasm: %.c
	$(WASI_CC) $(WASI_CFLAGS) $< -o $@

# Compile ahead-of-time module using wamrc
build-aots: $(AOTS)

%.aot: %.wasm
	$(WAMRC) -o $@ $<

# Convert the .aot files to C-style arrays (to embed them into the resulting host binary)
build-cwasms: $(CWASMS)

%_wasm.c: %.aot
	$(XXD) -i $< > $@

# Compile the host that will load and run the compiled wasm module
# The compiled wasm module is embedded as C-style array
build-hosts: $(HOSTS)

# The C-style array is called %_aot, e.g. test_aot
# We have to modify the host to refer to that with the correct name
%_host.elf: %_wasm.c
	cp embed/host.c embed/$*_host.c
	sed -i \
	    -e "s@__WASM_ARRAY_FILE__@../$*_wasm.c@g" \
            -e "s@__WASM_ARRAY__@$*_aot@g" \
            -e "s@__WASM_ARRAY_LEN__@$*_aot_len@g" \
            embed/$*_host.c
	$(EMBED_CC) $(EMBED_CFLAGS) embed/$*_host.c -o $@ $(INTER_LDFLAGS) $(INTER_LDLIBS)

clean:
	rm -f *.wasm
	rm -f *.aot
	rm -f *_wasm.c
	rm -f *.d
	rm -f *.o
	rm -f embed/*_host.c
	rm -f *_host.elf
