# shellcheck disable=SC2283,SC2046,SC2068,SC1089
# ^ cleaner lints this makefile as shell: `NAME = value`, `$(CFLAGS)` and a
#   recipe that is not a script are make syntax, not shell.
.POSIX:
.SUFFIXES:
.SUFFIXES: .c .o

# zash - a small, fast POSIX shell for z/OS UNIX.
#
# One flat makefile; the only make it runs again is `all`'s one-line
# choice of build for the host.
#
#   make                  build ./zash (Linux: clang, posix_spawn;
#                         z/OS: the ASCII z/OS build)
#   make check            run the test suite against ./zash
#   make asan             build ./zash-asan, run the suite under ASan + UBSan
#   make valgrind         run the test suite under Valgrind
#   make coverage         line coverage of the suite, gcc and gcov, into cov/
#   make bench            compare against other shells
#   make fuzz             fuzz the MVS decoders for FUZZTIME seconds (60)
#   make compdb           write compile_commands.json for clangd
#   make format           clang-format the sources
#   make tidy             clang-tidy the sources (runs compdb first)
#   make debug            ./zash-debug under lldb (ARGS='-c "echo hi"')
#   make attach           lldb -p $(PID)
#   make install          copy ./zash into $(DESTDIR)$(BINDIR)
#   make clean            remove what the targets above write
#
#   make spec             typeset formal/zash-spec.pdf with typst
#   make doc              the source reference, Doxygen into doc/
#   make other-docs       spec and doc: the documentation tools z/OS lacks
#   make docs             HTML and PDF of README.md and DESIGN.md, in docs/
#
#   make zos-ascii        z/OS default: 64-bit ASCII build of ./zash (IBM Open XL)
#   make zos-ebcdic       z/OS EBCDIC build of ./zash-ebcdic
#   make zos-check        z/OS: the functional tests, then the EBCDIC ones
#   make zos-heapcheck    z/OS: the same tests under LE heap checking
#   make zos-leakcheck    z/OS: the same tests, LE leak reports into build/leaks
#   make zos-lint         compile the z/OS code paths on Linux, shim headers
#   make mvs-asan         the suite with SYS_MVS forced on, under ASan
#   make zos-debug        z/OS debug build ./zash-dbg (dbx wants -g)
#   make zos-dbx          z/OS: ./zash-dbg under dbx (ARGS='-c "echo hi"')
#   make zos-attach       z/OS: dbx -a $(PID)
#   make zos-dump         z/OS: read an SVC or SYSMDUMP dump (DUMP=file)
#   make zos-amblist      z/OS: map the program object's CSECTs with AMBLIST

CC       = clang
CSTD     = -std=c23
WARN     = -Wall -Wextra -Wshadow -Wstrict-prototypes -Wmissing-prototypes \
           -Wconversion -Wno-sign-conversion
OPT      = -O2
CFLAGS   = $(CSTD) $(WARN) $(OPT) -g
CPPFLAGS = -D_XOPEN_SOURCE=700
LDFLAGS  =
SYS      = posix

SANFLAGS = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined \
           -fno-omit-frame-pointer

ZCC       = ibm-clang
# 64-bit.  A start used to cost 29 ms against 1 ms at 31 bits, and fork()
# 4.2 ms against 0.10; both were the 64-bit C run-time being loaded out of
# the linklist instead of the LPA.  With the run-time LPA-resident the two
# widths cost the same, so the shell is built at the width IBM builds for.
# bench/README.md and notes/investigation.md have the measurements.
ZCFLAGS   = $(CSTD) $(WARN) -O2 -m64

# _POSIX_C_SOURCE=200809L: z/OS exposes SUSv4 names only through it
# (_XOPEN_SOURCE 700 is not accepted).  _EXT: IBM extensions (fetch()).
ZCPPFLAGS = -D_XOPEN_SOURCE=600 -D_POSIX_C_SOURCE=200809L -D_ALL_SOURCE \
            -D_EXT -D_OPEN_SYS_FILE_EXT=1

