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