# Example 4: Advanced PEB/LDR with Position Independent Code
# =============================================================================

CC = clang
AS = clang
LD = clang
OBJDUMP = llvm-objdump
OBJCOPY = llvm-objcopy
PYTHON = python3
TARGET = x86_64-w64-mingw32
OBFUSCATOR = ../../obfuscator/enc_pic_str

# PIC-safe compiler flags
COMMON_FLAGS = --target=$(TARGET) -fno-ident -fno-asynchronous-unwind-tables \
    -fno-vectorize -fno-slp-vectorize -fno-unwind-tables -fno-stack-protector \
    -fno-builtin -nostdlib -fdata-sections -ffunction-sections \
    -fomit-frame-pointer -fno-jump-tables -falign-functions=1 -mno-stack-arg-probe \
    -fno-builtin-memcpy -I../..

OPT_FLAGS = -Os

BUILD_DIR = build
SOURCE = main.c
OBFUSCATED = $(BUILD_DIR)/obfuscated.c
OUTPUT = $(BUILD_DIR)/example4.exe

.PHONY: all clean

all: clean $(OUTPUT)

$(BUILD_DIR):
	@mkdir -p $(BUILD_DIR)

$(OBFUSCATED): $(SOURCE) | $(BUILD_DIR)
	@echo "[*] Step 1: Obfuscating source..."
	$(OBFUSCATOR) -i $(SOURCE) -o $(OBFUSCATED)

$(BUILD_DIR)/pic.exe: $(OBFUSCATED)
	@echo "[*] Step 2: Compiling PIC Image..."
	@echo "WinMainCRTStartup" > $(BUILD_DIR)/order.txt
	$(CC) $(OBFUSCATED) $(OPT_FLAGS) $(COMMON_FLAGS) \
		-fuse-ld=lld \
		-Wl,-s \
		-Wl,-eWinMainCRTStartup \
		-Wl,--subsystem,windows \
		-Wl,/order:@$(BUILD_DIR)/order.txt \
		-Wl,/map:$(BUILD_DIR)/build.map \
		-o $(BUILD_DIR)/pic.exe

$(BUILD_DIR)/shellcode.bin: $(BUILD_DIR)/pic.exe
	@echo "[*] Step 3: Extracting Shellcode..."
	$(OBJCOPY) --dump-section .text=$(BUILD_DIR)/shellcode.bin $(BUILD_DIR)/pic.exe

$(BUILD_DIR)/stub.exe: minimal.s
	@echo "[*] Step 4: Creating Stub..."
	$(AS) --target=$(TARGET) -c minimal.s -o $(BUILD_DIR)/stub.o
	$(LD) --target=$(TARGET) $(BUILD_DIR)/stub.o -o $(BUILD_DIR)/stub.exe \
		-fuse-ld=lld -nostdlib \
		-Wl,--subsystem=windows \
		-Wl,--image-base=0x140000000 \
		-Wl,-s \
		-Wl,-e_mainCRTStartup

$(OUTPUT): $(BUILD_DIR)/shellcode.bin $(BUILD_DIR)/stub.exe
	@echo "[*] Step 5: Patching Shellcode into Stub..."
	$(PYTHON) patcher.py $(BUILD_DIR)/stub.exe $(BUILD_DIR)/shellcode.bin $(OUTPUT)
	@echo "[+] Success: $(OUTPUT)"

clean:
	@rm -rf $(BUILD_DIR)