PREFIX = /usr/local
BINDIR = $(PREFIX)/bin

# The line editor: "builtin" (no dependencies) or "libedit"
# (make EDIT=libedit LDLIBS=-ledit).
CLANG_FORMAT = clang-format
CLANG_TIDY   = clang-tidy

LLDB = lldb
DBGFLAGS = -O0 -g3 -fno-omit-frame-pointer 
# dbx is what z/OS has; lldb and gdb are not there.  (`NAME = value` is
# make syntax, as everywhere else in this file; z/OS make rejects `?=`.)
DBX = dbx
# dbx needs -g and read/write load; no optimisation or inlining.
ZDBGFLAGS = -O0 -g3 -m64 -fno-omit-frame-pointer
ARGS =
PID =
DUMP =
# LISTLOAD|LISTIDR|LISTOBJ, see mvs-diagnosis-tools-and-aids for the syntax
AMBLIST_STMT = LISTLOAD OUTPUT=BOTH


EDIT   = builtin
LDLIBS =

HDRS = src/ast.h src/charset.h src/exec.h src/expand.h src/interact.h src/mvsfmt.h \
       src/parser.h src/shell.h src/sys.h src/var.h
COMMON = src/alias.c src/arith.c src/builtin.c src/builtin_ext.c \
         src/complete.c src/cond.c src/exec.c src/expand.c src/history.c src/input.c \
         src/interact.c src/jobs.c src/main.c src/mvsfmt.c src/parser.c src/pattern.c \
         src/printf.c src/redir.c src/test.c src/trap.c src/unparse.c \
         src/util.c src/var.c src/edit_$(EDIT).c
OBJS = src/alias.o src/arith.o src/builtin.o src/builtin_ext.o \
       src/complete.o src/cond.o src/exec.o src/expand.o src/history.o src/input.o \
       src/interact.o src/jobs.o src/main.o src/mvsfmt.o src/parser.o src/pattern.o \
       src/printf.o src/redir.o src/test.o src/trap.o src/unparse.o \
       src/util.o src/var.o src/edit_$(EDIT).o src/sys_$(SYS).o

# z/OS builds zash with IBM Open XL (ibm-clang, not clang) and without
# posix_spawn, so plain `make` builds the ASCII z/OS build there.  z/OS make
# is POSIX make, with no $(shell) and no conditionals, so the shell picks.
all:
	@uname -s | grep OS/390 >/dev/null && exec $(MAKE) zos-ascii; $(MAKE) zash

zash: $(OBJS)
ifeq ($(shell uname -s),OS/390)
	@exec $(MAKE) zos-ascii
else
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)
endif

# The z/OS default build: 64-bit XPLINK, ASCII characters.  `make` and
# `make zash` both land here on z/OS.


# Debug build: unoptimised, full debug info, separate binary.
zash-debug: $(COMMON) src/sys_posix.c $(HDRS)
	$(CC) $(CPPFLAGS) $(CSTD) $(WARN) $(DBGFLAGS) -o $@ $(COMMON) src/sys_posix.c \
	    $(LDLIBS)

# make debug ARGS='-c "echo hi"'
debug: zash-debug
	$(LLDB) -- ./zash-debug $(ARGS)


# make attach PID=12345
attach:
	@if [ -z "$(PID)" ]; then echo 'usage: make attach PID=pid' >&2; exit 2; fi
	$(LLDB) -p $(PID)


# z/OS debug build: same sources, -O0 -g3, no inlining.
zos-debug: zash-dbg

zash-dbg: $(COMMON) src/sys_zos.c $(HDRS)
	$(ZCC) $(ZCPPFLAGS) $(CSTD) $(WARN) $(ZDBGFLAGS) -fzos-le-char-mode=ascii \
	    -o $@ $(COMMON) src/sys_zos.c $(LDLIBS)

