# =============================================================================
# Makefile for CMU 15-213 Lecture 3 (machine-level programming I: basics)
# =============================================================================
#
#   make          build the oracle programs (real compiled funcs.c):
#                   build/oracle      for this machine
#                   build/oracle_x86  for x86-64 (Apple Silicon: runs under Rosetta 2)
#   make asm      build/funcs.x86_64.s (x86-64, AT&T syntax) and, on a non-x86
#                 machine, build/funcs.native.s for comparison
#   make disasm   objdump -d of the x86-64 object file: addresses + machine code bytes
#   make run      run every Python demo (they also compile what they need themselves)
#   make clean
#
# The asm flags make the output look like the textbook's:
#   -Og                              "debug-friendly" optimization (CS:APP uses it)
#   -fno-asynchronous-unwind-tables  drop the .cfi_* directives
#   -fomit-frame-pointer             no push %rbp / mov %rsp,%rbp boilerplate
#   -fno-stack-protector             no stack canary code (Lecture 6)
#   -fcf-protection=none             no endbr64 instructions
# -----------------------------------------------------------------------------

CC      ?= cc
ASMFLAGS := -std=c11 -Og -fno-asynchronous-unwind-tables -fomit-frame-pointer \
            -fno-stack-protector -fcf-protection=none
# The oracles use the SAME flags, so their machine code matches the listing.
CFLAGS  := $(ASMFLAGS) -Wall -Wextra -g
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)

# How to target x86-64 from this machine (empty on an x86-64 machine).
ifeq ($(UNAME_M),x86_64)
  X86 :=
else ifeq ($(UNAME_S),Darwin)
  X86 := -arch x86_64
else
  X86 := NONE
endif

PY := 01_c_to_machine_code.py 02_trace_swap.py 03_arith_and_lea.py \
      04_operands_and_sizes.py 05_condition_codes.py 06_crosscheck.py

.PHONY: all asm disasm run clean
all: build/oracle build/oracle_x86

build:
	mkdir -p build

build/oracle: oracle.c funcs.c funcs.h | build
	$(CC) $(CFLAGS) -o $@ oracle.c funcs.c

build/oracle_x86: oracle.c funcs.c funcs.h | build
ifeq ($(X86),NONE)
	@echo "no x86-64 compiler here; skipping $@"
else
	$(CC) $(CFLAGS) $(X86) -o $@ oracle.c funcs.c
endif

asm: funcs.c funcs.h | build
ifneq ($(X86),NONE)
	$(CC) $(ASMFLAGS) $(X86) -S -o build/funcs.x86_64.s funcs.c
endif
ifneq ($(UNAME_M),x86_64)
	$(CC) -std=c11 -Og -fno-asynchronous-unwind-tables -S -o build/funcs.native.s funcs.c
endif

disasm: funcs.c funcs.h | build
	$(CC) $(ASMFLAGS) $(X86) -c -o build/funcs.x86_64.o funcs.c
	objdump -d build/funcs.x86_64.o

run: all
	@for p in $(PY); do echo; python3 $$p; done

clean:
	rm -rf build __pycache__
