CC     = gcc
CFLAGS = -Wall -Wextra -O0 -g -pthread
TSAN   = -fsanitize=thread

GOOD   = race_counter counter_fixed producer_consumer deadlock

all: $(GOOD)

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

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

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

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

# ---- ThreadSanitizer build, for the tools slide ------------------------
tsan: race_counter.tsan

race_counter.tsan: race_counter.c
	$(CC) $(CFLAGS) $(TSAN) -o $@ $<

# ---- the race disappearing at -O2 --------------------------------------
race_counter.O2: race_counter.c
	$(CC) -Wall -Wextra -O2 -g -pthread -o $@ $<

# ---- the three assembly instructions behind counter++ -------------------
# Shows the body of bump(). Look for the load / add / store trio:
#     movq  counter(%rip), %rax
#     addq  $1, %rax
#     movq  %rax, counter(%rip)
asm:
	$(CC) -O0 -S race_counter.c -o - | sed -n '/^bump:/,/^[ \t]*ret/p' | grep -v '^[ \t]*\.'

# ---- running the TSan build --------------------------------------------
# On recent kernels TSan dies with "unexpected memory mapping" because ASLR
# entropy is higher than it expects. setarch -R turns ASLR off for the one
# process and needs no root. (The sudo alternative: sysctl vm.mmap_rnd_bits=28)
run-tsan: race_counter.tsan
	setarch $$(uname -m) -R ./race_counter.tsan

clean:
	rm -f $(GOOD) race_counter.tsan race_counter.O2

.PHONY: all tsan asm run-tsan clean
