# ---------------------------------------------------------------------------
# elf_tools -- elfrenamesym, elflintsym, elfbundle, bin2obj, data2obj,
#              elf2asm, elfcmp.
#
# $Id: Makefile,v 1.9 2026/11/02 23:18:24 rec Exp $
#
# Author:  Robert Cousins
# Purpose: Build the tools, run the test suite, build the manual, install,
#          and roll the release tarball.
#
# The release contract: unpack elf_tools-<version>.tar.gz in an empty
# directory and type
#
#       make ; sudo make install
#
# There is no configure script.  Platform differences are handled by the
# uname-driven block below.
#
# Libraries:
#   libelf    elfrenamesym, elflintsym, elfbundle (elfutils on Linux, base
#             system on FreeBSD; FreeBSD still needs an explicit -lelf).
#   zlib      elf2asm, elfcmp (compressed debug sections).
#   Capstone  elf2asm only (x86-64 and AArch64 decoding; version 4 or
#             later).  Without it elf2asm is skipped with a message and
#             everything else still builds.
#   bin2obj and data2obj use no library.
#
# Versions:
#   1.08  2026-09-07  Robert Cousins  Last release before 2.00.
#   2.00  2026-10-17  Robert Cousins  elf2asm and elfcmp; Capstone
#                                     detection; dist and manual targets.
#   2.00  2026-10-27  Robert Cousins  Capstone include path: add the
#                                     parent of pkg-config's .../capstone.
#   2.01  2026-11-02  Robert Cousins  data2obj 1.05: constructor-array
#                                     fix, weak extern, visibilities,
#                                     function symbols, retain.
# ---------------------------------------------------------------------------

PKG      = elf_tools
VERSION  = 2.01
DISTDIR  = $(PKG)-$(VERSION)

CC      ?= cc
CFLAGS  ?= -std=c17 -Wall -Wextra -O2
LDFLAGS ?=

# ----- platform detection ---------------------------------------------------

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
    ELF_LIBS = -lelf
endif
ifeq ($(UNAME_S),FreeBSD)
    # libelf is in base, but must still be linked explicitly; Capstone from
    # pkg(8) lives under /usr/local.
    ELF_LIBS = -lelf
    CS_FALLBACK_CFLAGS = -I/usr/local/include
    CS_FALLBACK_LIBS = -L/usr/local/lib -lcapstone
endif
CS_FALLBACK_LIBS ?= -lcapstone

# Capstone: pkg-config when it knows the library, the platform default
# otherwise.  HAVE_CAPSTONE is decided by preprocessing the header.
# pkg-config names the directory holding capstone.h (".../capstone"), but
# the sources include <capstone/capstone.h>, so its parent is added too;
# without it FreeBSD, whose /usr/local/include is not searched by default,
# quietly builds without elf2asm.
CS_PC_CFLAGS := $(shell pkg-config --cflags capstone 2>/dev/null)
CS_CFLAGS := $(if $(CS_PC_CFLAGS),$(CS_PC_CFLAGS) \
               $(patsubst %/capstone,%,$(filter -I%/capstone,$(CS_PC_CFLAGS))),\
               $(CS_FALLBACK_CFLAGS))
CS_LIBS   := $(shell pkg-config --libs capstone 2>/dev/null || \
                     echo "$(CS_FALLBACK_LIBS)")
HAVE_CAPSTONE := $(shell printf '\043include <capstone/capstone.h>\n' | \
                   $(CC) $(CS_CFLAGS) -E -x c - >/dev/null 2>&1 && echo yes)

PREFIX     ?= /usr/local
BINDIR     ?= $(PREFIX)/bin
MANDIR     ?= $(PREFIX)/share/man
INSTALL    ?= install

# ----- what we build --------------------------------------------------------

E2A_CORE  = e2a_elf.o e2a_ar.o e2a_cmp.o e2a_sem.o e2a_util.o e2a_dwarf.o \
            e2a_cfi.o