# make zos-dbx ARGS='-c "echo hi"'
#
# Subcommands worth knowing: `st in main` to stop in a function, where,
# next, print, dump, catch SIGNAL, and multproc on|parent|child to follow
# a fork or spawn.  Break by function or address here: with ibm-clang's
# debug info dbx reports `st at "file":line` as source not found, though
# next and where do report file and line.  A dump taken by the system is
# read with `make zos-dump DUMP=file` (dbx reads SVC and SYSMDUMP dumps,
# not SYSUDUMP or CEEDUMP).
zos-dbx: zash-dbg
	$(DBX) ./zash-dbg $(ARGS)

# make zos-attach PID=12345
zos-attach: zash-dbg
	@if [ -z "$(PID)" ]; then echo 'usage: make zos-attach PID=pid' >&2; exit 2; fi
	$(DBX) -a $(PID) ./zash-dbg

# make zos-dump DUMP=/tmp/sysmdu
zos-dump: zash-dbg
	@if [ -z "$(DUMP)" ]; then echo 'usage: make zos-dump DUMP=file' >&2; exit 2; fi
	$(DBX) -C $(DUMP) ./zash-dbg

# Map the CSECTs, AMODE/RMODE and entry points of the built program object.
# amblist reads the control statement on stdin and needs a leading blank;
# the output is long, so it goes to a file.
zos-amblist: zos-ascii
	echo ' $(AMBLIST_STMT)' | amblist ./zash > zash.amblist





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

$(OBJS): $(HDRS)

# Variant builds are one compile-and-link each: no second object tree.
# The Linux build with the z/OS code paths switched on (SYS_MVS) over the
# Linux platform layer, under ASan and UBSan: exercises the tagging hooks,
# _TAG_REDIR_* handling and ZOS_* variables in everything but the calls.
zash-mvslint: $(COMMON) src/sys_posix.c $(HDRS)
	$(CC) $(CPPFLAGS) -DZASH_LINT_MVS $(CSTD) $(WARN) $(SANFLAGS) -o $@ \
	    $(COMMON) src/sys_posix.c $(LDLIBS)

mvs-asan: zash-mvslint
	ASAN_OPTIONS=detect_leaks=1 sh tests/run.sh ./zash-mvslint

zash-asan: $(COMMON) src/sys_posix.c $(HDRS)
	$(CC) $(CPPFLAGS) $(CSTD) $(WARN) $(SANFLAGS) -o $@ $(COMMON) src/sys_posix.c \
	    $(LDLIBS)

# z/OS: ASCII is the build zopen uses, and the one ./zash is.  EBCDIC
# goes to its own name so the two never overwrite each other: make would
# otherwise call a rebuild of the other mode "up to date" and leave the
# old one in place.
zos-ascii: $(COMMON) src/sys_zos.c $(HDRS)
	$(ZCC) $(ZCPPFLAGS) $(ZCFLAGS) -fzos-le-char-mode=ascii -o zash \
	    $(COMMON) src/sys_zos.c $(LDLIBS)

zos-ebcdic: $(COMMON) src/sys_zos.c $(HDRS)
	$(ZCC) $(ZCPPFLAGS) $(ZCFLAGS) -fzos-le-char-mode=ebcdic -o zash-ebcdic \
	    $(COMMON) src/sys_zos.c $(LDLIBS)

# /bin/sleep on z/OS takes whole seconds -- "0.3" is an error -- and the
# tests order background jobs with sub-second sleeps.  The z/OS test runs
# put a sleep that takes fractions in front of PATH.
ZTOOLS = build/zos-tools

$(ZTOOLS)/sleep: tests/tools/zos-sleep.c
	@mkdir -p $(ZTOOLS)
	$(ZCC) $(ZCPPFLAGS) $(CSTD) -O2 -m32 -Wall -Wextra \
	    -fzos-le-char-mode=ascii -o $@ tests/tools/zos-sleep.c

