# Build the Week 7 RDTSC timing-check specimen.
#
# See ../anti_analysis_activity.md for the exercise. The binary is build
# output, not a tracked artifact -- it is in the root .gitignore, and `make`
# here recreates it. Addresses are NOT stable across compiler versions, so
# every address printed on the activity page is labelled as belonging to one
# particular build; re-derive yours with `make disas`.

CC     = gcc

# -O1 so the disassembly reads like release code rather than -O0 stack churn,
# but with the three flags that make the specimen teachable:
#
#   -fno-inline          keeps environment_is_clean(), evade() and payload()
#                        as separate functions, so there is something to break
#                        on and something to see in the call graph. ticks() is
#                        marked always_inline in the source and inlines anyway,
#                        which is the point -- both RDTSC instructions land
#                        inside the checking function.
#   -fno-pie -no-pie     fixed load address, so `break *0x...` and the
#                        addresses on the activity page mean the same thing in
#                        every run without `set disable-randomization`.
#   -g                   DWARF, so `set var delta = 0` works. A real sample has
#                        no symbols; the activity does the no-symbol version of
#                        the same bypass second, on purpose.
CFLAGS = -O1 -g -fno-inline -fno-pie -no-pie -Wall -Wextra

TARGET = timecheck

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

# The pair of RDTSC instructions and the comparison between them. This is the
# pattern to recognise; the addresses are yours, not the page's.
disas: $(TARGET)
	objdump -d --no-show-raw-insn -M intel $(TARGET) \
	    | sed -n '/<environment_is_clean>:/,/^$$/p'

# Sanity check that a flag edit has not quietly changed the specimen's shape.
check: $(TARGET)
	@nm $(TARGET) | grep -q " t environment_is_clean$$" \
	    || { echo "FAIL: environment_is_clean was inlined away"; exit 1; }
	@test $$(objdump -d $(TARGET) | grep -c rdtsc) -eq 2 \
	    || { echo "FAIL: expected exactly two rdtsc instructions"; exit 1; }
	@objdump -d $(TARGET) | sed -n '/<environment_is_clean>:/,/^$$/p' \
	    | grep -c rdtsc | grep -qx 2 \
	    || { echo "FAIL: the rdtsc pair is not both inside the check"; exit 1; }
	@echo "OK: two rdtsc reads, both inside environment_is_clean"

clean:
	rm -f $(TARGET) $(TARGET).upx $(TARGET).unpacked

.PHONY: disas check clean
