blob: aed7d3e95d5cd6da074f4a96b7fbbdac4aef79b3 [file] [log] [blame]
Hidehiko Abe0411add2017-12-13 19:00:02 +09001# 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:
10# https://chromium.googlesource.com/chromiumos/platform2/+/master/common-mk
11# 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/b.o,CC,c,CFLAGS))
55# - For C++ source files
56# $(eval $(call add_object_rules,sub/dir/gen_a.o sub/dir/b.o,CXX,cc,CXXFLAGS))
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)
67# - 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.
72# - 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
103CXXEXCEPTIONS ?= 0
104ARCH ?= $(shell uname -m)
105
106# Put objects in a separate tree based on makefile locations
107# This means you can build a tree without touching it:
108# make -C $SRCDIR # will create ./build-$(MODE)
109# Or
110# make -C $SRCDIR OUT=$PWD
111# This variable is extended on subdir calls and doesn't need to be re-called.
112OUT ?= $(PWD)/
113
114# Make OUT now so we can use realpath.
115$(shell mkdir -p "$(OUT)")
116
117# TODO(wad) Relative paths are resolved against SRC and not the calling dir.
118# Ensure a command-line supplied OUT has a slash
119override OUT := $(realpath $(OUT))/
120
121# SRC is not meant to be set by the end user, but during make call relocation.
122# $(PWD) != $(CURDIR) all the time.
123export SRC ?= $(CURDIR)
124
125# Re-start in the $(OUT) directory if we're not there.
126# We may be invoked using -C or bare and we need to ensure behavior
127# is consistent so we check both PWD vs OUT and PWD vs CURDIR.
128override RELOCATE_BUILD := 0
129ifneq (${PWD}/,${OUT})
130override RELOCATE_BUILD := 1
131endif
132# Make sure we're running with no builtin targets. They cause
133# leakage and mayhem!
134ifneq (${PWD},${CURDIR})
135override RELOCATE_BUILD := 1
136# If we're run from the build dir, don't let it get cleaned up later.
137ifeq (${PWD}/,${OUT})
138$(shell touch "$(PWD)/.dont_delete_on_clean")
139endif
140endif # ifneq (${PWD},${CURDIR}
141
142# "Relocate" if we need to restart without implicit rules.
143ifeq ($(subst r,,$(MAKEFLAGS)),$(MAKEFLAGS))
144override RELOCATE_BUILD := 1
145endif
146
147ifeq (${RELOCATE_BUILD},1)
148# By default, silence build output. Reused below as well.
149QUIET = @
150ifeq ($(VERBOSE),1)
151 QUIET=
152endif
153
154# This target will override all targets, including prerequisites. To avoid
155# calling $(MAKE) once per prereq on the given CMDGOAL, we guard it with a local
156# variable.
157RUN_ONCE := 0
158MAKECMDGOALS ?= all
159# Keep the rules split as newer make does not allow them to be declared
160# on the same line. But the way :: rules work, the _all here will also
161# invoke the %:: rule while retaining "_all" as the default.
162_all::
163%::
164 $(if $(filter 0,$(RUN_ONCE)), \
165 cd "$(OUT)" && \
166 $(MAKE) -r -I "$(SRC)" -f "$(CURDIR)/Makefile" \
167 SRC="$(CURDIR)" OUT="$(OUT)" $(foreach g,$(MAKECMDGOALS),"$(g)"),)
168 $(eval RUN_ONCE := 1)
169pass-to-subcall := 1
170endif
171
172ifeq ($(pass-to-subcall),)
173
174# Only call MODULE if we're in a submodule
175MODULES_LIST := $(filter-out Makefile %.d,$(MAKEFILE_LIST))
176ifeq ($(words $(filter-out Makefile common.mk %.d $(SRC)/Makefile \
177 $(SRC)/common.mk,$(MAKEFILE_LIST))),0)
178
179# All the top-level defines outside of module.mk.
180
181#
182# Helper macros
183#
184
185# Create the directory if it doesn't yet exist.
186define auto_mkdir
187 $(if $(wildcard $(dir $1)),$2,$(QUIET)mkdir -p "$(dir $1)")
188endef
189
190# Creates the actual archive with an index.
191# The target $@ must end with .pic.a or .pie.a.
192define update_archive
193 $(call auto_mkdir,$(TARGET_OR_MEMBER))
194 $(QUIET)# Create the archive in one step to avoid parallel use accessing it
195 $(QUIET)# before all the symbols are present.
196 @$(ECHO) "AR $(subst \
197$(SRC)/,,$(^:.o=$(suffix $(basename $(TARGET_OR_MEMBER))).o)) \
198-> $(subst $(SRC)/,,$(TARGET_OR_MEMBER))"
199 $(QUIET)$(AR) rcs $(TARGET_OR_MEMBER) \
200 $(subst $(SRC)/,,$(^:.o=$(suffix $(basename $(TARGET_OR_MEMBER))).o))
201endef
202
203# Default compile from objects using pre-requisites but filters out
204# subdirs and .d files.
205define cc_binary
206 $(call COMPILE_BINARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
207endef
208
209define cxx_binary
210 $(call COMPILE_BINARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
211endef
212
213# Default compile from objects using pre-requisites but filters out
214# subdirs and .d files.
215define cc_library
216 $(call COMPILE_LIBRARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
217endef
218define cxx_library
219 $(call COMPILE_LIBRARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
220endef
221
222# Deletes files silently if they exist. Meant for use in any local
223# clean targets.
224define silent_rm
225 $(if $(wildcard $(1)),
226 $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANFILE$(COLOR_RESET) ' && \
227 $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
228 $(RM) $(1) 2>/dev/null) || true,)
229endef
230define silent_rmdir
231 $(if $(wildcard $(1)),
232 $(if $(wildcard $(1)/*),
233 $(QUIET)# $(1) not empty [$(wildcard $(1)/*)]. Not deleting.,
234 $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANDIR$(COLOR_RESET) ' && \
235 $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
236 $(RMDIR) $(1) 2>/dev/null) || true),)
237endef
238
239#
240# Default variable values
241#
242
243# Only override toolchain vars if they are from make.
244CROSS_COMPILE ?=
245define override_var
246ifneq ($(filter undefined default,$(origin $1)),)
247$1 = $(CROSS_COMPILE)$2
248endif
249endef
250$(eval $(call override_var,AR,ar))
251$(eval $(call override_var,CC,gcc))
252$(eval $(call override_var,CXX,g++))
253$(eval $(call override_var,OBJCOPY,objcopy))
254$(eval $(call override_var,PKG_CONFIG,pkg-config))
255$(eval $(call override_var,RANLIB,ranlib))
256$(eval $(call override_var,STRIP,strip))
257
258RMDIR ?= rmdir
259ECHO = /bin/echo -e
260
261ifeq ($(lastword $(subst /, ,$(CC))),clang)
262CDRIVER = clang
263else
264CDRIVER = gcc
265endif
266
267ifeq ($(lastword $(subst /, ,$(CXX))),clang++)
268CXXDRIVER = clang
269else
270CXXDRIVER = gcc
271endif
272
273# Internal macro to support check_XXX macros below.
274# Usage: $(call check_compile, [code], [compiler], [code_type], [c_flags],
275# [extra_c_flags], [library_flags], [success_ret], [fail_ret])
276# Return: [success_ret] if compile succeeded, otherwise [fail_ret]
277check_compile = $(shell printf '%b\n' $(1) | \
278 $($(2)) $($(4)) -x $(3) $(LDFLAGS) $(5) - $(6) -o /dev/null > /dev/null 2>&1 \
279 && echo "$(7)" || echo "$(8)")
280
281# Helper macro to check whether a test program will compile with the specified
282# compiler flags.
283# Usage: $(call check_compile_cc, [code], [flags], [alternate_flags])
284# Return: [flags] if compile succeeded, otherwise [alternate_flags]
285check_compile_cc = $(call check_compile,$(1),CC,c,CFLAGS,$(2),,$(2),$(3))
286check_compile_cxx = $(call check_compile,$(1),CXX,c++,CXXFLAGS,$(2),,$(2),$(3))
287
288# Helper macro to check whether a test program will compile with the specified
289# libraries.
290# Usage: $(call check_compile_cc, [code], [library_flags], [alternate_flags])
291# Return: [library_flags] if compile succeeded, otherwise [alternate_flags]
292check_libs_cc = $(call check_compile,$(1),CC,c,CFLAGS,,$(2),$(2),$(3))
293check_libs_cxx = $(call check_compile,$(1),CXX,c++,CXXFLAGS,,$(2),$(2),$(3))
294
295# Helper macro to check whether the compiler accepts the specified flags.
296# Usage: $(call check_compile_cc, [flags], [alternate_flags])
297# Return: [flags] if compile succeeded, otherwise [alternate_flags]
298check_cc = $(call check_compile_cc,'int main() { return 0; }',$(1),$(2))
299check_cxx = $(call check_compile_cxx,'int main() { return 0; }',$(1),$(2))
300
301# Choose the stack protector flags based on whats supported by the compiler.
302SSP_CFLAGS := $(call check_cc,-fstack-protector-strong)
303ifeq ($(SSP_CFLAGS),)
304 SSP_CFLAGS := $(call check_cc,-fstack-protector-all)
305endif
306
307# To update these from an including Makefile:
308# CXXFLAGS += -mahflag # Append to the list
309# CXXFLAGS := -mahflag $(CXXFLAGS) # Prepend to the list
310# CXXFLAGS := $(filter-out badflag,$(CXXFLAGS)) # Filter out a value
311# The same goes for CFLAGS.
312COMMON_CFLAGS-gcc := -fvisibility=internal -ggdb3 -Wa,--noexecstack
313COMMON_CFLAGS-clang := -fvisibility=hidden -ggdb
314COMMON_CFLAGS := -Wall -Werror -fno-strict-aliasing $(SSP_CFLAGS) -O1 -Wformat=2
315CXXFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CXXDRIVER))
316CFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CDRIVER))
317CPPFLAGS += -D_FORTIFY_SOURCE=2
318
319# Enable large file support.
320CPPFLAGS += -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
321
322# Disable exceptions based on the CXXEXCEPTIONS setting.
323ifeq ($(CXXEXCEPTIONS),0)
324 CXXFLAGS := $(CXXFLAGS) -fno-exceptions -fno-unwind-tables \
325 -fno-asynchronous-unwind-tables
326endif
327
328ifeq ($(MODE),opt)
329 # Up the optimizations.
330 CFLAGS := $(filter-out -O1,$(CFLAGS)) -O2
331 CXXFLAGS := $(filter-out -O1,$(CXXFLAGS)) -O2
332 # Only drop -g* if symbols aren't desired.
333 ifeq ($(NOSTRIP),0)
334 # TODO: do we want -fomit-frame-pointer on x86?
335 CFLAGS := $(filter-out -ggdb3,$(CFLAGS))
336 CXXFLAGS := $(filter-out -ggdb3,$(CXXFLAGS))
337 endif
338endif
339
340ifeq ($(MODE),profiling)
341 CFLAGS := $(CFLAGS) -O0 -g --coverage
342 CXXFLAGS := $(CXXFLAGS) -O0 -g --coverage
343 LDFLAGS := $(LDFLAGS) --coverage
344endif
345
346LDFLAGS := $(LDFLAGS) -Wl,-z,relro -Wl,-z,noexecstack -Wl,-z,now
347
348# Fancy helpers for color if a prompt is defined
349ifeq ($(COLOR),1)
350COLOR_RESET = \x1b[0m
351COLOR_GREEN = \x1b[32;01m
352COLOR_RED = \x1b[31;01m
353COLOR_YELLOW = \x1b[33;01m
354endif
355
356# By default, silence build output.
357QUIET = @
358ifeq ($(VERBOSE),1)
359 QUIET=
360endif
361
362#
363# Implementation macros for compile helpers above
364#
365
366# Useful for dealing with pie-broken toolchains.
367# Call make with PIE=0 to disable default PIE use.
368OBJ_PIE_FLAG = -fPIE
369COMPILE_PIE_FLAG = -pie
370ifeq ($(PIE),0)
371 OBJ_PIE_FLAG =
372 COMPILE_PIE_FLAG =
373endif
374
375# Favor member targets first for CXX_BINARY(%) magic.
376# And strip out nested members if possible.
377LP := (
378RP := )
379TARGET_OR_MEMBER = $(lastword $(subst $(LP), ,$(subst $(RP),,$(or $%,$@))))
380
381# Default compile from objects using pre-requisites but filters out
382# all non-.o files.
383define COMPILE_BINARY_implementation
384 @$(ECHO) "LD$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
385 $(call auto_mkdir,$(TARGET_OR_MEMBER))
386 $(QUIET)$($(1)) $(COMPILE_PIE_FLAGS) -o $(TARGET_OR_MEMBER) \
387 $(2) $(LDFLAGS) \
388 $(filter %.o %.a,$(^:.o=.pie.o)) \
389 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
390 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
391 $(LDLIBS)
392 $(call conditional_strip)
393 @$(ECHO) -n "BIN "
394 @$(ECHO) "$(COLOR_GREEN)$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
395 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
396endef
397
398# TODO: add version support extracted from PV environment variable
399#ifeq ($(PV),9999)
400#$(warning PV=$(PV). If shared object versions matter, please force PV=.)
401#endif
402# Then add -Wl,-soname,$@.$(PV) ?
403
404# Default compile from objects using pre-requisites but filters out
405# all non-.o values. (Remember to add -L$(OUT) -llib)
406COMMA := ,
407define COMPILE_LIBRARY_implementation
408 @$(ECHO) "SHARED$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
409 $(call auto_mkdir,$(TARGET_OR_MEMBER))
410 $(QUIET)$($(1)) -shared -Wl,-E -o $(TARGET_OR_MEMBER) \
411 $(2) $(LDFLAGS) \
412 $(if $(filter %.a,$^),-Wl$(COMMA)--whole-archive,) \
413 $(filter %.o ,$(^:.o=.pic.o)) \
414 $(foreach a,$(filter %.a,$^),-L$(dir $(a)) \
415 -l$(patsubst lib%,%,$(basename $(notdir $(a))))) \
416 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
417 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
418 $(LDLIBS)
419 $(call conditional_strip)
420 @$(ECHO) -n "LIB $(COLOR_GREEN)"
421 @$(ECHO) "$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
422 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
423endef
424
425define conditional_strip
426 $(if $(filter 0,$(NOSTRIP)),$(call strip_artifact))
427endef
428
429define strip_artifact
430 @$(ECHO) "STRIP $(subst $(OUT)/,,$(TARGET_OR_MEMBER))"
431 $(if $(filter 1,$(SPLITDEBUG)), @$(ECHO) -n "DEBUG "; \
432 $(ECHO) "$(COLOR_YELLOW)\
433$(subst $(OUT)/,,$(TARGET_OR_MEMBER)).debug$(COLOR_RESET)")
434 $(if $(filter 1,$(SPLITDEBUG)), \
435 $(QUIET)$(OBJCOPY) --only-keep-debug "$(TARGET_OR_MEMBER)" \
436 "$(TARGET_OR_MEMBER).debug")
437 $(if $(filter-out dbg,$(MODE)),$(QUIET)$(STRIP) --strip-unneeded \
438 "$(TARGET_OR_MEMBER)",)
439endef
440
441#
442# Global pattern rules
443#
444
445# Below, the archive member syntax is abused to create fancier
446# syntactic sugar for recipe authors that avoids needed to know
447# subcall options. The downside is that make attempts to look
448# into the phony archives for timestamps. This will cause the final
449# target to be rebuilt/linked on _every_ call to make even when nothing
450# has changed. Until a better way presents itself, we have helpers that
451# do the stat check on make's behalf. Dodgy but simple.
452define old_or_no_timestamp
453 $(if $(realpath $%),,$(1))
454 $(if $(shell find $^ -cnewer "$%" 2>/dev/null),$(1))
455endef
456
457define check_deps
458 $(if $(filter 0,$(words $^)),\
459 $(error Missing dependencies or declaration of $@($%)),)
460endef
461
462# Build a cxx target magically
463CXX_BINARY(%):
464 $(call check_deps)
465 $(call old_or_no_timestamp,$(call cxx_binary))
466clean: CLEAN(CXX_BINARY*)
467
468CC_BINARY(%):
469 $(call check_deps)
470 $(call old_or_no_timestamp,$(call cc_binary))
471clean: CLEAN(CC_BINARY*)
472
473CXX_STATIC_BINARY(%):
474 $(call check_deps)
475 $(call old_or_no_timestamp,$(call cxx_binary,-static))
476clean: CLEAN(CXX_STATIC_BINARY*)
477
478CC_STATIC_BINARY(%):
479 $(call check_deps)
480 $(call old_or_no_timestamp,$(call cc_binary,-static))
481clean: CLEAN(CC_STATIC_BINARY*)
482
483CXX_LIBRARY(%):
484 $(call check_deps)
485 $(call old_or_no_timestamp,$(call cxx_library))
486clean: CLEAN(CXX_LIBRARY*)
487
488CXX_LIBARY(%):
489 $(error Typo alert! LIBARY != LIBRARY)
490
491CC_LIBRARY(%):
492 $(call check_deps)
493 $(call old_or_no_timestamp,$(call cc_library))
494clean: CLEAN(CC_LIBRARY*)
495
496CC_LIBARY(%):
497 $(error Typo alert! LIBARY != LIBRARY)
498
499CXX_STATIC_LIBRARY(%):
500 $(call check_deps)
501 $(call old_or_no_timestamp,$(call update_archive))
502clean: CLEAN(CXX_STATIC_LIBRARY*)
503
504CXX_STATIC_LIBARY(%):
505 $(error Typo alert! LIBARY != LIBRARY)
506
507CC_STATIC_LIBRARY(%):
508 $(call check_deps)
509 $(call old_or_no_timestamp,$(call update_archive))
510clean: CLEAN(CC_STATIC_LIBRARY*)
511
512CC_STATIC_LIBARY(%):
513 $(error Typo alert! LIBARY != LIBRARY)
514
515
516TEST(%): % qemu_chroot_install
517 $(call TEST_implementation)
518.PHONY: TEST
519
520# multiple targets with a wildcard need to share an directory.
521# Don't use this directly it just makes sure the directory is removed _after_
522# the files are.
523CLEANFILE(%):
524 $(call silent_rm,$(TARGET_OR_MEMBER))
525.PHONY: CLEANFILE
526
527CLEAN(%): CLEANFILE(%)
528 $(QUIET)# CLEAN($%) meta-target called
529 $(if $(filter-out $(PWD)/,$(dir $(abspath $(TARGET_OR_MEMBER)))), \
530 $(call silent_rmdir,$(dir $(abspath $(TARGET_OR_MEMBER)))),\
531 $(QUIET)# Not deleting $(dir $(abspath $(TARGET_OR_MEMBER))) yet.)
532.PHONY: CLEAN
533
534#
535# Top-level objects and pattern rules
536#
537
538# All objects for .c files at the top level
539C_OBJECTS = $(patsubst $(SRC)/%.c,%.o,$(wildcard $(SRC)/*.c))
540
541
542# All objects for .cxx files at the top level
543CXX_OBJECTS = $(patsubst $(SRC)/%.cc,%.o,$(wildcard $(SRC)/*.cc))
544
545# Note, the catch-all pattern rules don't work in subdirectories because
546# we're building from the $(OUT) directory. At the top-level (here) they will
547# work, but we go ahead and match using the module form. Then we can place a
548# generic pattern rule to capture leakage from the main Makefile. (Later in the
549# file.)
550#
551# The reason target specific pattern rules work well for modules,
552# MODULE_C_OBJECTS, is because it scopes the behavior to the given target which
553# ensures we get a relative directory offset from $(OUT) which otherwise would
554# not match without further magic on a per-subdirectory basis.
555
556# Creates object file rules. Call with eval.
557# $(1) list of .o files
558# $(2) source type (CC or CXX)
559# $(3) source suffix (cc or c)
560# $(4) compiler flag name (CFLAGS or CXXFLAGS)
561# $(5) source dir: _only_ if $(SRC). Leave blank for obj tree.
562define add_object_rules
563$(patsubst %.o,%.pie.o,$(1)): %.pie.o: $(5)%.$(3) %.o.depends
564 $$(call auto_mkdir,$$@)
565 $$(call OBJECT_PATTERN_implementation,$(2),\
566 $$(basename $$@),$$($(4)) $$(CPPFLAGS) $$(OBJ_PIE_FLAG))
567
568$(patsubst %.o,%.pic.o,$(1)): %.pic.o: $(5)%.$(3) %.o.depends
569 $$(call auto_mkdir,$$@)
570 $$(call OBJECT_PATTERN_implementation,$(2),\
571 $$(basename $$@),$$($(4)) $$(CPPFLAGS) -fPIC)
572
573# Placeholder for depends
574$(patsubst %.o,%.o.depends,$(1)):
575 $$(call auto_mkdir,$$@)
576 $$(QUIET)touch "$$@"
577
578$(1): %.o: %.pic.o %.pie.o
579 $$(call auto_mkdir,$$@)
580 $$(QUIET)touch "$$@"
581endef
582
583define OBJECT_PATTERN_implementation
584 @$(ECHO) "$(1) $(subst $(SRC)/,,$<) -> $(2).o"
585 $(call auto_mkdir,$@)
586 $(QUIET)$($(1)) -c -MD -MF $(2).d $(3) -o $(2).o $<
587 $(QUIET)# Wrap all the deps in $$(wildcard) so a missing header
588 $(QUIET)# won't cause weirdness. First we remove newlines and \,
589 $(QUIET)# then wrap it.
590 $(QUIET)sed -i -e :j -e '$$!N;s|\\\s*\n| |;tj' \
591 -e 's|^\(.*\s*:\s*\)\(.*\)$$|\1 $$\(wildcard \2\)|' $(2).d
592endef
593
594# Now actually register handlers for C(XX)_OBJECTS.
595$(eval $(call add_object_rules,$(C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
596$(eval $(call add_object_rules,$(CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
597
598# Disable default pattern rules to help avoid leakage.
599# These may already be handled by '-r', but let's keep it to be safe.
600%: %.o ;
601%.a: %.o ;
602%.o: %.c ;
603%.o: %.cc ;
604
605# NOTE: A specific rule for archive objects is avoided because parallel
606# update of the archive causes build flakiness.
607# Instead, just make the objects the prerequisites and use update_archive
608# To use the foo.a(obj.o) functionality, targets would need to specify the
609# explicit object they expect on the prerequisite line.
610
611#
612# Architecture detection and QEMU wrapping
613#
614
615HOST_ARCH ?= $(shell uname -m)
616override ARCH := $(strip $(ARCH))
617override HOST_ARCH := $(strip $(HOST_ARCH))
618# emake will supply "x86" or "arm" for ARCH, but
619# if uname -m runs and you get x86_64, then this subst
620# will break.
621ifeq ($(subst x86,i386,$(ARCH)),i386)
622 QEMU_ARCH := $(subst x86,i386,$(ARCH)) # x86 -> i386
623else ifeq ($(subst amd64,x86_64,$(ARCH)),x86_64)
624 QEMU_ARCH := $(subst amd64,x86_64,$(ARCH)) # amd64 -> x86_64
625else
626 QEMU_ARCH = $(ARCH)
627endif
628override QEMU_ARCH := $(strip $(QEMU_ARCH))
629
630# If we're cross-compiling, try to use qemu for running the tests.
631ifneq ($(QEMU_ARCH),$(HOST_ARCH))
632 ifeq ($(SYSROOT),)
633 $(info SYSROOT not defined. qemu-based testing disabled)
634 else
635 # A SYSROOT is assumed for QEmu use.
636 USE_QEMU ?= 1
637
638 # Allow 64-bit hosts to run 32-bit without qemu.
639 ifeq ($(HOST_ARCH),x86_64)
640 ifeq ($(QEMU_ARCH),i386)
641 USE_QEMU = 0
642 endif
643 endif
644 endif
645else
646 USE_QEMU ?= 0
647endif
648
649# Normally we don't need to run as root or do bind mounts, so only
650# enable it by default when we're using QEMU.
651NEEDS_ROOT ?= $(USE_QEMU)
652NEEDS_MOUNTS ?= $(USE_QEMU)
653
654SYSROOT_OUT = $(OUT)
655ifneq ($(SYSROOT),)
656 SYSROOT_OUT = $(subst $(SYSROOT),,$(OUT))
657else
658 # Default to / when all the empty-sysroot logic is done.
659 SYSROOT = /
660endif
661
662QEMU_NAME = qemu-$(QEMU_ARCH)
663QEMU_PATH = /build/bin/$(QEMU_NAME)
664QEMU_SYSROOT_PATH = $(SYSROOT)$(QEMU_PATH)
665QEMU_SRC_PATH = /usr/bin/$(QEMU_NAME)
666QEMU_BINFMT_PATH = /proc/sys/fs/binfmt_misc/$(QEMU_NAME)
667QEMU_REGISTER_PATH = /proc/sys/fs/binfmt_misc/register
668
669QEMU_MAGIC_arm = ":$(QEMU_NAME):M::\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x28\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/build/bin/qemu-arm:"
670
671
672#
673# Output full configuration at top level
674#
675
676# Don't show on clean
677ifneq ($(MAKECMDGOALS),clean)
678 $(info build configuration:)
679 $(info - OUT=$(OUT))
680 $(info - SRC=$(SRC))
681 $(info - MODE=$(MODE))
682 $(info - SPLITDEBUG=$(SPLITDEBUG))
683 $(info - NOSTRIP=$(NOSTRIP))
684 $(info - VALGRIND=$(VALGRIND))
685 $(info - COLOR=$(COLOR))
686 $(info - CXXEXCEPTIONS=$(CXXEXCEPTIONS))
687 $(info - ARCH=$(ARCH))
688 $(info - QEMU_ARCH=$(QEMU_ARCH))
689 $(info - USE_QEMU=$(USE_QEMU))
690 $(info - NEEDS_ROOT=$(NEEDS_ROOT))
691 $(info - NEEDS_MOUNTS=$(NEEDS_MOUNTS))
692 $(info - SYSROOT=$(SYSROOT))
693 $(info )
694endif
695
696#
697# Standard targets with detection for when they are improperly configured.
698#
699
700# all does not include tests by default
701all:
702 $(QUIET)(test -z "$^" && \
703 $(ECHO) "You must add your targets as 'all' prerequisites") || true
704 $(QUIET)test -n "$^"
705
706# Builds and runs tests for the target arch
707# Run them in parallel
708# After the test have completed, if profiling, run coverage analysis
709tests:
710ifeq ($(MODE),profiling)
711 @$(ECHO) "COVERAGE [$(COLOR_YELLOW)STARTED$(COLOR_RESET)]"
712 $(QUIET)FILES=""; \
713 for GCNO in `find . -name "*.gcno"`; do \
714 GCDA="$${GCNO%.gcno}.gcda"; \
715 if [ -e $${GCDA} ]; then \
716 FILES="$${FILES} $${GCDA}"; \
717 fi \
718 done; \
719 if [ -n "$${FILES}" ]; then \
720 gcov -l $${FILES}; \
721 lcov --capture --directory . \
722 --output-file=lcov-coverage.info; \
723 genhtml lcov-coverage.info \
724 --output-directory lcov-html; \
725 fi
726 @$(ECHO) "COVERAGE [$(COLOR_YELLOW)FINISHED$(COLOR_RESET)]"
727endif
728.PHONY: tests
729
730qemu_chroot_install:
731ifeq ($(USE_QEMU),1)
732 $(QUIET)$(ECHO) "QEMU Preparing $(QEMU_NAME)"
733 @# Copying strategy
734 @# Compare /usr/bin/qemu inode to /build/$board/build/bin/qemu, if different
735 @# hard link to a temporary file, then rename temp to target. This should
736 @# ensure that once $QEMU_SYSROOT_PATH exists it will always exist, regardless
737 @# of simultaneous test setups.
738 $(QUIET)if [[ ! -e $(QEMU_SYSROOT_PATH) || \
739 `stat -c %i $(QEMU_SRC_PATH)` != `stat -c %i $(QEMU_SYSROOT_PATH)` \
740 ]]; then \
741 $(ROOT_CMD) ln -Tf $(QEMU_SRC_PATH) $(QEMU_SYSROOT_PATH).$$$$; \
742 $(ROOT_CMD) mv -Tf $(QEMU_SYSROOT_PATH).$$$$ $(QEMU_SYSROOT_PATH); \
743 fi
744
745 @# Prep the binfmt handler. First mount if needed, then unregister any bad
746 @# mappings and then register our mapping.
747 @# There may still be some race conditions here where one script de-registers
748 @# and another script starts executing before it gets re-registered, however
749 @# it should be rare.
750 -$(QUIET)[[ -e $(QEMU_REGISTER_PATH) ]] || \
751 $(ROOT_CMD) mount binfmt_misc -t binfmt_misc \
752 /proc/sys/fs/binfmt_misc
753
754 -$(QUIET)if [[ -e $(QEMU_BINFMT_PATH) && \
755 `awk '$$1 == "interpreter" {print $$NF}' $(QEMU_BINFMT_PATH)` != \
756 "$(QEMU_PATH)" ]]; then \
757 echo -1 | $(ROOT_CMD) tee $(QEMU_BINFMT_PATH) >/dev/null; \
758 fi
759
760 -$(if $(QEMU_MAGIC_$(ARCH)),$(QUIET)[[ -e $(QEMU_BINFMT_PATH) ]] || \
761 echo $(QEMU_MAGIC_$(ARCH)) | $(ROOT_CMD) tee $(QEMU_REGISTER_PATH) \
762 >/dev/null)
763endif
764.PHONY: qemu_clean qemu_chroot_install
765
766# TODO(wad) Move to -L $(SYSROOT) and fakechroot when qemu-user
767# doesn't hang traversing /proc from SYSROOT.
768SUDO_CMD = sudo
769UNSHARE_CMD = unshare
770QEMU_CMD =
771ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),$(SUDO_CMD) , )
772MOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) mount, \#)
773UMOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) umount, \#)
774QEMU_LDPATH = $(SYSROOT_LDPATH):/lib64:/lib:/usr/lib64:/usr/lib
775ROOT_CMD_LDPATH = $(SYSROOT_LDPATH):$(SYSROOT)/lib64:
776ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/lib:$(SYSROOT)/usr/lib64:
777ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/usr/lib
778ifeq ($(USE_QEMU),1)
779 export QEMU_CMD = \
780 $(SUDO_CMD) chroot $(SYSROOT) $(QEMU_PATH) \
781 -drop-ld-preload \
782 -E LD_LIBRARY_PATH="$(QEMU_LDPATH):$(patsubst $(OUT),,$(LD_DIRS))" \
783 -E HOME="$(HOME)" -E SRC="$(SRC)" --
784 # USE_QEMU conditional function
785 define if_qemu
786 $(1)
787 endef
788else
789 ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),sudo, ) \
790 LD_LIBRARY_PATH="$(ROOT_CMD_LDPATH):$(LD_DIRS)"
791 define if_qemu
792 $(2)
793 endef
794endif
795
796VALGRIND_CMD =
797ifeq ($(VALGRIND),1)
798 VALGRIND_CMD = /usr/bin/valgrind --tool=memcheck $(VALGRIND_ARGS) --
799endif
800
801define TEST_implementation
802 $(QUIET)$(call TEST_setup)
803 $(QUIET)$(call TEST_run)
804 $(QUIET)$(call TEST_teardown)
805 $(QUIET)exit $$(cat $(OUT)$(TARGET_OR_MEMBER).status.test)
806endef
807
808define TEST_setup
809 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
810 @$(ECHO) "[$(COLOR_YELLOW)SETUP$(COLOR_RESET)]"
811 $(QUIET)# Setup a target-specific results file
812 $(QUIET)(echo > $(OUT)$(TARGET_OR_MEMBER).setup.test)
813 $(QUIET)(echo 1 > $(OUT)$(TARGET_OR_MEMBER).status.test)
814 $(QUIET)(echo > $(OUT)$(TARGET_OR_MEMBER).cleanup.test)
815 $(QUIET)# No setup if we are not using QEMU
816 $(QUIET)# TODO(wad) this is racy until we use a vfs namespace
817 $(call if_qemu,\
818 $(QUIET)(echo "mkdir -p '$(SYSROOT)/proc' '$(SYSROOT)/dev' \
819 '$(SYSROOT)/mnt/host/source'" \
820 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
821 $(call if_qemu,\
822 $(QUIET)(echo "$(MOUNT_CMD) --bind /mnt/host/source \
823 '$(SYSROOT)/mnt/host/source'" \
824 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
825 $(call if_qemu,\
826 $(QUIET)(echo "$(MOUNT_CMD) --bind /proc '$(SYSROOT)/proc'" \
827 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
828 $(call if_qemu,\
829 $(QUIET)(echo "$(MOUNT_CMD) --bind /dev '$(SYSROOT)/dev'" \
830 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
831endef
832
833define TEST_teardown
834 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
835 @$(ECHO) "[$(COLOR_YELLOW)TEARDOWN$(COLOR_RESET)]"
836 $(call if_qemu, $(QUIET)$(SHELL) "$(OUT)$(TARGET_OR_MEMBER).cleanup.test")
837endef
838
839# Use GTEST_ARGS.[arch] if defined.
840override GTEST_ARGS.real = \
841 $(call if_qemu,$(GTEST_ARGS.qemu.$(QEMU_ARCH)),$(GTEST_ARGS.host.$(HOST_ARCH)))
842
843define TEST_run
844 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
845 @$(ECHO) "[$(COLOR_GREEN)RUN$(COLOR_RESET)]"
846 $(QUIET)(echo 1 > "$(OUT)$(TARGET_OR_MEMBER).status.test")
847 $(QUIET)(echo $(ROOT_CMD) SRC="$(SRC)" $(QEMU_CMD) $(VALGRIND_CMD) \
848 "$(strip $(call if_qemu, $(SYSROOT_OUT),$(OUT))$(TARGET_OR_MEMBER))" \
849 $(if $(filter-out 0,$(words $(GTEST_ARGS.real))),$(GTEST_ARGS.real),\
850 $(GTEST_ARGS)) >> "$(OUT)$(TARGET_OR_MEMBER).setup.test")
851 -$(QUIET)$(call if_qemu,$(SUDO_CMD) $(UNSHARE_CMD) -m) $(SHELL) \
852 $(OUT)$(TARGET_OR_MEMBER).setup.test \
853 && echo 0 > "$(OUT)$(TARGET_OR_MEMBER).status.test"
854endef
855
856# Recursive list reversal so that we get RMDIR_ON_CLEAN in reverse order.
857define reverse
858$(if $(1),$(call reverse,$(wordlist 2,$(words $(1)),$(1)))) $(firstword $(1))
859endef
860
861clean: qemu_clean
862clean: CLEAN($(OUT)*.d) CLEAN($(OUT)*.o) CLEAN($(OUT)*.debug)
863clean: CLEAN($(OUT)*.test) CLEAN($(OUT)*.depends)
864clean: CLEAN($(OUT)*.gcno) CLEAN($(OUT)*.gcda) CLEAN($(OUT)*.gcov)
865clean: CLEAN($(OUT)lcov-coverage.info) CLEAN($(OUT)lcov-html)
866
867clean:
868 $(QUIET)# Always delete the containing directory last.
869 $(call silent_rmdir,$(OUT))
870
871FORCE: ;
872# Empty rule for use when no special targets are needed, like large_tests
873NONE:
874
875.PHONY: clean NONE valgrind NONE
876.DEFAULT_GOAL := all
877# Don't let make blow away "intermediates"
878.PRECIOUS: %.pic.o %.pie.o %.a %.pic.a %.pie.a %.test
879
880# Start accruing build info
881OUT_DIRS = $(OUT)
882LD_DIRS = $(OUT)
883SRC_DIRS = $(SRC)
884
885include $(wildcard $(OUT)*.d)
886SUBMODULE_DIRS = $(wildcard $(SRC)/*/module.mk)
887include $(SUBMODULE_DIRS)
888
889
890else ## In duplicate inclusions of common.mk
891
892# Get the current inclusion directory without a trailing slash
893MODULE := $(patsubst %/,%, \
894 $(dir $(lastword $(filter-out %common.mk,$(MAKEFILE_LIST)))))
895MODULE := $(subst $(SRC)/,,$(MODULE))
896MODULE_NAME := $(subst /,_,$(MODULE))
897#VPATH := $(MODULE):$(VPATH)
898
899
900# Depth first
901$(eval OUT_DIRS += $(OUT)$(MODULE))
902$(eval SRC_DIRS += $(OUT)$(MODULE))
903$(eval LD_DIRS := $(LD_DIRS):$(OUT)$(MODULE))
904
905# Add the defaults from this dir to rm_clean
906clean: CLEAN($(OUT)$(MODULE)/*.d) CLEAN($(OUT)$(MODULE)/*.o)
907clean: CLEAN($(OUT)$(MODULE)/*.debug) CLEAN($(OUT)$(MODULE)/*.test)
908clean: CLEAN($(OUT)$(MODULE)/*.depends)
909clean: CLEAN($(OUT)$(MODULE)/*.gcno) CLEAN($(OUT)$(MODULE)/*.gcda)
910clean: CLEAN($(OUT)$(MODULE)/*.gcov) CLEAN($(OUT)lcov-coverage.info)
911clean: CLEAN($(OUT)lcov-html)
912
913$(info + submodule: $(MODULE_NAME))
914# We must eval otherwise they may be dropped.
915MODULE_C_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.c,$(MODULE)/%.o,\
916 $(wildcard $(SRC)/$(MODULE)/*.c))
917$(eval $(MODULE_NAME)_C_OBJECTS ?= $(MODULE_C_OBJECTS))
918MODULE_CXX_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.cc,$(MODULE)/%.o,\
919 $(wildcard $(SRC)/$(MODULE)/*.cc))
920$(eval $(MODULE_NAME)_CXX_OBJECTS ?= $(MODULE_CXX_OBJECTS))
921
922# Note, $(MODULE) is implicit in the path to the %.c.
923# See $(C_OBJECTS) for more details.
924# Register rules for the module objects.
925$(eval $(call add_object_rules,$(MODULE_C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
926$(eval $(call add_object_rules,$(MODULE_CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
927
928# Continue recursive inclusion of module.mk files
929SUBMODULE_DIRS = $(wildcard $(SRC)/$(MODULE)/*/module.mk)
930include $(wildcard $(OUT)$(MODULE)/*.d)
931include $(SUBMODULE_DIRS)
932
933endif
934endif ## pass-to-subcall wrapper for relocating the call directory