# The start-up benchmark's clock.  The compiler is chosen in the recipe,
# not by a conditional: z/OS make has .IF, GNU make has ifeq, and one
# recipe both understand is cheaper than two make dialects.  The z/OS
# build is EBCDIC, because the harness that reads the number is the
# system's sh.
$(ZTOOLS)/now: tests/tools/now.c
	@mkdir -p $(ZTOOLS)
	@if uname -s | grep -q OS/390; then \
	    $(ZCC) $(ZCPPFLAGS) $(CSTD) -O2 -m32 -Wall -Wextra \
	        -o $@ tests/tools/now.c; \
	else \
	    $(CC) $(CPPFLAGS) $(CSTD) -O2 -Wall -Wextra -o $@ tests/tools/now.c; \
	fi

# One child at a time, wall and CPU.  `bench/le-init.sh` cannot use a shell
# loop for that: on z/OS the shell is an LE program, so its children would
# pay the shell's own LE price instead of the price of a bare start.
$(ZTOOLS)/spawn: tests/tools/spawn.c
	@mkdir -p $(ZTOOLS)
	@if uname -s | grep -q OS/390; then \
	    $(ZCC) $(ZCPPFLAGS) $(CSTD) -O2 -m32 -Wall -Wextra \
	        -o $@ tests/tools/spawn.c; \
	else \
	    $(CC) $(CPPFLAGS) $(CSTD) -O2 -Wall -Wextra -o $@ tests/tools/spawn.c; \
	fi

# On z/OS the `zash` build above wants clang and posix_spawn, so run the z/OS
# build and both its test passes instead.
check:
	@if uname -s | grep OS/390 >/dev/null; then \
	    $(MAKE) zos-check; \
	else \
	    $(MAKE) zash && sh tests/run.sh ./zash; \
	fi

# z/OS has no ASan, but Language Environment can put a check zone after
# every heap element and validate the heap on every request, which turns
# an overlay into a U4042 abend.  Meant for a run on the real system:
#   make zos-heapcheck
zos-heapcheck: $(ZTOOLS)/sleep
	_CEE_RUNOPTS='HEAPZONES(0,ABEND,32,ABEND) HEAPCHK(ON)' \
	    PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash

# LE's other checker: no per-call heap walk, but a report at normal
# termination naming every allocation still live at exit.  Each process
# writes one CEEDUMP into build/leaks, for reading when a leak is
# suspected; tests/zos/leak.sh is the part that fails by itself.
#
# zash/limits dies of storage exhaustion here: the checker keeps an entry
# for every allocation still live, and that test recurses very deep.
#
#   make zos-leakcheck
zos-leakcheck: zos-ascii $(ZTOOLS)/sleep
	@rm -rf build/leaks && mkdir -p build/leaks
	_CEE_RUNOPTS='HEAPCHK(ON,0,0,16,0)' \
	    _CEE_DMPTARG="$$(pwd)/build/leaks" \
	    ZASH_TEST_SKIP='zash/limits' \
	    PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash
	@echo "reports in build/leaks: $$(ls build/leaks | wc -l)"

asan: zash-asan
	ASAN_OPTIONS=detect_leaks=1:abort_on_error=0 sh tests/run.sh ./zash-asan

# Valgrind emulates posix_spawn() with fork+exec and so cannot hand an exec
# failure back to the caller, and it does not let a program lower its own
# descriptor limit; the two tests that need those are left out.
# Compile the z/OS build's C on Linux, as far as that can go: sys_zos.c
# against declarations transcribed from the z/OS headers
# (tests/tools/zos-shim), everything else with SYS_MVS forced on.  Catches
# type errors and warnings in code that only z/OS would otherwise see.
zos-lint:
	$(CC) $(CSTD) $(WARN) -D_XOPEN_SOURCE=700 -D_DEFAULT_SOURCE \
	    -Itests/tools/zos-shim -include tests/tools/zos-shim/zos_shim.h \
	    -fsyntax-only src/sys_zos.c
	for f in $(COMMON); do \
	    $(CC) $(CPPFLAGS) $(CSTD) $(WARN) -DZASH_LINT_MVS -fsyntax-only $$f || exit 1; \
	done