E2A_EMIT  = e2a_emit.o e2a_x86.o e2a_a64.o e2a_rv.o e2a_src.o e2a_hdr.o \
            e2a_cfiemit.o
E2A_HDRS  = e2a.h e2a_emit.h e2a_sem.h e2a_dwarf.h e2a_cfi.h

BASE_PROGS := elfrenamesym elflintsym elfbundle bin2obj data2obj elfcmp
ifeq ($(HAVE_CAPSTONE),yes)
PROGS := $(BASE_PROGS) elf2asm
else
PROGS := $(BASE_PROGS)
endif
MANS  := elfrenamesym.1 elflintsym.1 elfbundle.1 bin2obj.1 data2obj.1 \
         elf2asm.1 elfcmp.1

MANUAL = $(PKG)_manual.pdf

DISTFILES = Makefile README $(MANS) $(PKG)_manual.tex $(MANUAL) \
            elfrenamesym.c elflintsym.c elfbundle.c bin2obj.c data2obj.c \
            elf2asm.c elfcmp.c $(E2A_CORE:.o=.c) $(E2A_EMIT:.o=.c) \
            $(E2A_HDRS) bin2obj_example.sh data2obj_example.sh \
            elf2asm_example.sh tests

.PHONY: all clean distclean check install uninstall test sanitize-test \
        manual dist no-capstone

all: $(PROGS) no-capstone

no-capstone:
ifneq ($(HAVE_CAPSTONE),yes)
	@echo "elf_tools: Capstone not found; elf2asm was not built."
	@echo "elf_tools: install it (Ubuntu: libcapstone-dev, FreeBSD:" \
	      "pkg install capstone) and run make again."
endif

# ----- libelf-based tools ---------------------------------------------------

elfrenamesym: elfrenamesym.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(ELF_LIBS)

elflintsym: elflintsym.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(ELF_LIBS)

elfbundle: elfbundle.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(ELF_LIBS)

# ----- bin2obj, data2obj: standalone, no libelf -----------------------------

bin2obj: bin2obj.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

data2obj: data2obj.o
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

# ----- elfcmp, elf2asm ------------------------------------------------------
# Neither uses libelf: they read ELF themselves, identically on Linux and
# FreeBSD.  elfcmp needs only zlib; elf2asm adds Capstone.

elfcmp: elfcmp.o $(E2A_CORE)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ elfcmp.o $(E2A_CORE) -lz

elf2asm: elf2asm.o $(E2A_CORE) $(E2A_EMIT)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ elf2asm.o $(E2A_CORE) $(E2A_EMIT) \
	    $(CS_LIBS) -lz

# The objects that include <capstone/capstone.h> need its include path.
elf2asm.o: elf2asm.c $(E2A_HDRS)
	$(CC) $(CFLAGS) $(CS_CFLAGS) -c -o $@ elf2asm.c

e2a_x86.o: e2a_x86.c $(E2A_HDRS)
	$(CC) $(CFLAGS) $(CS_CFLAGS) -c -o $@ e2a_x86.c

e2a_a64.o: e2a_a64.c $(E2A_HDRS)
	$(CC) $(CFLAGS) $(CS_CFLAGS) -c -o $@ e2a_a64.c

elfcmp.o $(E2A_CORE) e2a_emit.o e2a_rv.o e2a_src.o e2a_hdr.o \
e2a_cfiemit.o: $(E2A_HDRS)

# ----- pattern rule ---------------------------------------------------------

%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

# ----- housekeeping ---------------------------------------------------------

clean:
	rm -f $(BASE_PROGS) elf2asm *.o

distclean: clean
	rm -f $(PKG)_manual.aux $(PKG)_manual.log $(PKG)_manual.toc \
	      $(PKG)_manual.idx $(PKG)_manual.ind $(PKG)_manual.ilg \
	      $(PKG)_manual.out
	$(MAKE) -C tests/data clean

