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