TOP = .

# Cross-compiler osclass toolchain
CC	:= i386-osclass-aout-gcc -pipe
GCC_LIB := $(shell $(CC) -print-libgcc-file-name)
AS	:= i386-osclass-aout-as
AR	:= i386-osclass-aout-ar
LD	:= i386-osclass-aout-ld
OBJCOPY	:= i386-osclass-aout-objcopy
OBJDUMP	:= i386-osclass-aout-objdump

# Native commands
NCC	:= gcc $(CC_VER) -pipe
TAR	:= gtar
PERL	:= perl

# Compiler flags
# Note that -O2 is required for the boot loader to fit within 512 bytes;
# -fno-builtin is required to avoid refs to undefined functions in the kernel.
DEFS	:=
CFLAGS	:= $(CFLAGS) $(DEFS) -O2 -fno-builtin -I$(TOP) -MD -MP -Wall -Wno-format -ggdb -Iuser/

# Linker flags for user programs
ULDFLAGS := -Ttext 0x800020

# Lists that the */Makefrag makefile fragments will add to
OBJDIRS :=
CLEAN_FILES := .deps bochs.log
CLEAN_PATS := *.o *.d *.asm *~


# Make sure that 'all' is the first target
all:


# Include Makefrags for subdirectories
include kern/Makefrag
include boot/Makefrag
include user/Makefrag
include fs/Makefrag

# Eliminate default suffix rules
.SUFFIXES:
                                                                                

# Rules for building regular object files
%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<
%.o: %.S
	$(CC) $(CFLAGS) -c -o $@ $<


# For embedding one program in another
%.b.c: %.b
	rm -f $@
	$(TOP)/tools/bintoc/bintoc $< $*_bin > $@~ && $(MV) -f $@~ $@
%.b.s: %.b
	rm -f $@
	$(TOP)/tools/bintoc/bintoc -S $< $*_bin > $@~ && $(MV) -f $@~ $@



bochs: kern/bochs.img fs/fs.img
	bochs-nogui

kernel.asm: kern/kernel
	$(OBJDUMP) -S --adjust-vma=0xf00ff000 kern/kernel >kernel.asm

# For cleaning the source tree
clean:
	rm -rf $(CLEAN_FILES) $(foreach dir,$(OBJDIRS), \
				$(addprefix $(dir)/,$(CLEAN_PATS)))

grade:
	@gmake clean >/dev/null 2>/dev/null
	gmake all
	sh grade.sh
	@gmake clean >/dev/null 2>/dev/null

handin: clean
	-rm -f handin5.tgz
	tar cf - . | gzip | uuencode handin.tar.gz | mail 6.828-handin@pdos.lcs.mit.edu

showoff: clean
	-rm -f handin5.tgz
	tar cf - . | gzip | uuencode showoff.tar.gz | mail 6.828-handin@pdos.lcs.mit.edu

# For test runs
run-%:
	@rm -f kern/init.o kern/bochs.img
	@gmake "DEFS=-DTEST=binary_user_$*_start -DTESTSIZE=binary_user_$*_size" kern/bochs.img fs/fs.img
	bochs-nogui

xrun-%:
	@rm -f kern/init.o kern/bochs.img
	@gmake "DEFS=-DTEST=binary_user_$*_start -DTESTSIZE=binary_user_$*_size" kern/bochs.img fs/fs.img
	bochs

# This magic automatically generates makefile dependencies
# for header files included from C source files we compile,
# and keeps those dependencies up-to-date every time we recompile.
# See 'mergedep.pl' for more information.
.deps: $(foreach dir, $(OBJDIRS), $(wildcard $(dir)/*.d))
	@$(PERL) mergedep.pl $@ $^

-include .deps

.phony: lab%.tar.gz

