# ---------------------------------------------------------------------------
# turbotools -- native tools for TurboDOS object code
#
# $Id: Makefile,v 1.5 2026/11/10 18:55:22 rec Exp rec $
#
# Author:  Robert Cousins
# Purpose: Build gen, disasm and serial: the three programs that need to know
#          something about TurboDOS, as distinct from the format-generic
#          tools that live in REL_tools.
#
#          The release contract: unpack turbotools-<version>.tar.gz in an
#          empty directory and
#
#                make ; sudo make install
#
#          There is no configure script.  Platform differences are handled by
#          the uname-driven block below.
#
# Depends: REL_tools' librel -- these programs read and write REL files and
#          none of them contains a copy of the codec.  LIBREL points at a
#          sibling REL_tools source tree by default; set it to an installed
#          location, or set RELPREFIX, to build against an installed library.
#
#          A C compiler accepting -std=c2x (gcc 13 or clang 19); libc.
#
# Note:    gcc 13.3 rejects -std=c23, so -std=c2x is the newest both
#          toolchains accept.  Every .c defines _POSIX_C_SOURCE 200809L
#          before its first include, because c2x is strict ISO and otherwise
#          hides most of POSIX.
#
# Versions:
#   1.4  2026-11-23  Robert Cousins  Version 1.4: a comment in disasm.c no
#                                    longer names a particular vendor's
#                                    boards; paired with REL_tools 1.7.
#   1.3  2026-11-10  Robert Cousins  Version 1.3: serial validates its numbers,
#                                    disasm is bounds-safe on hostile objects,
#                                    gen leaks nothing; tests/cli.sh ships.
#                                    Pairs with REL_tools 1.6.
#   1.2  2026-11-09  Robert Cousins  Objects depend on a stamp named for the
#                                    compiler's target, so a tree built for
#                                    one CPU is rebuilt, not patched, for
#                                    another.  Pairs with REL_tools 1.5,
#                                    whose librel fix gen inherits: a word
#                                    in one COMMON naming a label in another
#                                    is now deposited in the right block.
#   1.1  2026-09-10  Robert Cousins  Verified on 64-bit RISC-V as well as on
#                                    x86-64 Linux and FreeBSD: built both
#                                    cross-compiled and with a native riscv64
#                                    gcc, suite passing, and gen linking a
#                                    system byte-identical to the x86-64 one.
#                                    No code change was needed; this release
#                                    is the documentation of that and the
#                                    REL_tools 1.4 pairing.
#   1.0  2026-09-02  Robert Cousins  Initial version.  The programs were
#                                    previously built by the reconstruction's
#                                    tools/Makefile, alongside the generic
#                                    REL tools that have since moved to
#                                    REL_tools.
# ---------------------------------------------------------------------------

PKG      = turbotools
VERSION  = 1.4
DISTDIR  = $(PKG)-$(VERSION)

# ----- toolchain -----------------------------------------------------------

CC       ?= cc
CSTD     ?= -std=c2x
CWARN    ?= -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual \
            -Wstrict-prototypes
COPT     ?= -O2
CFLAGS   ?= $(CSTD) $(CWARN) $(COPT)
LDFLAGS  ?=
LIBS     ?=
INSTALL  ?= install

# ----- where librel comes from ---------------------------------------------
# Two arrangements, because both happen.  In the reconstruction and in the
# vendored copy inside the TurboDOS distribution, REL_tools sits beside this
# directory and is built from source.  Standing alone, the package builds
# against an installed REL_tools: set RELPREFIX (default /usr/local) and the
# headers and library are taken from there.

# A user who unpacks both tarballs gets a versioned REL_tools-1.4/ rather
# than REL_tools/, so the sibling is looked for under either name and the
# version is not written down here -- naming one would go stale the first
# time REL_tools moved, which it has.  The last element is the
# fallback when nothing matches: the wildcard test below then fails and the
# build uses an installed library instead.
LIBREL   ?= $(firstword $(wildcard ../REL_tools/librel ../REL_tools-*/librel) \
                        ../REL_tools/librel)

