aboutsummaryrefslogtreecommitdiffstats
path: root/gpxe/src/Makefile.housekeeping
blob: 1f5e115f20d7e107d3e7d8374b749c4564f561a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
# -*- makefile -*- : Force emacs to use Makefile mode
#
# This file contains various boring housekeeping functions that would
# otherwise seriously clutter up the main Makefile.

###############################################################################
#
# Find a usable "echo -e" substitute.
#
TAB 			:= $(shell $(PRINTF) '\t')
ECHO_E_ECHO		:= $(ECHO)
ECHO_E_ECHO_E		:= $(ECHO) -e
ECHO_E_BIN_ECHO 	:= /bin/echo
ECHO_E_BIN_ECHO_E 	:= /bin/echo -e
ECHO_E_ECHO_TAB		:= $(shell $(ECHO_E_ECHO) '\t' | cat)
ECHO_E_ECHO_E_TAB	:= $(shell $(ECHO_E_ECHO_E) '\t' | cat)
ECHO_E_BIN_ECHO_TAB 	:= $(shell $(ECHO_E_BIN_ECHO) '\t')
ECHO_E_BIN_ECHO_E_TAB 	:= $(shell $(ECHO_E_BIN_ECHO_E) '\t')

ifeq ($(ECHO_E_ECHO_TAB),$(TAB))
ECHO_E		:= $(ECHO_E_ECHO)
endif
ifeq ($(ECHO_E_ECHO_E_TAB),$(TAB))
ECHO_E		:= $(ECHO_E_ECHO_E)
endif
ifeq ($(ECHO_E_BIN_ECHO_TAB),$(TAB))
ECHO_E		:= $(ECHO_E_BIN_ECHO)
endif
ifeq ($(ECHO_E_BIN_ECHO_E_TAB),$(TAB))
ECHO_E		:= $(ECHO_E_BIN_ECHO_E)
endif

.echocheck :
ifdef ECHO_E
	@$(TOUCH) $@
else
	@$(PRINTF) '%24s : x%sx\n' 'tab' '$(TAB)'
	@$(PRINTF) '%24s : x%sx\n' '"$(ECHO_E_ECHO) \t"' \
				    '$(ECHO_E_ECHO_TAB)'
	@$(PRINTF) '%24s : x%sx\n' '"$(ECHO_E_ECHO_E) \t"' \
				    '$(ECHO_E_ECHO_E_TAB)'
	@$(PRINTF) '%24s : x%sx\n' '"$(ECHO_E_BIN_ECHO) \t"' \
				    '$(ECHO_E_BIN_ECHO_TAB)'
	@$(PRINTF) '%24s : x%sx\n' '"$(ECHO_E_BIN_ECHO_E) \t"' \
				    '$(ECHO_E_BIN_ECHO_E_TAB)'
	@$(ECHO) "No usable \"echo -e\" substitute found"
	@exit 1
endif
MAKEDEPS	+= .echocheck
VERYCLEANUP	+= .echocheck

echo :
	@$(ECHO) "Using \"$(ECHO_E)\" for \"echo -e\""

###############################################################################
#
# Generate a usable "seq" substitute
#
define seq
	$(shell awk 'BEGIN { for ( i = $(1) ; i <= $(2) ; i++ ) print i }')
endef

###############################################################################
#
# Determine host OS
#
HOST_OS		:= $(shell uname -s)
hostos :
	@$(ECHO) $(HOST_OS)

###############################################################################
#
# Determine compiler

CCDEFS		:= $(shell $(CC) -E -x c -c /dev/null -dM | cut -d" " -f2)
ccdefs:
	@$(ECHO) $(CCDEFS)

ifeq ($(filter __ICC,$(CCDEFS)),__ICC)
CCTYPE		:= icc
else
CCTYPE		:= gcc
endif
cctype:
	@$(ECHO) $(CCTYPE)

###############################################################################
#
# Check for tools that can cause failed builds
#
.toolcheck :
	@if $(CC) -v 2>&1 | grep -is 'gcc version 2\.96' > /dev/null; then \
		$(ECHO) 'gcc 2.96 is unsuitable for compiling Etherboot'; \
		$(ECHO) 'Use gcc 2.95 or gcc 3.x instead'; \
		exit 1; \
	fi
	@if [ `perl -e 'use bytes; print chr(255)' | wc -c` = 2 ]; then \
		$(ECHO) 'Your Perl version has a Unicode handling bug'; \
		$(ECHO) 'Execute this command before compiling Etherboot:'; \
		$(ECHO) 'export LANG=$${LANG%.UTF-8}'; \
		exit 1; \
	fi
	@$(TOUCH) $@
MAKEDEPS	+= .toolcheck
VERYCLEANUP	+= .toolcheck

###############################################################################
#
# Check for various tool workarounds
#

# Make syntax does not allow use of comma or space in certain places.
# This ugly workaround is suggested in the manual.
#
COMMA	:= ,
EMPTY	:=
SPACE	:= $(EMPTY) $(EMPTY)

# Check for an old version of gas (binutils 2.9.1)
#
OLDGAS	:= $(shell $(AS) --version | grep -q '2\.9\.1' && $(ECHO) -DGAS291)
CFLAGS	+= $(OLDGAS)
oldgas :
	@$(ECHO) $(oldgas)