install: $(PROGS)
	$(INSTALL) -d $(DESTDIR)$(BINDIR)
	$(INSTALL) -d $(DESTDIR)$(MANDIR)/man1
	for p in $(PROGS); do $(INSTALL) -m 0755 $$p $(DESTDIR)$(BINDIR)/$$p; done
	for m in $(MANS);  do $(INSTALL) -m 0644 $$m $(DESTDIR)$(MANDIR)/man1/$$m; done

uninstall:
	for p in $(BASE_PROGS) elf2asm; do rm -f $(DESTDIR)$(BINDIR)/$$p; done
	for m in $(MANS);  do rm -f $(DESTDIR)$(MANDIR)/man1/$$m; done

# ----- test suite -----------------------------------------------------------
# `make test' runs every test under tests/tests.d/.  Fixtures are built on
# demand by tests/data/Makefile.  The elf2asm tests skip themselves when
# elf2asm was not built, and the cross-architecture ones when no assembler
# for that target is installed.  Exits non-zero if any test fails.

test: $(PROGS)
	$(MAKE) -C tests/data
	tests/run_all.sh

# `make sanitize-test' rebuilds every tool with ASan + UBSan and runs the
# full test suite.  Used before releases.

sanitize-test:
	$(MAKE) clean
	$(MAKE) CFLAGS="-std=c17 -Wall -Wextra -O1 -g -fno-omit-frame-pointer \
                        -fsanitize=address,undefined" \
                LDFLAGS="-fsanitize=address,undefined"
	$(MAKE) -C tests/data
	tests/run_all.sh

# Quick smoke test of the tools.  Run as: make check IN=/path/to/file.o
check: $(PROGS)
	@if [ -z "$(IN)" ]; then \
		echo "usage: make check IN=/path/to/input.o"; exit 1; \
	fi
	@echo "d sl_init sl_init_RENAMED" > /tmp/elf_tools_test.rules
	./elfrenamesym -v /tmp/elf_tools_test.rules "$(IN)" /tmp/elf_tools_test.o
	@echo "--- nm of renamed output (first 6 lines) ---"
	@nm /tmp/elf_tools_test.o | head -6
	@echo "d ^_init$$" > /tmp/elf_tools_test.lint
	@echo "u ^malloc$$ banned for testing" >> /tmp/elf_tools_test.lint
	@echo "--- elflintsym -v on the renamed output ---"
	./elflintsym -v /tmp/elf_tools_test.lint /tmp/elf_tools_test.o || true
	@echo "--- elfcmp of the input against itself ---"
	./elfcmp "$(IN)" "$(IN)" && echo "equivalent"
	@rm -f /tmp/elf_tools_test.*

# ----- manual ---------------------------------------------------------------
# Three pdflatex passes with makeindex between the first and second.

manual: $(MANUAL)

$(MANUAL): $(PKG)_manual.tex
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null
	makeindex $(PKG)_manual.idx >/dev/null 2>&1 || true
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null
	rm -f $(PKG)_manual.aux $(PKG)_manual.log $(PKG)_manual.toc \
	      $(PKG)_manual.idx $(PKG)_manual.ind $(PKG)_manual.ilg \
	      $(PKG)_manual.out

# ----- release --------------------------------------------------------------
# The tarball ships the PDF so a reader without LaTeX still has the manual,
# and leaves out generated test fixtures, which tests/data/Makefile builds.

dist: $(MANUAL)
	rm -rf $(DISTDIR) $(DISTDIR).tar.gz
	mkdir $(DISTDIR)
	cp -R $(DISTFILES) $(DISTDIR)/
	$(MAKE) -C $(DISTDIR)/tests/data clean >/dev/null
	rm -f $(DISTDIR)/tests/e2a/corpus/*.o
	tar czf $(DISTDIR).tar.gz $(DISTDIR)
	rm -rf $(DISTDIR)
	@echo "wrote $(DISTDIR).tar.gz"