ifneq ($(wildcard $(LIBREL)/rel.h),)
    RELINC  = -I$(LIBREL)
    RELLIB  = $(LIBREL)/librel.a
    RELDEP  = $(LIBREL)/librel.a
else
    RELPREFIX ?= /usr/local
    RELINC  = -I$(RELPREFIX)/include
    RELLIB  = -L$(RELPREFIX)/lib -lrel
    RELDEP  =
endif

CPPFLAGS ?= -I.
CPPFLAGS += $(RELINC)

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

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
    PLATFORM_LIBS =
endif
ifeq ($(UNAME_S),FreeBSD)
    PLATFORM_LIBS =
endif
ifeq ($(UNAME_S),Darwin)
    PLATFORM_LIBS =
endif

# ----- install layout ------------------------------------------------------

PREFIX     ?= /usr/local
BINDIR     ?= $(PREFIX)/bin
MANDIR     ?= $(PREFIX)/share/man
DOCDIR     ?= $(PREFIX)/share/doc/$(PKG)

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

PROGS    = gen disasm serial
HDRS     = z80dis.h
MANS     = gen.1 disasm.1 serial.1

MANUAL   = $(PKG)_manual.pdf
MANSRC   = $(PKG)_manual.tex
PARTS    = manual/gen.tex manual/disasm.tex manual/serial.tex \
           manual/verify.tex

DISTFILES = Makefile README $(HDRS) gen.c disasm.c serial.c z80dis.c \
            $(MANS) $(MANSRC) $(PARTS) $(MANUAL) tests/run.sh tests/cli.sh \
            tests/t_dis.c

# ----- targets -------------------------------------------------------------

all: $(PROGS)

$(LIBREL)/librel.a:
	@test -d $(LIBREL) && $(MAKE) -C $(LIBREL) librel.a || true

gen: gen.o $(RELDEP)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ gen.o $(RELLIB) \
	    $(LIBS) $(PLATFORM_LIBS)

serial: serial.o $(RELDEP)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ serial.o $(RELLIB) \
	    $(LIBS) $(PLATFORM_LIBS)

disasm: disasm.o z80dis.o $(RELDEP)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ disasm.o z80dis.o $(RELLIB) \
	    $(LIBS) $(PLATFORM_LIBS)

disasm.o z80dis.o: $(HDRS)

# ----- one architecture per tree -------------------------------------------

# Every object depends on a stamp named for the compiler's target, so that a
# build for another CPU in the same tree -- a native make after a cross
# build, or the reverse -- rebuilds everything instead of recompiling only
# what changed and linking objects of two architectures together.  REL_tools
# 1.5 does the same, after exactly that happened in a RISC-V tree.
TARGET  := $(subst /,_,$(shell $(CC) -dumpmachine 2>/dev/null || uname -m))
STAMP    = .target-$(TARGET)

$(STAMP):
	rm -f .target-*
	@touch $@

OBJS     = gen.o serial.o disasm.o z80dis.o

$(OBJS): $(STAMP)

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

TESTS    = tests/t_dis

tests: $(TESTS)

# A test depends on its own source, so that editing it rebuilds it.
tests/%: tests/%.c z80dis.o $(HDRS)
	$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o $@ $< z80dis.o $(LIBS)

test check: $(PROGS) tests
	@sh tests/run.sh

# librel is SHARED with REL_tools and is not ours to leave in a strange
# state.  Building it with sanitizers and walking away leaves an archive that
# the next ordinary build links against and fails on, with a page of
# undefined __asan_* references and no clue where they came from.  So it is
# cleaned before, to be rebuilt instrumented, and cleaned after, to be
# rebuilt normally by whoever comes next.
sanitize-test:
	$(MAKE) clean
	-test -d $(LIBREL) && $(MAKE) -C $(LIBREL) clean
	$(MAKE) CFLAGS="$(CSTD) $(CWARN) -g -O1 \
	    -fsanitize=address,undefined" test
	$(MAKE) clean
	-test -d $(LIBREL) && $(MAKE) -C $(LIBREL) clean

