OSDN Git Service

minigbm: Use the stride value returned by mapImage
[android-x86/external-minigbm.git] / common.mk
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.
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
97 SPLITDEBUG ?= 0
98 NOSTRIP ?= 1
99 VALGRIND ?= 0
100 COLOR ?= 1
101 VERBOSE ?= 0
102 MODE ?= opt
103 CXXEXCEPTIONS ?= 0
104 ARCH ?= $(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.
112 OUT ?= $(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
119 override 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.
123 export SRC ?= $(CURDIR)
124
125 # Re-start in the $(OUT) directory if we're not there.
126 # We may be invoked using -C or bare and we need to ensure behavior
127 # is consistent so we check both PWD vs OUT and PWD vs CURDIR.
128 override RELOCATE_BUILD := 0
129 ifneq (${PWD}/,${OUT})
130 override RELOCATE_BUILD := 1
131 endif
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")
139 endif
140 endif  # ifneq (${PWD},${CURDIR}
141
142 # "Relocate" if we need to restart without implicit rules.
143 ifeq ($(subst r,,$(MAKEFLAGS)),$(MAKEFLAGS))
144 override RELOCATE_BUILD := 1
145 endif
146
147 ifeq (${RELOCATE_BUILD},1)
148 # By default, silence build output. Reused below as well.
149 QUIET = @
150 ifeq ($(VERBOSE),1)
151   QUIET=
152 endif
153
154 # This target will override all targets, including prerequisites. To avoid
155 # calling $(MAKE) once per prereq on the given CMDGOAL, we guard it with a local
156 # variable.
157 RUN_ONCE := 0
158 MAKECMDGOALS ?= all
159 # Keep the rules split as newer make does not allow them to be declared
160 # on the same line.  But the way :: rules work, the _all here will also
161 # invoke the %:: rule while retaining "_all" as the default.
162 _all::
163 %::
164         $(if $(filter 0,$(RUN_ONCE)), \
165           cd "$(OUT)" && \
166           $(MAKE) -r -I "$(SRC)" -f "$(CURDIR)/Makefile" \
167             SRC="$(CURDIR)" OUT="$(OUT)" $(foreach g,$(MAKECMDGOALS),"$(g)"),)
168         $(eval RUN_ONCE := 1)
169 pass-to-subcall := 1
170 endif
171
172 ifeq ($(pass-to-subcall),)
173
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)
178
179 # All the top-level defines outside of module.mk.
180
181 #
182 # Helper macros
183 #
184
185 # Create the directory if it doesn't yet exist.
186 define auto_mkdir
187   $(if $(wildcard $(dir $1)),$2,$(QUIET)mkdir -p "$(dir $1)")
188 endef
189
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))
201 endef
202
203 # Default compile from objects using pre-requisites but filters out
204 # subdirs and .d files.
205 define cc_binary
206   $(call COMPILE_BINARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
207 endef
208
209 define cxx_binary
210   $(call COMPILE_BINARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
211 endef
212
213 # Default compile from objects using pre-requisites but filters out
214 # subdirs and .d files.
215 define cc_library
216   $(call COMPILE_LIBRARY_implementation,CC,$(CFLAGS) $(1),$(EXTRA_FLAGS))
217 endef
218 define cxx_library
219   $(call COMPILE_LIBRARY_implementation,CXX,$(CXXFLAGS) $(1),$(EXTRA_FLAGS))
220 endef
221
222 # Deletes files silently if they exist. Meant for use in any local
223 # clean targets.
224 define silent_rm
225   $(if $(wildcard $(1)),
226   $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANFILE$(COLOR_RESET)              ' && \
227     $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
228     $(RM) $(1) 2>/dev/null) || true,)
229 endef
230 define silent_rmdir
231   $(if $(wildcard $(1)),
232     $(if $(wildcard $(1)/*),
233   $(QUIET)# $(1) not empty [$(wildcard $(1)/*)]. Not deleting.,
234   $(QUIET)($(ECHO) -n '$(COLOR_RED)CLEANDIR$(COLOR_RESET)               ' && \
235     $(ECHO) '$(subst $(OUT)/,,$(wildcard $(1)))' && \
236     $(RMDIR) $(1) 2>/dev/null) || true),)
237 endef
238
239 #
240 # Default variable values
241 #
242
243 # Only override toolchain vars if they are from make.
244 CROSS_COMPILE ?=
245 define override_var
246 ifneq ($(filter undefined default,$(origin $1)),)
247 $1 = $(CROSS_COMPILE)$2
248 endif
249 endef
250 $(eval $(call override_var,AR,ar))
251 $(eval $(call override_var,CC,gcc))
252 $(eval $(call override_var,CXX,g++))
253 $(eval $(call override_var,OBJCOPY,objcopy))
254 $(eval $(call override_var,PKG_CONFIG,pkg-config))
255 $(eval $(call override_var,RANLIB,ranlib))
256 $(eval $(call override_var,STRIP,strip))
257
258 RMDIR ?= rmdir
259 ECHO = /bin/echo -e
260
261 ifeq ($(lastword $(subst /, ,$(CC))),clang)
262 CDRIVER = clang
263 else
264 CDRIVER = gcc
265 endif
266
267 ifeq ($(lastword $(subst /, ,$(CXX))),clang++)
268 CXXDRIVER = clang
269 else
270 CXXDRIVER = gcc
271 endif
272
273 # Internal macro to support check_XXX macros below.
274 # Usage: $(call check_compile, [code], [compiler], [code_type], [c_flags],
275 #               [extra_c_flags], [library_flags], [success_ret], [fail_ret])
276 # Return: [success_ret] if compile succeeded, otherwise [fail_ret]
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)")
280
281 # Helper macro to check whether a test program will compile with the specified
282 # compiler flags.
283 # Usage: $(call check_compile_cc, [code], [flags], [alternate_flags])
284 # Return: [flags] if compile succeeded, otherwise [alternate_flags]
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))
287
288 # Helper macro to check whether a test program will compile with the specified
289 # libraries.
290 # Usage: $(call check_compile_cc, [code], [library_flags], [alternate_flags])
291 # Return: [library_flags] if compile succeeded, otherwise [alternate_flags]
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))
294
295 # Helper macro to check whether the compiler accepts the specified flags.
296 # Usage: $(call check_compile_cc, [flags], [alternate_flags])
297 # Return: [flags] if compile succeeded, otherwise [alternate_flags]
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))
300
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)
305 endif
306
307 # To update these from an including Makefile:
308 #  CXXFLAGS += -mahflag  # Append to the list
309 #  CXXFLAGS := -mahflag $(CXXFLAGS) # Prepend to the list
310 #  CXXFLAGS := $(filter-out badflag,$(CXXFLAGS)) # Filter out a value
311 # The same goes for CFLAGS.
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
318
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
323 endif
324
325 ifeq ($(MODE),opt)
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.
330   ifeq ($(NOSTRIP),0)
331     # TODO: do we want -fomit-frame-pointer on x86?
332     CFLAGS := $(filter-out -ggdb3,$(CFLAGS))
333     CXXFLAGS := $(filter-out -ggdb3,$(CXXFLAGS))
334   endif
335 endif
336
337 ifeq ($(MODE),profiling)
338   CFLAGS := $(CFLAGS) -O0 -g  --coverage
339   CXXFLAGS := $(CXXFLAGS) -O0 -g  --coverage
340   LDFLAGS := $(LDFLAGS) --coverage
341 endif
342
343 LDFLAGS := $(LDFLAGS) -Wl,-z,relro -Wl,-z,noexecstack -Wl,-z,now
344
345 # Fancy helpers for color if a prompt is defined
346 ifeq ($(COLOR),1)
347 COLOR_RESET = \x1b[0m
348 COLOR_GREEN = \x1b[32;01m
349 COLOR_RED = \x1b[31;01m
350 COLOR_YELLOW = \x1b[33;01m
351 endif
352
353 # By default, silence build output.
354 QUIET = @
355 ifeq ($(VERBOSE),1)
356   QUIET=
357 endif
358
359 #
360 # Implementation macros for compile helpers above
361 #
362
363 # Useful for dealing with pie-broken toolchains.
364 # Call make with PIE=0 to disable default PIE use.
365 OBJ_PIE_FLAG = -fPIE
366 COMPILE_PIE_FLAG = -pie
367 ifeq ($(PIE),0)
368   OBJ_PIE_FLAG =
369   COMPILE_PIE_FLAG =
370 endif
371
372 # Favor member targets first for CXX_BINARY(%) magic.
373 # And strip out nested members if possible.
374 LP := (
375 RP := )
376 TARGET_OR_MEMBER = $(lastword $(subst $(LP), ,$(subst $(RP),,$(or $%,$@))))
377
378 # Default compile from objects using pre-requisites but filters out
379 # all non-.o files.
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) \
384     $(2) $(LDFLAGS) \
385     $(filter %.o %.a,$(^:.o=.pie.o)) \
386     $(foreach so,$(filter %.so,$^),-L$(dir $(so)) \
387                             -l$(patsubst lib%,%,$(basename $(notdir $(so))))) \
388     $(LDLIBS)
389   $(call conditional_strip)
390   @$(ECHO) -n "BIN              "
391   @$(ECHO) "$(COLOR_GREEN)$(subst $(PWD)/,,$(TARGET_OR_MEMBER))$(COLOR_RESET)"
392   @$(ECHO) "    $(COLOR_YELLOW)-----$(COLOR_RESET)"
393 endef
394
395 # TODO: add version support extracted from PV environment variable
396 #ifeq ($(PV),9999)
397 #$(warning PV=$(PV). If shared object versions matter, please force PV=.)
398 #endif
399 # Then add -Wl,-soname,$@.$(PV) ?
400
401 # Default compile from objects using pre-requisites but filters out
402 # all non-.o values. (Remember to add -L$(OUT) -llib)
403 COMMA := ,
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) \
408     $(2) $(LDFLAGS) \
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))))) \
415     $(LDLIBS)
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)"
420 endef
421
422 define conditional_strip
423   $(if $(filter 0,$(NOSTRIP)),$(call strip_artifact))
424 endef
425
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)",)
436 endef
437
438 #
439 # Global pattern rules
440 #
441
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))
452 endef
453
454 define check_deps
455   $(if $(filter 0,$(words $^)),\
456     $(error Missing dependencies or declaration of $@($%)),)
457 endef
458
459 # Build a cxx target magically
460 CXX_BINARY(%):
461         $(call check_deps)
462         $(call old_or_no_timestamp,$(call cxx_binary))
463 clean: CLEAN(CXX_BINARY*)
464
465 CC_BINARY(%):
466         $(call check_deps)
467         $(call old_or_no_timestamp,$(call cc_binary))
468 clean: CLEAN(CC_BINARY*)
469
470 CXX_STATIC_BINARY(%):
471         $(call check_deps)
472         $(call old_or_no_timestamp,$(call cxx_binary,-static))
473 clean: CLEAN(CXX_STATIC_BINARY*)
474
475 CC_STATIC_BINARY(%):
476         $(call check_deps)
477         $(call old_or_no_timestamp,$(call cc_binary,-static))
478 clean: CLEAN(CC_STATIC_BINARY*)
479
480 CXX_LIBRARY(%):
481         $(call check_deps)
482         $(call old_or_no_timestamp,$(call cxx_library))
483 clean: CLEAN(CXX_LIBRARY*)
484
485 CXX_LIBARY(%):
486         $(error Typo alert! LIBARY != LIBRARY)
487
488 CC_LIBRARY(%):
489         $(call check_deps)
490         $(call old_or_no_timestamp,$(call cc_library))
491 clean: CLEAN(CC_LIBRARY*)
492
493 CC_LIBARY(%):
494         $(error Typo alert! LIBARY != LIBRARY)
495
496 CXX_STATIC_LIBRARY(%):
497         $(call check_deps)
498         $(call old_or_no_timestamp,$(call update_archive))
499 clean: CLEAN(CXX_STATIC_LIBRARY*)
500
501 CXX_STATIC_LIBARY(%):
502         $(error Typo alert! LIBARY != LIBRARY)
503
504 CC_STATIC_LIBRARY(%):
505         $(call check_deps)
506         $(call old_or_no_timestamp,$(call update_archive))
507 clean: CLEAN(CC_STATIC_LIBRARY*)
508
509 CC_STATIC_LIBARY(%):
510         $(error Typo alert! LIBARY != LIBRARY)
511
512
513 TEST(%): % qemu_chroot_install
514         $(call TEST_implementation)
515 .PHONY: TEST
516
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_
519 # the files are.
520 CLEANFILE(%):
521         $(call silent_rm,$(TARGET_OR_MEMBER))
522 .PHONY: CLEANFILE
523
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.)
529 .PHONY: CLEAN
530
531 #
532 # Top-level objects and pattern rules
533 #
534
535 # All objects for .c files at the top level
536 C_OBJECTS = $(patsubst $(SRC)/%.c,%.o,$(wildcard $(SRC)/*.c))
537
538
539 # All objects for .cxx files at the top level
540 CXX_OBJECTS = $(patsubst $(SRC)/%.cc,%.o,$(wildcard $(SRC)/*.cc))
541
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
546 # file.)
547 #
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.
552
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))
564
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)
569
570 # Placeholder for depends
571 $(patsubst %.o,%.o.depends,$(1)):
572         $$(call auto_mkdir,$$@)
573         $$(QUIET)touch "$$@"
574
575 $(1): %.o: %.pic.o %.pie.o
576         $$(call auto_mkdir,$$@)
577         $$(QUIET)touch "$$@"
578 endef
579
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
589 endef
590
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)/))
594
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.
597 %: %.o ;
598 %.a: %.o ;
599 %.o: %.c ;
600 %.o: %.cc ;
601
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.
607
608 #
609 # Architecture detection and QEMU wrapping
610 #
611
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
617 # will break.
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
622 else
623   QEMU_ARCH = $(ARCH)
624 endif
625 override QEMU_ARCH := $(strip $(QEMU_ARCH))
626
627 # If we're cross-compiling, try to use qemu for running the tests.
628 ifneq ($(QEMU_ARCH),$(HOST_ARCH))
629   ifeq ($(SYSROOT),)
630     $(info SYSROOT not defined. qemu-based testing disabled)
631   else
632     # A SYSROOT is assumed for QEmu use.
633     USE_QEMU ?= 1
634
635     # Allow 64-bit hosts to run 32-bit without qemu.
636     ifeq ($(HOST_ARCH),x86_64)
637       ifeq ($(QEMU_ARCH),i386)
638         USE_QEMU = 0
639       endif
640     endif
641   endif
642 else
643   USE_QEMU ?= 0
644 endif
645
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)
650
651 SYSROOT_OUT = $(OUT)
652 ifneq ($(SYSROOT),)
653   SYSROOT_OUT = $(subst $(SYSROOT),,$(OUT))
654 else
655   # Default to / when all the empty-sysroot logic is done.
656   SYSROOT = /
657 endif
658
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
665
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:"
667
668
669 #
670 # Output full configuration at top level
671 #
672
673 # Don't show on clean
674 ifneq ($(MAKECMDGOALS),clean)
675   $(info build configuration:)
676   $(info - OUT=$(OUT))
677   $(info - SRC=$(SRC))
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))
690   $(info )
691 endif
692
693 #
694 # Standard targets with detection for when they are improperly configured.
695 #
696
697 # all does not include tests by default
698 all:
699         $(QUIET)(test -z "$^" && \
700         $(ECHO) "You must add your targets as 'all' prerequisites") || true
701         $(QUIET)test -n "$^"
702
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
706 tests:
707 ifeq ($(MODE),profiling)
708         @$(ECHO) "COVERAGE [$(COLOR_YELLOW)STARTED$(COLOR_RESET)]"
709         $(QUIET)FILES="";                                               \
710                 for GCNO in `find . -name "*.gcno"`; do                 \
711                         GCDA="$${GCNO%.gcno}.gcda";                     \
712                         if [ -e $${GCDA} ]; then                        \
713                                 FILES="$${FILES} $${GCDA}";             \
714                         fi                                              \
715                 done;                                                   \
716                 if [ -n "$${FILES}" ]; then                             \
717                         gcov -l $${FILES};                              \
718                         lcov --capture --directory .                    \
719                                 --output-file=lcov-coverage.info;       \
720                         genhtml lcov-coverage.info                      \
721                                 --output-directory lcov-html;           \
722                 fi
723         @$(ECHO) "COVERAGE [$(COLOR_YELLOW)FINISHED$(COLOR_RESET)]"
724 endif
725 .PHONY: tests
726
727 qemu_chroot_install:
728 ifeq ($(USE_QEMU),1)
729         $(QUIET)$(ECHO) "QEMU   Preparing $(QEMU_NAME)"
730         @# Copying strategy
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)` \
737             ]]; then \
738           $(ROOT_CMD) ln -Tf $(QEMU_SRC_PATH) $(QEMU_SYSROOT_PATH).$$$$; \
739           $(ROOT_CMD) mv -Tf $(QEMU_SYSROOT_PATH).$$$$ $(QEMU_SYSROOT_PATH); \
740         fi
741
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
750
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; \
755         fi
756
757         -$(if $(QEMU_MAGIC_$(ARCH)),$(QUIET)[[ -e $(QEMU_BINFMT_PATH) ]] || \
758           echo $(QEMU_MAGIC_$(ARCH)) | $(ROOT_CMD) tee $(QEMU_REGISTER_PATH) \
759             >/dev/null)
760 endif
761 .PHONY: qemu_clean qemu_chroot_install
762
763 # TODO(wad) Move to -L $(SYSROOT) and fakechroot when qemu-user
764 #           doesn't hang traversing /proc from SYSROOT.
765 SUDO_CMD = sudo
766 UNSHARE_CMD = unshare
767 QEMU_CMD =
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
775 ifeq ($(USE_QEMU),1)
776   export QEMU_CMD = \
777    $(SUDO_CMD) chroot $(SYSROOT) $(QEMU_PATH) \
778    -drop-ld-preload \
779    -E LD_LIBRARY_PATH="$(QEMU_LDPATH):$(patsubst $(OUT),,$(LD_DIRS))" \
780    -E HOME="$(HOME)" -E SRC="$(SRC)" --
781   # USE_QEMU conditional function
782   define if_qemu
783     $(1)
784   endef
785 else
786   ROOT_CMD = $(if $(filter 1,$(NEEDS_ROOT)),sudo, ) \
787     LD_LIBRARY_PATH="$(ROOT_CMD_LDPATH):$(LD_DIRS)"
788   define if_qemu
789     $(2)
790   endef
791 endif
792
793 VALGRIND_CMD =
794 ifeq ($(VALGRIND),1)
795   VALGRIND_CMD = /usr/bin/valgrind --tool=memcheck $(VALGRIND_ARGS) --
796 endif
797
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)
803 endef
804
805 define TEST_setup
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
814   $(call if_qemu,\
815     $(QUIET)(echo "mkdir -p '$(SYSROOT)/proc' '$(SYSROOT)/dev' \
816                             '$(SYSROOT)/mnt/host/source'" \
817              >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
818   $(call if_qemu,\
819     $(QUIET)(echo "$(MOUNT_CMD) --bind /mnt/host/source \
820              '$(SYSROOT)/mnt/host/source'" \
821              >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
822   $(call if_qemu,\
823     $(QUIET)(echo "$(MOUNT_CMD) --bind /proc '$(SYSROOT)/proc'" \
824              >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
825   $(call if_qemu,\
826     $(QUIET)(echo "$(MOUNT_CMD) --bind /dev '$(SYSROOT)/dev'" \
827              >> "$(OUT)$(TARGET_OR_MEMBER).setup.test"))
828 endef
829
830 define TEST_teardown
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")
834 endef
835
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)))
839
840 define TEST_run
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"
851 endef
852
853 # Recursive list reversal so that we get RMDIR_ON_CLEAN in reverse order.
854 define reverse
855 $(if $(1),$(call reverse,$(wordlist 2,$(words $(1)),$(1)))) $(firstword $(1))
856 endef
857
858 clean: qemu_clean
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)
863
864 clean:
865         $(QUIET)# Always delete the containing directory last.
866         $(call silent_rmdir,$(OUT))
867
868 FORCE: ;
869 # Empty rule for use when no special targets are needed, like large_tests
870 NONE:
871
872 .PHONY: clean NONE valgrind NONE
873 .DEFAULT_GOAL  :=  all
874 # Don't let make blow away "intermediates"
875 .PRECIOUS: %.pic.o %.pie.o %.a %.pic.a %.pie.a %.test
876
877 # Start accruing build info
878 OUT_DIRS = $(OUT)
879 LD_DIRS = $(OUT)
880 SRC_DIRS = $(SRC)
881
882 include $(wildcard $(OUT)*.d)
883 SUBMODULE_DIRS = $(wildcard $(SRC)/*/module.mk)
884 include $(SUBMODULE_DIRS)
885
886
887 else  ## In duplicate inclusions of common.mk
888
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)
895
896
897 # Depth first
898 $(eval OUT_DIRS += $(OUT)$(MODULE))
899 $(eval SRC_DIRS += $(OUT)$(MODULE))
900 $(eval LD_DIRS := $(LD_DIRS):$(OUT)$(MODULE))
901
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)
909
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))
918
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)/))
924
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)
929
930 endif
931 endif  ## pass-to-subcall wrapper for relocating the call directory