# Fuzz the MVS decoders (needs clang with libFuzzer): FUZZTIME seconds.
FUZZTIME = 60
fuzz-mvsfmt: fuzz/mvsfmt.c src/mvsfmt.c src/mvsfmt.h src/charset.h
	$(CC) $(CSTD) $(WARN) -g -O1 -fsanitize=fuzzer,address,undefined \
	    -fno-sanitize-recover=all -o $@ fuzz/mvsfmt.c src/mvsfmt.c

fuzz: fuzz-mvsfmt
	mkdir -p fuzz/corpus
	./fuzz-mvsfmt -max_total_time=$(FUZZTIME) -max_len=4096 fuzz/corpus

valgrind: zash
	ZASH_TEST_WRAP="valgrind -q --error-exitcode=99 --trace-children=no --leak-check=full --errors-for-leak-kinds=definite" \
	ZASH_TEST_SKIP="posix/execfail scripts/library zash/ulimit" sh tests/run.sh ./zash

# z/OS: behaviour only (no sanitizers or Valgrind there), against the
# ./zash that zos-ascii or zos-ebcdic built.
zos-check: zos-ascii zos-ebcdic $(ZTOOLS)/sleep
	PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash
	PATH="$$(pwd)/$(ZTOOLS):$$PATH" sh tests/run.sh ./zash-ebcdic zos/ebcdic

bench: zash $(ZTOOLS)/now $(ZTOOLS)/spawn
	sh bench/run.sh $$(pwd)/zash
	sh bench/startup.sh $$(pwd)/zash

compdb:
	@{ printf '[\n'; first=1; \
	for f in $(COMMON) src/sys_$(SYS).c; do \
	    [ "$$first" = 1 ] || printf ',\n'; first=0; \
	    printf '{"directory":"%s","file":"%s","command":"%s %s %s -c %s"}' \
	        "$$(pwd)" "$$f" "$(CC)" "$(CPPFLAGS)" "$(CSTD) $(WARN)" "$$f"; \
	done; printf '\n]\n'; } > compile_commands.json