# Some widespread patched versions of gcc include -fstack-protector by
# default, even when -ffreestanding is specified.  We therefore need
# to disable -fstack-protector if the compiler supports it.
#
ifeq ($(CCTYPE),gcc)
SP_TEST = $(CC) -fno-stack-protector -x c -c /dev/null \
		-o /dev/null >/dev/null 2>&1
SP_FLAGS := $(shell $(SP_TEST) && $(ECHO) '-fno-stack-protector')
CFLAGS	+= $(SP_FLAGS)
endif

# gcc 4.4 generates .eh_frame sections by default, which distort the
# output of "size".  Inhibit this.
#
ifeq ($(CCTYPE),gcc)
CFI_TEST = $(CC) -fno-dwarf2-cfi-asm -x c -c /dev/null \
		 -o /dev/null >/dev/null 2>&1
CFI_FLAGS := $(shell $(CFI_TEST) && $(ECHO) '-fno-dwarf2-cfi-asm')
CFLAGS	+= $(CFI_FLAGS)
endif

# Some versions of gas choke on division operators, treating them as
# comment markers.  Specifying --divide will work around this problem,
# but isn't available on older gas versions.
#
DIVIDE_TEST = $(AS) --divide /dev/null -o /dev/null 2>/dev/null
DIVIDE_FLAGS := $(shell $(DIVIDE_TEST) && $(ECHO) '--divide')
ASFLAGS	+= $(DIVIDE_FLAGS)

###############################################################################
#
# Build verbosity
#
ifeq ($(V),1)
Q :=
QM := @\#
else
Q := @
QM := @
endif

###############################################################################
#
# Set BIN according to whatever was specified on the command line as
# the build target.
#

# Determine how many different BIN directories are mentioned in the
# make goals.
#
BIN_GOALS	:= $(filter bin/% bin-%,$(MAKECMDGOALS))
BIN_GOAL_BINS	:= $(foreach BG,$(BIN_GOALS),$(firstword $(subst /, ,$(BG))))
NUM_BINS	:= $(words $(sort $(BIN_GOAL_BINS)))

ifeq ($(NUM_BINS),0)

# No BIN directory was specified.  Set BIN to "bin" as a sensible
# default.

BIN		:= bin

else # NUM_BINS == 0

ifeq ($(NUM_BINS),1)

# If exactly one BIN directory was specified, set BIN to match this
# directory.
#
BIN		:= $(firstword $(BIN_GOAL_BINS))

else # NUM_BINS == 1

# More than one BIN directory was specified.  We cannot handle the
# latter case within a single make invocation, so set up recursive
# targets for each BIN directory.
#
# Leave $(BIN) undefined.  This has implications for any target that
# depends on $(BIN); such targets should be made conditional upon the
# existence of $(BIN).
#
$(BIN_GOALS) : % : BIN_RECURSE
	$(Q)$(MAKE) --no-print-directory BIN=$(firstword $(subst /, ,$@)) $@
.PHONY : BIN_RECURSE

endif # NUM_BINS == 1
endif # NUM_BINS == 0

ifdef BIN

# Create $(BIN) directory if it doesn't exist yet
#
ifeq ($(wildcard $(BIN)),)
$(shell $(MKDIR) -p $(BIN))
endif

# Target to allow e.g. "make bin-efi arch"
#
$(BIN) :
	@# Do nothing, silently
.PHONY : $(BIN)

