blob: 7939883ac4f292f65dac28f3617f72e93945f8f3 [file] [log] [blame]
Dennis Kempinbf37f5d2012-06-14 18:44:07 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4#
5# If this file is part of another source distribution, it's license may be
6# stored in LICENSE.makefile or LICENSE.common.mk.
7#
8# NOTE NOTE NOTE
9# The authoritative common.mk is located in:
Aaron Gable7a3b32c2013-09-27 18:35:55 -070010# https://chromium.googlesource.com/chromiumos/platform/common-mk.git
Dennis Kempinbf37f5d2012-06-14 18:44:07 -070011# Please make all changes there, then copy into place in other repos.
12# NOTE NOTE NOTE
13#
14# This file provides a common architecture for building C/C++ source trees.
15# It uses recursive makefile inclusion to create a single make process which
16# can be built in the source tree or with the build artifacts placed elsewhere.
17#
18# It is fully parallelizable for all targets, including static archives.
19#
20# To use:
21# 1. Place common.mk in your top source level
22# 2. In your top-level Makefile, place "include common.mk" at the top
23# 3. In all subdirectories, create a 'module.mk' file that starts with:
24# include common.mk
25# And then contains the remainder of your targets.
26# 4. All build targets should look like:
27# relative/path/target: relative/path/obj.o
28#
29# See existing makefiles for rule examples.
30#
31# Exported macros:
32# - cc_binary, cxx_binary provide standard compilation steps for binaries
33# - cxx_library, cc_library provide standard compilation steps for
34# shared objects.
35# All of the above optionally take an argument for extra flags.
36# - update_archive creates/updates a given .a target
37#
38# Instead of using the build macros, most users can just use wrapped targets:
39# - CXX_BINARY, CC_BINARY, CC_STATIC_BINARY, CXX_STATIC_BINARY
40# - CXX_LIBRARY, CC_LIBRARY, CC_STATIC_LIBRARY, CXX_STATIC_LIBRARY
41# - E.g., CXX_BINARY(mahbinary): foo.o
42# - object.depends targets may be used when a prerequisite is required for an
43# object file. Because object files result in multiple build artifacts to
44# handle PIC and PIE weirdness. E.g.
45# foo.o.depends: generated/dbus.h
46# - TEST(binary) or TEST(CXX_BINARY(binary)) may be used as a prerequisite
47# for the tests target to trigger an automated test run.
48# - CLEAN(file_or_dir) dependency can be added to 'clean'.
49#
50# If source code is being generated, rules will need to be registered for
51# compiling the objects. This can be done by adding one of the following
52# to the Makefile:
53# - For C source files
54# $(eval $(call add_object_rules,sub/dir/gen_a.o sub/dir/gen_b.o,CC,c))
55# - For C++ source files
56# $(eval $(call add_object_rules,sub/dir/gen_a.o sub/dir/gen_b.o,CXX,cc))
57#
58# Exported targets meant to have prerequisites added to:
59# - all - Your desired targets should be given
60# - tests - Any TEST(test_binary) targets should be given
61# - FORCE - force the given target to run regardless of changes
62# In most cases, using .PHONY is preferred.
63#
64# Possible command line variables:
65# - COLOR=[0|1] to set ANSI color output (default: 1)
66# - VERBOSE=[0|1] to hide/show commands (default: 0)
Ryan Harrison3e776a12013-02-06 16:39:30 -050067# - MODE=[opt|dbg|profiling] (default: opt)
68# opt - Enable optimizations for release builds
69# dbg - Turn down optimization for debugging
70# profiling - Turn off optimization and turn on profiling/coverage
71# support.
Dennis Kempinbf37f5d2012-06-14 18:44:07 -070072# - ARCH=[x86|arm|supported qemu name] (default: from portage or uname -m)
73# - SPLITDEBUG=[0|1] splits debug info in target.debug (default: 0)
74# If NOSTRIP=1, SPLITDEBUG will never strip the final emitted objects.
75# - NOSTRIP=[0|1] determines if binaries are stripped. (default: 1)
76# NOSTRIP=0 and MODE=opt will also drop -g from the CFLAGS.
77# - VALGRIND=[0|1] runs tests under valgrind (default: 0)
78# - OUT=/path/to/builddir puts all output in given path (default: $PWD)
79# - VALGRIND_ARGS="" supplies extra memcheck arguments
80#
81# Per-target(-ish) variable:
82# - NEEDS_ROOT=[0|1] allows a TEST() target to run with root.
83# Default is 0 unless it is running under QEmu.
84# - NEEDS_MOUNTS=[0|1] allows a TEST() target running on QEmu to get
85# setup mounts in the $(SYSROOT)
86#
87# Caveats:
88# - Directories or files with spaces in them DO NOT get along with GNU Make.
89# If you need them, all uses of dir/notdir/etc will need to have magic
90# wrappers. Proceed at risk to your own sanity.
91# - External CXXFLAGS and CFLAGS should be passed via the environment since
92# this file does not use 'override' to control them.
93# - Our version of GNU Make doesn't seem to support the 'private' variable
94# annotation, so you can't tag a variable private on a wrapping target.
95
96# Behavior configuration variables
97SPLITDEBUG ?= 0
98NOSTRIP ?= 1
99VALGRIND ?= 0
100COLOR ?= 1
101VERBOSE ?= 0
102MODE ?= opt
103ARCH ?= $(shell uname -m)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700104NEEDS_ROOT = 0
105NEEDS_MOUNTS = 0
106
107# Put objects in a separate tree based on makefile locations
108# This means you can build a tree without touching it:
109# make -C $SRCDIR # will create ./build-$(MODE)
110# Or
111# make -C $SRCDIR OUT=$PWD
112# This variable is extended on subdir calls and doesn't need to be re-called.
113OUT ?= $(PWD)/
114
115# Make OUT now so we can use realpath.
116$(shell mkdir -p "$(OUT)")
117
118# TODO(wad) Relative paths are resolved against SRC and not the calling dir.
119# Ensure a command-line supplied OUT has a slash
120override OUT := $(realpath $(OUT))/
121
122# SRC is not meant to be set by the end user, but during make call relocation.
123# $(PWD) != $(CURDIR) all the time.
124export SRC ?= $(CURDIR)
125
126# Re-start in the $(OUT) directory if we're not there.
127# We may be invoked using -C or bare and we need to ensure behavior
128# is consistent so we check both PWD vs OUT and PWD vs CURDIR.
129override RELOCATE_BUILD := 0
130ifneq (${PWD}/,${OUT})
131override RELOCATE_BUILD := 1
132endif
133# Make sure we're running with no builtin targets. They cause
134# leakage and mayhem!
135ifneq (${PWD},${CURDIR})
136override RELOCATE_BUILD := 1
137# If we're run from the build dir, don't let it get cleaned up later.
138ifeq (${PWD}/,${OUT})
139$(shell touch "$(PWD)/.dont_delete_on_clean")
140endif
141endif # ifneq (${PWD},${CURDIR}
142
143# "Relocate" if we need to restart without implicit rules.
144ifeq ($(subst r,,$(MAKEFLAGS)),$(MAKEFLAGS))
145override RELOCATE_BUILD := 1
146endif
147
148ifeq (${RELOCATE_BUILD},1)
149# By default, silence build output. Reused below as well.
150QUIET = @
151ifeq ($(VERBOSE),1)
152 QUIET=
153endif
154
155# This target will override all targets, including prerequisites. To avoid
156# calling $(MAKE) once per prereq on the given CMDGOAL, we guard it with a local
157# variable.
158RUN_ONCE := 0
159MAKECMDGOALS ?= all
160# Keep the rules split as newer make does not allow them to be declared
161# on the same line. But the way :: rules work, the _all here will also
162# invoke the %:: rule while retaining "_all" as the default.
163_all::
164%::
165 $(if $(filter 0,$(RUN_ONCE)), \
Ryan Harrison3e776a12013-02-06 16:39:30 -0500166 cd "$(OUT)" && \
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700167 $(MAKE) -r -I "$(SRC)" -f "$(CURDIR)/Makefile" \
168 SRC="$(CURDIR)" OUT="$(OUT)" $(foreach g,$(MAKECMDGOALS),"$(g)"),)
169 $(eval RUN_ONCE := 1)
170pass-to-subcall := 1
171endif
172
173ifeq ($(pass-to-subcall),)
174
175# Only call MODULE if we're in a submodule
176MODULES_LIST := $(filter-out Makefile %.d,$(MAKEFILE_LIST))
177ifeq ($(words $(filter-out Makefile common.mk %.d $(SRC)/Makefile \
178 $(SRC)/common.mk,$(MAKEFILE_LIST))),0)
179
180# All the top-level defines outside of module.mk.
181
182#
183# Helper macros
184#
185
Ryan Harrison3e776a12013-02-06 16:39:30 -0500186# Create the directory if it doesn't yet exist.
187define auto_mkdir
188 $(if $(wildcard $(dir $1)),$2,$(QUIET)mkdir -p "$(dir $1)")
189endef
190
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700191# Creates the actual archive with an index.
192# The target $@ must end with .pic.a or .pie.a.
193define update_archive
Ryan Harrison3e776a12013-02-06 16:39:30 -0500194 $(call auto_mkdir,$(TARGET_OR_MEMBER))
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700195 $(QUIET)# Create the archive in one step to avoid parallel use accessing it
196 $(QUIET)# before all the symbols are present.
197 @$(ECHO) "AR $(subst \
198$(SRC)/,,$(^:.o=$(suffix $(basename $(TARGET_OR_MEMBER))).o)) \
199-> $(subst $(SRC)/,,$(TARGET_OR_MEMBER))"
200 $(QUIET)$(AR) rcs $(TARGET_OR_MEMBER) \
201 $(subst $(SRC)/,,$(^:.o=$(suffix $(basename $(TARGET_OR_MEMBER))).o))
202endef
203
204# Default compile from objects using pre-requisites but filters out
205# subdirs and .d files.
206define cc_binary
207 $(call COMPILE_BINARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
208endef
209
210define cxx_binary
211 $(call COMPILE_BINARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
212endef
213
214# Default compile from objects using pre-requisites but filters out
215# subdirs and .d files.
216define cc_library
217 $(call COMPILE_LIBRARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
218endef
219define cxx_library
220 $(call COMPILE_LIBRARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
221endef
222
223# Deletes files silently if they exist. Meant for use in any local
224# clean targets.
225define silent_rm
226 $(if $(wildcard $(1)),
227 $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANFILE$(COLOR_RESET) ' && \
228 $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
229 $(RM) $(1) 2>/dev/null) || true,)
230endef
231define silent_rmdir
232 $(if $(wildcard $(1)),
233 $(if $(wildcard $(1)/*),
234 $(QUIET)# $(1) not empty [$(wildcard $(1)/*)]. Not deleting.,
235 $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANDIR$(COLOR_RESET) ' && \
236 $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
237 $(RMDIR) $(1) 2>/dev/null) || true),)
238endef
239
240#
241# Default variable values
242#
243
Ryan Harrison3e776a12013-02-06 16:39:30 -0500244# Only override toolchain vars if they are from make.
245CROSS_COMPILE ?=
246define override_var
247ifneq ($(filter undefined default,$(origin $1)),)
248$1 = $(CROSS_COMPILE)$2
249endif
250endef
251$(eval $(call override_var,AR,ar))
252$(eval $(call override_var,CC,gcc))
253$(eval $(call override_var,CXX,g++))
254$(eval $(call override_var,OBJCOPY,objcopy))
255$(eval $(call override_var,PKG_CONFIG,pkg-config))
256$(eval $(call override_var,RANLIB,ranlib))
257$(eval $(call override_var,STRIP,strip))
258
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700259RMDIR ?= rmdir
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700260ECHO = /bin/echo -e
261
Ryan Harrison3e776a12013-02-06 16:39:30 -0500262ifeq ($(lastword $(subst /, ,$(CC))),clang)
263CDRIVER = clang
264else
265CDRIVER = gcc
266endif
267
268ifeq ($(lastword $(subst /, ,$(CXX))),clang++)
269CXXDRIVER = clang
270else
271CXXDRIVER = gcc
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700272endif
273
274# To update these from an including Makefile:
275# CXXFLAGS += -mahflag # Append to the list
276# CXXFLAGS := -mahflag $(CXXFLAGS) # Prepend to the list
277# CXXFLAGS := $(filter-out badflag,$(CXXFLAGS)) # Filter out a value
278# The same goes for CFLAGS.
Ryan Harrison3e776a12013-02-06 16:39:30 -0500279COMMON_CFLAGS-gcc := -fstack-protector-strong -fvisibility=internal -ggdb3 \
280 -Wa,--noexecstack
281COMMON_CFLAGS-clang := -fstack-protector-all -fvisibility=hidden -ggdb
282COMMON_CFLAGS := -Wall -Werror -fno-strict-aliasing -O1 -Wformat=2
283CXXFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CXXDRIVER))
284CFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CDRIVER))
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700285CPPFLAGS += -D_FORTIFY_SOURCE=2
286
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700287
288ifeq ($(MODE),opt)
289 # Up the optimizations.
290 CFLAGS := $(filter-out -O1,$(CFLAGS)) -O2
291 CXXFLAGS := $(filter-out -O1,$(CXXFLAGS)) -O2
292 # Only drop -g* if symbols aren't desired.
293 ifeq ($(NOSTRIP),0)
294 # TODO: do we want -fomit-frame-pointer on x86?
295 CFLAGS := $(filter-out -ggdb3,$(CFLAGS))
296 CXXFLAGS := $(filter-out -ggdb3,$(CXXFLAGS))
297 endif
298endif
299
Ryan Harrison3e776a12013-02-06 16:39:30 -0500300ifeq ($(MODE),profiling)
301 CFLAGS := $(CFLAGS) -O0 -g --coverage
302 CXXFLAGS := $(CXXFLAGS) -O0 -g --coverage
303 LDFLAGS := $(LDFLAGS) --coverage
304endif
305
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700306LDFLAGS := $(LDFLAGS) -Wl,-z,relro -Wl,-z,noexecstack -Wl,-z,now
307
308# Fancy helpers for color if a prompt is defined
309ifeq ($(COLOR),1)
310COLOR_RESET = \x1b[0m
311COLOR_GREEN = \x1b[32;01m
312COLOR_RED = \x1b[31;01m
313COLOR_YELLOW = \x1b[33;01m
314endif
315
316# By default, silence build output.
317QUIET = @
318ifeq ($(VERBOSE),1)
319 QUIET=
320endif
321
322#
323# Implementation macros for compile helpers above
324#
325
326# Useful for dealing with pie-broken toolchains.
327# Call make with PIE=0 to disable default PIE use.
328OBJ_PIE_FLAG = -fPIE
329COMPILE_PIE_FLAG = -pie
330ifeq ($(PIE),0)
331 OBJ_PIE_FLAG =
332 COMPILE_PIE_FLAG =
333endif
334
335# Favor member targets first for CXX_BINARY(%) magic.
336# And strip out nested members if possible.
337LP := (
338RP := )
339TARGET_OR_MEMBER = $(lastword $(subst $(LP), ,$(subst $(RP),,$(or $%,$@))))
340
341# Default compile from objects using pre-requisites but filters out
342# all non-.o files.
343define COMPILE_BINARY_implementation
344 @$(ECHO) "LD$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
Ryan Harrison3e776a12013-02-06 16:39:30 -0500345 $(call auto_mkdir,$(TARGET_OR_MEMBER))
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700346 $(QUIET)$($(1)) $(COMPILE_PIE_FLAGS) -o $(TARGET_OR_MEMBER) \
347 $(2) $(LDFLAGS) \
348 $(filter %.o %.a,$(^:.o=.pie.o)) \
349 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
350 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
351 $(LDLIBS)
352 $(call conditional_strip)
353 @$(ECHO) -n "BIN "
354 @$(ECHO) "$(COLOR_GREEN)$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
355 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
356endef
357
358# TODO: add version support extracted from PV environment variable
359#ifeq ($(PV),9999)
360#$(warning PV=$(PV). If shared object versions matter, please force PV=.)
361#endif
362# Then add -Wl,-soname,$@.$(PV) ?
363
364# Default compile from objects using pre-requisites but filters out
365# all non-.o values. (Remember to add -L$(OUT) -llib)
366COMMA := ,
367define COMPILE_LIBRARY_implementation
368 @$(ECHO) "SHARED$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
Ryan Harrison3e776a12013-02-06 16:39:30 -0500369 $(call auto_mkdir,$(TARGET_OR_MEMBER))
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700370 $(QUIET)$($(1)) -shared -Wl,-E -o $(TARGET_OR_MEMBER) \
371 $(2) $(LDFLAGS) \
372 $(if $(filter %.a,$^),-Wl$(COMMA)--whole-archive,) \
373 $(filter %.o ,$(^:.o=.pic.o)) \
374 $(foreach a,$(filter %.a,$^),-L$(dir $(a)) \
375 -l$(patsubst lib%,%,$(basename $(notdir $(a))))) \
376 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
377 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
378 $(LDLIBS)
379 $(call conditional_strip)
380 @$(ECHO) -n "LIB $(COLOR_GREEN)"
381 @$(ECHO) "$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
382 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
383endef
384
385define conditional_strip
386 $(if $(filter 0,$(NOSTRIP)),$(call strip_artifact))
387endef
388
389define strip_artifact
390 @$(ECHO) "STRIP $(subst $(OUT)/,,$(TARGET_OR_MEMBER))"
391 $(if $(filter 1,$(SPLITDEBUG)), @$(ECHO) -n "DEBUG "; \
392 $(ECHO) "$(COLOR_YELLOW)\
393$(subst $(OUT)/,,$(TARGET_OR_MEMBER)).debug$(COLOR_RESET)")
394 $(if $(filter 1,$(SPLITDEBUG)), \
395 $(QUIET)$(OBJCOPY) --only-keep-debug "$(TARGET_OR_MEMBER)" \
396 "$(TARGET_OR_MEMBER).debug")
397 $(if $(filter-out dbg,$(MODE)),$(QUIET)$(STRIP) --strip-unneeded \
398 "$(TARGET_OR_MEMBER)",)
399endef
400
401#
402# Global pattern rules
403#
404
405# Below, the archive member syntax is abused to create fancier
406# syntactic sugar for recipe authors that avoids needed to know
407# subcall options. The downside is that make attempts to look
408# into the phony archives for timestamps. This will cause the final
409# target to be rebuilt/linked on _every_ call to make even when nothing
410# has changed. Until a better way presents itself, we have helpers that
411# do the stat check on make's behalf. Dodgy but simple.
412define old_or_no_timestamp
413 $(if $(realpath $%),,$(1))
414 $(if $(shell find $^ -cnewer "$%" 2>/dev/null),$(1))
415endef
416
417define check_deps
418 $(if $(filter 0,$(words $^)),\
419 $(error Missing dependencies or declaration of $@($%)),)
420endef
421
422# Build a cxx target magically
423CXX_BINARY(%):
424 $(call check_deps)
425 $(call old_or_no_timestamp,$(call cxx_binary))
426clean: CLEAN(CXX_BINARY*)
427
428CC_BINARY(%):
429 $(call check_deps)
430 $(call old_or_no_timestamp,$(call cc_binary))
431clean: CLEAN(CC_BINARY*)
432
433CXX_STATIC_BINARY(%):
434 $(call check_deps)
435 $(call old_or_no_timestamp,$(call cxx_binary,-static))
436clean: CLEAN(CXX_STATIC_BINARY*)
437
438CC_STATIC_BINARY(%):
439 $(call check_deps)
440 $(call old_or_no_timestamp,$(call cc_binary,-static))
441clean: CLEAN(CC_STATIC_BINARY*)
442
443CXX_LIBRARY(%):
444 $(call check_deps)
445 $(call old_or_no_timestamp,$(call cxx_library))
446clean: CLEAN(CXX_LIBRARY*)
447
448CXX_LIBARY(%):
449 $(error Typo alert! LIBARY != LIBRARY)
450
451CC_LIBRARY(%):
452 $(call check_deps)
453 $(call old_or_no_timestamp,$(call cc_library))
454clean: CLEAN(CC_LIBRARY*)
455
456CC_LIBARY(%):
457 $(error Typo alert! LIBARY != LIBRARY)
458
459CXX_STATIC_LIBRARY(%):
460 $(call check_deps)
461 $(call old_or_no_timestamp,$(call update_archive))
462clean: CLEAN(CXX_STATIC_LIBRARY*)
463
464CXX_STATIC_LIBARY(%):
465 $(error Typo alert! LIBARY != LIBRARY)
466
467CC_STATIC_LIBRARY(%):
468 $(call check_deps)
469 $(call old_or_no_timestamp,$(call update_archive))
470clean: CLEAN(CC_STATIC_LIBRARY*)
471
472CC_STATIC_LIBARY(%):
473 $(error Typo alert! LIBARY != LIBRARY)
474
475
476TEST(%): % qemu_chroot_install
477 $(call TEST_implementation)
478.PHONY: TEST
479
480# multiple targets with a wildcard need to share an directory.
481# Don't use this directly it just makes sure the directory is removed _after_
482# the files are.
483CLEANFILE(%):
484 $(call silent_rm,$(TARGET_OR_MEMBER))
485.PHONY: CLEANFILE
486
487CLEAN(%): CLEANFILE(%)
488 $(QUIET)# CLEAN($%) meta-target called
489 $(if $(filter-out $(PWD)/,$(dir $(abspath $(TARGET_OR_MEMBER)))), \
490 $(call silent_rmdir,$(dir $(abspath $(TARGET_OR_MEMBER)))),\
491 $(QUIET)# Not deleting $(dir $(abspath $(TARGET_OR_MEMBER))) yet.)
492.PHONY: CLEAN
493
494#
495# Top-level objects and pattern rules
496#
497
498# All objects for .c files at the top level
499C_OBJECTS = $(patsubst $(SRC)/%.c,%.o,$(wildcard $(SRC)/*.c))
500
501
502# All objects for .cxx files at the top level
503CXX_OBJECTS = $(patsubst $(SRC)/%.cc,%.o,$(wildcard $(SRC)/*.cc))
504
505# Note, the catch-all pattern rules don't work in subdirectories because
506# we're building from the $(OUT) directory. At the top-level (here) they will
507# work, but we go ahead and match using the module form. Then we can place a
508# generic pattern rule to capture leakage from the main Makefile. (Later in the
509# file.)
510#
511# The reason target specific pattern rules work well for modules,
512# MODULE_C_OBJECTS, is because it scopes the behavior to the given target which
513# ensures we get a relative directory offset from $(OUT) which otherwise would
514# not match without further magic on a per-subdirectory basis.
515
516# Creates object file rules. Call with eval.
517# $(1) list of .o files
518# $(2) source type (CC or CXX)
519# $(3) source suffix (cc or c)
520# $(4) compiler flag name (CFLAGS or CXXFLAGS)
521# $(5) source dir: _only_ if $(SRC). Leave blank for obj tree.
522define add_object_rules
523$(patsubst %.o,%.pie.o,$(1)): %.pie.o: $(5)%.$(3) %.o.depends
Ryan Harrison3e776a12013-02-06 16:39:30 -0500524 $$(call auto_mkdir,$$@)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700525 $$(call OBJECT_PATTERN_implementation,$(2),\
526 $$(basename $$@),$$($(4)) $$(CPPFLAGS) $$(OBJ_PIE_FLAG))
527
528$(patsubst %.o,%.pic.o,$(1)): %.pic.o: $(5)%.$(3) %.o.depends
Ryan Harrison3e776a12013-02-06 16:39:30 -0500529 $$(call auto_mkdir,$$@)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700530 $$(call OBJECT_PATTERN_implementation,$(2),\
531 $$(basename $$@),$$($(4)) $$(CPPFLAGS) -fPIC)
532
533# Placeholder for depends
534$(patsubst %.o,%.o.depends,$(1)):
Ryan Harrison3e776a12013-02-06 16:39:30 -0500535 $$(call auto_mkdir,$$@)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700536 $$(QUIET)touch "$$@"
537
538$(1): %.o: %.pic.o %.pie.o
Ryan Harrison3e776a12013-02-06 16:39:30 -0500539 $$(call auto_mkdir,$$@)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700540 $$(QUIET)touch "$$@"
541endef
542
543define OBJECT_PATTERN_implementation
544 @$(ECHO) "$(1) $(subst $(SRC)/,,$<) -> $(2).o"
Ryan Harrison3e776a12013-02-06 16:39:30 -0500545 $(call auto_mkdir,$@)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700546 $(QUIET)$($(1)) -c -MD -MF $(2).d $(3) -o $(2).o $<
Ryan Harrison3e776a12013-02-06 16:39:30 -0500547 $(QUIET)# Wrap all the deps in $$(wildcard) so a missing header
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700548 $(QUIET)# won't cause weirdness. First we remove newlines and \,
549 $(QUIET)# then wrap it.
550 $(QUIET)sed -i -e :j -e '$$!N;s|\\\s*\n| |;tj' \
551 -e 's|^\(.*\s*:\s*\)\(.*\)$$|\1 $$\(wildcard \2\)|' $(2).d
552endef
553
554# Now actually register handlers for C(XX)_OBJECTS.
555$(eval $(call add_object_rules,$(C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
556$(eval $(call add_object_rules,$(CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
557
558# Disable default pattern rules to help avoid leakage.
559# These may already be handled by '-r', but let's keep it to be safe.
560%: %.o ;
561%.a: %.o ;
562%.o: %.c ;
563%.o: %.cc ;
564
565# NOTE: A specific rule for archive objects is avoided because parallel
566# update of the archive causes build flakiness.
567# Instead, just make the objects the prerequisites and use update_archive
568# To use the foo.a(obj.o) functionality, targets would need to specify the
569# explicit object they expect on the prerequisite line.
570
571#
572# Architecture detection and QEMU wrapping
573#
574
575HOST_ARCH ?= $(shell uname -m)
576override ARCH := $(strip $(ARCH))
577override HOST_ARCH := $(strip $(HOST_ARCH))
578# emake will supply "x86" or "arm" for ARCH, but
579# if uname -m runs and you get x86_64, then this subst
580# will break.
581ifeq ($(subst x86,i386,$(ARCH)),i386)
582 QEMU_ARCH := $(subst x86,i386,$(ARCH)) # x86 -> i386
583else ifeq ($(subst amd64,x86_64,$(ARCH)),x86_64)
584 QEMU_ARCH := $(subst amd64,x86_64,$(ARCH)) # amd64 -> x86_64
585else
586 QEMU_ARCH = $(ARCH)
587endif
588override QEMU_ARCH := $(strip $(QEMU_ARCH))
589
590# If we're cross-compiling, try to use qemu for running the tests.
591ifneq ($(QEMU_ARCH),$(HOST_ARCH))
592 ifeq ($(SYSROOT),)
593 $(info SYSROOT not defined. qemu-based testing disabled)
594 else
595 # A SYSROOT is assumed for QEmu use.
596 USE_QEMU ?= 1
597
598 # Allow 64-bit hosts to run 32-bit without qemu.
599 ifeq ($(HOST_ARCH),x86_64)
600 ifeq ($(QEMU_ARCH),i386)
601 USE_QEMU = 0
602 endif
603 endif
604 endif
605else
606 USE_QEMU ?= 0
607endif
608
609SYSROOT_OUT = $(OUT)
610ifneq ($(SYSROOT),)
611 SYSROOT_OUT = $(subst $(SYSROOT),,$(OUT))
612else
613 # Default to / when all the empty-sysroot logic is done.
614 SYSROOT = /
615endif
616
617
618#
619# Output full configuration at top level
620#
621
622# Don't show on clean
623ifneq ($(MAKECMDGOALS),clean)
624 $(info build configuration:)
625 $(info - OUT=$(OUT))
626 $(info - SRC=$(SRC))
627 $(info - MODE=$(MODE))
628 $(info - SPLITDEBUG=$(SPLITDEBUG))
629 $(info - NOSTRIP=$(NOSTRIP))
630 $(info - VALGRIND=$(VALGRIND))
631 $(info - COLOR=$(COLOR))
632 $(info - ARCH=$(ARCH))
633 $(info - QEMU_ARCH=$(QEMU_ARCH))
634 $(info - SYSROOT=$(SYSROOT))
635 $(info )
636endif
637
638#
639# Standard targets with detection for when they are improperly configured.
640#
641
642# all does not include tests by default
643all:
644 $(QUIET)(test -z "$^" && \
645 $(ECHO) "You must add your targets as 'all' prerequisites") || true
646 $(QUIET)test -n "$^"
647
648# Builds and runs tests for the target arch
649# Run them in parallel
Ryan Harrison3e776a12013-02-06 16:39:30 -0500650# After the test have completed, if profiling, run coverage analysis
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700651tests:
Ryan Harrison3e776a12013-02-06 16:39:30 -0500652ifeq ($(MODE),profiling)
653 @$(ECHO) -n "COVERAGE gcov "
654 @$(ECHO) "[$(COLOR_YELLOW)STARTED$(COLOR_RESET)]"
655 $(QUIET)(FILES=""; \
656 for GCNO in `find . -name "*.gcno"`; \
657 do \
658 GCDA="$${GCNO%.gcno}.gcda"; \
659 [ -e $${GCDA} ] && FILES="$${FILES} $${GCDA}"; \
660 done; \
661 gcov -l $${FILES})
662 @$(ECHO) -n "COVERAGE gcov "
663 @$(ECHO) "[$(COLOR_YELLOW)FINISHED$(COLOR_RESET)]"
664 @$(ECHO) -n "COVERAGE lcov "
665 @$(ECHO) "[$(COLOR_YELLOW)STARTED$(COLOR_RESET)]"
666 $(QUIET)lcov --capture --directory . --output-file=lcov-coverage.info
667 $(QUIET)genhtml lcov-coverage.info --output-directory lcov-html
668 @$(ECHO) -n "COVERAGE lcov "
669 @$(ECHO) "[$(COLOR_YELLOW)FINISHED$(COLOR_RESET)]"
670endif
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700671.PHONY: tests
672
673qemu_clean:
674 $(call if_qemu,$(call silent_rm,$(OUT)/qemu-$(QEMU_ARCH)))
675
676qemu_chroot_install:
677ifeq ($(USE_QEMU),1)
678 $(QUIET)$(ECHO) "QEMU Preparing qemu-$(QEMU_ARCH)"
679 $(QUIET)cp -fu /usr/bin/qemu-$(QEMU_ARCH) $(OUT)/qemu-$(QEMU_ARCH)
680 $(QUIET)chmod a+rx $(OUT)/qemu-$(QEMU_ARCH)
681endif
682.PHONY: qemu_clean qemu_chroot_install
683
684# TODO(wad) Move to -L $(SYSROOT) and fakechroot when qemu-user
685# doesn't hang traversing /proc from SYSROOT.
686QEMU_CMD =
687ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),sudo , )
688MOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) mount, \#)
689UMOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) umount, \#)
690QEMU_LDPATH = $(SYSROOT_LDPATH):/lib64:/lib:/usr/lib64:/usr/lib
691ROOT_CMD_LDPATH = $(SYSROOT_LDPATH):$(SYSROOT)/lib64:
692ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/lib:$(SYSROOT)/usr/lib64:
693ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/usr/lib
694ifeq ($(USE_QEMU),1)
695 export QEMU_CMD = \
696 sudo chroot $(SYSROOT) $(SYSROOT_OUT)qemu-$(QEMU_ARCH) \
697 -drop-ld-preload \
698 -E LD_LIBRARY_PATH="$(QEMU_LDPATH):$(patsubst $(OUT),,$(LD_DIRS))" \
699 -E HOME="$(HOME)" --
700 # USE_QEMU conditional function
701 define if_qemu
702 $(1)
703 endef
704else
705 ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),sudo, ) \
706 LD_LIBRARY_PATH="$(ROOT_CMD_LDPATH):$(LD_DIRS)"
707 define if_qemu
708 $(2)
709 endef
710endif
711
712VALGRIND_CMD =
713ifeq ($(VALGRIND),1)
714 VALGRIND_CMD = /usr/bin/valgrind --tool=memcheck $(VALGRIND_ARGS) --
715endif
716
717define TEST_implementation
718 $(QUIET)$(call TEST_setup)
719 $(QUIET)$(call TEST_run)
720 $(QUIET)$(call TEST_teardown)
721 $(QUIET)exit $$(cat $(OUT)$(TARGET_OR_MEMBER).status.test)
722endef
723
724define TEST_setup
725 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
726 @$(ECHO) "[$(COLOR_YELLOW)SETUP$(COLOR_RESET)]"
727 $(QUIET)# Setup a target-specific results file
728 $(QUIET)(echo 1 > $(OUT)$(TARGET_OR_MEMBER).status.test)
729 $(QUIET)(echo > $(OUT)$(TARGET_OR_MEMBER).cleanup.test)
730 $(QUIET)# No setup if we are not using QEMU
731 $(QUIET)# TODO(wad) this is racy until we use a vfs namespace
732 $(call if_qemu,\
733 $(QUIET)sudo mkdir -p "$(SYSROOT)/proc" "$(SYSROOT)/dev")
734 $(call if_qemu,\
735 $(QUIET)$(MOUNT_CMD) --bind /proc "$(SYSROOT)/proc")
736 $(call if_qemu,\
737 $(QUIET)$(MOUNT_CMD) --bind /dev "$(SYSROOT)/dev")
738 $(call if_qemu,\
739 $(QUIET)(echo "$(UMOUNT_CMD) -l '$(SYSROOT)/proc'" \
740 >> "$(OUT)$(TARGET_OR_MEMBER).cleanup.test"))
741 $(call if_qemu,\
742 $(QUIET)(echo "$(UMOUNT_CMD) -l '$(SYSROOT)/dev'" \
743 >> "$(OUT)$(TARGET_OR_MEMBER).cleanup.test"))
744endef
745
746define TEST_teardown
747 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
748 @$(ECHO) "[$(COLOR_YELLOW)TEARDOWN$(COLOR_RESET)]"
749 $(call if_qemu, $(QUIET)$(SHELL) "$(OUT)$(TARGET_OR_MEMBER).cleanup.test")
750endef
751
752# Use GTEST_ARGS.[arch] if defined.
753override GTEST_ARGS.real = \
754 $(call if_qemu,$(GTEST_ARGS.qemu.$(QEMU_ARCH)),$(GTEST_ARGS.host.$(HOST_ARCH)))
755
756define TEST_run
757 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
758 @$(ECHO) "[$(COLOR_GREEN)RUN$(COLOR_RESET)]"
759 $(QUIET)(echo 1 > "$(OUT)$(TARGET_OR_MEMBER).status.test")
760 -($(ROOT_CMD) $(QEMU_CMD) $(VALGRIND_CMD) \
761 "$(strip $(call if_qemu, $(SYSROOT_OUT),$(OUT))$(TARGET_OR_MEMBER))" \
762 $(if $(filter-out 0,$(words $(GTEST_ARGS.real))),$(GTEST_ARGS.real),\
763 $(GTEST_ARGS)) && \
764 echo 0 > "$(OUT)$(TARGET_OR_MEMBER).status.test")
765endef
766
767# Recursive list reversal so that we get RMDIR_ON_CLEAN in reverse order.
768define reverse
769$(if $(1),$(call reverse,$(wordlist 2,$(words $(1)),$(1)))) $(firstword $(1))
770endef
771
772clean: qemu_clean
773clean: CLEAN($(OUT)*.d) CLEAN($(OUT)*.o) CLEAN($(OUT)*.debug)
774clean: CLEAN($(OUT)*.test) CLEAN($(OUT)*.depends)
Ryan Harrison3e776a12013-02-06 16:39:30 -0500775clean: CLEAN($(OUT)*.gcno) CLEAN($(OUT)*.gcda) CLEAN($(OUT)*.gcov)
776clean: CLEAN($(OUT)lcov-coverage.info) CLEAN($(OUT)lcov-html)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700777
778clean:
779 $(QUIET)# Always delete the containing directory last.
780 $(call silent_rmdir,$(OUT))
781
782FORCE: ;
783# Empty rule for use when no special targets are needed, like large_tests
784NONE:
785
786.PHONY: clean NONE valgrind NONE
787.DEFAULT_GOAL := all
788# Don't let make blow away "intermediates"
789.PRECIOUS: %.pic.o %.pie.o %.a %.pic.a %.pie.a %.test
790
791# Start accruing build info
792OUT_DIRS = $(OUT)
793LD_DIRS = $(OUT)
794SRC_DIRS = $(SRC)
795
796include $(wildcard $(OUT)*.d)
797SUBMODULE_DIRS = $(wildcard $(SRC)/*/module.mk)
798include $(SUBMODULE_DIRS)
799
800
801else ## In duplicate inclusions of common.mk
802
803# Get the current inclusion directory without a trailing slash
804MODULE := $(patsubst %/,%, \
805 $(dir $(lastword $(filter-out %common.mk,$(MAKEFILE_LIST)))))
806MODULE := $(subst $(SRC)/,,$(MODULE))
807MODULE_NAME := $(subst /,_,$(MODULE))
808#VPATH := $(MODULE):$(VPATH)
809
810
811# Depth first
812$(eval OUT_DIRS += $(OUT)$(MODULE))
813$(eval SRC_DIRS += $(OUT)$(MODULE))
814$(eval LD_DIRS := $(LD_DIRS):$(OUT)$(MODULE))
815
816# Add the defaults from this dir to rm_clean
817clean: CLEAN($(OUT)$(MODULE)/*.d) CLEAN($(OUT)$(MODULE)/*.o)
818clean: CLEAN($(OUT)$(MODULE)/*.debug) CLEAN($(OUT)$(MODULE)/*.test)
819clean: CLEAN($(OUT)$(MODULE)/*.depends)
Ryan Harrison3e776a12013-02-06 16:39:30 -0500820clean: CLEAN($(OUT)$(MODULE)/*.gcno) CLEAN($(OUT)$(MODULE)/*.gcda)
821clean: CLEAN($(OUT)$(MODULE)/*.gcov) CLEAN($(OUT)lcov-coverage.info)
822clean: CLEAN($(OUT)lcov-html)
Dennis Kempinbf37f5d2012-06-14 18:44:07 -0700823
824$(info + submodule: $(MODULE_NAME))
825# We must eval otherwise they may be dropped.
826MODULE_C_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.c,$(MODULE)/%.o,\
827 $(wildcard $(SRC)/$(MODULE)/*.c))
828$(eval $(MODULE_NAME)_C_OBJECTS ?= $(MODULE_C_OBJECTS))
829MODULE_CXX_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.cc,$(MODULE)/%.o,\
830 $(wildcard $(SRC)/$(MODULE)/*.cc))
831$(eval $(MODULE_NAME)_CXX_OBJECTS ?= $(MODULE_CXX_OBJECTS))
832
833# Note, $(MODULE) is implicit in the path to the %.c.
834# See $(C_OBJECTS) for more details.
835# Register rules for the module objects.
836$(eval $(call add_object_rules,$(MODULE_C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
837$(eval $(call add_object_rules,$(MODULE_CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
838
839# Continue recursive inclusion of module.mk files
840SUBMODULE_DIRS = $(wildcard $(SRC)/$(MODULE)/*/module.mk)
841include $(wildcard $(OUT)$(MODULE)/*.d)
842include $(SUBMODULE_DIRS)
843
844endif
845endif ## pass-to-subcall wrapper for relocating the call directory