1 # Copyright 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.
5 # If this file is part of another source distribution, it's license may be
6 # stored in LICENSE.makefile or LICENSE.common.mk.
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.
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.
18 # It is fully parallelizable for all targets, including static archives.
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:
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
29 # See existing makefiles for rule examples.
32 # - cc_binary, cxx_binary provide standard compilation steps for binaries
33 # - cxx_library, cc_library provide standard compilation steps for
35 # All of the above optionally take an argument for extra flags.
36 # - update_archive creates/updates a given .a target
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'.
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
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))
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.
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
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
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)
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.
96 # Behavior configuration variables
104 ARCH ?= $(shell uname -m)
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)
110 # make -C $SRCDIR OUT=$PWD
111 # This variable is extended on subdir calls and doesn't need to be re-called.
114 # Make OUT now so we can use realpath.
115 $(shell mkdir -p "$(OUT)")
117 # TODO(wad) Relative paths are resolved against SRC and not the calling dir.
118 # Ensure a command-line supplied OUT has a slash
119 override OUT := $(realpath $(OUT))/
121 # SRC is not meant to be set by the end user, but during make call relocation.
122 # $(PWD) != $(CURDIR) all the time.
123 export SRC ?= $(CURDIR)
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.
128 override RELOCATE_BUILD := 0
129 ifneq (${PWD}/,${OUT})
130 override RELOCATE_BUILD := 1
132 # Make sure we're running with no builtin targets. They cause
133 # leakage and mayhem!
134 ifneq (${PWD},${CURDIR})
135 override RELOCATE_BUILD := 1
136 # If we're run from the build dir, don't let it get cleaned up later.
137 ifeq (${PWD}/,${OUT})
138 $(shell touch "$(PWD)/.dont_delete_on_clean")
140 endif # ifneq (${PWD},${CURDIR}
142 # "Relocate" if we need to restart without implicit rules.
143 ifeq ($(subst r,,$(MAKEFLAGS)),$(MAKEFLAGS))
144 override RELOCATE_BUILD := 1
147 ifeq (${RELOCATE_BUILD},1)
148 # By default, silence build output. Reused below as well.
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
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.
164 $(if $(filter 0,$(RUN_ONCE)), \
166 $(MAKE) -r -I "$(SRC)" -f "$(CURDIR)/Makefile" \
167 SRC="$(CURDIR)" OUT="$(OUT)" $(foreach g,$(MAKECMDGOALS),"$(g)"),)
168 $(eval RUN_ONCE := 1)
172 ifeq ($(pass-to-subcall),)
174 # Only call MODULE if we're in a submodule
175 MODULES_LIST := $(filter-out Makefile %.d,$(MAKEFILE_LIST))
176 ifeq ($(words $(filter-out Makefile common.mk %.d $(SRC)/Makefile \
177 $(SRC)/common.mk,$(MAKEFILE_LIST))),0)
179 # All the top-level defines outside of module.mk.
185 # Create the directory if it doesn't yet exist.
187 $(if $(wildcard $(dir $1)),$2,$(QUIET)mkdir -p "$(dir $1)")
190 # Creates the actual archive with an index.
191 # The target $@ must end with .pic.a or .pie.a.
192 define 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))
203 # Default compile from objects using pre-requisites but filters out
204 # subdirs and .d files.
206 $(call COMPILE_BINARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
210 $(call COMPILE_BINARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
213 # Default compile from objects using pre-requisites but filters out
214 # subdirs and .d files.
216 $(call COMPILE_LIBRARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
219 $(call COMPILE_LIBRARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
222 # Deletes files silently if they exist. Meant for use in any local
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,)
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),)
240 # Default variable values
243 # Only override toolchain vars if they are from make.
246 ifneq ($(filter undefined default,$(origin $1)),)
247 $1 = $(CROSS_COMPILE)$2
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))
261 ifeq ($(lastword $(subst /, ,$(CC))),clang)
267 ifeq ($(lastword $(subst /, ,$(CXX))),clang++)
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]
277 check_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)")
281 # Helper macro to check whether a test program will compile with the specified
283 # Usage: $(call check_compile_cc, [code], [flags], [alternate_flags])
284 # Return: [flags] if compile succeeded, otherwise [alternate_flags]
285 check_compile_cc = $(call check_compile,$(1),CC,c,CFLAGS,$(2),,$(2),$(3))
286 check_compile_cxx = $(call check_compile,$(1),CXX,c++,CXXFLAGS,$(2),,$(2),$(3))
288 # Helper macro to check whether a test program will compile with the specified
290 # Usage: $(call check_compile_cc, [code], [library_flags], [alternate_flags])
291 # Return: [library_flags] if compile succeeded, otherwise [alternate_flags]
292 check_libs_cc = $(call check_compile,$(1),CC,c,CFLAGS,,$(2),$(2),$(3))
293 check_libs_cxx = $(call check_compile,$(1),CXX,c++,CXXFLAGS,,$(2),$(2),$(3))
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]
298 check_cc = $(call check_compile_cc,'int main() { return 0; }',$(1),$(2))
299 check_cxx = $(call check_compile_cxx,'int main() { return 0; }',$(1),$(2))
301 # Choose the stack protector flags based on whats supported by the compiler.
302 SSP_CFLAGS := $(call check_cc,-fstack-protector-strong)
303 ifeq ($(SSP_CFLAGS),)
304 SSP_CFLAGS := $(call check_cc,-fstack-protector-all)
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.
312 COMMON_CFLAGS-gcc := -fvisibility=internal -ggdb3 -Wa,--noexecstack
313 COMMON_CFLAGS-clang := -fvisibility=hidden -ggdb
314 COMMON_CFLAGS := -Wall -Werror -fno-strict-aliasing $(SSP_CFLAGS) -O1 -Wformat=2
315 CXXFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CXXDRIVER))
316 CFLAGS += $(COMMON_CFLAGS) $(COMMON_CFLAGS-$(CDRIVER))
317 CPPFLAGS += -D_FORTIFY_SOURCE=2
319 # Disable exceptions based on the CXXEXCEPTIONS setting.
320 ifeq ($(CXXEXCEPTIONS),0)
321 CXXFLAGS := $(CXXFLAGS) -fno-exceptions -fno-unwind-tables \
322 -fno-asynchronous-unwind-tables
326 # Up the optimizations.
327 CFLAGS := $(filter-out -O1,$(CFLAGS)) -O2
328 CXXFLAGS := $(filter-out -O1,$(CXXFLAGS)) -O2
329 # Only drop -g* if symbols aren't desired.
331 # TODO: do we want -fomit-frame-pointer on x86?
332 CFLAGS := $(filter-out -ggdb3,$(CFLAGS))
333 CXXFLAGS := $(filter-out -ggdb3,$(CXXFLAGS))
337 ifeq ($(MODE),profiling)
338 CFLAGS := $(CFLAGS) -O0 -g --coverage
339 CXXFLAGS := $(CXXFLAGS) -O0 -g --coverage
340 LDFLAGS := $(LDFLAGS) --coverage
343 LDFLAGS := $(LDFLAGS) -Wl,-z,relro -Wl,-z,noexecstack -Wl,-z,now
345 # Fancy helpers for color if a prompt is defined
347 COLOR_RESET = \x1b[0m
348 COLOR_GREEN = \x1b[32;01m
349 COLOR_RED = \x1b[31;01m
350 COLOR_YELLOW = \x1b[33;01m
353 # By default, silence build output.
360 # Implementation macros for compile helpers above
363 # Useful for dealing with pie-broken toolchains.
364 # Call make with PIE=0 to disable default PIE use.
366 COMPILE_PIE_FLAG = -pie
372 # Favor member targets first for CXX_BINARY(%) magic.
373 # And strip out nested members if possible.
376 TARGET_OR_MEMBER = $(lastword $(subst $(LP), ,$(subst $(RP),,$(or $%,$@))))
378 # Default compile from objects using pre-requisites but filters out
380 define COMPILE_BINARY_implementation
381 @$(ECHO) "LD$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
382 $(call auto_mkdir,$(TARGET_OR_MEMBER))
383 $(QUIET)$($(1)) $(COMPILE_PIE_FLAGS) -o $(TARGET_OR_MEMBER) \
385 $(filter %.o %.a,$(^:.o=.pie.o)) \
386 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
387 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
389 $(call conditional_strip)
391 @$(ECHO) "$(COLOR_GREEN)$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
392 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
395 # TODO: add version support extracted from PV environment variable
397 #$(warning PV=$(PV). If shared object versions matter, please force PV=.)
399 # Then add -Wl,-soname,$@.$(PV) ?
401 # Default compile from objects using pre-requisites but filters out
402 # all non-.o values. (Remember to add -L$(OUT) -llib)
404 define COMPILE_LIBRARY_implementation
405 @$(ECHO) "SHARED$(1) $(subst $(PWD)/,,$(TARGET_OR_MEMBER))"
406 $(call auto_mkdir,$(TARGET_OR_MEMBER))
407 $(QUIET)$($(1)) -shared -Wl,-E -o $(TARGET_OR_MEMBER) \
409 $(if $(filter %.a,$^),-Wl$(COMMA)--whole-archive,) \
410 $(filter %.o ,$(^:.o=.pic.o)) \
411 $(foreach a,$(filter %.a,$^),-L$(dir $(a)) \
412 -l$(patsubst lib%,%,$(basename $(notdir $(a))))) \
413 $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
414 -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
416 $(call conditional_strip)
417 @$(ECHO) -n "LIB $(COLOR_GREEN)"
418 @$(ECHO) "$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
419 @$(ECHO) " $(COLOR_YELLOW)-----$(COLOR_RESET)"
422 define conditional_strip
423 $(if $(filter 0,$(NOSTRIP)),$(call strip_artifact))
426 define strip_artifact
427 @$(ECHO) "STRIP $(subst $(OUT)/,,$(TARGET_OR_MEMBER))"
428 $(if $(filter 1,$(SPLITDEBUG)), @$(ECHO) -n "DEBUG "; \
429 $(ECHO) "$(COLOR_YELLOW)\
430 $(subst $(OUT)/,,$(TARGET_OR_MEMBER)).debug$(COLOR_RESET)")
431 $(if $(filter 1,$(SPLITDEBUG)), \
432 $(QUIET)$(OBJCOPY) --only-keep-debug "$(TARGET_OR_MEMBER)" \
433 "$(TARGET_OR_MEMBER).debug")
434 $(if $(filter-out dbg,$(MODE)),$(QUIET)$(STRIP) --strip-unneeded \
435 "$(TARGET_OR_MEMBER)",)
439 # Global pattern rules
442 # Below, the archive member syntax is abused to create fancier
443 # syntactic sugar for recipe authors that avoids needed to know
444 # subcall options. The downside is that make attempts to look
445 # into the phony archives for timestamps. This will cause the final
446 # target to be rebuilt/linked on _every_ call to make even when nothing
447 # has changed. Until a better way presents itself, we have helpers that
448 # do the stat check on make's behalf. Dodgy but simple.
449 define old_or_no_timestamp
450 $(if $(realpath $%),,$(1))
451 $(if $(shell find $^ -cnewer "$%" 2>/dev/null),$(1))
455 $(if $(filter 0,$(words $^)),\
456 $(error Missing dependencies or declaration of $@($%)),)
459 # Build a cxx target magically
462 $(call old_or_no_timestamp,$(call cxx_binary))
463 clean: CLEAN(CXX_BINARY*)
467 $(call old_or_no_timestamp,$(call cc_binary))
468 clean: CLEAN(CC_BINARY*)
470 CXX_STATIC_BINARY(%):
472 $(call old_or_no_timestamp,$(call cxx_binary,-static))
473 clean: CLEAN(CXX_STATIC_BINARY*)
477 $(call old_or_no_timestamp,$(call cc_binary,-static))
478 clean: CLEAN(CC_STATIC_BINARY*)
482 $(call old_or_no_timestamp,$(call cxx_library))
483 clean: CLEAN(CXX_LIBRARY*)
486 $(error Typo alert! LIBARY != LIBRARY)
490 $(call old_or_no_timestamp,$(call cc_library))
491 clean: CLEAN(CC_LIBRARY*)
494 $(error Typo alert! LIBARY != LIBRARY)
496 CXX_STATIC_LIBRARY(%):
498 $(call old_or_no_timestamp,$(call update_archive))
499 clean: CLEAN(CXX_STATIC_LIBRARY*)
501 CXX_STATIC_LIBARY(%):
502 $(error Typo alert! LIBARY != LIBRARY)
504 CC_STATIC_LIBRARY(%):
506 $(call old_or_no_timestamp,$(call update_archive))
507 clean: CLEAN(CC_STATIC_LIBRARY*)
510 $(error Typo alert! LIBARY != LIBRARY)
513 TEST(%): % qemu_chroot_install
514 $(call TEST_implementation)
517 # multiple targets with a wildcard need to share an directory.
518 # Don't use this directly it just makes sure the directory is removed _after_
521 $(call silent_rm,$(TARGET_OR_MEMBER))
524 CLEAN(%): CLEANFILE(%)
525 $(QUIET)# CLEAN($%) meta-target called
526 $(if $(filter-out $(PWD)/,$(dir $(abspath $(TARGET_OR_MEMBER)))), \
527 $(call silent_rmdir,$(dir $(abspath $(TARGET_OR_MEMBER)))),\
528 $(QUIET)# Not deleting $(dir $(abspath $(TARGET_OR_MEMBER))) yet.)
532 # Top-level objects and pattern rules
535 # All objects for .c files at the top level
536 C_OBJECTS = $(patsubst $(SRC)/%.c,%.o,$(wildcard $(SRC)/*.c))
539 # All objects for .cxx files at the top level
540 CXX_OBJECTS = $(patsubst $(SRC)/%.cc,%.o,$(wildcard $(SRC)/*.cc))
542 # Note, the catch-all pattern rules don't work in subdirectories because
543 # we're building from the $(OUT) directory. At the top-level (here) they will
544 # work, but we go ahead and match using the module form. Then we can place a
545 # generic pattern rule to capture leakage from the main Makefile. (Later in the
548 # The reason target specific pattern rules work well for modules,
549 # MODULE_C_OBJECTS, is because it scopes the behavior to the given target which
550 # ensures we get a relative directory offset from $(OUT) which otherwise would
551 # not match without further magic on a per-subdirectory basis.
553 # Creates object file rules. Call with eval.
554 # $(1) list of .o files
555 # $(2) source type (CC or CXX)
556 # $(3) source suffix (cc or c)
557 # $(4) compiler flag name (CFLAGS or CXXFLAGS)
558 # $(5) source dir: _only_ if $(SRC). Leave blank for obj tree.
559 define add_object_rules
560 $(patsubst %.o,%.pie.o,$(1)): %.pie.o: $(5)%.$(3) %.o.depends
561 $$(call auto_mkdir,$$@)
562 $$(call OBJECT_PATTERN_implementation,$(2),\
563 $$(basename $$@),$$($(4)) $$(CPPFLAGS) $$(OBJ_PIE_FLAG))
565 $(patsubst %.o,%.pic.o,$(1)): %.pic.o: $(5)%.$(3) %.o.depends
566 $$(call auto_mkdir,$$@)
567 $$(call OBJECT_PATTERN_implementation,$(2),\
568 $$(basename $$@),$$($(4)) $$(CPPFLAGS) -fPIC)
570 # Placeholder for depends
571 $(patsubst %.o,%.o.depends,$(1)):
572 $$(call auto_mkdir,$$@)
575 $(1): %.o: %.pic.o %.pie.o
576 $$(call auto_mkdir,$$@)
580 define OBJECT_PATTERN_implementation
581 @$(ECHO) "$(1) $(subst $(SRC)/,,$<) -> $(2).o"
582 $(call auto_mkdir,$@)
583 $(QUIET)$($(1)) -c -MD -MF $(2).d $(3) -o $(2).o $<
584 $(QUIET)# Wrap all the deps in $$(wildcard) so a missing header
585 $(QUIET)# won't cause weirdness. First we remove newlines and \,
586 $(QUIET)# then wrap it.
587 $(QUIET)sed -i -e :j -e '$$!N;s|\\\s*\n| |;tj' \
588 -e 's|^\(.*\s*:\s*\)\(.*\)$$|\1 $$\(wildcard \2\)|' $(2).d
591 # Now actually register handlers for C(XX)_OBJECTS.
592 $(eval $(call add_object_rules,$(C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
593 $(eval $(call add_object_rules,$(CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
595 # Disable default pattern rules to help avoid leakage.
596 # These may already be handled by '-r', but let's keep it to be safe.
602 # NOTE: A specific rule for archive objects is avoided because parallel
603 # update of the archive causes build flakiness.
604 # Instead, just make the objects the prerequisites and use update_archive
605 # To use the foo.a(obj.o) functionality, targets would need to specify the
606 # explicit object they expect on the prerequisite line.
609 # Architecture detection and QEMU wrapping
612 HOST_ARCH ?= $(shell uname -m)
613 override ARCH := $(strip $(ARCH))
614 override HOST_ARCH := $(strip $(HOST_ARCH))
615 # emake will supply "x86" or "arm" for ARCH, but
616 # if uname -m runs and you get x86_64, then this subst
618 ifeq ($(subst x86,i386,$(ARCH)),i386)
619 QEMU_ARCH := $(subst x86,i386,$(ARCH)) # x86 -> i386
620 else ifeq ($(subst amd64,x86_64,$(ARCH)),x86_64)
621 QEMU_ARCH := $(subst amd64,x86_64,$(ARCH)) # amd64 -> x86_64
625 override QEMU_ARCH := $(strip $(QEMU_ARCH))
627 # If we're cross-compiling, try to use qemu for running the tests.
628 ifneq ($(QEMU_ARCH),$(HOST_ARCH))
630 $(info SYSROOT not defined. qemu-based testing disabled)
632 # A SYSROOT is assumed for QEmu use.
635 # Allow 64-bit hosts to run 32-bit without qemu.
636 ifeq ($(HOST_ARCH),x86_64)
637 ifeq ($(QEMU_ARCH),i386)
646 # Normally we don't need to run as root or do bind mounts, so only
647 # enable it by default when we're using QEMU.
648 NEEDS_ROOT ?= $(USE_QEMU)
649 NEEDS_MOUNTS ?= $(USE_QEMU)
653 SYSROOT_OUT = $(subst $(SYSROOT),,$(OUT))
655 # Default to / when all the empty-sysroot logic is done.
659 QEMU_NAME = qemu-$(QEMU_ARCH)
660 QEMU_PATH = /build/bin/$(QEMU_NAME)
661 QEMU_SYSROOT_PATH = $(SYSROOT)$(QEMU_PATH)
662 QEMU_SRC_PATH = /usr/bin/$(QEMU_NAME)
663 QEMU_BINFMT_PATH = /proc/sys/fs/binfmt_misc/$(QEMU_NAME)
664 QEMU_REGISTER_PATH = /proc/sys/fs/binfmt_misc/register
666 QEMU_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 # Output full configuration at top level
673 # Don't show on clean
674 ifneq ($(MAKECMDGOALS),clean)
675 $(info build configuration:)
678 $(info - MODE=$(MODE))
679 $(info - SPLITDEBUG=$(SPLITDEBUG))
680 $(info - NOSTRIP=$(NOSTRIP))
681 $(info - VALGRIND=$(VALGRIND))
682 $(info - COLOR=$(COLOR))
683 $(info - CXXEXCEPTIONS=$(CXXEXCEPTIONS))
684 $(info - ARCH=$(ARCH))
685 $(info - QEMU_ARCH=$(QEMU_ARCH))
686 $(info - USE_QEMU=$(USE_QEMU))
687 $(info - NEEDS_ROOT=$(NEEDS_ROOT))
688 $(info - NEEDS_MOUNTS=$(NEEDS_MOUNTS))
689 $(info - SYSROOT=$(SYSROOT))
694 # Standard targets with detection for when they are improperly configured.
697 # all does not include tests by default
699 $(QUIET)(test -z "$^" && \
700 $(ECHO) "You must add your targets as 'all' prerequisites") || true
703 # Builds and runs tests for the target arch
704 # Run them in parallel
705 # After the test have completed, if profiling, run coverage analysis
707 ifeq ($(MODE),profiling)
708 @$(ECHO) "COVERAGE [$(COLOR_YELLOW)STARTED$(COLOR_RESET)]"
710 for GCNO in `find . -name "*.gcno"`; do \
711 GCDA="$${GCNO%.gcno}.gcda"; \
712 if [ -e $${GCDA} ]; then \
713 FILES="$${FILES} $${GCDA}"; \
716 if [ -n "$${FILES}" ]; then \
718 lcov --capture --directory . \
719 --output-file=lcov-coverage.info; \
720 genhtml lcov-coverage.info \
721 --output-directory lcov-html; \
723 @$(ECHO) "COVERAGE [$(COLOR_YELLOW)FINISHED$(COLOR_RESET)]"
729 $(QUIET)$(ECHO) "QEMU Preparing $(QEMU_NAME)"
731 @# Compare /usr/bin/qemu inode to /build/$board/build/bin/qemu, if different
732 @# hard link to a temporary file, then rename temp to target. This should
733 @# ensure that once $QEMU_SYSROOT_PATH exists it will always exist, regardless
734 @# of simultaneous test setups.
735 $(QUIET)if [[ ! -e $(QEMU_SYSROOT_PATH) || \
736 `stat -c %i $(QEMU_SRC_PATH)` != `stat -c %i $(QEMU_SYSROOT_PATH)` \
738 $(ROOT_CMD) ln -Tf $(QEMU_SRC_PATH) $(QEMU_SYSROOT_PATH).$$$$; \
739 $(ROOT_CMD) mv -Tf $(QEMU_SYSROOT_PATH).$$$$ $(QEMU_SYSROOT_PATH); \
742 @# Prep the binfmt handler. First mount if needed, then unregister any bad
743 @# mappings and then register our mapping.
744 @# There may still be some race conditions here where one script de-registers
745 @# and another script starts executing before it gets re-registered, however
746 @# it should be rare.
747 -$(QUIET)[[ -e $(QEMU_REGISTER_PATH) ]] || \
748 $(ROOT_CMD) mount binfmt_misc -t binfmt_misc \
749 /proc/sys/fs/binfmt_misc
751 -$(QUIET)if [[ -e $(QEMU_BINFMT_PATH) && \
752 `awk '$$1 == "interpreter" {print $$NF}' $(QEMU_BINFMT_PATH)` != \
753 "$(QEMU_PATH)" ]]; then \
754 echo -1 | $(ROOT_CMD) tee $(QEMU_BINFMT_PATH) >/dev/null; \
757 -$(if $(QEMU_MAGIC_$(ARCH)),$(QUIET)[[ -e $(QEMU_BINFMT_PATH) ]] || \
758 echo $(QEMU_MAGIC_$(ARCH)) | $(ROOT_CMD) tee $(QEMU_REGISTER_PATH) \
761 .PHONY: qemu_clean qemu_chroot_install
763 # TODO(wad) Move to -L $(SYSROOT) and fakechroot when qemu-user
764 # doesn't hang traversing /proc from SYSROOT.
766 UNSHARE_CMD = unshare
768 ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),$(SUDO_CMD) , )
769 MOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) mount, \#)
770 UMOUNT_CMD = $(if $(filter 1,$(NEEDS_MOUNTS)),$(ROOT_CMD) umount, \#)
771 QEMU_LDPATH = $(SYSROOT_LDPATH):/lib64:/lib:/usr/lib64:/usr/lib
772 ROOT_CMD_LDPATH = $(SYSROOT_LDPATH):$(SYSROOT)/lib64:
773 ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/lib:$(SYSROOT)/usr/lib64:
774 ROOT_CMD_LDPATH := $(ROOT_CMD_LDPATH):$(SYSROOT)/usr/lib
777 $(SUDO_CMD) chroot $(SYSROOT) $(QEMU_PATH) \
779 -E LD_LIBRARY_PATH="$(QEMU_LDPATH):$(patsubst $(OUT),,$(LD_DIRS))" \
780 -E HOME="$(HOME)" -E SRC="$(SRC)" --
781 # USE_QEMU conditional function
786 ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),sudo, ) \
787 LD_LIBRARY_PATH="$(ROOT_CMD_LDPATH):$(LD_DIRS)"
795 VALGRIND_CMD = /usr/bin/valgrind --tool=memcheck $(VALGRIND_ARGS) --
798 define TEST_implementation
799 $(QUIET)$(call TEST_setup)
800 $(QUIET)$(call TEST_run)
801 $(QUIET)$(call TEST_teardown)
802 $(QUIET)exit $$(cat $(OUT)$(TARGET_OR_MEMBER).status.test)
806 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
807 @$(ECHO) "[$(COLOR_YELLOW)SETUP$(COLOR_RESET)]"
808 $(QUIET)# Setup a target-specific results file
809 $(QUIET)(echo > $(OUT)$(TARGET_OR_MEMBER).setup.test)
810 $(QUIET)(echo 1 > $(OUT)$(TARGET_OR_MEMBER).status.test)
811 $(QUIET)(echo > $(OUT)$(TARGET_OR_MEMBER).cleanup.test)
812 $(QUIET)# No setup if we are not using QEMU
813 $(QUIET)# TODO(wad) this is racy until we use a vfs namespace
815 $(QUIET)(echo "mkdir -p '$(SYSROOT)/proc' '$(SYSROOT)/dev' \
816 '$(SYSROOT)/mnt/host/source'" \
817 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
819 $(QUIET)(echo "$(MOUNT_CMD) --bind /mnt/host/source \
820 '$(SYSROOT)/mnt/host/source'" \
821 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
823 $(QUIET)(echo "$(MOUNT_CMD) --bind /proc '$(SYSROOT)/proc'" \
824 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
826 $(QUIET)(echo "$(MOUNT_CMD) --bind /dev '$(SYSROOT)/dev'" \
827 >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
831 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
832 @$(ECHO) "[$(COLOR_YELLOW)TEARDOWN$(COLOR_RESET)]"
833 $(call if_qemu, $(QUIET)$(SHELL) "$(OUT)$(TARGET_OR_MEMBER).cleanup.test")
836 # Use GTEST_ARGS.[arch] if defined.
837 override GTEST_ARGS.real = \
838 $(call if_qemu,$(GTEST_ARGS.qemu.$(QEMU_ARCH)),$(GTEST_ARGS.host.$(HOST_ARCH)))
841 @$(ECHO) -n "TEST $(TARGET_OR_MEMBER) "
842 @$(ECHO) "[$(COLOR_GREEN)RUN$(COLOR_RESET)]"
843 $(QUIET)(echo 1 > "$(OUT)$(TARGET_OR_MEMBER).status.test")
844 $(QUIET)(echo $(ROOT_CMD) SRC="$(SRC)" $(QEMU_CMD) $(VALGRIND_CMD) \
845 "$(strip $(call if_qemu, $(SYSROOT_OUT),$(OUT))$(TARGET_OR_MEMBER))" \
846 $(if $(filter-out 0,$(words $(GTEST_ARGS.real))),$(GTEST_ARGS.real),\
847 $(GTEST_ARGS)) >> "$(OUT)$(TARGET_OR_MEMBER).setup.test")
848 -$(QUIET)$(call if_qemu,$(SUDO_CMD) $(UNSHARE_CMD) -m) $(SHELL) \
849 $(OUT)$(TARGET_OR_MEMBER).setup.test \
850 && echo 0 > "$(OUT)$(TARGET_OR_MEMBER).status.test"
853 # Recursive list reversal so that we get RMDIR_ON_CLEAN in reverse order.
855 $(if $(1),$(call reverse,$(wordlist 2,$(words $(1)),$(1)))) $(firstword $(1))
859 clean: CLEAN($(OUT)*.d) CLEAN($(OUT)*.o) CLEAN($(OUT)*.debug)
860 clean: CLEAN($(OUT)*.test) CLEAN($(OUT)*.depends)
861 clean: CLEAN($(OUT)*.gcno) CLEAN($(OUT)*.gcda) CLEAN($(OUT)*.gcov)
862 clean: CLEAN($(OUT)lcov-coverage.info) CLEAN($(OUT)lcov-html)
865 $(QUIET)# Always delete the containing directory last.
866 $(call silent_rmdir,$(OUT))
869 # Empty rule for use when no special targets are needed, like large_tests
872 .PHONY: clean NONE valgrind NONE
874 # Don't let make blow away "intermediates"
875 .PRECIOUS: %.pic.o %.pie.o %.a %.pic.a %.pie.a %.test
877 # Start accruing build info
882 include $(wildcard $(OUT)*.d)
883 SUBMODULE_DIRS = $(wildcard $(SRC)/*/module.mk)
884 include $(SUBMODULE_DIRS)
887 else ## In duplicate inclusions of common.mk
889 # Get the current inclusion directory without a trailing slash
890 MODULE := $(patsubst %/,%, \
891 $(dir $(lastword $(filter-out %common.mk,$(MAKEFILE_LIST)))))
892 MODULE := $(subst $(SRC)/,,$(MODULE))
893 MODULE_NAME := $(subst /,_,$(MODULE))
894 #VPATH := $(MODULE):$(VPATH)
898 $(eval OUT_DIRS += $(OUT)$(MODULE))
899 $(eval SRC_DIRS += $(OUT)$(MODULE))
900 $(eval LD_DIRS := $(LD_DIRS):$(OUT)$(MODULE))
902 # Add the defaults from this dir to rm_clean
903 clean: CLEAN($(OUT)$(MODULE)/*.d) CLEAN($(OUT)$(MODULE)/*.o)
904 clean: CLEAN($(OUT)$(MODULE)/*.debug) CLEAN($(OUT)$(MODULE)/*.test)
905 clean: CLEAN($(OUT)$(MODULE)/*.depends)
906 clean: CLEAN($(OUT)$(MODULE)/*.gcno) CLEAN($(OUT)$(MODULE)/*.gcda)
907 clean: CLEAN($(OUT)$(MODULE)/*.gcov) CLEAN($(OUT)lcov-coverage.info)
908 clean: CLEAN($(OUT)lcov-html)
910 $(info + submodule: $(MODULE_NAME))
911 # We must eval otherwise they may be dropped.
912 MODULE_C_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.c,$(MODULE)/%.o,\
913 $(wildcard $(SRC)/$(MODULE)/*.c))
914 $(eval $(MODULE_NAME)_C_OBJECTS ?= $(MODULE_C_OBJECTS))
915 MODULE_CXX_OBJECTS = $(patsubst $(SRC)/$(MODULE)/%.cc,$(MODULE)/%.o,\
916 $(wildcard $(SRC)/$(MODULE)/*.cc))
917 $(eval $(MODULE_NAME)_CXX_OBJECTS ?= $(MODULE_CXX_OBJECTS))
919 # Note, $(MODULE) is implicit in the path to the %.c.
920 # See $(C_OBJECTS) for more details.
921 # Register rules for the module objects.
922 $(eval $(call add_object_rules,$(MODULE_C_OBJECTS),CC,c,CFLAGS,$(SRC)/))
923 $(eval $(call add_object_rules,$(MODULE_CXX_OBJECTS),CXX,cc,CXXFLAGS,$(SRC)/))
925 # Continue recursive inclusion of module.mk files
926 SUBMODULE_DIRS = $(wildcard $(SRC)/$(MODULE)/*/module.mk)
927 include $(wildcard $(OUT)$(MODULE)/*.d)
928 include $(SUBMODULE_DIRS)
931 endif ## pass-to-subcall wrapper for relocating the call directory