format:
	$(CLANG_FORMAT) -i src/*.c src/*.h

# Line coverage of the test suite, with GCC and gcov.  One compile command;
# the counters land in cov/.  Prints a per-file summary; `gcov` leaves the
# annotated sources in cov/*.gcov.
coverage:
	rm -rf cov && mkdir cov
	gcc $(CPPFLAGS) $(CSTD) -O0 --coverage -DZASH_COVERAGE -o cov/zash \
	    $(COMMON) src/sys_posix.c $(LDLIBS)
	-sh tests/run.sh cov/zash
	gcov -o cov cov/zash-*.gcda >cov/gcov.log 2>&1; mv ./*.gcov cov/; \
	cd cov && \
	awk '/^File .src\//{f=$$2} /^Lines executed/ && f {split($$2,a,":"); \
	    printf "%-24s %7s of %s\n", f, a[2], $$4; f=""}' gcov.log | tr -d "'"; \
	tail -n 1 gcov.log

# The source reference.  docs/html/ for browsing, and docs/zash-reference.pdf
# as one file to send: Doxygen's LaTeX output built with pdflatex, which needs
# its packages installed (Fedora: texlive-{amsfonts,wasysym,fancyhdr,cmap,
# tocbibind,etoolbox,float,varwidth,adjustbox,alphalph,caption,changepage,
# enumitem,etoc,fancyvrb,geometry,hanging,multirow,natbib,newunicodechar,
# stackengine,tabularray,tocloft,ulem,xltabular,ec,cm-super,metafont,
# collection-fontsrecommended}).  Without pdflatex, docs/html is all you get.
# The LaTeX build is quiet unless it fails; its log is docs/latex.log.
doc:
	@rm -rf docs/html docs/latex docs/zash-reference.pdf
	doxygen Doxyfile
	@if command -v pdflatex >/dev/null 2>&1; then \
	    $(MAKE) -C docs/latex > docs/latex.log 2>&1 \
	        && cp docs/latex/refman.pdf docs/zash-reference.pdf \
	        && echo "docs/zash-reference.pdf"; \
	else \
	    echo "doc: pdflatex not found, docs/html only"; \
	fi

# HTML and PDF of the two documents, in docs/ (which is not committed).
# The PDF comes from the HTML through a headless browser, so no LaTeX
# installation is needed; without one, the HTML is still written.
# The colours are the ones formal/zash-spec.typ uses.
# z/OS make has no $(shell) and rejects ?=, so the recipe finds the browser.
# Set CHROME on the command line to override it.
DOCS = README DESIGN
CHROME =

docs: doc
	@mkdir -p docs
	printf '%s\n' \
	    'body { max-width: 46em; margin: 2em auto; padding: 0 1em;' \
	    '       font: 16px/1.55 Helvetica, Arial, sans-serif; color: #1b1f24;' \
	    '       -webkit-print-color-adjust: exact; print-color-adjust: exact; }' \
	    'h1 { border-bottom: 2px solid #3fb950; padding-bottom: .2em; }' \
	    'a { color: #1f5fa8; }' \
	    'code { color: #7a3e9d; }' \
	    'pre { background: #f6f8fa; border: 1px solid #d0d7de; padding: .6em;' \
	    '      white-space: pre-wrap; }' \
	    'th { background: #eef3fb; }' \
	    'tr:nth-child(even) td { background: #fafbfc; }' \
	    'blockquote { border-left: 4px solid #3fb950; margin-left: 0;' \
	    '             padding-left: 1em; color: #57606a; }' \
	    'img { max-width: 100%; }' > docs/style.css
	for d in $(DOCS); do \
	    awk '/^<p align="center">$$/{print "<p align=\"center\"><img " \
	        "src=\"packaging/zash-logo.svg\" alt=\"zash\" width=\"128\"></p>"; \
	        skip=1; next} skip && /^<\/p>$$/{skip=0; next} !skip' \
	        $$d.md > docs/$$d.md; \
	    pandoc -s --embed-resources --resource-path=. \
	        --metadata pagetitle="zash $$d" --css docs/style.css \
	        -o docs/$$d.html docs/$$d.md || exit 1; \
	    rm -f docs/$$d.md; \
	    chrome="$(CHROME)"; \
	    [ -n "$$chrome" ] || \
	        chrome=$$(command -v google-chrome || command -v chromium || \
	            command -v chromium-browser); \
	    if [ -n "$$chrome" ]; then \
	        $$chrome --headless --disable-gpu --no-sandbox \
	            --no-pdf-header-footer --user-data-dir=docs/.chrome \
	            --print-to-pdf="$$(pwd)/docs/$$d.pdf" \
	            "file://$$(pwd)/docs/$$d.html" >/dev/null 2>&1 || exit 1; \
	    else \
	        echo "docs: no browser found, docs/$$d.html only"; \
	    fi; \
	done

# The language specification: formal/zash-spec.typ, typeset by typst.
spec:
	sh build/spec-pdf.sh

# The documentation that needs a tool z/OS does not have: typst for the
# specification, Doxygen for the source reference.
other-docs: spec doc

tidy: compdb
	$(CLANG_TIDY) $(COMMON) src/sys_$(SYS).c

# No prerequisite: on z/OS the generic zash target needs objects that only
# the Linux build produces.  zopen builds first and then installs.
install:
	mkdir -p $(DESTDIR)$(BINDIR)
	cp zash $(DESTDIR)$(BINDIR)/zash

clean:
	rm -f zash zash-asan zash-dbg zash-debug zash-mvslint fuzz-mvsfmt \
	    src/*.o compile_commands.json
	rm -f zash.amblist
	rm -rf docs cov $(ZTOOLS)

.PHONY: fuzz zos-lint mvs-asan all check asan valgrind bench compdb format tidy \
        doc docs spec other-docs coverage install clean \
        zos-ascii zos-ebcdic zos-check zos-heapcheck zos-leakcheck zos-debug \
        zos-dbx zos-attach zos-dump zos-amblist
