
CFLAGS += -std=c99 -Wall -O3
ALL_CFLAGS = -D_XOPEN_SOURCE=600 -fPIC -DFIU_ENABLE=1 \
		-I. -I../../libfiu/ -L../../libfiu/ $(CFLAGS)

ifdef DEBUG
ALL_CFLAGS += -g
endif

ifdef PROFILE
ALL_CFLAGS += -g -pg -fprofile-arcs -ftest-coverage
endif

# prefix for installing the binaries
PREFIX=/usr/local

# install utility, we assume it's GNU/BSD compatible
INSTALL=install


MODS = $(wildcard modules/*.mod)
GEN_C = $(addsuffix .c,$(MODS))
GEN_OBJS = $(addsuffix .o,$(MODS))
GEN_FL = $(addsuffix .fl,$(MODS))
CUSTOM_OBJS = $(patsubst %.c,%.o,$(wildcard modules/*.custom.c))
OBJS = codegen.o $(GEN_OBJS) $(CUSTOM_OBJS)


ifneq ($(V), 1)
	NICE_CC = @echo "  CC  $@"; $(CC)
	NICE_GEN = @echo "  GEN $@"; ./generate
	Q = @
else
	NICE_CC = $(CC)
	NICE_GEN = ./generate
	Q =
endif


default: all
	
all: fiu_posix_preload.so function_list

BF = $(ALL_CFLAGS) ~ $(PREFIX)
build-flags: .force-build-flags
	@if [ x"$(BF)" != x"`cat build-flags 2>/dev/null`" ]; then \
		if [ -f build-flags ]; then \
			echo "build flags changed, rebuilding"; \
		fi; \
		echo "$(BF)" > build-flags; \
	fi

$(GEN_OBJS): $(GEN_C)

$(OBJS): build-flags

%.mod.c: %.mod
	$(NICE_GEN) $< $@ $<.fl

.c.o:
	$(NICE_CC) $(ALL_CFLAGS) -c $< -o $@

# some platforms do not have libdl, we only use it if available
NEED_LIBDL := $(shell ld -o dlcheck.so -shared -ldl 2>/dev/null && echo -ldl; \
	rm -f dlcheck.so)

fiu_posix_preload.so: build-flags $(OBJS)
	$(NICE_CC) $(ALL_CFLAGS) -shared -fPIC $(OBJS) -lfiu $(NEED_LIBDL) \
		-o fiu_posix_preload.so

# this should only be needed when building the function list and not the
# preload library
%.mod.fl: %.mod
	$(NICE_GEN) $< $<.c $@

function_list: $(GEN_FL) function_list.in
	@echo "  function_list"
	$(Q) cp function_list.in function_list
	$(Q) for i in $(GEN_FL); do cat $$i >> function_list; done

install: fiu_posix_preload.so
	$(INSTALL) -d $(PREFIX)/lib
	$(INSTALL) -m 0755 fiu_posix_preload.so $(PREFIX)/lib

uninstall:
	$(RM) $(PREFIX)/lib/fiu_posix_preload.so

clean:
	rm -f $(OBJS) $(GEN_OBJS:.o=.c) $(GEN_FL) build-flags
	rm -f function_list fiu_posix_preload.so
	rm -f *.bb *.bbg *.da *.gcov *.gcda *.gcno gmon.out

.PHONY: default install uninstall clean .force-build-flags