# Remove everything in $(BIN) for a "make clean"
#
CLEANUP	+= $(BIN)/*.* # Avoid picking up directories

endif # defined(BIN)

# Determine whether or not we need to include the dependency files
#
NO_DEP_TARGETS	:= $(BIN) clean veryclean
ifeq ($(MAKECMDGOALS),)
NEED_DEPS	:= 1
endif
ifneq ($(strip $(filter-out $(NO_DEP_TARGETS),$(MAKECMDGOALS))),)
NEED_DEPS	:= 1
endif

###############################################################################
#
# Select build architecture and platform based on $(BIN)
#
# BIN has the form bin[-[arch-]platform]

ARCHS		:= $(patsubst arch/%,%,$(wildcard arch/*))
PLATFORMS	:= $(patsubst config/defaults/%.h,%,\
		     $(wildcard config/defaults/*.h))
archs :
	@$(ECHO) $(ARCHS)

platforms :
	@$(ECHO) $(PLATFORMS)

ifdef BIN

# Determine architecture portion of $(BIN), if present
BIN_ARCH	:= $(strip $(foreach A,$(ARCHS),\
			     $(patsubst bin-$(A)-%,$(A),\
			       $(filter bin-$(A)-%,$(BIN)))))

# Determine platform portion of $(BIN), if present
ifeq ($(BIN_ARCH),)
BIN_PLATFORM	:= $(patsubst bin-%,%,$(filter bin-%,$(BIN)))
else
BIN_PLATFORM	:= $(patsubst bin-$(BIN_ARCH)-%,%,$(BIN))
endif

# Determine build architecture
DEFAULT_ARCH	:= i386
ARCH		:= $(firstword $(BIN_ARCH) $(DEFAULT_ARCH))
CFLAGS		+= -DARCH=$(ARCH)
arch :
	@$(ECHO) $(ARCH)
.PHONY : arch

# Determine build platform
DEFAULT_PLATFORM := pcbios
PLATFORM	:= $(firstword $(BIN_PLATFORM) $(DEFAULT_PLATFORM))
CFLAGS		+= -DPLATFORM=$(PLATFORM)
platform :
	@$(ECHO) $(PLATFORM)

endif # defined(BIN)

# Include architecture-specific Makefile
ifdef ARCH
MAKEDEPS	+= arch/$(ARCH)/Makefile
include arch/$(ARCH)/Makefile
endif

# Include architecture-specific include path
ifdef ARCH
INCDIRS		+= arch/$(ARCH)/include
endif

###############################################################################
#
# Source file handling

# SRCDIRS lists all directories containing source files.
srcdirs :
	@$(ECHO) $(SRCDIRS)

# SRCS lists all .c or .S files found in any SRCDIR
#
SRCS	+= $(wildcard $(patsubst %,%/*.c,$(SRCDIRS)))
SRCS	+= $(wildcard $(patsubst %,%/*.S,$(SRCDIRS)))
srcs :
	@$(ECHO) $(SRCS)

# AUTO_SRCS lists all files in SRCS that are not mentioned in
# NON_AUTO_SRCS.  Files should be added to NON_AUTO_SRCS if they
# cannot be built using the standard build template.
#
AUTO_SRCS = $(filter-out $(NON_AUTO_SRCS),$(SRCS))
autosrcs :
	@$(ECHO) $(AUTO_SRCS)

# Just about everything else in this section depends upon having
# $(BIN) set

ifdef BIN

# INCDIRS lists the include path
incdirs :
	@$(ECHO) $(INCDIRS)

# Common flags
#
CFLAGS		+= $(foreach INC,$(INCDIRS),-I$(INC))
CFLAGS		+= -Os
CFLAGS		+= -g
ifeq ($(CCTYPE),gcc)
CFLAGS		+= -ffreestanding
CFLAGS		+= -Wall -W -Wformat-nonliteral
endif
ifeq ($(CCTYPE),icc)
CFLAGS		+= -fno-builtin
CFLAGS		+= -no-ip
CFLAGS		+= -no-gcc
CFLAGS		+= -diag-disable 111 # Unreachable code
CFLAGS		+= -diag-disable 128 # Unreachable loop
CFLAGS		+= -diag-disable 170 # Array boundary checks
CFLAGS		+= -diag-disable 177 # Unused functions
CFLAGS		+= -diag-disable 181 # printf() format checks
CFLAGS		+= -diag-disable 188 # enum strictness
CFLAGS		+= -diag-disable 193 # Undefined preprocessor identifiers
CFLAGS		+= -diag-disable 280 # switch ( constant )
CFLAGS		+= -diag-disable 310 # K&R parameter lists
CFLAGS		+= -diag-disable 424 # Extra semicolon
CFLAGS		+= -diag-disable 589 # Declarations mid-code
CFLAGS		+= -diag-disable 593 # Unused variables
CFLAGS		+= -diag-disable 810 # Casting ints to smaller ints
CFLAGS		+= -diag-disable 981 # Sequence point violations
CFLAGS		+= -diag-disable 1292 # Ignored attributes
CFLAGS		+= -diag-disable 1338 # void pointer arithmetic
CFLAGS		+= -diag-disable 1361 # Variable-length arrays
CFLAGS		+= -diag-disable 1418 # Missing prototypes
CFLAGS		+= -diag-disable 1419 # Missing prototypes
CFLAGS		+= -diag-disable 1599 # Hidden variables
CFLAGS		+= -Wall -Wmissing-declarations
endif
CFLAGS		+= $(EXTRA_CFLAGS)
ASFLAGS		+= $(EXTRA_ASFLAGS)
LDFLAGS		+= $(EXTRA_LDFLAGS)

# Inhibit -Werror if NO_WERROR is specified on make command line
#
ifneq ($(NO_WERROR),1)
CFLAGS		+= -Werror
ASFLAGS		+= --fatal-warnings
endif

# compiler.h is needed for our linking and debugging system
#
CFLAGS		+= -include compiler.h

# CFLAGS for specific object types
#
CFLAGS_c	+=
CFLAGS_S 	+= -DASSEMBLY

# Base object name of the current target
#
OBJECT		= $(firstword $(subst ., ,$(@F)))

# CFLAGS for specific object files.  You can define
# e.g. CFLAGS_rtl8139, and have those flags automatically used when
# compiling bin/rtl8139.o.
#
OBJ_CFLAGS	= $(CFLAGS_$(OBJECT)) -DOBJECT=$(subst -,_,$(OBJECT))
$(BIN)/%.flags :
	@$(ECHO) $(OBJ_CFLAGS)

# ICC requires postprocessing objects to fix up table alignments
#
ifeq ($(CCTYPE),icc)
POST_O		= && $(ICCFIX) $@
POST_O_DEPS	:= $(ICCFIX)
else
POST_O		:=
POST_O_DEPS	:=
endif

# Rules for specific object types.
#
COMPILE_c	= $(CC) $(CFLAGS) $(CFLAGS_c) $(OBJ_CFLAGS)
RULE_c		= $(Q)$(COMPILE_c) -c $< -o $@ $(POST_O)
RULE_c_to_dbg%.o = $(Q)$(COMPILE_c) -Ddebug_$(subst -,_,$(OBJECT))=$* -c $< -o $@ $(POST_O)
RULE_c_to_c	= $(Q)$(COMPILE_c) -E -c $< > $@
RULE_c_to_s	= $(Q)$(COMPILE_c) -S -g0 -c $< -o $@

PREPROCESS_S	= $(CPP) $(CFLAGS) $(CFLAGS_S) $(OBJ_CFLAGS)
ASSEMBLE_S	= $(AS) $(ASFLAGS)
RULE_S		= $(Q)$(PREPROCESS_S) $< | $(ASSEMBLE_S) -o $@
RULE_S_to_s	= $(Q)$(PREPROCESS_S) $< > $@

DEBUG_TARGETS	+= dbg%.o c s

# We automatically generate rules for any file mentioned in AUTO_SRCS
# using the following set of templates.  It would be cleaner to use
# $(eval ...), but this function exists only in GNU make >= 3.80.

# src_template : generate Makefile rules for a given source file
#
# $(1) is the full path to the source file (e.g. "drivers/net/rtl8139.c")
# $(2) is the full path to the .d file (e.g. "bin/deps/drivers/net/rtl8139.d")
# $(3) is the source type (e.g. "c")
# $(4) is the source base name (e.g. "rtl8139")
#
define src_template

	@$(ECHO) "  [DEPS] $(1)"
	@$(MKDIR) -p $(dir $(2))
	@$(RM) $(2)
	@$(TOUCH) $(2)
	@$(CPP) $(CFLAGS) $(CFLAGS_$(3)) $(CFLAGS_$(4)) -DOBJECT=$(4) \
		-Wno-error -MM $(1) -MG -MP | \
		sed 's/\.o\s*:/_DEPS =/' >> $(2)
	@$(ECHO_E) '\n$$(BIN)/$(4).o :' \
		 '$(1) $$(MAKEDEPS) $$(POST_O_DEPS) $$($(4)_DEPS)' \
		 '\n\t$$(QM)$(ECHO) "  [BUILD] $$@"' \
		 '\n\t$$(RULE_$(3))\n' \
		 '\nBOBJS += $$(BIN)/$(4).o\n' \
		 $(foreach TGT,$(DEBUG_TARGETS), \
		    $(if $(RULE_$(3)_to_$(TGT)), \
		    '\n$$(BIN)/$(4).$(TGT) :' \
		    '$(1) $$(MAKEDEPS) $$(POST_O_DEPS) $$($(4)_DEPS)' \
		    '\n\t$$(QM)$(ECHO) "  [BUILD] $$@"' \
		    '\n\t$$(RULE_$(3)_to_$(TGT))\n' \
		    '\n$(TGT)_OBJS += $$(BIN)/$(4).$(TGT)\n' ) ) \
		 '\n$(2) : $$($(4)_DEPS)\n' \
		 '\nTAGS : $$($(4)_DEPS)\n' \
		>> $(2)
	@$(PARSEROM) $(1) >> $(2)

endef

# Rule to generate the Makefile rules files to be included
#
$(BIN)/deps/%.d : % $(MAKEDEPS) $(PARSEROM)
	$(if $(filter $(AUTO_SRCS),$<),$(call src_template,$<,$@,$(subst .,,$(suffix $<)),$(basename $(notdir $<))),@$(ECHO) 'ERROR: $< is not an AUTO_SRC' ; exit 1)

# Calculate and include the list of Makefile rules files
#
AUTO_DEPS	= $(patsubst %,$(BIN)/deps/%.d,$(AUTO_SRCS))
ifdef NEED_DEPS
ifneq ($(AUTO_DEPS),)
-include $(AUTO_DEPS)
endif
endif
autodeps :
	@$(ECHO) $(AUTO_DEPS)
VERYCLEANUP	+= $(BIN)/deps

# The following variables are created by the Makefile rules files
#
bobjs :
	@$(ECHO) $(BOBJS)
drivers :
	@$(ECHO) $(DRIVERS)
.PHONY : drivers
roms :
	@$(ECHO) $(ROMS)

# List of embedded images included in the last build of embedded.o.
# This is needed in order to correctly rebuild embedded.o whenever the
# list of objects changes.
#
EMBEDDED_LIST	:= $(BIN)/.embedded.list
ifeq ($(wildcard $(EMBEDDED_LIST)),)
EMBEDDED_LIST_IMAGE := <invalid>
else
EMBEDDED_LIST_IMAGE := $(shell cat $(EMBEDDED_LIST))
endif
ifneq ($(EMBEDDED_LIST_IMAGE),$(EMBEDDED_IMAGE))
$(shell $(ECHO) "$(EMBEDDED_IMAGE)" > $(EMBEDDED_LIST))
endif

$(EMBEDDED_LIST) :

VERYCLEANUP	+= $(EMBEDDED_LIST)

EMBEDDED_FILES	:= $(subst $(COMMA), ,$(EMBEDDED_IMAGE))
EMBED_ALL	:= $(foreach i,$(call seq,1,$(words $(EMBEDDED_FILES))),\
		     EMBED ( $(i), \"$(word $(i), $(EMBEDDED_FILES))\",\
			     \"$(notdir $(word $(i),$(EMBEDDED_FILES)))\" ))

$(BIN)/embedded.o : $(EMBEDDED_FILES) $(EMBEDDED_LIST)
CFLAGS_embedded = -DEMBED_ALL="$(EMBED_ALL)"

# Generate the NIC file from the parsed source files.  The NIC file is
# only for rom-o-matic.
#
$(BIN)/NIC : $(AUTO_DEPS)
	@$(ECHO) '# This is an automatically generated file, do not edit' > $@
	@$(ECHO) '# It does not affect anything in the build, ' \
	     'it is only for rom-o-matic' >> $@
	@$(ECHO) >> $@
	@perl -ne 'chomp; print "$$1\n" if /\# NIC\t(.*)$$/' $^ >> $@
CLEANUP		+= $(BIN)/NIC	# Doesn't match the $(BIN)/*.* pattern

# Analyse a target name (e.g. "bin/dfe538--prism2_pci.zrom.tmp") and
# derive the variables:
# 
# TGT_ELEMENTS : the elements of the target (e.g. "dfe538 prism2_pci")
# TGT_PREFIX   : the prefix type (e.g. "zrom")
# TGT_DRIVERS  : the driver for each element (e.g. "rtl8139 prism2_pci")
# TGT_ROM_NAME : the ROM name (e.g. "dfe538")
# TGT_MEDIA    : the media type (e.g. "rom")
#
DRIVERS_gpxe	= $(DRIVERS)
CARD_DRIVER	= $(firstword $(DRIVER_$(1)) $(1))
TGT_ELEMENTS	= $(subst --, ,$(firstword $(subst ., ,$(notdir $@))))
TGT_PREFIX	= $(word 2,$(subst ., ,$(notdir $@)))
TGT_ROM_NAME	= $(firstword $(TGT_ELEMENTS))
TGT_DRIVERS	= $(strip $(if $(DRIVERS_$(TGT_ROM_NAME)), \
			       $(DRIVERS_$(TGT_ROM_NAME)), \
			       $(foreach TGT_ELEMENT,$(TGT_ELEMENTS), \
			         $(call CARD_DRIVER,$(TGT_ELEMENT))) ))
TGT_MEDIA	= $(subst z,,$(TGT_PREFIX))

# Look up ROM IDs for the current target
# (e.g. "bin/dfe538--prism2_pci.zrom.tmp") and derive the variables:
#
# TGT_PCI_VENDOR : the PCI vendor ID (e.g. "0x1186")
# TGT_PCI_DEVICE : the PCI device ID (e.g. "0x1300")
#
TGT_PCI_VENDOR	= $(PCI_VENDOR_$(TGT_ROM_NAME))
TGT_PCI_DEVICE	= $(PCI_DEVICE_$(TGT_ROM_NAME))

# Calculate link-time options for the current target
# (e.g. "bin/dfe538--prism2_pci.zrom.tmp") and derive the variables:
#
# TGT_LD_DRIVERS : symbols to require in order to drag in the relevant drivers
#		   (e.g. "obj_rtl8139 obj_prism2_pci")
# TGT_LD_IDS :     symbols to define in order to fill in ID structures in the
#		   ROM header (e.g."pci_vendor_id=0x1186 pci_device_id=0x1300")
#
TGT_LD_DRIVERS	= $(subst -,_,$(patsubst %,obj_%,$(TGT_DRIVERS)))
TGT_LD_PREFIX	= obj_$(TGT_PREFIX)prefix
TGT_LD_IDS	= pci_vendor_id=$(firstword $(TGT_PCI_VENDOR) 0) \
		  pci_device_id=$(firstword $(TGT_PCI_DEVICE) 0)

# Calculate linker flags based on link-time options for the current
# target type (e.g. "bin/dfe538--prism2_pci.zrom.tmp") and derive the
# variables:
#
# TGT_LD_FLAGS : target-specific flags to pass to linker (e.g.
#		 "-u obj_zpciprefix -u obj_rtl8139 -u obj_prism2_pci
#		  --defsym pci_vendor=0x1186 --defsym pci_device=0x1300")
#
TGT_LD_FLAGS	= $(foreach SYM,$(TGT_LD_PREFIX) $(TGT_LD_DRIVERS) obj_config,\
		    -u $(SYM) --defsym check_$(SYM)=$(SYM) ) \
		  $(patsubst %,--defsym %,$(TGT_LD_IDS))

# Calculate makerom flags for the specific target
# (e.g. "bin/dfe538--prism2_pci.zrom.tmp") and derive the variables:
#
# TGT_MAKEROM_FLAGS : target-specific flags for makerom (e.g.
#		      "-p 0x1186,0x1300")
#
TGT_MAKEROM_FLAGS = $(strip $(MAKEROM_FLAGS_$(TGT_ROM_NAME)) \
       $(if $(TGT_PCI_VENDOR),$(strip -p $(TGT_PCI_VENDOR),$(TGT_PCI_DEVICE))))

# Calculate list of debugging versions of objects to be included in
# the target.
#
DEBUG_LIST	= $(subst $(COMMA), ,$(DEBUG))
DEBUG_OBJ_LEVEL	= $(firstword $(word 2,$(subst :, ,$(1))) 1)
DEBUG_OBJ_BASE	= $(word 1,$(subst :, ,$(1))).dbg$(call DEBUG_OBJ_LEVEL,$(1))
DEBUG_OBJ	= $(BIN)/$(call DEBUG_OBJ_BASE,$(1)).o
DEBUG_ORIG_OBJ	= $(BIN)/$(word 1,$(subst :, ,$(1))).o
DEBUG_OBJS	= $(foreach D,$(DEBUG_LIST),$(call DEBUG_OBJ,$(D)))
DEBUG_ORIG_OBJS	= $(foreach D,$(DEBUG_LIST),$(call DEBUG_ORIG_OBJ,$(D)))
BLIB_OBJS	= $(DEBUG_OBJS) $(filter-out $(DEBUG_ORIG_OBJS),$(BOBJS))

# Print out all derived information for a given target.
#
$(BIN)/%.info :
	@$(ECHO) 'Elements             : $(TGT_ELEMENTS)'
	@$(ECHO) 'Prefix               : $(TGT_PREFIX)'
	@$(ECHO) 'Drivers              : $(TGT_DRIVERS)'
	@$(ECHO) 'ROM name             : $(TGT_ROM_NAME)'
	@$(ECHO) 'Media                : $(TGT_MEDIA)'
	@$(ECHO)
	@$(ECHO) 'PCI vendor           : $(TGT_PCI_VENDOR)'
	@$(ECHO) 'PCI device           : $(TGT_PCI_DEVICE)'
	@$(ECHO)
	@$(ECHO) 'LD driver symbols    : $(TGT_LD_DRIVERS)'
	@$(ECHO) 'LD prefix symbols    : $(TGT_LD_PREFIX)'
	@$(ECHO) 'LD ID symbols        : $(TGT_LD_IDS)'
	@$(ECHO)
	@$(ECHO) 'LD target flags      : $(TGT_LD_FLAGS)'
	@$(ECHO)
	@$(ECHO) 'makerom target flags : $(TGT_MAKEROM_FLAGS)'
	@$(ECHO)
	@$(ECHO) 'Debugging objects    : $(DEBUG_OBJS)'
	@$(ECHO) 'Replaced objects     : $(DEBUG_ORIG_OBJS)'

# List of objects included in the last build of blib.  This is needed
# in order to correctly rebuild blib whenever the list of objects
# changes.
#
BLIB_LIST	:= $(BIN)/.blib.list
ifeq ($(wildcard $(BLIB_LIST)),)
BLIB_LIST_OBJS	:= <invalid>
else
BLIB_LIST_OBJS	:= $(shell cat $(BLIB_LIST))
endif
ifneq ($(BLIB_LIST_OBJS),$(BLIB_OBJS))
$(shell $(ECHO) "$(BLIB_OBJS)" > $(BLIB_LIST))
endif

$(BLIB_LIST) :

VERYCLEANUP	+= $(BLIB_LIST)

# Library of all objects
#
BLIB		= $(BIN)/blib.a
$(BLIB) : $(BLIB_OBJS) $(BLIB_LIST) $(MAKEDEPS)
	$(Q)$(RM) $(BLIB)
	$(QM)$(ECHO) "  [AR] $@"
	$(Q)$(AR) r $@ $(BLIB_OBJS)
	$(Q)$(RANLIB) $@
blib : $(BLIB)

# Build an intermediate object file from the objects required for the
# specified target.
#
$(BIN)/%.tmp : $(BLIB) $(MAKEDEPS) $(LDSCRIPT) 
	$(QM)$(ECHO) "  [LD] $@"
	$(Q)$(LD) $(LDFLAGS) -T $(LDSCRIPT) $(TGT_LD_FLAGS) $(BLIB) -o $@ \
		-Map $(BIN)/$*.tmp.map
	$(Q)$(OBJDUMP) -ht $@ | $(SORTOBJDUMP) >> $(BIN)/$*.tmp.map

# Keep intermediate object file (useful for debugging)
.PRECIOUS : $(BIN)/%.tmp

# Show a linker map for the specified target
#
$(BIN)/%.map : $(BIN)/%.tmp
	@less $(BIN)/$*.tmp.map

# Get objects list for the specified target
#
define objs_list
	$(sort $(foreach OBJ_SYMBOL,\
		 $(filter obj_%,$(shell $(NM) $(1) | cut -d" " -f3)),\
		 $(patsubst obj_%,%,$(OBJ_SYMBOL))))
endef
$(BIN)/%.objs : $(BIN)/%.tmp
	$(Q)$(ECHO) $(call objs_list,$<)
$(BIN)/%.sizes : $(BIN)/%.tmp
	$(Q)$(SIZE) -t $(foreach OBJ,$(call objs_list,$<),$(wildcard $(BIN)/$(subst _,?,$(OBJ)).o)) | \
		sort -g

# Get dependency list for the specified target
#
define deps_list
	$(sort $(foreach OBJ,$(call objs_list,$(1)),$($(OBJ)_DEPS)))
endef
$(BIN)/%.deps : $(BIN)/%.tmp
	$(Q)$(ECHO) $(call deps_list,$<)

# Get unneeded source files for the specified target
#
define nodeps_list
	$(sort $(filter-out $(call deps_list,$(1)),\
		 $(foreach BOBJ,$(BOBJS),\
		   $($(basename $(notdir $(BOBJ)))_DEPS))))
endef
$(BIN)/%.nodeps : $(BIN)/%.tmp
	$(Q)$(ECHO) $(call nodeps_list,$<)

# Get licensing verdict for the specified target
#
define unlicensed_deps_list
	$(shell grep -L FILE_LICENCE $(call deps_list,$(1)))
endef
define licence_list
	$(patsubst __licence_%,%,\
	  $(filter __licence_%,$(shell $(NM) $(1) | cut -d" " -f3)))
endef
$(BIN)/%.licence : $(BIN)/%.tmp
	$(QM)$(ECHO) "  [LICENCE] $@"
	$(Q)$(if $(strip $(call unlicensed_deps_list,$<)),\
		echo -n "Unable to determine licence because the following " ;\
		echo "files are missing a licence declaration:" ;\
		echo $(call unlicensed_deps_list,$<);\
		exit 1,\
		$(LICENCE) $(call licence_list,$<))

# Extract compression information from intermediate object file
#
$(BIN)/%.zinfo : $(BIN)/%.tmp
	$(QM)$(ECHO) "  [ZINFO] $@"
	$(Q)$(OBJCOPY) -O binary -j .zinfo $< $@

# Build raw binary file from intermediate object file
#
$(BIN)/%.bin : $(BIN)/%.tmp
	$(QM)$(ECHO) "  [BIN] $@"
	$(Q)$(OBJCOPY) -O binary -R .zinfo $< $@

# Compress raw binary file
#
$(BIN)/%.zbin : $(BIN)/%.bin $(BIN)/%.zinfo $(ZBIN)
	$(QM)$(ECHO) "  [ZBIN] $@"
	$(Q)$(ZBIN) $(BIN)/$*.bin $(BIN)/$*.zinfo > $@

# Rules for each media format.  These are generated and placed in an
# external Makefile fragment.  We could do this via $(eval ...), but
# that would require make >= 3.80.
# 
# Note that there's an alternative way to generate most .rom images:
# they can be copied from their 'master' ROM image using cp and
# reprocessed with makerom to add the PCI IDs and ident string.  The
# relevant rule would look something like:
#
#   $(BIN)/dfe538%rom : $(BIN)/rtl8139%rom
#	cat $< $@
#	$(FINALISE_rom)
# 
# You can derive the ROM/driver relationships using the variables
# DRIVER_<rom> and/or ROMS_<driver>.
# 
# We don't currently do this, because (a) it would require generating
# yet more Makefile fragments (since you need a rule for each ROM in
# ROMS), and (b) the linker is so fast that it probably wouldn't make
# much difference to the overall build time.

media :
	@$(ECHO) $(MEDIA)

AUTO_MEDIA	= $(filter-out $(NON_AUTO_MEDIA),$(MEDIA))
automedia :
	@$(ECHO) $(AUTO_MEDIA)

# media_template : create Makefile rules for specified media
#
# $(1) is the media name (e.g. "rom")
# $(2) is the full path to the .d file (e.g. "bin/deps/rom.media.d")
#
define media_template

	@$(ECHO) "  [MEDIADEPS] $(1)"
	@$(MKDIR) -p $(dir $(2))
	@$(RM) $(2)
	@$(TOUCH) $(2)
	@$(ECHO_E) '$$(BIN)/%.$(1) : $$(BIN)/%.$(1).zbin' \
		  '\n\t$$(QM)$(ECHO) "  [FINISH] $$@"' \
		  '\n\t$$(Q)$$(CP) $$< $$@' \
		  '\n\t$$(Q)$$(PAD_$(1))' \
		  '\n\t$$(Q)$$(FINALISE_$(1))' \
		> $(2)

endef

# Rule to generate the Makefile rules to be included
#
$(BIN)/deps/%.media.d : $(MAKEDEPS)
	$(if $(filter $(AUTO_MEDIA),$*), \
		$(call media_template,$*,$@), \
		@$(ECHO) 'ERROR: $* is not an AUTO_MEDIA' ; exit 1)

# Calculate and include the list of Makefile rules files
#
MEDIA_DEPS		= $(patsubst %,$(BIN)/deps/%.media.d,$(AUTO_MEDIA))
mediadeps :
	@$(ECHO) $(MEDIA_DEPS)
ifdef NEED_DEPS
ifneq ($(MEDIA_DEPS),)
-include $(MEDIA_DEPS)
endif
endif

# Wrap up binary blobs (for embedded images)
#
$(BIN)/%.o : payload/%.img
	$(QM)echo "  [WRAP] $@"
	$(Q)$(LD) -b binary -r -o $@ $< --undefined obj_payload \
		--defsym obj_$*=0

BOBJS += $(patsubst payload/%.img,$(BIN)/%.o,$(wildcard payload/*.img))

# The "allXXXs" targets for each suffix
#
allall: allroms allzroms allpxes allisos alldsks
allroms allzroms : all%s : $(foreach ROM,$(ROMS),$(BIN)/$(ROM).%)
allpxes allisos alldsks : all%s : $(foreach DRIVER,$(DRIVERS),$(BIN)/$(DRIVER).%)

# Alias for gpxe.%
#
$(BIN)/etherboot.% : $(BIN)/gpxe.%
	ln -sf $(notdir $<) $@

endif # defined(BIN)

###############################################################################
#
# Rules for finalising files.  TGT_MAKEROM_FLAGS is defined as part of
# the automatic build system and varies by target; it includes the
# "-p 0x1234,0x5678" string to set the PCI IDs.
#
FINALISE_rom	= $(MAKEROM) $(MAKEROM_FLAGS) $(TGT_MAKEROM_FLAGS) \
		  -i$(IDENT) -s 0 $@
FINALISE_hrom	= $(FINALISE_rom)
FINALISE_xrom	= $(MAKEROM) $(MAKEROM_FLAGS) $(TGT_MAKEROM_FLAGS) \
		  -i$(IDENT) -n -s 0 $@

# Some ROMs require specific flags to be passed to makerom.pl
#
MAKEROM_FLAGS_3c503 = -3

###############################################################################
#
# The compression utilities
#
$(NRV2B) : util/nrv2b.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) -O2 -DENCODE -DDECODE -DMAIN -DVERBOSE -DNDEBUG \
		       -DBITSIZE=32 -DENDIAN=0 -o $@ $<
CLEANUP	+= $(NRV2B)

$(ZBIN) : util/zbin.c util/nrv2b.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) -O2 -o $@ $<
CLEANUP += $(ZBIN)

###############################################################################
#
# The EFI image converter
#
ELF2EFI_CFLAGS	:= -I$(BINUTILS_DIR)/include -I$(BFD_DIR)/include \
		   -idirafter include -L$(BINUTILS_DIR)/lib -L$(BFD_DIR)/lib \
		   -lbfd -liberty -lz

$(ELF2EFI32) : util/elf2efi.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) $(ELF2EFI_CFLAGS) -DMDE_CPU_IA32 -O2 -o $@ $<
CLEANUP += $(ELF2EFI32)

$(ELF2EFI64) : util/elf2efi.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) $(ELF2EFI_CFLAGS) -DMDE_CPU_X64 -O2 -o $@ $<
CLEANUP += $(ELF2EFI64)

$(EFIROM) : util/efirom.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) -idirafter include -O2 -o $@ $<
CLEANUP += $(EFIROM)

###############################################################################
#
# The ICC fixup utility
#
$(ICCFIX) : util/iccfix.c $(MAKEDEPS)
	$(QM)$(ECHO) "  [HOSTCC] $@"
	$(Q)$(HOST_CC) -idirafter include -O2 -o $@ $<
CLEANUP += $(ICCFIX)

###############################################################################
#
# Auto-incrementing build serial number.  Append "bs" to your list of
# build targets to get a serial number printed at the end of the
# build.  Enable -DBUILD_SERIAL in order to see it when the code runs.
#
BUILDSERIAL_H		= config/.buildserial.h
BUILDSERIAL_NOW		= config/.buildserial.now
BUILDSERIAL_NEXT	= config/.buildserial.next

$(BUILDSERIAL_NOW) $(BUILDSERIAL_NEXT) :
	$(ECHO) 1 > $@

$(BUILDSERIAL_H) : $(BUILDSERIAL_NOW) $(BUILDSERIAL_NEXT)
	$(ECHO) '#define BUILD_SERIAL_NUM $(shell cat $<)' > $@

ifeq ($(filter bs,$(MAKECMDGOALS)),bs)
$(shell diff -q $(BUILDSERIAL_NOW) $(BUILDSERIAL_NEXT) > /dev/null || \
	cp -f $(BUILDSERIAL_NEXT) $(BUILDSERIAL_NOW))
endif

bs : $(BUILDSERIAL_NOW)
	@$(ECHO) $$(( $(shell cat $<) + 1 )) > $(BUILDSERIAL_NEXT)
	@$(ECHO) "Build serial number is $(shell cat $<)"

###############################################################################
#
# Build the TAGS file(s) for emacs
#
TAGS :
	ctags -e -R -f $@ --exclude=bin

CLEANUP	+= TAGS

###############################################################################
#
# Force rebuild for any given target
#
%.rebuild :
	rm -f $*
	$(Q)$(MAKE) $*

###############################################################################
#
# Symbol table checks
#

ifdef BIN

SYMTAB	= $(BIN)/symtab
$(SYMTAB) : $(BLIB)
	$(OBJDUMP) -w -t $< > $@

CLEANUP	+= $(BIN)/symtab

symcheck : $(SYMTAB)
	$(SYMCHECK) $<

endif # defined(BIN)

###############################################################################
#
# Build bochs symbol table
#

ifdef BIN

$(BIN)/%.bxs : $(BIN)/%.tmp
	$(NM) $< | cut -d" " -f1,3 > $@

endif # defined(BIN)

###############################################################################
#
# Documentation
#

ifdef BIN

$(BIN)/doxygen.cfg : doxygen.cfg $(MAKEDEPS)
	$(Q)$(PERL) -pe 's{\@SRCDIRS\@}{$(SRCDIRS)}; ' \
		-e  's{\@INCDIRS\@}{$(filter-out .,$(INCDIRS))}; ' \
		-e  's{\@BIN\@}{$(BIN)}; ' \
		-e  's{\@ARCH\@}{$(ARCH)}; ' \
		$< > $@

$(BIN)/doc : $(BIN)/doxygen.cfg
	$(Q)$(DOXYGEN) $<

.PHONY : $(BIN)/doc

doc : $(BIN)/doc

doc-clean :
	$(Q)$(RM) -r $(BIN)/doc

VERYCLEANUP	+= $(BIN)/doc

docview :
	@[ -f $(BIN)/doc/html/index.html ] || $(MAKE) $(BIN)/doc
	@if [ -n "$$BROWSER" ] ; then \
		( $$BROWSER $(BIN)/doc/html/index.html & ) ; \
	else \
		$(ECHO) "Documentation index in $(BIN)/doc/html/index.html" ; \
	fi

endif # defined(BIN)

###############################################################################
#
# Clean-up
#
clean :
	$(RM) $(CLEANUP)

veryclean : clean
	$(RM) -r $(VERYCLEANUP)