# =============================================================================
# Makefile for CMU 15-213 Lecture 6 (machine-level programming IV:
# data & security -- structures, alignment, memory layout, defenses, unions)
# =============================================================================
#
#   make          oracles (real compiled structs.c) + native demos
#   make asm      build/structs.{Og,O1}.x86_64.s, and guarded.c compiled with
#                 and without the stack-protector (read by 05)
#   make run      run every demo
#   make clean
#
# The Python demos import x86sim from ../lecture03 (see course_path.py).
# -----------------------------------------------------------------------------

CC       ?= cc
ASMFLAGS := -std=c11 -Og -fno-asynchronous-unwind-tables -fomit-frame-pointer \
            -fno-stack-protector -fcf-protection=none
CFLAGS   := $(ASMFLAGS) -Wall -Wextra -g
UNAME_S  := $(shell uname -s)
UNAME_M  := $(shell uname -m)

ifeq ($(UNAME_M),x86_64)
  X86 :=
else ifeq ($(UNAME_S),Darwin)
  X86 := -arch x86_64
else
  X86 := NONE
endif

NATIVE := -std=c11 -Wall -Wextra -O1

.PHONY: all asm run clean
all: build/oracle build/oracle_x86 build/01_struct_layout build/01_struct_layout_x86 \
     build/03_memory_layout build/04_bounded_strings build/06_unions

build:
	mkdir -p build

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

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

build/01_struct_layout: 01_struct_layout.c structs.h | build
	$(CC) $(NATIVE) -o $@ 01_struct_layout.c

build/01_struct_layout_x86: 01_struct_layout.c structs.h | build
ifeq ($(X86),NONE)
	@echo "no x86-64 compiler here; skipping $@"
else
	$(CC) $(NATIVE) $(X86) -o $@ 01_struct_layout.c
endif

build/03_memory_layout: 03_memory_layout.c | build
	$(CC) $(NATIVE) -o $@ 03_memory_layout.c

build/04_bounded_strings: 04_bounded_strings.c | build
	$(CC) $(NATIVE) -o $@ 04_bounded_strings.c

build/06_unions: 06_unions.c structs.h | build
	$(CC) $(NATIVE) -o $@ 06_unions.c

asm: structs.c structs.h guarded.c | build
ifneq ($(X86),NONE)
	$(CC) $(ASMFLAGS) $(X86) -S -o build/structs.Og.x86_64.s structs.c
	$(CC) $(subst -Og,-O1,$(ASMFLAGS)) $(X86) -S -o build/structs.O1.x86_64.s structs.c
	# guarded.c compiled WITHOUT and WITH the stack-protector defense, for demo 05
	$(CC) -std=c11 -Og $(X86) -S -fno-stack-protector  -o build/guarded.nosp.x86_64.s guarded.c
	$(CC) -std=c11 -Og $(X86) -S -fstack-protector-all -o build/guarded.sp.x86_64.s   guarded.c
endif

run: all asm
	@./build/01_struct_layout
	@echo; python3 02_struct_code.py
	@echo; ./build/03_memory_layout
	@echo; ./build/04_bounded_strings
	@echo; python3 05_stack_protection.py
	@echo; ./build/06_unions

clean:
	rm -rf build __pycache__
