1 # Copyright (c) 2013 Google Inc. 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.
7 # This is all roughly based on the Makefile system used by the Linux
8 # kernel, but is a non-recursive make -- we put the entire dependency
9 # graph in front of make and let it figure it out.
11 # The code below generates a separate .mk file for each target, but
12 # all are sourced by the top-level Makefile. This means that all
13 # variables in .mk-files clobber one another. Be careful to use :=
14 # where appropriate for immediate evaluation, and similarly to watch
15 # that you're not relying on a variable value to last beween different
20 # Global settings and utility functions are currently stuffed in the
21 # toplevel Makefile. It may make sense to generate some .mk files on
22 # the side to keep the the files readable.
30 import gyp.xcode_emulation
31 from gyp.common import GetEnvironFallback
33 generator_default_variables = {
34 'EXECUTABLE_PREFIX': '',
35 'EXECUTABLE_SUFFIX': '',
36 'STATIC_LIB_PREFIX': 'lib',
37 'SHARED_LIB_PREFIX': 'lib',
38 'STATIC_LIB_SUFFIX': '.a',
39 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/$(TARGET)/geni',
40 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen',
41 'PRODUCT_DIR': '$(builddir)',
42 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python.
43 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python.
44 'RULE_INPUT_PATH': '$(abspath $<)',
45 'RULE_INPUT_EXT': '$(suffix $<)',
46 'RULE_INPUT_NAME': '$(notdir $<)',
47 'CONFIGURATION_NAME': '$(BUILDTYPE)',
50 # Make supports multiple toolsets
51 generator_supports_multiple_toolsets = True
53 # Request sorted dependencies in the order from dependents to dependencies.
54 generator_wants_sorted_dependencies = False
57 generator_additional_non_configuration_keys = []
58 generator_additional_path_sections = []
59 generator_extra_sources_for_rules = []
62 def CalculateVariables(default_variables, params):
63 """Calculate additional variables for use in the build (called by gyp)."""
64 flavor = gyp.common.GetFlavor(params)
66 default_variables.setdefault('OS', 'mac')
67 default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib')
68 default_variables.setdefault('SHARED_LIB_DIR',
69 generator_default_variables['PRODUCT_DIR'])
70 default_variables.setdefault('LIB_DIR',
71 generator_default_variables['PRODUCT_DIR'])
73 # Copy additional generator configuration data from Xcode, which is shared
74 # by the Mac Make generator.
75 import gyp.generator.xcode as xcode_generator
76 global generator_additional_non_configuration_keys
77 generator_additional_non_configuration_keys = getattr(xcode_generator,
78 'generator_additional_non_configuration_keys', [])
79 global generator_additional_path_sections
80 generator_additional_path_sections = getattr(xcode_generator,
81 'generator_additional_path_sections', [])
82 global generator_extra_sources_for_rules
83 generator_extra_sources_for_rules = getattr(xcode_generator,
84 'generator_extra_sources_for_rules', [])
85 COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'})
87 operating_system = flavor
88 if flavor == 'android':
89 operating_system = 'linux' # Keep this legacy behavior for now.
90 default_variables.setdefault('OS', operating_system)
91 default_variables.setdefault('SHARED_LIB_SUFFIX', '.so')
92 default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)')
93 default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)')
96 def CalculateGeneratorInputInfo(params):
97 """Calculate the generator specific info that gets fed to input (called by
99 generator_flags = params.get('generator_flags', {})
100 android_ndk_version = generator_flags.get('android_ndk_version', None)
101 # Android NDK requires a strict link order.
102 if android_ndk_version:
103 global generator_wants_sorted_dependencies
104 generator_wants_sorted_dependencies = True
107 def ensure_directory_exists(path):
108 dir = os.path.dirname(path)
109 if dir and not os.path.exists(dir):
113 # The .d checking code below uses these functions:
114 # wildcard, sort, foreach, shell, wordlist
115 # wildcard can handle spaces, the rest can't.
116 # Since I could find no way to make foreach work with spaces in filenames
117 # correctly, the .d files have spaces replaced with another character. The .d
119 # Chromium\ Framework.framework/foo
121 # out/Release/.deps/out/Release/Chromium?Framework.framework/foo
122 # This is the replacement character.
123 SPACE_REPLACEMENT = '?'
126 LINK_COMMANDS_LINUX = """\
127 quiet_cmd_alink = AR($(TOOLSET)) $@
128 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
130 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
131 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
133 # Due to circular dependencies between libraries :(, we wrap the
134 # special "figure out circular dependencies" flags around the entire
135 # input list during linking.
136 quiet_cmd_link = LINK($(TOOLSET)) $@
137 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
139 # We support two kinds of shared objects (.so):
140 # 1) shared_library, which is just bundling together many dependent libraries
142 # 2) loadable_module, which is generating a module intended for dlopen().
144 # They differ only slightly:
145 # In the former case, we want to package all dependent code into the .so.
146 # In the latter case, we want to package just the API exposed by the
148 # This means shared_library uses --whole-archive, while loadable_module doesn't.
149 # (Note that --whole-archive is incompatible with the --start-group used in
152 # Other shared-object link notes:
153 # - Set SONAME to the library filename so our binaries don't reference
154 # the local, absolute paths used on the link command-line.
155 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
156 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
158 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
159 cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
162 LINK_COMMANDS_MAC = """\
163 quiet_cmd_alink = LIBTOOL-STATIC $@
164 cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
166 quiet_cmd_link = LINK($(TOOLSET)) $@
167 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
169 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
170 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
172 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
173 cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
176 LINK_COMMANDS_ANDROID = """\
177 quiet_cmd_alink = AR($(TOOLSET)) $@
178 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
180 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
181 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
183 # Due to circular dependencies between libraries :(, we wrap the
184 # special "figure out circular dependencies" flags around the entire
185 # input list during linking.
186 quiet_cmd_link = LINK($(TOOLSET)) $@
187 quiet_cmd_link_host = LINK($(TOOLSET)) $@
188 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
189 cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
191 # Other shared-object link notes:
192 # - Set SONAME to the library filename so our binaries don't reference
193 # the local, absolute paths used on the link command-line.
194 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
195 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
197 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
198 cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
199 quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@
200 cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
204 LINK_COMMANDS_AIX = """\
205 quiet_cmd_alink = AR($(TOOLSET)) $@
206 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
208 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
209 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
211 quiet_cmd_link = LINK($(TOOLSET)) $@
212 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
214 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
215 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
217 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
218 cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
222 # Header of toplevel Makefile.
223 # This should go into the build tree, but it's easier to keep it here for now.
224 SHARED_HEADER = ("""\
225 # We borrow heavily from the kernel build setup, though we are simpler since
226 # we don't have Kconfig tweaking settings on us.
228 # The implicit make rules have it looking for RCS files, among other things.
229 # We instead explicitly write all the rules we care about.
230 # It's even quicker (saves ~200ms) to pass -r on the command line.
233 # The source directory tree.
235 abs_srcdir := $(abspath $(srcdir))
237 # The name of the builddir.
238 builddir_name ?= %(builddir)s
240 # The V=1 flag on command line makes us verbosely print command lines.
247 # Specify BUILDTYPE=Release on the command line for a release build.
248 BUILDTYPE ?= %(default_configuration)s
250 # Directory all our build output goes into.
251 # Note that this must be two directories beneath src/ for unit tests to pass,
252 # as they reach into the src/ directory for data with relative paths.
253 builddir ?= $(builddir_name)/$(BUILDTYPE)
254 abs_builddir := $(abspath $(builddir))
255 depsdir := $(builddir)/.deps
257 # Object output directory.
258 obj := $(builddir)/obj
259 abs_obj := $(abspath $(obj))
261 # We build up a list of every single one of the targets so we can slurp in the
262 # generated dependency rule Makefiles in one pass.
265 %(make_global_settings)s
267 CC.target ?= %(CC.target)s
268 CFLAGS.target ?= $(CFLAGS)
269 CXX.target ?= %(CXX.target)s
270 CXXFLAGS.target ?= $(CXXFLAGS)
271 LINK.target ?= %(LINK.target)s
272 LDFLAGS.target ?= $(LDFLAGS)
275 # C++ apps need to be linked with g++.
277 # Note: flock is used to seralize linking. Linking is a memory-intensive
278 # process so running parallel links can often lead to thrashing. To disable
279 # the serialization, override LINK via an envrionment variable as follows:
283 # This will allow make to invoke N linker processes as specified in -jN.
284 LINK ?= %(flock)s $(builddir)/linker.lock $(CXX.target)
286 # TODO(evan): move all cross-compilation logic to gyp-time so we don't need
287 # to replicate this environment fallback in make as well.
288 CC.host ?= %(CC.host)s
290 CXX.host ?= %(CXX.host)s
292 LINK.host ?= %(LINK.host)s
294 AR.host ?= %(AR.host)s
296 # Define a dir function that can handle spaces.
297 # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
298 # "leading spaces cannot appear in the text of the first argument as written.
299 # These characters can be put into the argument value by variable substitution."
301 space := $(empty) $(empty)
303 # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
304 replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1)
305 unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1)
306 dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
308 # Flags to make gcc output dependency info. Note that you need to be
309 # careful here to use the flags that ccache and distcc can understand.
310 # We write to a dep file on the side first and then rename at the end
311 # so we can't end up with a broken dep file.
312 depfile = $(depsdir)/$(call replace_spaces,$@).d
313 DEPFLAGS = -MMD -MF $(depfile).raw
315 # We have to fixup the deps output in a few ways.
316 # (1) the file output should mention the proper .o file.
317 # ccache or distcc lose the path to the target, so we convert a rule of
319 # foobar.o: DEP1 DEP2
321 # path/to/foobar.o: DEP1 DEP2
322 # (2) we want missing files not to cause us to fail to build.
324 # foobar.o: DEP1 DEP2 \\
330 # so if the files are missing, they're just considered phony rules.
331 # We have to do some pretty insane escaping to get those backslashes
332 # and dollar signs past make, the shell, and sed at the same time.
333 # Doesn't work with spaces, but that's fine: .d files have spaces in
334 # their names replaced with other characters."""
337 # The depfile may not exist if the input file didn't have any #includes.
339 # Fixup path as in (1).
340 sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
341 # Add extra rules as in (2).
342 # We remove slashes and replace spaces with new lines;
343 # remove blank lines;
344 # delete the first line and append a colon to the remaining lines.
345 sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
347 sed -e 1d -e 's|$$|:|' \
353 # Command definitions:
354 # - cmd_foo is the actual command to run;
355 # - quiet_cmd_foo is the brief-output summary of the command.
357 quiet_cmd_cc = CC($(TOOLSET)) $@
358 cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
360 quiet_cmd_cxx = CXX($(TOOLSET)) $@
361 cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
363 quiet_cmd_touch = TOUCH $@
366 quiet_cmd_copy = COPY $@
367 # send stderr to /dev/null to ignore messages when linking directories.
368 cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
374 # Define an escape_quotes function to escape single quotes.
375 # This allows us to handle quotes properly as long as we always use
376 # use single quotes and escape_quotes.
377 escape_quotes = $(subst ','\'',$(1))
378 # This comment is here just to include a ' to unconfuse syntax highlighting.
379 # Define an escape_vars function to escape '$' variable syntax.
380 # This allows us to read/write command lines with shell variables (e.g.
381 # $LD_LIBRARY_PATH), without triggering make substitution.
382 escape_vars = $(subst $$,$$$$,$(1))
383 # Helper that expands to a shell command to echo a string exactly as it is in
384 # make. This uses printf instead of echo because printf's behaviour with respect
385 # to escape sequences is more portable than echo's across different shells
386 # (e.g., dash, bash).
387 exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))'
390 # Helper to compare the command we're about to run against the command
391 # we logged the last time we ran the command. Produces an empty
392 # string (false) when the commands match.
393 # Tricky point: Make has no string-equality test function.
394 # The kernel uses the following, but it seems like it would have false
395 # positives, where one string reordered its arguments.
396 # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\
397 # $(filter-out $(cmd_$@), $(cmd_$(1))))
398 # We instead substitute each for the empty string into the other, and
399 # say they're equal if both substitutions produce the empty string.
400 # .d files contain """ + SPACE_REPLACEMENT + \
401 """ instead of spaces, take that into account.
402 command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\
403 $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
405 # Helper that is non-empty when a prerequisite changes.
406 # Normally make does this implicitly, but we force rules to always run
407 # so we can check their command lines.
408 # $? -- new prerequisites
409 # $| -- order-only dependencies
410 prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
412 # Helper that executes all postbuilds until one fails.
415 for p in $(POSTBUILDS); do\\
418 if [ $$E -ne 0 ]; then\\
422 if [ $$E -ne 0 ]; then\\
428 # do_cmd: run a command via the above cmd_foo names, if necessary.
429 # Should always run for a given target to handle command-line changes.
430 # Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
431 # Third argument, if non-zero, makes it do POSTBUILDS processing.
432 # Note: We intentionally do NOT call dirx for depfile, since it contains """ + \
433 SPACE_REPLACEMENT + """ for
434 # spaces already and dirx strips the """ + SPACE_REPLACEMENT + \
437 $(if $(or $(command_changed),$(prereq_changed)),
438 @$(call exact_echo, $($(quiet)cmd_$(1)))
439 @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
440 $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))),
442 @echo " $(quiet_cmd_$(1)): Finished",
445 @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
446 @$(if $(2),$(fixup_dep))
447 $(if $(and $(3), $(POSTBUILDS)),
448 $(call do_postbuilds)
453 # Declare the "%(default_target)s" target first so it is the default,
454 # even though we don't have the deps yet.
455 .PHONY: %(default_target)s
458 # make looks for ways to re-generate included makefiles, but in our case, we
459 # don't have a direct way. Explicitly telling make that it has nothing to do
460 # for them makes it go faster.
463 # Use FORCE_DO_CMD to force a target to run. Should be coupled with
470 SHARED_HEADER_MAC_COMMANDS = """
471 quiet_cmd_objc = CXX($(TOOLSET)) $@
472 cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
474 quiet_cmd_objcxx = CXX($(TOOLSET)) $@
475 cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
477 # Commands for precompiled header files.
478 quiet_cmd_pch_c = CXX($(TOOLSET)) $@
479 cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
480 quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
481 cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
482 quiet_cmd_pch_m = CXX($(TOOLSET)) $@
483 cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
484 quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
485 cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
487 # gyp-mac-tool is written next to the root Makefile by gyp.
488 # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
490 quiet_cmd_mac_tool = MACTOOL $(4) $<
491 cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
493 quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
494 cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
496 quiet_cmd_infoplist = INFOPLIST $@
497 cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
501 def WriteRootHeaderSuffixRules(writer):
502 extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower)
504 writer.write('# Suffix rules, putting all outputs into $(obj).\n')
505 for ext in extensions:
506 writer.write('$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n' % ext)
507 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
509 writer.write('\n# Try building from generated source, too.\n')
510 for ext in extensions:
512 '$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n' % ext)
513 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
515 for ext in extensions:
516 writer.write('$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n' % ext)
517 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
521 SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\
522 # Suffix rules, putting all outputs into $(obj).
526 SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\
527 # Try building from generated source, too.
532 # "all" is a concatenation of the "all" targets from all the included
533 # sub-makefiles. This is just here to clarify.
536 # Add in dependency-tracking rules. $(all_deps) is the list of every single
537 # target in our tree. Only consider the ones with .d (dependency) info:
538 d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
545 # This file is generated by gyp; do not edit.
549 # Maps every compilable file extension to the do_cmd that compiles it.
550 COMPILABLE_EXTENSIONS = {
559 def Compilable(filename):
560 """Return true if the file is compilable (should be in OBJS)."""
561 for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS):
567 def Linkable(filename):
568 """Return true if the file is linkable (should be on the link line)."""
569 return filename.endswith('.o')
572 def Target(filename):
573 """Translate a compilable filename to its .o target."""
574 return os.path.splitext(filename)[0] + '.o'
577 def EscapeShellArgument(s):
578 """Quotes an argument so that it will be interpreted literally by a POSIX
580 http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
582 return "'" + s.replace("'", "'\\''") + "'"
585 def EscapeMakeVariableExpansion(s):
586 """Make has its own variable expansion syntax using $. We must escape it for
587 string to be interpreted literally."""
588 return s.replace('$', '$$')
591 def EscapeCppDefine(s):
592 """Escapes a CPP define so that it will reach the compiler unaltered."""
593 s = EscapeShellArgument(s)
594 s = EscapeMakeVariableExpansion(s)
595 # '#' characters must be escaped even embedded in a string, else Make will
596 # treat it as the start of a comment.
597 return s.replace('#', r'\#')
600 def QuoteIfNecessary(string):
601 """TODO: Should this ideally be replaced with one or more of the above
604 string = '"' + string.replace('"', '\\"') + '"'
608 def StringToMakefileVariable(string):
609 """Convert a string to a value that is acceptable as a make variable name."""
610 return re.sub('[^a-zA-Z0-9_]', '_', string)
615 """Convert a path to its source directory form."""
618 if os.path.isabs(path):
620 return srcdir_prefix + path
623 def QuoteSpaces(s, quote=r'\ '):
624 return s.replace(' ', quote)
627 # Map from qualified target to path to output.
629 # Map from qualified target to any linkable output. A subset
630 # of target_outputs. E.g. when mybinary depends on liba, we want to
631 # include liba in the linker line; when otherbinary depends on
632 # mybinary, we just want to build mybinary first.
633 target_link_deps = {}
636 class MakefileWriter:
637 """MakefileWriter packages up the writing of one target-specific foobar.mk.
639 Its only real entry point is Write(), and is mostly used for namespacing.
642 def __init__(self, generator_flags, flavor):
643 self.generator_flags = generator_flags
646 self.suffix_rules_srcdir = {}
647 self.suffix_rules_objdir1 = {}
648 self.suffix_rules_objdir2 = {}
650 # Generate suffix rules for all compilable extensions.
651 for ext in COMPILABLE_EXTENSIONS.keys():
652 # Suffix rules for source folder.
653 self.suffix_rules_srcdir.update({ext: ("""\
654 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD
656 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
658 # Suffix rules for generated source files.
659 self.suffix_rules_objdir1.update({ext: ("""\
660 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD
662 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
663 self.suffix_rules_objdir2.update({ext: ("""\
664 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
666 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
669 def Write(self, qualified_target, base_path, output_filename, spec, configs,
671 """The main entry point: writes a .mk file for a single target.
674 qualified_target: target we're generating
675 base_path: path relative to source root we're building in, used to resolve
676 target-relative paths
677 output_filename: output .mk file name to write
678 spec, configs: gyp info
679 part_of_all: flag indicating this target is part of 'all'
681 ensure_directory_exists(output_filename)
683 self.fp = open(output_filename, 'w')
685 self.fp.write(header)
687 self.qualified_target = qualified_target
688 self.path = base_path
689 self.target = spec['target_name']
690 self.type = spec['type']
691 self.toolset = spec['toolset']
693 self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
694 if self.flavor == 'mac':
695 self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
697 self.xcode_settings = None
699 deps, link_deps = self.ComputeDeps(spec)
701 # Some of the generation below can add extra output, sources, or
702 # link dependencies. All of the out params of the functions that
703 # follow use names like extra_foo.
707 extra_mac_bundle_resources = []
710 if self.is_mac_bundle:
711 self.output = self.ComputeMacBundleOutput(spec)
712 self.output_binary = self.ComputeMacBundleBinaryOutput(spec)
714 self.output = self.output_binary = self.ComputeOutput(spec)
716 self.is_standalone_static_library = bool(
717 spec.get('standalone_static_library', 0))
718 self._INSTALLABLE_TARGETS = ('executable', 'loadable_module',
720 if (self.is_standalone_static_library or
721 self.type in self._INSTALLABLE_TARGETS):
722 self.alias = os.path.basename(self.output)
723 install_path = self._InstallableTargetInstallPath()
725 self.alias = self.output
726 install_path = self.output
728 self.WriteLn("TOOLSET := " + self.toolset)
729 self.WriteLn("TARGET := " + self.target)
731 # Actions must come first, since they can generate more OBJs for use below.
732 if 'actions' in spec:
733 self.WriteActions(spec['actions'], extra_sources, extra_outputs,
734 extra_mac_bundle_resources, part_of_all)
736 # Rules must be early like actions.
738 self.WriteRules(spec['rules'], extra_sources, extra_outputs,
739 extra_mac_bundle_resources, part_of_all)
742 self.WriteCopies(spec['copies'], extra_outputs, part_of_all)
745 if self.is_mac_bundle:
746 all_mac_bundle_resources = (
747 spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources)
748 self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps)
749 self.WriteMacInfoPlist(mac_bundle_deps)
752 all_sources = spec.get('sources', []) + extra_sources
755 configs, deps, all_sources, extra_outputs,
756 extra_link_deps, part_of_all,
757 gyp.xcode_emulation.MacPrefixHeader(
758 self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)),
760 sources = filter(Compilable, all_sources)
762 self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1)
763 extensions = set([os.path.splitext(s)[1] for s in sources])
764 for ext in extensions:
765 if ext in self.suffix_rules_srcdir:
766 self.WriteLn(self.suffix_rules_srcdir[ext])
767 self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2)
768 for ext in extensions:
769 if ext in self.suffix_rules_objdir1:
770 self.WriteLn(self.suffix_rules_objdir1[ext])
771 for ext in extensions:
772 if ext in self.suffix_rules_objdir2:
773 self.WriteLn(self.suffix_rules_objdir2[ext])
774 self.WriteLn('# End of this set of suffix rules')
776 # Add dependency from bundle to bundle binary.
777 if self.is_mac_bundle:
778 mac_bundle_deps.append(self.output_binary)
780 self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps,
781 mac_bundle_deps, extra_outputs, part_of_all)
783 # Update global list of target outputs, used in dependency tracking.
784 target_outputs[qualified_target] = install_path
786 # Update global list of link dependencies.
787 if self.type in ('static_library', 'shared_library'):
788 target_link_deps[qualified_target] = self.output_binary
790 # Currently any versions have the same effect, but in future the behavior
791 # could be different.
792 if self.generator_flags.get('android_ndk_version', None):
793 self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps)
798 def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
799 """Write a "sub-project" Makefile.
801 This is a small, wrapper Makefile that calls the top-level Makefile to build
802 the targets from a single gyp file (i.e. a sub-project).
805 output_filename: sub-project Makefile name to write
806 makefile_path: path to the top-level Makefile
807 targets: list of "all" targets for this sub-project
808 build_dir: build output directory, relative to the sub-project
810 ensure_directory_exists(output_filename)
811 self.fp = open(output_filename, 'w')
812 self.fp.write(header)
813 # For consistency with other builders, put sub-project build output in the
814 # sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
815 self.WriteLn('export builddir_name ?= %s' %
816 os.path.join(os.path.dirname(output_filename), build_dir))
817 self.WriteLn('.PHONY: all')
820 makefile_path = ' -C ' + makefile_path
821 self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
825 def WriteActions(self, actions, extra_sources, extra_outputs,
826 extra_mac_bundle_resources, part_of_all):
827 """Write Makefile code for any 'actions' from the gyp input.
829 extra_sources: a list that will be filled in with newly generated source
831 extra_outputs: a list that will be filled in with any outputs of these
832 actions (used to make other pieces dependent on these
834 part_of_all: flag indicating this target is part of 'all'
836 env = self.GetSortedXcodeEnv()
837 for action in actions:
838 name = StringToMakefileVariable('%s_%s' % (self.qualified_target,
839 action['action_name']))
840 self.WriteLn('### Rules for action "%s":' % action['action_name'])
841 inputs = action['inputs']
842 outputs = action['outputs']
844 # Build up a list of outputs.
845 # Collect the output dirs we'll need.
848 dir = os.path.split(out)[0]
851 if int(action.get('process_outputs_as_sources', False)):
852 extra_sources += outputs
853 if int(action.get('process_outputs_as_mac_bundle_resources', False)):
854 extra_mac_bundle_resources += outputs
856 # Write the actual command.
857 action_commands = action['action']
858 if self.flavor == 'mac':
859 action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env)
860 for command in action_commands]
861 command = gyp.common.EncodePOSIXShellList(action_commands)
862 if 'message' in action:
863 self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message']))
865 self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name))
867 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
869 cd_action = 'cd %s; ' % Sourceify(self.path or '.')
871 # command and cd_action get written to a toplevel variable called
872 # cmd_foo. Toplevel variables can't handle things that change per
873 # makefile like $(TARGET), so hardcode the target.
874 command = command.replace('$(TARGET)', self.target)
875 cd_action = cd_action.replace('$(TARGET)', self.target)
877 # Set LD_LIBRARY_PATH in case the action runs an executable from this
878 # build which links to shared libs from this build.
879 # actions run on the host, so they should in theory only use host
880 # libraries, but until everything is made cross-compile safe, also use
882 # TODO(piman): when everything is cross-compile safe, remove lib.target
883 self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:'
884 '$(builddir)/lib.target:$$LD_LIBRARY_PATH; '
885 'export LD_LIBRARY_PATH; '
887 % (name, cd_action, command))
889 outputs = map(self.Absolutify, outputs)
890 # The makefile rules are all relative to the top dir, but the gyp actions
891 # are defined relative to their containing dir. This replaces the obj
892 # variable for the action rule with an absolute version so that the output
893 # goes in the right place.
894 # Only write the 'obj' and 'builddir' rules for the "primary" output (:1);
895 # it's superfluous for the "extra outputs", and this avoids accidentally
896 # writing duplicate dummy rules for those outputs.
897 # Same for environment.
898 self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0]))
899 self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0]))
900 self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv())
903 assert ' ' not in input, (
904 "Spaces in action input filenames not supported (%s)" % input)
905 for output in outputs:
906 assert ' ' not in output, (
907 "Spaces in action output filenames not supported (%s)" % output)
909 # See the comment in WriteCopies about expanding env vars.
910 outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
911 inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
913 self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)),
914 part_of_all=part_of_all, command=name)
916 # Stuff the outputs in a variable so we can refer to them later.
917 outputs_variable = 'action_%s_outputs' % name
918 self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs)))
919 extra_outputs.append('$(%s)' % outputs_variable)
925 def WriteRules(self, rules, extra_sources, extra_outputs,
926 extra_mac_bundle_resources, part_of_all):
927 """Write Makefile code for any 'rules' from the gyp input.
929 extra_sources: a list that will be filled in with newly generated source
931 extra_outputs: a list that will be filled in with any outputs of these
932 rules (used to make other pieces dependent on these rules)
933 part_of_all: flag indicating this target is part of 'all'
935 env = self.GetSortedXcodeEnv()
937 name = StringToMakefileVariable('%s_%s' % (self.qualified_target,
940 self.WriteLn('### Generated for rule %s:' % name)
944 for rule_source in rule.get('rule_sources', []):
946 (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
947 (rule_source_root, rule_source_ext) = \
948 os.path.splitext(rule_source_basename)
950 outputs = [self.ExpandInputRoot(out, rule_source_root,
952 for out in rule['outputs']]
955 dir = os.path.dirname(out)
958 if int(rule.get('process_outputs_as_sources', False)):
959 extra_sources += outputs
960 if int(rule.get('process_outputs_as_mac_bundle_resources', False)):
961 extra_mac_bundle_resources += outputs
962 inputs = map(Sourceify, map(self.Absolutify, [rule_source] +
963 rule.get('inputs', [])))
964 actions = ['$(call do_cmd,%s_%d)' % (name, count)]
966 if name == 'resources_grit':
967 # HACK: This is ugly. Grit intentionally doesn't touch the
968 # timestamp of its output file when the file doesn't change,
969 # which is fine in hash-based dependency systems like scons
970 # and forge, but not kosher in the make world. After some
971 # discussion, hacking around it here seems like the least
973 actions += ['@touch --no-create $@']
975 # See the comment in WriteCopies about expanding env vars.
976 outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
977 inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
979 outputs = map(self.Absolutify, outputs)
980 all_outputs += outputs
981 # Only write the 'obj' and 'builddir' rules for the "primary" output
982 # (:1); it's superfluous for the "extra outputs", and this avoids
983 # accidentally writing duplicate dummy rules for those outputs.
984 self.WriteLn('%s: obj := $(abs_obj)' % outputs[0])
985 self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0])
986 self.WriteMakeRule(outputs, inputs + ['FORCE_DO_CMD'], actions)
987 # Spaces in rule filenames are not supported, but rule variables have
988 # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)').
989 # The spaces within the variables are valid, so remove the variables
991 variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)')
992 for output in outputs:
993 output = re.sub(variables_with_spaces, '', output)
994 assert ' ' not in output, (
995 "Spaces in rule filenames not yet supported (%s)" % output)
996 self.WriteLn('all_deps += %s' % ' '.join(outputs))
998 action = [self.ExpandInputRoot(ac, rule_source_root,
1000 for ac in rule['action']]
1003 mkdirs = 'mkdir -p %s; ' % ' '.join(dirs)
1004 cd_action = 'cd %s; ' % Sourceify(self.path or '.')
1006 # action, cd_action, and mkdirs get written to a toplevel variable
1007 # called cmd_foo. Toplevel variables can't handle things that change
1008 # per makefile like $(TARGET), so hardcode the target.
1009 if self.flavor == 'mac':
1010 action = [gyp.xcode_emulation.ExpandEnvVars(command, env)
1011 for command in action]
1012 action = gyp.common.EncodePOSIXShellList(action)
1013 action = action.replace('$(TARGET)', self.target)
1014 cd_action = cd_action.replace('$(TARGET)', self.target)
1015 mkdirs = mkdirs.replace('$(TARGET)', self.target)
1017 # Set LD_LIBRARY_PATH in case the rule runs an executable from this
1018 # build which links to shared libs from this build.
1019 # rules run on the host, so they should in theory only use host
1020 # libraries, but until everything is made cross-compile safe, also use
1022 # TODO(piman): when everything is cross-compile safe, remove lib.target
1024 "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH="
1025 "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; "
1026 "export LD_LIBRARY_PATH; "
1027 "%(cd_action)s%(mkdirs)s%(action)s" % {
1029 'cd_action': cd_action,
1035 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % {
1042 outputs_variable = 'rule_%s_outputs' % name
1043 self.WriteList(all_outputs, outputs_variable)
1044 extra_outputs.append('$(%s)' % outputs_variable)
1046 self.WriteLn('### Finished generating for rule: %s' % name)
1048 self.WriteLn('### Finished generating for all rules')
1052 def WriteCopies(self, copies, extra_outputs, part_of_all):
1053 """Write Makefile code for any 'copies' from the gyp input.
1055 extra_outputs: a list that will be filled in with any outputs of this action
1056 (used to make other pieces dependent on this action)
1057 part_of_all: flag indicating this target is part of 'all'
1059 self.WriteLn('### Generated for copy rule.')
1061 variable = StringToMakefileVariable(self.qualified_target + '_copies')
1064 for path in copy['files']:
1065 # Absolutify() may call normpath, and will strip trailing slashes.
1066 path = Sourceify(self.Absolutify(path))
1067 filename = os.path.split(path)[1]
1068 output = Sourceify(self.Absolutify(os.path.join(copy['destination'],
1071 # If the output path has variables in it, which happens in practice for
1072 # 'copies', writing the environment as target-local doesn't work,
1073 # because the variables are already needed for the target name.
1074 # Copying the environment variables into global make variables doesn't
1075 # work either, because then the .d files will potentially contain spaces
1076 # after variable expansion, and .d file handling cannot handle spaces.
1077 # As a workaround, manually expand variables at gyp time. Since 'copies'
1078 # can't run scripts, there's no need to write the env then.
1079 # WriteDoCmd() will escape spaces for .d files.
1080 env = self.GetSortedXcodeEnv()
1081 output = gyp.xcode_emulation.ExpandEnvVars(output, env)
1082 path = gyp.xcode_emulation.ExpandEnvVars(path, env)
1083 self.WriteDoCmd([output], [path], 'copy', part_of_all)
1084 outputs.append(output)
1085 self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs))))
1086 extra_outputs.append('$(%s)' % variable)
1090 def WriteMacBundleResources(self, resources, bundle_deps):
1091 """Writes Makefile code for 'mac_bundle_resources'."""
1092 self.WriteLn('### Generated for mac_bundle_resources')
1094 for output, res in gyp.xcode_emulation.GetMacBundleResources(
1095 generator_default_variables['PRODUCT_DIR'], self.xcode_settings,
1096 map(Sourceify, map(self.Absolutify, resources))):
1097 self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource',
1099 bundle_deps.append(output)
1102 def WriteMacInfoPlist(self, bundle_deps):
1103 """Write Makefile code for bundle Info.plist files."""
1104 info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
1105 generator_default_variables['PRODUCT_DIR'], self.xcode_settings,
1106 lambda p: Sourceify(self.Absolutify(p)))
1110 # Create an intermediate file to store preprocessed results.
1111 intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' +
1112 os.path.basename(info_plist))
1113 self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D',
1114 quoter=EscapeCppDefine)
1115 self.WriteMakeRule([intermediate_plist], [info_plist],
1116 ['$(call do_cmd,infoplist)',
1117 # "Convert" the plist so that any weird whitespace changes from the
1118 # preprocessor do not affect the XML parser in mac_tool.
1119 '@plutil -convert xml1 $@ $@'])
1120 info_plist = intermediate_plist
1121 # plists can contain envvars and substitute them into the file.
1122 self.WriteSortedXcodeEnv(
1123 out, self.GetSortedXcodeEnv(additional_settings=extra_env))
1124 self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist',
1126 bundle_deps.append(out)
1129 def WriteSources(self, configs, deps, sources,
1130 extra_outputs, extra_link_deps,
1131 part_of_all, precompiled_header):
1132 """Write Makefile code for any 'sources' from the gyp input.
1133 These are source files necessary to build the current target.
1135 configs, deps, sources: input from gyp.
1136 extra_outputs: a list of extra outputs this action should be dependent on;
1137 used to serialize action/rules before compilation
1138 extra_link_deps: a list that will be filled in with any outputs of
1139 compilation (to be used in link lines)
1140 part_of_all: flag indicating this target is part of 'all'
1143 # Write configuration-specific variables for CFLAGS, etc.
1144 for configname in sorted(configs.keys()):
1145 config = configs[configname]
1146 self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D',
1147 quoter=EscapeCppDefine)
1149 if self.flavor == 'mac':
1150 cflags = self.xcode_settings.GetCflags(configname)
1151 cflags_c = self.xcode_settings.GetCflagsC(configname)
1152 cflags_cc = self.xcode_settings.GetCflagsCC(configname)
1153 cflags_objc = self.xcode_settings.GetCflagsObjC(configname)
1154 cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname)
1156 cflags = config.get('cflags')
1157 cflags_c = config.get('cflags_c')
1158 cflags_cc = config.get('cflags_cc')
1160 self.WriteLn("# Flags passed to all source files.");
1161 self.WriteList(cflags, 'CFLAGS_%s' % configname)
1162 self.WriteLn("# Flags passed to only C files.");
1163 self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname)
1164 self.WriteLn("# Flags passed to only C++ files.");
1165 self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname)
1166 if self.flavor == 'mac':
1167 self.WriteLn("# Flags passed to only ObjC files.");
1168 self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname)
1169 self.WriteLn("# Flags passed to only ObjC++ files.");
1170 self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname)
1171 includes = config.get('include_dirs')
1173 includes = map(Sourceify, map(self.Absolutify, includes))
1174 self.WriteList(includes, 'INCS_%s' % configname, prefix='-I')
1176 compilable = filter(Compilable, sources)
1177 objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable)))
1178 self.WriteList(objs, 'OBJS')
1181 assert ' ' not in obj, (
1182 "Spaces in object filenames not supported (%s)" % obj)
1183 self.WriteLn('# Add to the list of files we specially track '
1184 'dependencies for.')
1185 self.WriteLn('all_deps += $(OBJS)')
1188 # Make sure our dependencies are built first.
1190 self.WriteMakeRule(['$(OBJS)'], deps,
1191 comment = 'Make sure our dependencies are built '
1192 'before any of us.',
1195 # Make sure the actions and rules run first.
1196 # If they generate any extra headers etc., the per-.o file dep tracking
1197 # will catch the proper rebuilds, so order only is still ok here.
1199 self.WriteMakeRule(['$(OBJS)'], extra_outputs,
1200 comment = 'Make sure our actions/rules run '
1201 'before any of us.',
1204 pchdeps = precompiled_header.GetObjDependencies(compilable, objs )
1206 self.WriteLn('# Dependencies from obj files to their precompiled headers')
1207 for source, obj, gch in pchdeps:
1208 self.WriteLn('%s: %s' % (obj, gch))
1209 self.WriteLn('# End precompiled header dependencies')
1212 extra_link_deps.append('$(OBJS)')
1214 # CFLAGS et al overrides must be target-local.
1215 # See "Target-specific Variable Values" in the GNU Make manual.""")
1216 self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)")
1217 self.WriteLn("$(OBJS): GYP_CFLAGS := "
1218 "$(DEFS_$(BUILDTYPE)) "
1219 "$(INCS_$(BUILDTYPE)) "
1220 "%s " % precompiled_header.GetInclude('c') +
1221 "$(CFLAGS_$(BUILDTYPE)) "
1222 "$(CFLAGS_C_$(BUILDTYPE))")
1223 self.WriteLn("$(OBJS): GYP_CXXFLAGS := "
1224 "$(DEFS_$(BUILDTYPE)) "
1225 "$(INCS_$(BUILDTYPE)) "
1226 "%s " % precompiled_header.GetInclude('cc') +
1227 "$(CFLAGS_$(BUILDTYPE)) "
1228 "$(CFLAGS_CC_$(BUILDTYPE))")
1229 if self.flavor == 'mac':
1230 self.WriteLn("$(OBJS): GYP_OBJCFLAGS := "
1231 "$(DEFS_$(BUILDTYPE)) "
1232 "$(INCS_$(BUILDTYPE)) "
1233 "%s " % precompiled_header.GetInclude('m') +
1234 "$(CFLAGS_$(BUILDTYPE)) "
1235 "$(CFLAGS_C_$(BUILDTYPE)) "
1236 "$(CFLAGS_OBJC_$(BUILDTYPE))")
1237 self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := "
1238 "$(DEFS_$(BUILDTYPE)) "
1239 "$(INCS_$(BUILDTYPE)) "
1240 "%s " % precompiled_header.GetInclude('mm') +
1241 "$(CFLAGS_$(BUILDTYPE)) "
1242 "$(CFLAGS_CC_$(BUILDTYPE)) "
1243 "$(CFLAGS_OBJCC_$(BUILDTYPE))")
1245 self.WritePchTargets(precompiled_header.GetPchBuildCommands())
1247 # If there are any object files in our input file list, link them into our
1249 extra_link_deps += filter(Linkable, sources)
1253 def WritePchTargets(self, pch_commands):
1254 """Writes make rules to compile prefix headers."""
1255 if not pch_commands:
1258 for gch, lang_flag, lang, input in pch_commands:
1260 'c': '$(CFLAGS_C_$(BUILDTYPE))',
1261 'cc': '$(CFLAGS_CC_$(BUILDTYPE))',
1262 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))',
1263 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))',
1266 'c': 'GYP_PCH_CFLAGS',
1267 'cc': 'GYP_PCH_CXXFLAGS',
1268 'm': 'GYP_PCH_OBJCFLAGS',
1269 'mm': 'GYP_PCH_OBJCXXFLAGS',
1271 self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) +
1272 "$(DEFS_$(BUILDTYPE)) "
1273 "$(INCS_$(BUILDTYPE)) "
1274 "$(CFLAGS_$(BUILDTYPE)) " +
1277 self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input))
1278 self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang)
1280 assert ' ' not in gch, (
1281 "Spaces in gch filenames not supported (%s)" % gch)
1282 self.WriteLn('all_deps += %s' % gch)
1286 def ComputeOutputBasename(self, spec):
1287 """Return the 'output basename' of a gyp spec.
1289 E.g., the loadable module 'foobar' in directory 'baz' will produce
1292 assert not self.is_mac_bundle
1294 if self.flavor == 'mac' and self.type in (
1295 'static_library', 'executable', 'shared_library', 'loadable_module'):
1296 return self.xcode_settings.GetExecutablePath()
1298 target = spec['target_name']
1301 if self.type == 'static_library':
1302 if target[:3] == 'lib':
1304 target_prefix = 'lib'
1306 elif self.type in ('loadable_module', 'shared_library'):
1307 if target[:3] == 'lib':
1309 target_prefix = 'lib'
1311 elif self.type == 'none':
1312 target = '%s.stamp' % target
1313 elif self.type != 'executable':
1314 print ("ERROR: What output file should be generated?",
1315 "type", self.type, "target", target)
1317 target_prefix = spec.get('product_prefix', target_prefix)
1318 target = spec.get('product_name', target)
1319 product_ext = spec.get('product_extension')
1321 target_ext = '.' + product_ext
1323 return target_prefix + target + target_ext
1326 def _InstallImmediately(self):
1327 return self.toolset == 'target' and self.flavor == 'mac' and self.type in (
1328 'static_library', 'executable', 'shared_library', 'loadable_module')
1331 def ComputeOutput(self, spec):
1332 """Return the 'output' (full output path) of a gyp spec.
1334 E.g., the loadable module 'foobar' in directory 'baz' will produce
1335 '$(obj)/baz/libfoobar.so'
1337 assert not self.is_mac_bundle
1339 path = os.path.join('$(obj).' + self.toolset, self.path)
1340 if self.type == 'executable' or self._InstallImmediately():
1341 path = '$(builddir)'
1342 path = spec.get('product_dir', path)
1343 return os.path.join(path, self.ComputeOutputBasename(spec))
1346 def ComputeMacBundleOutput(self, spec):
1347 """Return the 'output' (full output path) to a bundle output directory."""
1348 assert self.is_mac_bundle
1349 path = generator_default_variables['PRODUCT_DIR']
1350 return os.path.join(path, self.xcode_settings.GetWrapperName())
1353 def ComputeMacBundleBinaryOutput(self, spec):
1354 """Return the 'output' (full output path) to the binary in a bundle."""
1355 path = generator_default_variables['PRODUCT_DIR']
1356 return os.path.join(path, self.xcode_settings.GetExecutablePath())
1359 def ComputeDeps(self, spec):
1360 """Compute the dependencies of a gyp spec.
1362 Returns a tuple (deps, link_deps), where each is a list of
1363 filenames that will need to be put in front of make for either
1364 building (deps) or linking (link_deps).
1368 if 'dependencies' in spec:
1369 deps.extend([target_outputs[dep] for dep in spec['dependencies']
1370 if target_outputs[dep]])
1371 for dep in spec['dependencies']:
1372 if dep in target_link_deps:
1373 link_deps.append(target_link_deps[dep])
1374 deps.extend(link_deps)
1375 # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)?
1376 # This hack makes it work:
1377 # link_deps.extend(spec.get('libraries', []))
1378 return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
1381 def WriteDependencyOnExtraOutputs(self, target, extra_outputs):
1382 self.WriteMakeRule([self.output_binary], extra_outputs,
1383 comment = 'Build our special outputs first.',
1387 def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
1388 extra_outputs, part_of_all):
1389 """Write Makefile code to produce the final target of the gyp spec.
1391 spec, configs: input from gyp.
1392 deps, link_deps: dependency lists; see ComputeDeps()
1393 extra_outputs: any extra outputs that our target should depend on
1394 part_of_all: flag indicating this target is part of 'all'
1397 self.WriteLn('### Rules for final target.')
1400 self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs)
1401 self.WriteMakeRule(extra_outputs, deps,
1402 comment=('Preserve order dependency of '
1403 'special output on deps.'),
1406 target_postbuilds = {}
1407 if self.type != 'none':
1408 for configname in sorted(configs.keys()):
1409 config = configs[configname]
1410 if self.flavor == 'mac':
1411 ldflags = self.xcode_settings.GetLdflags(configname,
1412 generator_default_variables['PRODUCT_DIR'],
1413 lambda p: Sourceify(self.Absolutify(p)))
1415 # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.
1416 gyp_to_build = gyp.common.InvertRelativePath(self.path)
1417 target_postbuild = self.xcode_settings.AddImplicitPostbuilds(
1419 QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build,
1421 QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build,
1422 self.output_binary))))
1423 if target_postbuild:
1424 target_postbuilds[configname] = target_postbuild
1426 ldflags = config.get('ldflags', [])
1427 # Compute an rpath for this output if needed.
1428 if any(dep.endswith('.so') or '.so.' in dep for dep in deps):
1429 # We want to get the literal string "$ORIGIN" into the link command,
1430 # so we need lots of escaping.
1431 ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset)
1432 ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' %
1434 library_dirs = config.get('library_dirs', [])
1435 ldflags += [('-L%s' % library_dir) for library_dir in library_dirs]
1436 self.WriteList(ldflags, 'LDFLAGS_%s' % configname)
1437 if self.flavor == 'mac':
1438 self.WriteList(self.xcode_settings.GetLibtoolflags(configname),
1439 'LIBTOOLFLAGS_%s' % configname)
1440 libraries = spec.get('libraries')
1442 # Remove duplicate entries
1443 libraries = gyp.common.uniquer(libraries)
1444 if self.flavor == 'mac':
1445 libraries = self.xcode_settings.AdjustLibraries(libraries)
1446 self.WriteList(libraries, 'LIBS')
1447 self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' %
1448 QuoteSpaces(self.output_binary))
1449 self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary))
1451 if self.flavor == 'mac':
1452 self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' %
1453 QuoteSpaces(self.output_binary))
1455 # Postbuild actions. Like actions, but implicitly depend on the target's
1458 if self.flavor == 'mac':
1459 if target_postbuilds:
1460 postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))')
1462 gyp.xcode_emulation.GetSpecPostbuildCommands(spec))
1465 # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),
1466 # so we must output its definition first, since we declare variables
1468 self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv())
1470 for configname in target_postbuilds:
1471 self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' %
1472 (QuoteSpaces(self.output),
1474 gyp.common.EncodePOSIXShellList(target_postbuilds[configname])))
1476 # Postbuilds expect to be run in the gyp file's directory, so insert an
1477 # implicit postbuild to cd to there.
1478 postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path]))
1479 for i in xrange(len(postbuilds)):
1480 if not postbuilds[i].startswith('$'):
1481 postbuilds[i] = EscapeShellArgument(postbuilds[i])
1482 self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output))
1483 self.WriteLn('%s: POSTBUILDS := %s' % (
1484 QuoteSpaces(self.output), ' '.join(postbuilds)))
1486 # A bundle directory depends on its dependencies such as bundle resources
1487 # and bundle binary. When all dependencies have been built, the bundle
1488 # needs to be packaged.
1489 if self.is_mac_bundle:
1490 # If the framework doesn't contain a binary, then nothing depends
1491 # on the actions -- make the framework depend on them directly too.
1492 self.WriteDependencyOnExtraOutputs(self.output, extra_outputs)
1494 # Bundle dependencies. Note that the code below adds actions to this
1495 # target, so if you move these two lines, move the lines below as well.
1496 self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS')
1497 self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output))
1499 # After the framework is built, package it. Needs to happen before
1500 # postbuilds, since postbuilds depend on this.
1501 if self.type in ('shared_library', 'loadable_module'):
1502 self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' %
1503 self.xcode_settings.GetFrameworkVersion())
1505 # Bundle postbuilds can depend on the whole bundle, so run them after
1506 # the bundle is packaged, not already after the bundle binary is done.
1508 self.WriteLn('\t@$(call do_postbuilds)')
1509 postbuilds = [] # Don't write postbuilds for target's output.
1511 # Needed by test/mac/gyptest-rebuild.py.
1512 self.WriteLn('\t@true # No-op, used by tests')
1514 # Since this target depends on binary and resources which are in
1515 # nested subfolders, the framework directory will be older than
1516 # its dependencies usually. To prevent this rule from executing
1517 # on every build (expensive, especially with postbuilds), expliclity
1518 # update the time on the framework directory.
1519 self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output))
1522 assert not self.is_mac_bundle, ('Postbuilds for bundles should be done '
1523 'on the bundle, not the binary (target \'%s\')' % self.target)
1524 assert 'product_dir' not in spec, ('Postbuilds do not work with '
1525 'custom product_dir')
1527 if self.type == 'executable':
1528 self.WriteLn('%s: LD_INPUTS := %s' % (
1529 QuoteSpaces(self.output_binary),
1530 ' '.join(map(QuoteSpaces, link_deps))))
1531 if self.toolset == 'host' and self.flavor == 'android':
1532 self.WriteDoCmd([self.output_binary], link_deps, 'link_host',
1533 part_of_all, postbuilds=postbuilds)
1535 self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all,
1536 postbuilds=postbuilds)
1538 elif self.type == 'static_library':
1539 for link_dep in link_deps:
1540 assert ' ' not in link_dep, (
1541 "Spaces in alink input filenames not supported (%s)" % link_dep)
1542 if (self.flavor not in ('mac', 'openbsd', 'win') and not
1543 self.is_standalone_static_library):
1544 self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin',
1545 part_of_all, postbuilds=postbuilds)
1547 self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all,
1548 postbuilds=postbuilds)
1549 elif self.type == 'shared_library':
1550 self.WriteLn('%s: LD_INPUTS := %s' % (
1551 QuoteSpaces(self.output_binary),
1552 ' '.join(map(QuoteSpaces, link_deps))))
1553 self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all,
1554 postbuilds=postbuilds)
1555 elif self.type == 'loadable_module':
1556 for link_dep in link_deps:
1557 assert ' ' not in link_dep, (
1558 "Spaces in module input filenames not supported (%s)" % link_dep)
1559 if self.toolset == 'host' and self.flavor == 'android':
1560 self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host',
1561 part_of_all, postbuilds=postbuilds)
1564 [self.output_binary], link_deps, 'solink_module', part_of_all,
1565 postbuilds=postbuilds)
1566 elif self.type == 'none':
1567 # Write a stamp line.
1568 self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all,
1569 postbuilds=postbuilds)
1571 print "WARNING: no output for", self.type, target
1573 # Add an alias for each target (if there are any outputs).
1574 # Installable target aliases are created below.
1575 if ((self.output and self.output != self.target) and
1576 (self.type not in self._INSTALLABLE_TARGETS)):
1577 self.WriteMakeRule([self.target], [self.output],
1578 comment='Add target alias', phony = True)
1580 self.WriteMakeRule(['all'], [self.target],
1581 comment = 'Add target alias to "all" target.',
1584 # Add special-case rules for our installable targets.
1585 # 1) They need to install to the build dir or "product" dir.
1586 # 2) They get shortcuts for building (e.g. "make chrome").
1587 # 3) They are part of "make all".
1588 if (self.type in self._INSTALLABLE_TARGETS or
1589 self.is_standalone_static_library):
1590 if self.type == 'shared_library':
1591 file_desc = 'shared library'
1592 elif self.type == 'static_library':
1593 file_desc = 'static library'
1595 file_desc = 'executable'
1596 install_path = self._InstallableTargetInstallPath()
1597 installable_deps = [self.output]
1598 if (self.flavor == 'mac' and not 'product_dir' in spec and
1599 self.toolset == 'target'):
1600 # On mac, products are created in install_path immediately.
1601 assert install_path == self.output, '%s != %s' % (
1602 install_path, self.output)
1604 # Point the target alias to the final binary output.
1605 self.WriteMakeRule([self.target], [install_path],
1606 comment='Add target alias', phony = True)
1607 if install_path != self.output:
1608 assert not self.is_mac_bundle # See comment a few lines above.
1609 self.WriteDoCmd([install_path], [self.output], 'copy',
1610 comment = 'Copy this to the %s output path.' %
1611 file_desc, part_of_all=part_of_all)
1612 installable_deps.append(install_path)
1613 if self.output != self.alias and self.alias != self.target:
1614 self.WriteMakeRule([self.alias], installable_deps,
1615 comment = 'Short alias for building this %s.' %
1616 file_desc, phony = True)
1618 self.WriteMakeRule(['all'], [install_path],
1619 comment = 'Add %s to "all" target.' % file_desc,
1623 def WriteList(self, value_list, variable=None, prefix='',
1624 quoter=QuoteIfNecessary):
1625 """Write a variable definition that is a list of values.
1627 E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
1629 but in a pretty-printed style.
1633 value_list = [quoter(prefix + l) for l in value_list]
1634 values = ' \\\n\t' + ' \\\n\t'.join(value_list)
1635 self.fp.write('%s :=%s\n\n' % (variable, values))
1638 def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None,
1640 """Write a Makefile rule that uses do_cmd.
1642 This makes the outputs dependent on the command line that was run,
1643 as well as support the V= make command line flag.
1647 assert ',' not in command
1648 suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS
1649 self.WriteMakeRule(outputs, inputs,
1650 actions = ['$(call do_cmd,%s%s)' % (command, suffix)],
1653 # Add our outputs to the list of targets we read depfiles from.
1654 # all_deps is only used for deps file reading, and for deps files we replace
1655 # spaces with ? because escaping doesn't work with make's $(sort) and
1657 outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs]
1658 self.WriteLn('all_deps += %s' % ' '.join(outputs))
1661 def WriteMakeRule(self, outputs, inputs, actions=None, comment=None,
1662 order_only=False, force=False, phony=False):
1663 """Write a Makefile rule, with some extra tricks.
1665 outputs: a list of outputs for the rule (note: this is not directly
1666 supported by make; see comments below)
1667 inputs: a list of inputs for the rule
1668 actions: a list of shell commands to run for the rule
1669 comment: a comment to put in the Makefile above the rule (also useful
1670 for making this Python script's code self-documenting)
1671 order_only: if true, makes the dependency order-only
1672 force: if true, include FORCE_DO_CMD as an order-only dep
1673 phony: if true, the rule does not actually generate the named output, the
1674 output is just a name to run the rule
1676 outputs = map(QuoteSpaces, outputs)
1677 inputs = map(QuoteSpaces, inputs)
1680 self.WriteLn('# ' + comment)
1682 self.WriteLn('.PHONY: ' + ' '.join(outputs))
1683 # TODO(evanm): just make order_only a list of deps instead of these hacks.
1686 pick_output = ' '.join(outputs)
1689 pick_output = outputs[0]
1691 force_append = ' FORCE_DO_CMD'
1695 self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
1696 self.WriteLn('%s: %s%s%s' % (pick_output, order_insert, ' '.join(inputs),
1699 for action in actions:
1700 self.WriteLn('\t%s' % action)
1701 if not order_only and len(outputs) > 1:
1702 # If we have more than one output, a rule like
1704 # that for *each* output we must run the action, potentially
1705 # in parallel. That is not what we're trying to write -- what
1706 # we want is that we run the action once and it generates all
1708 # http://www.gnu.org/software/hello/manual/automake/Multiple-Outputs.html
1709 # discusses this problem and has this solution:
1710 # 1) Write the naive rule that would produce parallel runs of
1712 # 2) Make the outputs seralized on each other, so we won't start
1713 # a parallel run until the first run finishes, at which point
1714 # we'll have generated all the outputs and we're done.
1715 self.WriteLn('%s: %s' % (' '.join(outputs[1:]), outputs[0]))
1716 # Add a dummy command to the "extra outputs" rule, otherwise make seems to
1717 # think these outputs haven't (couldn't have?) changed, and thus doesn't
1718 # flag them as changed (i.e. include in '$?') when evaluating dependent
1719 # rules, which in turn causes do_cmd() to skip running dependent commands.
1720 self.WriteLn('%s: ;' % (' '.join(outputs[1:])))
1724 def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
1725 """Write a set of LOCAL_XXX definitions for Android NDK.
1727 These variable definitions will be used by Android NDK but do nothing for
1728 non-Android applications.
1731 module_name: Android NDK module name, which must be unique among all
1733 all_sources: A list of source files (will be filtered by Compilable).
1734 link_deps: A list of link dependencies, which must be sorted in
1735 the order from dependencies to dependents.
1737 if self.type not in ('executable', 'shared_library', 'static_library'):
1740 self.WriteLn('# Variable definitions for Android applications')
1741 self.WriteLn('include $(CLEAR_VARS)')
1742 self.WriteLn('LOCAL_MODULE := ' + module_name)
1743 self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) '
1744 '$(DEFS_$(BUILDTYPE)) '
1745 # LOCAL_CFLAGS is applied to both of C and C++. There is
1746 # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C
1748 '$(CFLAGS_C_$(BUILDTYPE)) '
1749 # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while
1750 # LOCAL_C_INCLUDES does not expect it. So put it in
1752 '$(INCS_$(BUILDTYPE))')
1753 # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred.
1754 self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))')
1755 self.WriteLn('LOCAL_C_INCLUDES :=')
1756 self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)')
1758 # Detect the C++ extension.
1759 cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0}
1760 default_cpp_ext = '.cpp'
1761 for filename in all_sources:
1762 ext = os.path.splitext(filename)[1]
1765 if cpp_ext[ext] > cpp_ext[default_cpp_ext]:
1766 default_cpp_ext = ext
1767 self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext)
1769 self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)),
1772 # Filter out those which do not match prefix and suffix and produce
1773 # the resulting list without prefix and suffix.
1774 def DepsToModules(deps, prefix, suffix):
1776 for filepath in deps:
1777 filename = os.path.basename(filepath)
1778 if filename.startswith(prefix) and filename.endswith(suffix):
1779 modules.append(filename[len(prefix):-len(suffix)])
1782 # Retrieve the default value of 'SHARED_LIB_SUFFIX'
1783 params = {'flavor': 'linux'}
1784 default_variables = {}
1785 CalculateVariables(default_variables, params)
1788 DepsToModules(link_deps,
1789 generator_default_variables['SHARED_LIB_PREFIX'],
1790 default_variables['SHARED_LIB_SUFFIX']),
1791 'LOCAL_SHARED_LIBRARIES')
1793 DepsToModules(link_deps,
1794 generator_default_variables['STATIC_LIB_PREFIX'],
1795 generator_default_variables['STATIC_LIB_SUFFIX']),
1796 'LOCAL_STATIC_LIBRARIES')
1798 if self.type == 'executable':
1799 self.WriteLn('include $(BUILD_EXECUTABLE)')
1800 elif self.type == 'shared_library':
1801 self.WriteLn('include $(BUILD_SHARED_LIBRARY)')
1802 elif self.type == 'static_library':
1803 self.WriteLn('include $(BUILD_STATIC_LIBRARY)')
1807 def WriteLn(self, text=''):
1808 self.fp.write(text + '\n')
1811 def GetSortedXcodeEnv(self, additional_settings=None):
1812 return gyp.xcode_emulation.GetSortedXcodeEnv(
1813 self.xcode_settings, "$(abs_builddir)",
1814 os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)",
1815 additional_settings)
1818 def GetSortedXcodePostbuildEnv(self):
1819 # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
1820 # TODO(thakis): It would be nice to have some general mechanism instead.
1821 strip_save_file = self.xcode_settings.GetPerTargetSetting(
1822 'CHROMIUM_STRIP_SAVE_FILE', '')
1823 # Even if strip_save_file is empty, explicitly write it. Else a postbuild
1824 # might pick up an export from an earlier target.
1825 return self.GetSortedXcodeEnv(
1826 additional_settings={'CHROMIUM_STRIP_SAVE_FILE': strip_save_file})
1829 def WriteSortedXcodeEnv(self, target, env):
1833 # the escaped space does the right thing. For
1834 # export foo := a\ b
1835 # it does not -- the backslash is written to the env as literal character.
1836 # So don't escape spaces in |env[k]|.
1837 self.WriteLn('%s: export %s := %s' % (QuoteSpaces(target), k, v))
1840 def Objectify(self, path):
1841 """Convert a path to its output directory form."""
1843 path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset)
1844 if not '$(obj)' in path:
1845 path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path)
1849 def Pchify(self, path, lang):
1850 """Convert a prefix header path to its output directory form."""
1851 path = self.Absolutify(path)
1853 path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' %
1854 (self.toolset, lang))
1856 return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
1859 def Absolutify(self, path):
1860 """Convert a subdirectory-relative path into a base-relative path.
1861 Skips over paths that contain variables."""
1863 # Don't call normpath in this case, as it might collapse the
1864 # path too aggressively if it features '..'. However it's still
1865 # important to strip trailing slashes.
1866 return path.rstrip('/')
1867 return os.path.normpath(os.path.join(self.path, path))
1870 def ExpandInputRoot(self, template, expansion, dirname):
1871 if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template:
1874 'INPUT_ROOT': expansion,
1875 'INPUT_DIRNAME': dirname,
1880 def _InstallableTargetInstallPath(self):
1881 """Returns the location of the final output for an installable target."""
1882 # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files
1883 # rely on this. Emulate this behavior for mac.
1884 if (self.type == 'shared_library' and
1885 (self.flavor != 'mac' or self.toolset != 'target')):
1886 # Install all shared libs into a common directory (per toolset) for
1887 # convenient access with LD_LIBRARY_PATH.
1888 return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias)
1889 return '$(builddir)/' + self.alias
1892 def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
1894 """Write the target to regenerate the Makefile."""
1895 options = params['options']
1896 build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir)
1897 for filename in params['build_files_arg']]
1899 gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'],
1900 options.toplevel_dir)
1901 if not gyp_binary.startswith(os.sep):
1902 gyp_binary = os.path.join('.', gyp_binary)
1904 root_makefile.write(
1905 "quiet_cmd_regen_makefile = ACTION Regenerating $@\n"
1906 "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n"
1907 "%(makefile_name)s: %(deps)s\n"
1908 "\t$(call do_cmd,regen_makefile)\n\n" % {
1909 'makefile_name': makefile_name,
1910 'deps': ' '.join(map(Sourceify, build_files)),
1911 'cmd': gyp.common.EncodePOSIXShellList(
1912 [gyp_binary, '-fmake'] +
1913 gyp.RegenerateFlags(options) +
1917 def PerformBuild(data, configurations, params):
1918 options = params['options']
1919 for config in configurations:
1920 arguments = ['make']
1921 if options.toplevel_dir and options.toplevel_dir != '.':
1922 arguments += '-C', options.toplevel_dir
1923 arguments.append('BUILDTYPE=' + config)
1924 print 'Building [%s]: %s' % (config, arguments)
1925 subprocess.check_call(arguments)
1928 def GenerateOutput(target_list, target_dicts, data, params):
1929 options = params['options']
1930 flavor = gyp.common.GetFlavor(params)
1931 generator_flags = params.get('generator_flags', {})
1932 builddir_name = generator_flags.get('output_dir', 'out')
1933 android_ndk_version = generator_flags.get('android_ndk_version', None)
1934 default_target = generator_flags.get('default_target', 'all')
1936 def CalculateMakefilePath(build_file, base_name):
1937 """Determine where to write a Makefile for a given gyp file."""
1938 # Paths in gyp files are relative to the .gyp file, but we want
1939 # paths relative to the source root for the master makefile. Grab
1940 # the path of the .gyp file as the base to relativize against.
1941 # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
1942 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
1944 # We write the file in the base_path directory.
1945 output_file = os.path.join(options.depth, base_path, base_name)
1946 if options.generator_output:
1947 output_file = os.path.join(options.generator_output, output_file)
1948 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
1949 options.toplevel_dir)
1950 return base_path, output_file
1952 # TODO: search for the first non-'Default' target. This can go
1953 # away when we add verification that all targets have the
1954 # necessary configurations.
1955 default_configuration = None
1956 toolsets = set([target_dicts[target]['toolset'] for target in target_list])
1957 for target in target_list:
1958 spec = target_dicts[target]
1959 if spec['default_configuration'] != 'Default':
1960 default_configuration = spec['default_configuration']
1962 if not default_configuration:
1963 default_configuration = 'Default'
1966 makefile_name = 'Makefile' + options.suffix
1967 makefile_path = os.path.join(options.toplevel_dir, makefile_name)
1968 if options.generator_output:
1969 global srcdir_prefix
1970 makefile_path = os.path.join(options.generator_output, makefile_path)
1971 srcdir = gyp.common.RelativePath(srcdir, options.generator_output)
1972 srcdir_prefix = '$(srcdir)/'
1974 flock_command= 'flock'
1976 'default_target': default_target,
1977 'builddir': builddir_name,
1978 'default_configuration': default_configuration,
1979 'flock': flock_command,
1981 'link_commands': LINK_COMMANDS_LINUX,
1982 'extra_commands': '',
1986 flock_command = './gyp-mac-tool flock'
1987 header_params.update({
1988 'flock': flock_command,
1990 'link_commands': LINK_COMMANDS_MAC,
1991 'extra_commands': SHARED_HEADER_MAC_COMMANDS,
1993 elif flavor == 'android':
1994 header_params.update({
1995 'link_commands': LINK_COMMANDS_ANDROID,
1997 elif flavor == 'solaris':
1998 header_params.update({
1999 'flock': './gyp-flock-tool flock',
2002 elif flavor == 'freebsd':
2003 # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific.
2004 header_params.update({
2007 elif flavor == 'aix':
2008 header_params.update({
2009 'link_commands': LINK_COMMANDS_AIX,
2010 'flock': './gyp-flock-tool flock',
2014 header_params.update({
2015 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'),
2016 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'),
2017 'CXX.target': GetEnvironFallback(('CXX_target', 'CXX'), '$(CXX)'),
2018 'LINK.target': GetEnvironFallback(('LINK_target', 'LINK'), '$(LINK)'),
2019 'CC.host': GetEnvironFallback(('CC_host',), 'gcc'),
2020 'AR.host': GetEnvironFallback(('AR_host',), 'ar'),
2021 'CXX.host': GetEnvironFallback(('CXX_host',), 'g++'),
2022 'LINK.host': GetEnvironFallback(('LINK_host',), '$(CXX.host)'),
2025 build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
2026 make_global_settings_array = data[build_file].get('make_global_settings', [])
2028 wrappers['LINK'] = '%s $(builddir)/linker.lock' % flock_command
2029 for key, value in make_global_settings_array:
2030 if key.endswith('_wrapper'):
2031 wrappers[key[:-len('_wrapper')]] = '$(abspath %s)' % value
2032 make_global_settings = ''
2033 for key, value in make_global_settings_array:
2034 if re.match('.*_wrapper', key):
2037 value = '$(abspath %s)' % value
2038 wrapper = wrappers.get(key)
2040 value = '%s %s' % (wrapper, value)
2042 if key in ('CC', 'CC.host', 'CXX', 'CXX.host'):
2043 make_global_settings += (
2044 'ifneq (,$(filter $(origin %s), undefined default))\n' % key)
2045 # Let gyp-time envvars win over global settings.
2046 if key in os.environ:
2047 value = os.environ[key]
2048 make_global_settings += ' %s = %s\n' % (key, value)
2049 make_global_settings += 'endif\n'
2051 make_global_settings += '%s ?= %s\n' % (key, value)
2052 # TODO(ukai): define cmd when only wrapper is specified in
2053 # make_global_settings.
2055 header_params['make_global_settings'] = make_global_settings
2057 ensure_directory_exists(makefile_path)
2058 root_makefile = open(makefile_path, 'w')
2059 root_makefile.write(SHARED_HEADER % header_params)
2060 # Currently any versions have the same effect, but in future the behavior
2061 # could be different.
2062 if android_ndk_version:
2063 root_makefile.write(
2064 '# Define LOCAL_PATH for build of Android applications.\n'
2065 'LOCAL_PATH := $(call my-dir)\n'
2067 for toolset in toolsets:
2068 root_makefile.write('TOOLSET := %s\n' % toolset)
2069 WriteRootHeaderSuffixRules(root_makefile)
2071 # Put build-time support tools next to the root Makefile.
2072 dest_path = os.path.dirname(makefile_path)
2073 gyp.common.CopyTool(flavor, dest_path)
2075 # Find the list of targets that derive from the gyp file(s) being built.
2076 needed_targets = set()
2077 for build_file in params['build_files']:
2078 for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
2079 needed_targets.add(target)
2082 include_list = set()
2083 for qualified_target in target_list:
2084 build_file, target, toolset = gyp.common.ParseQualifiedTarget(
2087 this_make_global_settings = data[build_file].get('make_global_settings', [])
2088 assert make_global_settings_array == this_make_global_settings, (
2089 "make_global_settings needs to be the same for all targets.")
2091 build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir))
2092 included_files = data[build_file]['included_files']
2093 for included_file in included_files:
2094 # The included_files entries are relative to the dir of the build file
2095 # that included them, so we have to undo that and then make them relative
2097 relative_include_file = gyp.common.RelativePath(
2098 gyp.common.UnrelativePath(included_file, build_file),
2099 options.toplevel_dir)
2100 abs_include_file = os.path.abspath(relative_include_file)
2101 # If the include file is from the ~/.gyp dir, we should use absolute path
2102 # so that relocating the src dir doesn't break the path.
2103 if (params['home_dot_gyp'] and
2104 abs_include_file.startswith(params['home_dot_gyp'])):
2105 build_files.add(abs_include_file)
2107 build_files.add(relative_include_file)
2109 base_path, output_file = CalculateMakefilePath(build_file,
2110 target + '.' + toolset + options.suffix + '.mk')
2112 spec = target_dicts[qualified_target]
2113 configs = spec['configurations']
2116 gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
2118 writer = MakefileWriter(generator_flags, flavor)
2119 writer.Write(qualified_target, base_path, output_file, spec, configs,
2120 part_of_all=qualified_target in needed_targets)
2122 # Our root_makefile lives at the source root. Compute the relative path
2123 # from there to the output_file for including.
2124 mkfile_rel_path = gyp.common.RelativePath(output_file,
2125 os.path.dirname(makefile_path))
2126 include_list.add(mkfile_rel_path)
2128 # Write out per-gyp (sub-project) Makefiles.
2129 depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd())
2130 for build_file in build_files:
2131 # The paths in build_files were relativized above, so undo that before
2132 # testing against the non-relativized items in target_list and before
2133 # calculating the Makefile path.
2134 build_file = os.path.join(depth_rel_path, build_file)
2135 gyp_targets = [target_dicts[target]['target_name'] for target in target_list
2136 if target.startswith(build_file) and
2137 target in needed_targets]
2138 # Only generate Makefiles for gyp files with targets.
2141 base_path, output_file = CalculateMakefilePath(build_file,
2142 os.path.splitext(os.path.basename(build_file))[0] + '.Makefile')
2143 makefile_rel_path = gyp.common.RelativePath(os.path.dirname(makefile_path),
2144 os.path.dirname(output_file))
2145 writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets,
2149 # Write out the sorted list of includes.
2150 root_makefile.write('\n')
2151 for include_file in sorted(include_list):
2152 # We wrap each .mk include in an if statement so users can tell make to
2153 # not load a file by setting NO_LOAD. The below make code says, only
2154 # load the .mk file if the .mk filename doesn't start with a token in
2156 root_makefile.write(
2157 "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n"
2158 " $(findstring $(join ^,$(prefix)),\\\n"
2159 " $(join ^," + include_file + ")))),)\n")
2160 root_makefile.write(" include " + include_file + "\n")
2161 root_makefile.write("endif\n")
2162 root_makefile.write('\n')
2164 if (not generator_flags.get('standalone')
2165 and generator_flags.get('auto_regeneration', True)):
2166 WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files)
2168 root_makefile.write(SHARED_FOOTER)
2170 root_makefile.close()