man:
	@for m in $(MANS); do \
	    (mandoc -Tascii $$m || groff -mdoc -Tascii $$m) > /dev/null || \
	    exit 1; \
	done
	@echo "man pages format cleanly"

# Three pdflatex passes with makeindex between the first and second, which is
# what an index and a table of contents between them require.
manual: $(MANUAL)

$(MANUAL): $(MANSRC) $(PARTS)
	pdflatex -interaction=batchmode $(MANSRC) >/dev/null 2>&1 || true
	-makeindex -q $(PKG)_manual.idx >/dev/null 2>&1
	pdflatex -interaction=batchmode $(MANSRC) >/dev/null 2>&1 || true
	pdflatex -interaction=batchmode $(MANSRC) >/dev/null 2>&1 || true
	@test -f $(MANUAL) || { echo "manual build FAILED"; exit 1; }
	@# batchmode hides errors: a run with a hundred of them still exits 0
	@# and still writes a PDF, silently missing whatever it could not set.
	@# This has bitten twice, so the log is checked rather than trusted.
	@if grep -q '^!' $(PKG)_manual.log; then \
	    echo "*** LaTeX errors in $(PKG)_manual.log:"; \
	    grep -A3 '^!' $(PKG)_manual.log | head -40; \
	    exit 1; \
	fi
	@echo "$(MANUAL): `pdfinfo $(MANUAL) | awk '/^Pages/{print $$2}'` pages, no errors"

docs: manual man

install: $(PROGS)
	$(INSTALL) -d $(DESTDIR)$(BINDIR)
	@for p in $(PROGS); do \
	    $(INSTALL) -m 755 $$p $(DESTDIR)$(BINDIR)/$$p || exit 1; \
	done
	$(INSTALL) -d $(DESTDIR)$(MANDIR)/man1
	$(INSTALL) -m 644 $(MANS) $(DESTDIR)$(MANDIR)/man1/
	$(INSTALL) -d $(DESTDIR)$(DOCDIR)
	-$(INSTALL) -m 644 $(MANUAL) $(DESTDIR)$(DOCDIR)/$(MANUAL)

uninstall:
	@for p in $(PROGS); do rm -f $(DESTDIR)$(BINDIR)/$$p; done
	@for m in $(MANS); do rm -f $(DESTDIR)$(MANDIR)/man1/$$m; done
	rm -f $(DESTDIR)$(DOCDIR)/$(MANUAL)

dist: $(MANUAL)
	rm -rf $(DISTDIR)
	mkdir -p $(DISTDIR)/tests
	@for f in $(DISTFILES); do \
	    mkdir -p $(DISTDIR)/`dirname $$f`; \
	    cp $$f $(DISTDIR)/$$f; \
	done
	tar czf $(DISTDIR).tar.gz $(DISTDIR)
	rm -rf $(DISTDIR)

# Copy this package's files into a staging tree, for the reconstruction's
# dist target which vendors turbotools inside its own tarball.
distfiles:
	@for f in $(DISTFILES); do \
	    mkdir -p $(DESTBASE)/`dirname $$f`; \
	    cp $$f $(DESTBASE)/$$f; \
	done

clean:
	rm -f .target-*
	rm -f $(PROGS) $(TESTS) *.o core *.core
	rm -f *.aux *.log *.idx *.ilg *.ind *.toc *.out

distclean: clean
	rm -f $(MANUAL) $(DISTDIR).tar.gz

.PHONY: all tests test check sanitize-test man manual docs install uninstall \
        dist distfiles clean distclean
.SUFFIXES: .c .o
