# 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 (ASan + UBSan) and test it
#   make valgrind         run the test suite under Valgrind
#   make bench            compare against other shells
#   make compdb           write compile_commands.json for clangd
#   make zos-ascii        z/OS build, ASCII program (IBM Open XL C/C++)
#   make zos-ebcdic       z/OS build, EBCDIC program
#   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-debug        z/OS debug build ./zash-dbg (dbx wants -g)
#   make zos-dbx          z/OS: run ./zash-dbg under dbx
#   make zos-amblist      z/OS: map the program object's CSECTs with AMBLIST
#   make docs             HTML and PDF of README.md and DESIGN.md, in docs/
#   make doc              the source reference, Doxygen into docs/
#   make format / tidy

CC       = clang
CSTD     = -std=c17
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
# 31-bit: a 64-bit fork() costs 4.2 ms and a 32-bit one 0.10 ms on z/OS,
# and a trivial program starts in 29.5 ms against 1.1 ms.  bench/README.md
# has the measurements.  Nothing in the sources needs 64 bits, so this is
# the whole fix for the fork-heavy benchmarks.
ZCFLAGS   = $(CSTD) $(WARN) -O2 -m32

# _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 -m32 -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)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)


# 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

# 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:
	@uname -s | grep OS/390 >/dev/null && exec make zos-check || $(MAKE) zash
	sh tests/run.sh ./zash

# 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

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
	sh bench/run.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.
DOCS = README DESIGN
CHROME ?= $(shell command -v google-chrome || command -v chromium || \
    command -v chromium-browser)

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; \
	    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

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

install: zash
	mkdir -p $(DESTDIR)$(BINDIR)
	cp zash $(DESTDIR)$(BINDIR)/zash

clean:
	rm -f zash zash-asan zash-dbg zash-mvslint 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 coverage install clean \
        zos-ascii zos-ebcdic zos-check zos-heapcheck zos-debug zos-dbx \
        zos-attach zos-dump zos-amblist
