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
32 from gyp.common import GypError
34 generator_default_variables = {
35 'EXECUTABLE_PREFIX': '',
36 'EXECUTABLE_SUFFIX': '',
37 'STATIC_LIB_PREFIX': 'lib',
38 'SHARED_LIB_PREFIX': 'lib',
39 'STATIC_LIB_SUFFIX': '.a',
40 'INTERMEDIATE_DIR': '$(obj).$(TOOLSET)/$(TARGET)/geni',
41 'SHARED_INTERMEDIATE_DIR': '$(obj)/gen',
42 'PRODUCT_DIR': '$(builddir)',
43 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python.
44 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python.
45 'RULE_INPUT_PATH': '$(abspath $<)',
46 'RULE_INPUT_EXT': '$(suffix $<)',
47 'RULE_INPUT_NAME': '$(notdir $<)',
48 'CONFIGURATION_NAME': '$(BUILDTYPE)',
51 # Make supports multiple toolsets
52 generator_supports_multiple_toolsets = True
54 # Request sorted dependencies in the order from dependents to dependencies.
55 generator_wants_sorted_dependencies = False
58 generator_additional_non_configuration_keys = []
59 generator_additional_path_sections = []
60 generator_extra_sources_for_rules = []
61 generator_filelist_paths = None
64 def CalculateVariables(default_variables, params):
65 """Calculate additional variables for use in the build (called by gyp)."""
66 flavor = gyp.common.GetFlavor(params)
68 default_variables.setdefault('OS', 'mac')
69 default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib')
70 default_variables.setdefault('SHARED_LIB_DIR',
71 generator_default_variables['PRODUCT_DIR'])
72 default_variables.setdefault('LIB_DIR',
73 generator_default_variables['PRODUCT_DIR'])
75 # Copy additional generator configuration data from Xcode, which is shared
76 # by the Mac Make generator.
77 import gyp.generator.xcode as xcode_generator
78 global generator_additional_non_configuration_keys
79 generator_additional_non_configuration_keys = getattr(xcode_generator,
80 'generator_additional_non_configuration_keys', [])
81 global generator_additional_path_sections
82 generator_additional_path_sections = getattr(xcode_generator,
83 'generator_additional_path_sections', [])
84 global generator_extra_sources_for_rules
85 generator_extra_sources_for_rules = getattr(xcode_generator,
86 'generator_extra_sources_for_rules', [])
87 COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'})
89 operating_system = flavor
90 if flavor == 'android':
91 operating_system = 'linux' # Keep this legacy behavior for now.
92 default_variables.setdefault('OS', operating_system)
93 default_variables.setdefault('SHARED_LIB_SUFFIX', '.so')
94 default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)')
95 default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)')
98 def CalculateGeneratorInputInfo(params):
99 """Calculate the generator specific info that gets fed to input (called by
101 generator_flags = params.get('generator_flags', {})
102 android_ndk_version = generator_flags.get('android_ndk_version', None)
103 # Android NDK requires a strict link order.
104 if android_ndk_version:
105 global generator_wants_sorted_dependencies
106 generator_wants_sorted_dependencies = True
108 output_dir = params['options'].generator_output or \
109 params['options'].toplevel_dir
110 builddir_name = generator_flags.get('output_dir', 'out')
111 qualified_out_dir = os.path.normpath(os.path.join(
112 output_dir, builddir_name, 'gypfiles'))
114 global generator_filelist_paths
115 generator_filelist_paths = {
116 'toplevel': params['options'].toplevel_dir,
117 'qualified_out_dir': qualified_out_dir,
121 # The .d checking code below uses these functions:
122 # wildcard, sort, foreach, shell, wordlist
123 # wildcard can handle spaces, the rest can't.
124 # Since I could find no way to make foreach work with spaces in filenames
125 # correctly, the .d files have spaces replaced with another character. The .d
127 # Chromium\ Framework.framework/foo
129 # out/Release/.deps/out/Release/Chromium?Framework.framework/foo
130 # This is the replacement character.
131 SPACE_REPLACEMENT = '?'
134 LINK_COMMANDS_LINUX = """\
135 quiet_cmd_alink = AR($(TOOLSET)) $@
136 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
138 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
139 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
141 # Due to circular dependencies between libraries :(, we wrap the
142 # special "figure out circular dependencies" flags around the entire
143 # input list during linking.
144 quiet_cmd_link = LINK($(TOOLSET)) $@
145 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
147 # We support two kinds of shared objects (.so):
148 # 1) shared_library, which is just bundling together many dependent libraries
150 # 2) loadable_module, which is generating a module intended for dlopen().
152 # They differ only slightly:
153 # In the former case, we want to package all dependent code into the .so.
154 # In the latter case, we want to package just the API exposed by the
156 # This means shared_library uses --whole-archive, while loadable_module doesn't.
157 # (Note that --whole-archive is incompatible with the --start-group used in
160 # Other shared-object link notes:
161 # - Set SONAME to the library filename so our binaries don't reference
162 # the local, absolute paths used on the link command-line.
163 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
164 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
166 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
167 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)
170 LINK_COMMANDS_MAC = """\
171 quiet_cmd_alink = LIBTOOL-STATIC $@
172 cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
174 quiet_cmd_link = LINK($(TOOLSET)) $@
175 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
177 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
178 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
180 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
181 cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
184 LINK_COMMANDS_ANDROID = """\
185 quiet_cmd_alink = AR($(TOOLSET)) $@
186 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
188 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
189 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
191 # Due to circular dependencies between libraries :(, we wrap the
192 # special "figure out circular dependencies" flags around the entire
193 # input list during linking.
194 quiet_cmd_link = LINK($(TOOLSET)) $@
195 quiet_cmd_link_host = LINK($(TOOLSET)) $@
196 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
197 cmd_link_host = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
199 # Other shared-object link notes:
200 # - Set SONAME to the library filename so our binaries don't reference
201 # the local, absolute paths used on the link command-line.
202 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
203 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
205 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
206 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)
207 quiet_cmd_solink_module_host = SOLINK_MODULE($(TOOLSET)) $@
208 cmd_solink_module_host = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
212 LINK_COMMANDS_AIX = """\
213 quiet_cmd_alink = AR($(TOOLSET)) $@
214 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
216 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
217 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
219 quiet_cmd_link = LINK($(TOOLSET)) $@
220 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
222 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
223 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
225 quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
226 cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
230 # Header of toplevel Makefile.
231 # This should go into the build tree, but it's easier to keep it here for now.
232 SHARED_HEADER = ("""\
233 # We borrow heavily from the kernel build setup, though we are simpler since
234 # we don't have Kconfig tweaking settings on us.
236 # The implicit make rules have it looking for RCS files, among other things.
237 # We instead explicitly write all the rules we care about.
238 # It's even quicker (saves ~200ms) to pass -r on the command line.
241 # The source directory tree.
243 abs_srcdir := $(abspath $(srcdir))
245 # The name of the builddir.
246 builddir_name ?= %(builddir)s
248 # The V=1 flag on command line makes us verbosely print command lines.
255 # Specify BUILDTYPE=Release on the command line for a release build.
256 BUILDTYPE ?= %(default_configuration)s
258 # Directory all our build output goes into.
259 # Note that this must be two directories beneath src/ for unit tests to pass,
260 # as they reach into the src/ directory for data with relative paths.
261 builddir ?= $(builddir_name)/$(BUILDTYPE)
262 abs_builddir := $(abspath $(builddir))
263 depsdir := $(builddir)/.deps
265 # Object output directory.
266 obj := $(builddir)/obj
267 abs_obj := $(abspath $(obj))
269 # We build up a list of every single one of the targets so we can slurp in the
270 # generated dependency rule Makefiles in one pass.
273 %(make_global_settings)s
275 CC.target ?= %(CC.target)s
276 CFLAGS.target ?= $(CFLAGS)
277 CXX.target ?= %(CXX.target)s
278 CXXFLAGS.target ?= $(CXXFLAGS)
279 LINK.target ?= %(LINK.target)s
280 LDFLAGS.target ?= $(LDFLAGS)
283 # C++ apps need to be linked with g++.
285 # Note: flock is used to seralize linking. Linking is a memory-intensive
286 # process so running parallel links can often lead to thrashing. To disable
287 # the serialization, override LINK via an envrionment variable as follows:
291 # This will allow make to invoke N linker processes as specified in -jN.
292 LINK ?= %(flock)s $(builddir)/linker.lock $(CXX.target)
294 # TODO(evan): move all cross-compilation logic to gyp-time so we don't need
295 # to replicate this environment fallback in make as well.
296 CC.host ?= %(CC.host)s
298 CXX.host ?= %(CXX.host)s
300 LINK.host ?= %(LINK.host)s
302 AR.host ?= %(AR.host)s
304 # Define a dir function that can handle spaces.
305 # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
306 # "leading spaces cannot appear in the text of the first argument as written.
307 # These characters can be put into the argument value by variable substitution."
309 space := $(empty) $(empty)
311 # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
312 replace_spaces = $(subst $(space),""" + SPACE_REPLACEMENT + """,$1)
313 unreplace_spaces = $(subst """ + SPACE_REPLACEMENT + """,$(space),$1)
314 dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
316 # Flags to make gcc output dependency info. Note that you need to be
317 # careful here to use the flags that ccache and distcc can understand.
318 # We write to a dep file on the side first and then rename at the end
319 # so we can't end up with a broken dep file.
320 depfile = $(depsdir)/$(call replace_spaces,$@).d
321 DEPFLAGS = -MMD -MF $(depfile).raw
323 # We have to fixup the deps output in a few ways.
324 # (1) the file output should mention the proper .o file.
325 # ccache or distcc lose the path to the target, so we convert a rule of
327 # foobar.o: DEP1 DEP2
329 # path/to/foobar.o: DEP1 DEP2
330 # (2) we want missing files not to cause us to fail to build.
332 # foobar.o: DEP1 DEP2 \\
338 # so if the files are missing, they're just considered phony rules.
339 # We have to do some pretty insane escaping to get those backslashes
340 # and dollar signs past make, the shell, and sed at the same time.
341 # Doesn't work with spaces, but that's fine: .d files have spaces in
342 # their names replaced with other characters."""
345 # The depfile may not exist if the input file didn't have any #includes.
347 # Fixup path as in (1).
348 sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
349 # Add extra rules as in (2).
350 # We remove slashes and replace spaces with new lines;
351 # remove blank lines;
352 # delete the first line and append a colon to the remaining lines.
353 sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
355 sed -e 1d -e 's|$$|:|' \
361 # Command definitions:
362 # - cmd_foo is the actual command to run;
363 # - quiet_cmd_foo is the brief-output summary of the command.
365 quiet_cmd_cc = CC($(TOOLSET)) $@
366 cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
368 quiet_cmd_cxx = CXX($(TOOLSET)) $@
369 cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
371 quiet_cmd_touch = TOUCH $@
374 quiet_cmd_copy = COPY $@
375 # send stderr to /dev/null to ignore messages when linking directories.
376 cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
382 # Define an escape_quotes function to escape single quotes.
383 # This allows us to handle quotes properly as long as we always use
384 # use single quotes and escape_quotes.
385 escape_quotes = $(subst ','\'',$(1))
386 # This comment is here just to include a ' to unconfuse syntax highlighting.
387 # Define an escape_vars function to escape '$' variable syntax.
388 # This allows us to read/write command lines with shell variables (e.g.
389 # $LD_LIBRARY_PATH), without triggering make substitution.
390 escape_vars = $(subst $$,$$$$,$(1))
391 # Helper that expands to a shell command to echo a string exactly as it is in
392 # make. This uses printf instead of echo because printf's behaviour with respect
393 # to escape sequences is more portable than echo's across different shells
394 # (e.g., dash, bash).
395 exact_echo = printf '%%s\n' '$(call escape_quotes,$(1))'
398 # Helper to compare the command we're about to run against the command
399 # we logged the last time we ran the command. Produces an empty
400 # string (false) when the commands match.
401 # Tricky point: Make has no string-equality test function.
402 # The kernel uses the following, but it seems like it would have false
403 # positives, where one string reordered its arguments.
404 # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \\
405 # $(filter-out $(cmd_$@), $(cmd_$(1))))
406 # We instead substitute each for the empty string into the other, and
407 # say they're equal if both substitutions produce the empty string.
408 # .d files contain """ + SPACE_REPLACEMENT + \
409 """ instead of spaces, take that into account.
410 command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\\
411 $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
413 # Helper that is non-empty when a prerequisite changes.
414 # Normally make does this implicitly, but we force rules to always run
415 # so we can check their command lines.
416 # $? -- new prerequisites
417 # $| -- order-only dependencies
418 prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
420 # Helper that executes all postbuilds until one fails.
423 for p in $(POSTBUILDS); do\\
426 if [ $$E -ne 0 ]; then\\
430 if [ $$E -ne 0 ]; then\\
436 # do_cmd: run a command via the above cmd_foo names, if necessary.
437 # Should always run for a given target to handle command-line changes.
438 # Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
439 # Third argument, if non-zero, makes it do POSTBUILDS processing.
440 # Note: We intentionally do NOT call dirx for depfile, since it contains """ + \
441 SPACE_REPLACEMENT + """ for
442 # spaces already and dirx strips the """ + SPACE_REPLACEMENT + \
445 $(if $(or $(command_changed),$(prereq_changed)),
446 @$(call exact_echo, $($(quiet)cmd_$(1)))
447 @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
448 $(if $(findstring flock,$(word %(flock_index)d,$(cmd_$1))),
450 @echo " $(quiet_cmd_$(1)): Finished",
453 @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
454 @$(if $(2),$(fixup_dep))
455 $(if $(and $(3), $(POSTBUILDS)),
456 $(call do_postbuilds)
461 # Declare the "%(default_target)s" target first so it is the default,
462 # even though we don't have the deps yet.
463 .PHONY: %(default_target)s
466 # make looks for ways to re-generate included makefiles, but in our case, we
467 # don't have a direct way. Explicitly telling make that it has nothing to do
468 # for them makes it go faster.
471 # Use FORCE_DO_CMD to force a target to run. Should be coupled with
478 SHARED_HEADER_MAC_COMMANDS = """
479 quiet_cmd_objc = CXX($(TOOLSET)) $@
480 cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
482 quiet_cmd_objcxx = CXX($(TOOLSET)) $@
483 cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
485 # Commands for precompiled header files.
486 quiet_cmd_pch_c = CXX($(TOOLSET)) $@
487 cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
488 quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
489 cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
490 quiet_cmd_pch_m = CXX($(TOOLSET)) $@
491 cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
492 quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
493 cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
495 # gyp-mac-tool is written next to the root Makefile by gyp.
496 # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
498 quiet_cmd_mac_tool = MACTOOL $(4) $<
499 cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
501 quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
502 cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
504 quiet_cmd_infoplist = INFOPLIST $@
505 cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
509 def WriteRootHeaderSuffixRules(writer):
510 extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower)
512 writer.write('# Suffix rules, putting all outputs into $(obj).\n')
513 for ext in extensions:
514 writer.write('$(obj).$(TOOLSET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD\n' % ext)
515 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
517 writer.write('\n# Try building from generated source, too.\n')
518 for ext in extensions:
520 '$(obj).$(TOOLSET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD\n' % ext)
521 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
523 for ext in extensions:
524 writer.write('$(obj).$(TOOLSET)/%%.o: $(obj)/%%%s FORCE_DO_CMD\n' % ext)
525 writer.write('\t@$(call do_cmd,%s,1)\n' % COMPILABLE_EXTENSIONS[ext])
529 SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\
530 # Suffix rules, putting all outputs into $(obj).
534 SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\
535 # Try building from generated source, too.
540 # "all" is a concatenation of the "all" targets from all the included
541 # sub-makefiles. This is just here to clarify.
544 # Add in dependency-tracking rules. $(all_deps) is the list of every single
545 # target in our tree. Only consider the ones with .d (dependency) info:
546 d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
553 # This file is generated by gyp; do not edit.
557 # Maps every compilable file extension to the do_cmd that compiles it.
558 COMPILABLE_EXTENSIONS = {
567 def Compilable(filename):
568 """Return true if the file is compilable (should be in OBJS)."""
569 for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS):
575 def Linkable(filename):
576 """Return true if the file is linkable (should be on the link line)."""
577 return filename.endswith('.o')
580 def Target(filename):
581 """Translate a compilable filename to its .o target."""
582 return os.path.splitext(filename)[0] + '.o'
585 def EscapeShellArgument(s):
586 """Quotes an argument so that it will be interpreted literally by a POSIX
588 http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
590 return "'" + s.replace("'", "'\\''") + "'"
593 def EscapeMakeVariableExpansion(s):
594 """Make has its own variable expansion syntax using $. We must escape it for
595 string to be interpreted literally."""
596 return s.replace('$', '$$')
599 def EscapeCppDefine(s):
600 """Escapes a CPP define so that it will reach the compiler unaltered."""
601 s = EscapeShellArgument(s)
602 s = EscapeMakeVariableExpansion(s)
603 # '#' characters must be escaped even embedded in a string, else Make will
604 # treat it as the start of a comment.
605 return s.replace('#', r'\#')
608 def QuoteIfNecessary(string):
609 """TODO: Should this ideally be replaced with one or more of the above
612 string = '"' + string.replace('"', '\\"') + '"'
616 def StringToMakefileVariable(string):
617 """Convert a string to a value that is acceptable as a make variable name."""
618 return re.sub('[^a-zA-Z0-9_]', '_', string)
623 """Convert a path to its source directory form."""
626 if os.path.isabs(path):
628 return srcdir_prefix + path
631 def QuoteSpaces(s, quote=r'\ '):
632 return s.replace(' ', quote)
635 # TODO: Avoid code duplication with _ValidateSourcesForMSVSProject in msvs.py.
636 def _ValidateSourcesForOSX(spec, all_sources):
637 """Makes sure if duplicate basenames are not specified in the source list.
640 spec: The target dictionary containing the properties of the target.
642 if spec.get('type', None) != 'static_library':
646 for source in all_sources:
647 name, ext = os.path.splitext(source)
648 is_compiled_file = ext in [
649 '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
650 if not is_compiled_file:
652 basename = os.path.basename(name) # Don't include extension.
653 basenames.setdefault(basename, []).append(source)
656 for basename, files in basenames.iteritems():
658 error += ' %s: %s\n' % (basename, ' '.join(files))
661 print('static library %s has several files with the same basename:\n' %
662 spec['target_name'] + error + 'libtool on OS X will generate' +
663 ' warnings for them.')
664 raise GypError('Duplicate basenames in sources section, see list above')
667 # Map from qualified target to path to output.
669 # Map from qualified target to any linkable output. A subset
670 # of target_outputs. E.g. when mybinary depends on liba, we want to
671 # include liba in the linker line; when otherbinary depends on
672 # mybinary, we just want to build mybinary first.
673 target_link_deps = {}
676 class MakefileWriter:
677 """MakefileWriter packages up the writing of one target-specific foobar.mk.
679 Its only real entry point is Write(), and is mostly used for namespacing.
682 def __init__(self, generator_flags, flavor):
683 self.generator_flags = generator_flags
686 self.suffix_rules_srcdir = {}
687 self.suffix_rules_objdir1 = {}
688 self.suffix_rules_objdir2 = {}
690 # Generate suffix rules for all compilable extensions.
691 for ext in COMPILABLE_EXTENSIONS.keys():
692 # Suffix rules for source folder.
693 self.suffix_rules_srcdir.update({ext: ("""\
694 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD
696 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
698 # Suffix rules for generated source files.
699 self.suffix_rules_objdir1.update({ext: ("""\
700 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj).$(TOOLSET)/%%%s FORCE_DO_CMD
702 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
703 self.suffix_rules_objdir2.update({ext: ("""\
704 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
706 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
709 def Write(self, qualified_target, base_path, output_filename, spec, configs,
711 """The main entry point: writes a .mk file for a single target.
714 qualified_target: target we're generating
715 base_path: path relative to source root we're building in, used to resolve
716 target-relative paths
717 output_filename: output .mk file name to write
718 spec, configs: gyp info
719 part_of_all: flag indicating this target is part of 'all'
721 gyp.common.EnsureDirExists(output_filename)
723 self.fp = open(output_filename, 'w')
725 self.fp.write(header)
727 self.qualified_target = qualified_target
728 self.path = base_path
729 self.target = spec['target_name']
730 self.type = spec['type']
731 self.toolset = spec['toolset']
733 self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec)
734 if self.flavor == 'mac':
735 self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec)
737 self.xcode_settings = None
739 deps, link_deps = self.ComputeDeps(spec)
741 # Some of the generation below can add extra output, sources, or
742 # link dependencies. All of the out params of the functions that
743 # follow use names like extra_foo.
747 extra_mac_bundle_resources = []
750 if self.is_mac_bundle:
751 self.output = self.ComputeMacBundleOutput(spec)
752 self.output_binary = self.ComputeMacBundleBinaryOutput(spec)
754 self.output = self.output_binary = self.ComputeOutput(spec)
756 self.is_standalone_static_library = bool(
757 spec.get('standalone_static_library', 0))
758 self._INSTALLABLE_TARGETS = ('executable', 'loadable_module',
760 if (self.is_standalone_static_library or
761 self.type in self._INSTALLABLE_TARGETS):
762 self.alias = os.path.basename(self.output)
763 install_path = self._InstallableTargetInstallPath()
765 self.alias = self.output
766 install_path = self.output
768 self.WriteLn("TOOLSET := " + self.toolset)
769 self.WriteLn("TARGET := " + self.target)
771 # Actions must come first, since they can generate more OBJs for use below.
772 if 'actions' in spec:
773 self.WriteActions(spec['actions'], extra_sources, extra_outputs,
774 extra_mac_bundle_resources, part_of_all)
776 # Rules must be early like actions.
778 self.WriteRules(spec['rules'], extra_sources, extra_outputs,
779 extra_mac_bundle_resources, part_of_all)
782 self.WriteCopies(spec['copies'], extra_outputs, part_of_all)
785 if self.is_mac_bundle:
786 all_mac_bundle_resources = (
787 spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources)
788 self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps)
789 self.WriteMacInfoPlist(mac_bundle_deps)
792 all_sources = spec.get('sources', []) + extra_sources
794 if self.flavor == 'mac':
795 # libtool on OS X generates warnings for duplicate basenames in the same
797 _ValidateSourcesForOSX(spec, all_sources)
799 configs, deps, all_sources, extra_outputs,
800 extra_link_deps, part_of_all,
801 gyp.xcode_emulation.MacPrefixHeader(
802 self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)),
804 sources = filter(Compilable, all_sources)
806 self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1)
807 extensions = set([os.path.splitext(s)[1] for s in sources])
808 for ext in extensions:
809 if ext in self.suffix_rules_srcdir:
810 self.WriteLn(self.suffix_rules_srcdir[ext])
811 self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2)
812 for ext in extensions:
813 if ext in self.suffix_rules_objdir1:
814 self.WriteLn(self.suffix_rules_objdir1[ext])
815 for ext in extensions:
816 if ext in self.suffix_rules_objdir2:
817 self.WriteLn(self.suffix_rules_objdir2[ext])
818 self.WriteLn('# End of this set of suffix rules')
820 # Add dependency from bundle to bundle binary.
821 if self.is_mac_bundle:
822 mac_bundle_deps.append(self.output_binary)
824 self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps,
825 mac_bundle_deps, extra_outputs, part_of_all)
827 # Update global list of target outputs, used in dependency tracking.
828 target_outputs[qualified_target] = install_path
830 # Update global list of link dependencies.
831 if self.type in ('static_library', 'shared_library'):
832 target_link_deps[qualified_target] = self.output_binary
834 # Currently any versions have the same effect, but in future the behavior
835 # could be different.
836 if self.generator_flags.get('android_ndk_version', None):
837 self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps)
842 def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
843 """Write a "sub-project" Makefile.
845 This is a small, wrapper Makefile that calls the top-level Makefile to build
846 the targets from a single gyp file (i.e. a sub-project).
849 output_filename: sub-project Makefile name to write
850 makefile_path: path to the top-level Makefile
851 targets: list of "all" targets for this sub-project
852 build_dir: build output directory, relative to the sub-project
854 gyp.common.EnsureDirExists(output_filename)
855 self.fp = open(output_filename, 'w')
856 self.fp.write(header)
857 # For consistency with other builders, put sub-project build output in the
858 # sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
859 self.WriteLn('export builddir_name ?= %s' %
860 os.path.join(os.path.dirname(output_filename), build_dir))
861 self.WriteLn('.PHONY: all')
864 makefile_path = ' -C ' + makefile_path
865 self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
869 def WriteActions(self, actions, extra_sources, extra_outputs,
870 extra_mac_bundle_resources, part_of_all):
871 """Write Makefile code for any 'actions' from the gyp input.
873 extra_sources: a list that will be filled in with newly generated source
875 extra_outputs: a list that will be filled in with any outputs of these
876 actions (used to make other pieces dependent on these
878 part_of_all: flag indicating this target is part of 'all'
880 env = self.GetSortedXcodeEnv()
881 for action in actions:
882 name = StringToMakefileVariable('%s_%s' % (self.qualified_target,
883 action['action_name']))
884 self.WriteLn('### Rules for action "%s":' % action['action_name'])
885 inputs = action['inputs']
886 outputs = action['outputs']
888 # Build up a list of outputs.
889 # Collect the output dirs we'll need.
892 dir = os.path.split(out)[0]
895 if int(action.get('process_outputs_as_sources', False)):
896 extra_sources += outputs
897 if int(action.get('process_outputs_as_mac_bundle_resources', False)):
898 extra_mac_bundle_resources += outputs
900 # Write the actual command.
901 action_commands = action['action']
902 if self.flavor == 'mac':
903 action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env)
904 for command in action_commands]
905 command = gyp.common.EncodePOSIXShellList(action_commands)
906 if 'message' in action:
907 self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message']))
909 self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name))
911 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
913 cd_action = 'cd %s; ' % Sourceify(self.path or '.')
915 # command and cd_action get written to a toplevel variable called
916 # cmd_foo. Toplevel variables can't handle things that change per
917 # makefile like $(TARGET), so hardcode the target.
918 command = command.replace('$(TARGET)', self.target)
919 cd_action = cd_action.replace('$(TARGET)', self.target)
921 # Set LD_LIBRARY_PATH in case the action runs an executable from this
922 # build which links to shared libs from this build.
923 # actions run on the host, so they should in theory only use host
924 # libraries, but until everything is made cross-compile safe, also use
926 # TODO(piman): when everything is cross-compile safe, remove lib.target
927 self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:'
928 '$(builddir)/lib.target:$$LD_LIBRARY_PATH; '
929 'export LD_LIBRARY_PATH; '
931 % (name, cd_action, command))
933 outputs = map(self.Absolutify, outputs)
934 # The makefile rules are all relative to the top dir, but the gyp actions
935 # are defined relative to their containing dir. This replaces the obj
936 # variable for the action rule with an absolute version so that the output
937 # goes in the right place.
938 # Only write the 'obj' and 'builddir' rules for the "primary" output (:1);
939 # it's superfluous for the "extra outputs", and this avoids accidentally
940 # writing duplicate dummy rules for those outputs.
941 # Same for environment.
942 self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0]))
943 self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0]))
944 self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv())
947 assert ' ' not in input, (
948 "Spaces in action input filenames not supported (%s)" % input)
949 for output in outputs:
950 assert ' ' not in output, (
951 "Spaces in action output filenames not supported (%s)" % output)
953 # See the comment in WriteCopies about expanding env vars.
954 outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
955 inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
957 self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)),
958 part_of_all=part_of_all, command=name)
960 # Stuff the outputs in a variable so we can refer to them later.
961 outputs_variable = 'action_%s_outputs' % name
962 self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs)))
963 extra_outputs.append('$(%s)' % outputs_variable)
969 def WriteRules(self, rules, extra_sources, extra_outputs,
970 extra_mac_bundle_resources, part_of_all):
971 """Write Makefile code for any 'rules' from the gyp input.
973 extra_sources: a list that will be filled in with newly generated source
975 extra_outputs: a list that will be filled in with any outputs of these
976 rules (used to make other pieces dependent on these rules)
977 part_of_all: flag indicating this target is part of 'all'
979 env = self.GetSortedXcodeEnv()
981 name = StringToMakefileVariable('%s_%s' % (self.qualified_target,
984 self.WriteLn('### Generated for rule %s:' % name)
988 for rule_source in rule.get('rule_sources', []):
990 (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
991 (rule_source_root, rule_source_ext) = \
992 os.path.splitext(rule_source_basename)
994 outputs = [self.ExpandInputRoot(out, rule_source_root,
996 for out in rule['outputs']]
999 dir = os.path.dirname(out)
1002 if int(rule.get('process_outputs_as_sources', False)):
1003 extra_sources += outputs
1004 if int(rule.get('process_outputs_as_mac_bundle_resources', False)):
1005 extra_mac_bundle_resources += outputs
1006 inputs = map(Sourceify, map(self.Absolutify, [rule_source] +
1007 rule.get('inputs', [])))
1008 actions = ['$(call do_cmd,%s_%d)' % (name, count)]
1010 if name == 'resources_grit':
1011 # HACK: This is ugly. Grit intentionally doesn't touch the
1012 # timestamp of its output file when the file doesn't change,
1013 # which is fine in hash-based dependency systems like scons
1014 # and forge, but not kosher in the make world. After some
1015 # discussion, hacking around it here seems like the least
1017 actions += ['@touch --no-create $@']
1019 # See the comment in WriteCopies about expanding env vars.
1020 outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs]
1021 inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs]
1023 outputs = map(self.Absolutify, outputs)
1024 all_outputs += outputs
1025 # Only write the 'obj' and 'builddir' rules for the "primary" output
1026 # (:1); it's superfluous for the "extra outputs", and this avoids
1027 # accidentally writing duplicate dummy rules for those outputs.
1028 self.WriteLn('%s: obj := $(abs_obj)' % outputs[0])
1029 self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0])
1030 self.WriteMakeRule(outputs, inputs + ['FORCE_DO_CMD'], actions)
1031 # Spaces in rule filenames are not supported, but rule variables have
1032 # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)').
1033 # The spaces within the variables are valid, so remove the variables
1035 variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)')
1036 for output in outputs:
1037 output = re.sub(variables_with_spaces, '', output)
1038 assert ' ' not in output, (
1039 "Spaces in rule filenames not yet supported (%s)" % output)
1040 self.WriteLn('all_deps += %s' % ' '.join(outputs))
1042 action = [self.ExpandInputRoot(ac, rule_source_root,
1043 rule_source_dirname)
1044 for ac in rule['action']]
1047 mkdirs = 'mkdir -p %s; ' % ' '.join(dirs)
1048 cd_action = 'cd %s; ' % Sourceify(self.path or '.')
1050 # action, cd_action, and mkdirs get written to a toplevel variable
1051 # called cmd_foo. Toplevel variables can't handle things that change
1052 # per makefile like $(TARGET), so hardcode the target.
1053 if self.flavor == 'mac':
1054 action = [gyp.xcode_emulation.ExpandEnvVars(command, env)
1055 for command in action]
1056 action = gyp.common.EncodePOSIXShellList(action)
1057 action = action.replace('$(TARGET)', self.target)
1058 cd_action = cd_action.replace('$(TARGET)', self.target)
1059 mkdirs = mkdirs.replace('$(TARGET)', self.target)
1061 # Set LD_LIBRARY_PATH in case the rule runs an executable from this
1062 # build which links to shared libs from this build.
1063 # rules run on the host, so they should in theory only use host
1064 # libraries, but until everything is made cross-compile safe, also use
1066 # TODO(piman): when everything is cross-compile safe, remove lib.target
1068 "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH="
1069 "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; "
1070 "export LD_LIBRARY_PATH; "
1071 "%(cd_action)s%(mkdirs)s%(action)s" % {
1073 'cd_action': cd_action,
1079 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % {
1086 outputs_variable = 'rule_%s_outputs' % name
1087 self.WriteList(all_outputs, outputs_variable)
1088 extra_outputs.append('$(%s)' % outputs_variable)
1090 self.WriteLn('### Finished generating for rule: %s' % name)
1092 self.WriteLn('### Finished generating for all rules')
1096 def WriteCopies(self, copies, extra_outputs, part_of_all):
1097 """Write Makefile code for any 'copies' from the gyp input.
1099 extra_outputs: a list that will be filled in with any outputs of this action
1100 (used to make other pieces dependent on this action)
1101 part_of_all: flag indicating this target is part of 'all'
1103 self.WriteLn('### Generated for copy rule.')
1105 variable = StringToMakefileVariable(self.qualified_target + '_copies')
1108 for path in copy['files']:
1109 # Absolutify() may call normpath, and will strip trailing slashes.
1110 path = Sourceify(self.Absolutify(path))
1111 filename = os.path.split(path)[1]
1112 output = Sourceify(self.Absolutify(os.path.join(copy['destination'],
1115 # If the output path has variables in it, which happens in practice for
1116 # 'copies', writing the environment as target-local doesn't work,
1117 # because the variables are already needed for the target name.
1118 # Copying the environment variables into global make variables doesn't
1119 # work either, because then the .d files will potentially contain spaces
1120 # after variable expansion, and .d file handling cannot handle spaces.
1121 # As a workaround, manually expand variables at gyp time. Since 'copies'
1122 # can't run scripts, there's no need to write the env then.
1123 # WriteDoCmd() will escape spaces for .d files.
1124 env = self.GetSortedXcodeEnv()
1125 output = gyp.xcode_emulation.ExpandEnvVars(output, env)
1126 path = gyp.xcode_emulation.ExpandEnvVars(path, env)
1127 self.WriteDoCmd([output], [path], 'copy', part_of_all)
1128 outputs.append(output)
1129 self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs))))
1130 extra_outputs.append('$(%s)' % variable)
1134 def WriteMacBundleResources(self, resources, bundle_deps):
1135 """Writes Makefile code for 'mac_bundle_resources'."""
1136 self.WriteLn('### Generated for mac_bundle_resources')
1138 for output, res in gyp.xcode_emulation.GetMacBundleResources(
1139 generator_default_variables['PRODUCT_DIR'], self.xcode_settings,
1140 map(Sourceify, map(self.Absolutify, resources))):
1141 self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource',
1143 bundle_deps.append(output)
1146 def WriteMacInfoPlist(self, bundle_deps):
1147 """Write Makefile code for bundle Info.plist files."""
1148 info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
1149 generator_default_variables['PRODUCT_DIR'], self.xcode_settings,
1150 lambda p: Sourceify(self.Absolutify(p)))
1154 # Create an intermediate file to store preprocessed results.
1155 intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' +
1156 os.path.basename(info_plist))
1157 self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D',
1158 quoter=EscapeCppDefine)
1159 self.WriteMakeRule([intermediate_plist], [info_plist],
1160 ['$(call do_cmd,infoplist)',
1161 # "Convert" the plist so that any weird whitespace changes from the
1162 # preprocessor do not affect the XML parser in mac_tool.
1163 '@plutil -convert xml1 $@ $@'])
1164 info_plist = intermediate_plist
1165 # plists can contain envvars and substitute them into the file.
1166 self.WriteSortedXcodeEnv(
1167 out, self.GetSortedXcodeEnv(additional_settings=extra_env))
1168 self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist',
1170 bundle_deps.append(out)
1173 def WriteSources(self, configs, deps, sources,
1174 extra_outputs, extra_link_deps,
1175 part_of_all, precompiled_header):
1176 """Write Makefile code for any 'sources' from the gyp input.
1177 These are source files necessary to build the current target.
1179 configs, deps, sources: input from gyp.
1180 extra_outputs: a list of extra outputs this action should be dependent on;
1181 used to serialize action/rules before compilation
1182 extra_link_deps: a list that will be filled in with any outputs of
1183 compilation (to be used in link lines)
1184 part_of_all: flag indicating this target is part of 'all'
1187 # Write configuration-specific variables for CFLAGS, etc.
1188 for configname in sorted(configs.keys()):
1189 config = configs[configname]
1190 self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D',
1191 quoter=EscapeCppDefine)
1193 if self.flavor == 'mac':
1194 cflags = self.xcode_settings.GetCflags(configname)
1195 cflags_c = self.xcode_settings.GetCflagsC(configname)
1196 cflags_cc = self.xcode_settings.GetCflagsCC(configname)
1197 cflags_objc = self.xcode_settings.GetCflagsObjC(configname)
1198 cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname)
1200 cflags = config.get('cflags')
1201 cflags_c = config.get('cflags_c')
1202 cflags_cc = config.get('cflags_cc')
1204 self.WriteLn("# Flags passed to all source files.");
1205 self.WriteList(cflags, 'CFLAGS_%s' % configname)
1206 self.WriteLn("# Flags passed to only C files.");
1207 self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname)
1208 self.WriteLn("# Flags passed to only C++ files.");
1209 self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname)
1210 if self.flavor == 'mac':
1211 self.WriteLn("# Flags passed to only ObjC files.");
1212 self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname)
1213 self.WriteLn("# Flags passed to only ObjC++ files.");
1214 self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname)
1215 includes = config.get('include_dirs')
1217 includes = map(Sourceify, map(self.Absolutify, includes))
1218 self.WriteList(includes, 'INCS_%s' % configname, prefix='-I')
1220 compilable = filter(Compilable, sources)
1221 objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable)))
1222 self.WriteList(objs, 'OBJS')
1225 assert ' ' not in obj, (
1226 "Spaces in object filenames not supported (%s)" % obj)
1227 self.WriteLn('# Add to the list of files we specially track '
1228 'dependencies for.')
1229 self.WriteLn('all_deps += $(OBJS)')
1232 # Make sure our dependencies are built first.
1234 self.WriteMakeRule(['$(OBJS)'], deps,
1235 comment = 'Make sure our dependencies are built '
1236 'before any of us.',
1239 # Make sure the actions and rules run first.
1240 # If they generate any extra headers etc., the per-.o file dep tracking
1241 # will catch the proper rebuilds, so order only is still ok here.
1243 self.WriteMakeRule(['$(OBJS)'], extra_outputs,
1244 comment = 'Make sure our actions/rules run '
1245 'before any of us.',
1248 pchdeps = precompiled_header.GetObjDependencies(compilable, objs )
1250 self.WriteLn('# Dependencies from obj files to their precompiled headers')
1251 for source, obj, gch in pchdeps:
1252 self.WriteLn('%s: %s' % (obj, gch))
1253 self.WriteLn('# End precompiled header dependencies')
1256 extra_link_deps.append('$(OBJS)')
1258 # CFLAGS et al overrides must be target-local.
1259 # See "Target-specific Variable Values" in the GNU Make manual.""")
1260 self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)")
1261 self.WriteLn("$(OBJS): GYP_CFLAGS := "
1262 "$(DEFS_$(BUILDTYPE)) "
1263 "$(INCS_$(BUILDTYPE)) "
1264 "%s " % precompiled_header.GetInclude('c') +
1265 "$(CFLAGS_$(BUILDTYPE)) "
1266 "$(CFLAGS_C_$(BUILDTYPE))")
1267 self.WriteLn("$(OBJS): GYP_CXXFLAGS := "
1268 "$(DEFS_$(BUILDTYPE)) "
1269 "$(INCS_$(BUILDTYPE)) "
1270 "%s " % precompiled_header.GetInclude('cc') +
1271 "$(CFLAGS_$(BUILDTYPE)) "
1272 "$(CFLAGS_CC_$(BUILDTYPE))")
1273 if self.flavor == 'mac':
1274 self.WriteLn("$(OBJS): GYP_OBJCFLAGS := "
1275 "$(DEFS_$(BUILDTYPE)) "
1276 "$(INCS_$(BUILDTYPE)) "
1277 "%s " % precompiled_header.GetInclude('m') +
1278 "$(CFLAGS_$(BUILDTYPE)) "
1279 "$(CFLAGS_C_$(BUILDTYPE)) "
1280 "$(CFLAGS_OBJC_$(BUILDTYPE))")
1281 self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := "
1282 "$(DEFS_$(BUILDTYPE)) "
1283 "$(INCS_$(BUILDTYPE)) "
1284 "%s " % precompiled_header.GetInclude('mm') +
1285 "$(CFLAGS_$(BUILDTYPE)) "
1286 "$(CFLAGS_CC_$(BUILDTYPE)) "
1287 "$(CFLAGS_OBJCC_$(BUILDTYPE))")
1289 self.WritePchTargets(precompiled_header.GetPchBuildCommands())
1291 # If there are any object files in our input file list, link them into our
1293 extra_link_deps += filter(Linkable, sources)
1297 def WritePchTargets(self, pch_commands):
1298 """Writes make rules to compile prefix headers."""
1299 if not pch_commands:
1302 for gch, lang_flag, lang, input in pch_commands:
1304 'c': '$(CFLAGS_C_$(BUILDTYPE))',
1305 'cc': '$(CFLAGS_CC_$(BUILDTYPE))',
1306 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))',
1307 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))',
1310 'c': 'GYP_PCH_CFLAGS',
1311 'cc': 'GYP_PCH_CXXFLAGS',
1312 'm': 'GYP_PCH_OBJCFLAGS',
1313 'mm': 'GYP_PCH_OBJCXXFLAGS',
1315 self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) +
1316 "$(DEFS_$(BUILDTYPE)) "
1317 "$(INCS_$(BUILDTYPE)) "
1318 "$(CFLAGS_$(BUILDTYPE)) " +
1321 self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input))
1322 self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang)
1324 assert ' ' not in gch, (
1325 "Spaces in gch filenames not supported (%s)" % gch)
1326 self.WriteLn('all_deps += %s' % gch)
1330 def ComputeOutputBasename(self, spec):
1331 """Return the 'output basename' of a gyp spec.
1333 E.g., the loadable module 'foobar' in directory 'baz' will produce
1336 assert not self.is_mac_bundle
1338 if self.flavor == 'mac' and self.type in (
1339 'static_library', 'executable', 'shared_library', 'loadable_module'):
1340 return self.xcode_settings.GetExecutablePath()
1342 target = spec['target_name']
1345 if self.type == 'static_library':
1346 if target[:3] == 'lib':
1348 target_prefix = 'lib'
1350 elif self.type in ('loadable_module', 'shared_library'):
1351 if target[:3] == 'lib':
1353 target_prefix = 'lib'
1355 elif self.type == 'none':
1356 target = '%s.stamp' % target
1357 elif self.type != 'executable':
1358 print ("ERROR: What output file should be generated?",
1359 "type", self.type, "target", target)
1361 target_prefix = spec.get('product_prefix', target_prefix)
1362 target = spec.get('product_name', target)
1363 product_ext = spec.get('product_extension')
1365 target_ext = '.' + product_ext
1367 return target_prefix + target + target_ext
1370 def _InstallImmediately(self):
1371 return self.toolset == 'target' and self.flavor == 'mac' and self.type in (
1372 'static_library', 'executable', 'shared_library', 'loadable_module')
1375 def ComputeOutput(self, spec):
1376 """Return the 'output' (full output path) of a gyp spec.
1378 E.g., the loadable module 'foobar' in directory 'baz' will produce
1379 '$(obj)/baz/libfoobar.so'
1381 assert not self.is_mac_bundle
1383 path = os.path.join('$(obj).' + self.toolset, self.path)
1384 if self.type == 'executable' or self._InstallImmediately():
1385 path = '$(builddir)'
1386 path = spec.get('product_dir', path)
1387 return os.path.join(path, self.ComputeOutputBasename(spec))
1390 def ComputeMacBundleOutput(self, spec):
1391 """Return the 'output' (full output path) to a bundle output directory."""
1392 assert self.is_mac_bundle
1393 path = generator_default_variables['PRODUCT_DIR']
1394 return os.path.join(path, self.xcode_settings.GetWrapperName())
1397 def ComputeMacBundleBinaryOutput(self, spec):
1398 """Return the 'output' (full output path) to the binary in a bundle."""
1399 path = generator_default_variables['PRODUCT_DIR']
1400 return os.path.join(path, self.xcode_settings.GetExecutablePath())
1403 def ComputeDeps(self, spec):
1404 """Compute the dependencies of a gyp spec.
1406 Returns a tuple (deps, link_deps), where each is a list of
1407 filenames that will need to be put in front of make for either
1408 building (deps) or linking (link_deps).
1412 if 'dependencies' in spec:
1413 deps.extend([target_outputs[dep] for dep in spec['dependencies']
1414 if target_outputs[dep]])
1415 for dep in spec['dependencies']:
1416 if dep in target_link_deps:
1417 link_deps.append(target_link_deps[dep])
1418 deps.extend(link_deps)
1419 # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)?
1420 # This hack makes it work:
1421 # link_deps.extend(spec.get('libraries', []))
1422 return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
1425 def WriteDependencyOnExtraOutputs(self, target, extra_outputs):
1426 self.WriteMakeRule([self.output_binary], extra_outputs,
1427 comment = 'Build our special outputs first.',
1431 def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps,
1432 extra_outputs, part_of_all):
1433 """Write Makefile code to produce the final target of the gyp spec.
1435 spec, configs: input from gyp.
1436 deps, link_deps: dependency lists; see ComputeDeps()
1437 extra_outputs: any extra outputs that our target should depend on
1438 part_of_all: flag indicating this target is part of 'all'
1441 self.WriteLn('### Rules for final target.')
1444 self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs)
1445 self.WriteMakeRule(extra_outputs, deps,
1446 comment=('Preserve order dependency of '
1447 'special output on deps.'),
1450 target_postbuilds = {}
1451 if self.type != 'none':
1452 for configname in sorted(configs.keys()):
1453 config = configs[configname]
1454 if self.flavor == 'mac':
1455 ldflags = self.xcode_settings.GetLdflags(configname,
1456 generator_default_variables['PRODUCT_DIR'],
1457 lambda p: Sourceify(self.Absolutify(p)))
1459 # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.
1460 gyp_to_build = gyp.common.InvertRelativePath(self.path)
1461 target_postbuild = self.xcode_settings.AddImplicitPostbuilds(
1463 QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build,
1465 QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build,
1466 self.output_binary))))
1467 if target_postbuild:
1468 target_postbuilds[configname] = target_postbuild
1470 ldflags = config.get('ldflags', [])
1471 # Compute an rpath for this output if needed.
1472 if any(dep.endswith('.so') or '.so.' in dep for dep in deps):
1473 # We want to get the literal string "$ORIGIN" into the link command,
1474 # so we need lots of escaping.
1475 ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset)
1476 ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' %
1478 library_dirs = config.get('library_dirs', [])
1479 ldflags += [('-L%s' % library_dir) for library_dir in library_dirs]
1480 self.WriteList(ldflags, 'LDFLAGS_%s' % configname)
1481 if self.flavor == 'mac':
1482 self.WriteList(self.xcode_settings.GetLibtoolflags(configname),
1483 'LIBTOOLFLAGS_%s' % configname)
1484 libraries = spec.get('libraries')
1486 # Remove duplicate entries
1487 libraries = gyp.common.uniquer(libraries)
1488 if self.flavor == 'mac':
1489 libraries = self.xcode_settings.AdjustLibraries(libraries)
1490 self.WriteList(libraries, 'LIBS')
1491 self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' %
1492 QuoteSpaces(self.output_binary))
1493 self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary))
1495 if self.flavor == 'mac':
1496 self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' %
1497 QuoteSpaces(self.output_binary))
1499 # Postbuild actions. Like actions, but implicitly depend on the target's
1502 if self.flavor == 'mac':
1503 if target_postbuilds:
1504 postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))')
1506 gyp.xcode_emulation.GetSpecPostbuildCommands(spec))
1509 # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),
1510 # so we must output its definition first, since we declare variables
1512 self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv())
1514 for configname in target_postbuilds:
1515 self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' %
1516 (QuoteSpaces(self.output),
1518 gyp.common.EncodePOSIXShellList(target_postbuilds[configname])))
1520 # Postbuilds expect to be run in the gyp file's directory, so insert an
1521 # implicit postbuild to cd to there.
1522 postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path]))
1523 for i in xrange(len(postbuilds)):
1524 if not postbuilds[i].startswith('$'):
1525 postbuilds[i] = EscapeShellArgument(postbuilds[i])
1526 self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output))
1527 self.WriteLn('%s: POSTBUILDS := %s' % (
1528 QuoteSpaces(self.output), ' '.join(postbuilds)))
1530 # A bundle directory depends on its dependencies such as bundle resources
1531 # and bundle binary. When all dependencies have been built, the bundle
1532 # needs to be packaged.
1533 if self.is_mac_bundle:
1534 # If the framework doesn't contain a binary, then nothing depends
1535 # on the actions -- make the framework depend on them directly too.
1536 self.WriteDependencyOnExtraOutputs(self.output, extra_outputs)
1538 # Bundle dependencies. Note that the code below adds actions to this
1539 # target, so if you move these two lines, move the lines below as well.
1540 self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS')
1541 self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output))
1543 # After the framework is built, package it. Needs to happen before
1544 # postbuilds, since postbuilds depend on this.
1545 if self.type in ('shared_library', 'loadable_module'):
1546 self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' %
1547 self.xcode_settings.GetFrameworkVersion())
1549 # Bundle postbuilds can depend on the whole bundle, so run them after
1550 # the bundle is packaged, not already after the bundle binary is done.
1552 self.WriteLn('\t@$(call do_postbuilds)')
1553 postbuilds = [] # Don't write postbuilds for target's output.
1555 # Needed by test/mac/gyptest-rebuild.py.
1556 self.WriteLn('\t@true # No-op, used by tests')
1558 # Since this target depends on binary and resources which are in
1559 # nested subfolders, the framework directory will be older than
1560 # its dependencies usually. To prevent this rule from executing
1561 # on every build (expensive, especially with postbuilds), expliclity
1562 # update the time on the framework directory.
1563 self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output))
1566 assert not self.is_mac_bundle, ('Postbuilds for bundles should be done '
1567 'on the bundle, not the binary (target \'%s\')' % self.target)
1568 assert 'product_dir' not in spec, ('Postbuilds do not work with '
1569 'custom product_dir')
1571 if self.type == 'executable':
1572 self.WriteLn('%s: LD_INPUTS := %s' % (
1573 QuoteSpaces(self.output_binary),
1574 ' '.join(map(QuoteSpaces, link_deps))))
1575 if self.toolset == 'host' and self.flavor == 'android':
1576 self.WriteDoCmd([self.output_binary], link_deps, 'link_host',
1577 part_of_all, postbuilds=postbuilds)
1579 self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all,
1580 postbuilds=postbuilds)
1582 elif self.type == 'static_library':
1583 for link_dep in link_deps:
1584 assert ' ' not in link_dep, (
1585 "Spaces in alink input filenames not supported (%s)" % link_dep)
1586 if (self.flavor not in ('mac', 'openbsd', 'win') and not
1587 self.is_standalone_static_library):
1588 self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin',
1589 part_of_all, postbuilds=postbuilds)
1591 self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all,
1592 postbuilds=postbuilds)
1593 elif self.type == 'shared_library':
1594 self.WriteLn('%s: LD_INPUTS := %s' % (
1595 QuoteSpaces(self.output_binary),
1596 ' '.join(map(QuoteSpaces, link_deps))))
1597 self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all,
1598 postbuilds=postbuilds)
1599 elif self.type == 'loadable_module':
1600 for link_dep in link_deps:
1601 assert ' ' not in link_dep, (
1602 "Spaces in module input filenames not supported (%s)" % link_dep)
1603 if self.toolset == 'host' and self.flavor == 'android':
1604 self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host',
1605 part_of_all, postbuilds=postbuilds)
1608 [self.output_binary], link_deps, 'solink_module', part_of_all,
1609 postbuilds=postbuilds)
1610 elif self.type == 'none':
1611 # Write a stamp line.
1612 self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all,
1613 postbuilds=postbuilds)
1615 print "WARNING: no output for", self.type, target
1617 # Add an alias for each target (if there are any outputs).
1618 # Installable target aliases are created below.
1619 if ((self.output and self.output != self.target) and
1620 (self.type not in self._INSTALLABLE_TARGETS)):
1621 self.WriteMakeRule([self.target], [self.output],
1622 comment='Add target alias', phony = True)
1624 self.WriteMakeRule(['all'], [self.target],
1625 comment = 'Add target alias to "all" target.',
1628 # Add special-case rules for our installable targets.
1629 # 1) They need to install to the build dir or "product" dir.
1630 # 2) They get shortcuts for building (e.g. "make chrome").
1631 # 3) They are part of "make all".
1632 if (self.type in self._INSTALLABLE_TARGETS or
1633 self.is_standalone_static_library):
1634 if self.type == 'shared_library':
1635 file_desc = 'shared library'
1636 elif self.type == 'static_library':
1637 file_desc = 'static library'
1639 file_desc = 'executable'
1640 install_path = self._InstallableTargetInstallPath()
1641 installable_deps = [self.output]
1642 if (self.flavor == 'mac' and not 'product_dir' in spec and
1643 self.toolset == 'target'):
1644 # On mac, products are created in install_path immediately.
1645 assert install_path == self.output, '%s != %s' % (
1646 install_path, self.output)
1648 # Point the target alias to the final binary output.
1649 self.WriteMakeRule([self.target], [install_path],
1650 comment='Add target alias', phony = True)
1651 if install_path != self.output:
1652 assert not self.is_mac_bundle # See comment a few lines above.
1653 self.WriteDoCmd([install_path], [self.output], 'copy',
1654 comment = 'Copy this to the %s output path.' %
1655 file_desc, part_of_all=part_of_all)
1656 installable_deps.append(install_path)
1657 if self.output != self.alias and self.alias != self.target:
1658 self.WriteMakeRule([self.alias], installable_deps,
1659 comment = 'Short alias for building this %s.' %
1660 file_desc, phony = True)
1662 self.WriteMakeRule(['all'], [install_path],
1663 comment = 'Add %s to "all" target.' % file_desc,
1667 def WriteList(self, value_list, variable=None, prefix='',
1668 quoter=QuoteIfNecessary):
1669 """Write a variable definition that is a list of values.
1671 E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
1673 but in a pretty-printed style.
1677 value_list = [quoter(prefix + l) for l in value_list]
1678 values = ' \\\n\t' + ' \\\n\t'.join(value_list)
1679 self.fp.write('%s :=%s\n\n' % (variable, values))
1682 def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None,
1684 """Write a Makefile rule that uses do_cmd.
1686 This makes the outputs dependent on the command line that was run,
1687 as well as support the V= make command line flag.
1691 assert ',' not in command
1692 suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS
1693 self.WriteMakeRule(outputs, inputs,
1694 actions = ['$(call do_cmd,%s%s)' % (command, suffix)],
1697 # Add our outputs to the list of targets we read depfiles from.
1698 # all_deps is only used for deps file reading, and for deps files we replace
1699 # spaces with ? because escaping doesn't work with make's $(sort) and
1701 outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs]
1702 self.WriteLn('all_deps += %s' % ' '.join(outputs))
1705 def WriteMakeRule(self, outputs, inputs, actions=None, comment=None,
1706 order_only=False, force=False, phony=False):
1707 """Write a Makefile rule, with some extra tricks.
1709 outputs: a list of outputs for the rule (note: this is not directly
1710 supported by make; see comments below)
1711 inputs: a list of inputs for the rule
1712 actions: a list of shell commands to run for the rule
1713 comment: a comment to put in the Makefile above the rule (also useful
1714 for making this Python script's code self-documenting)
1715 order_only: if true, makes the dependency order-only
1716 force: if true, include FORCE_DO_CMD as an order-only dep
1717 phony: if true, the rule does not actually generate the named output, the
1718 output is just a name to run the rule
1720 outputs = map(QuoteSpaces, outputs)
1721 inputs = map(QuoteSpaces, inputs)
1724 self.WriteLn('# ' + comment)
1726 self.WriteLn('.PHONY: ' + ' '.join(outputs))
1727 # TODO(evanm): just make order_only a list of deps instead of these hacks.
1730 pick_output = ' '.join(outputs)
1733 pick_output = outputs[0]
1735 force_append = ' FORCE_DO_CMD'
1739 self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
1740 self.WriteLn('%s: %s%s%s' % (pick_output, order_insert, ' '.join(inputs),
1743 for action in actions:
1744 self.WriteLn('\t%s' % action)
1745 if not order_only and len(outputs) > 1:
1746 # If we have more than one output, a rule like
1748 # that for *each* output we must run the action, potentially
1749 # in parallel. That is not what we're trying to write -- what
1750 # we want is that we run the action once and it generates all
1752 # http://www.gnu.org/software/hello/manual/automake/Multiple-Outputs.html
1753 # discusses this problem and has this solution:
1754 # 1) Write the naive rule that would produce parallel runs of
1756 # 2) Make the outputs seralized on each other, so we won't start
1757 # a parallel run until the first run finishes, at which point
1758 # we'll have generated all the outputs and we're done.
1759 self.WriteLn('%s: %s' % (' '.join(outputs[1:]), outputs[0]))
1760 # Add a dummy command to the "extra outputs" rule, otherwise make seems to
1761 # think these outputs haven't (couldn't have?) changed, and thus doesn't
1762 # flag them as changed (i.e. include in '$?') when evaluating dependent
1763 # rules, which in turn causes do_cmd() to skip running dependent commands.
1764 self.WriteLn('%s: ;' % (' '.join(outputs[1:])))
1768 def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
1769 """Write a set of LOCAL_XXX definitions for Android NDK.
1771 These variable definitions will be used by Android NDK but do nothing for
1772 non-Android applications.
1775 module_name: Android NDK module name, which must be unique among all
1777 all_sources: A list of source files (will be filtered by Compilable).
1778 link_deps: A list of link dependencies, which must be sorted in
1779 the order from dependencies to dependents.
1781 if self.type not in ('executable', 'shared_library', 'static_library'):
1784 self.WriteLn('# Variable definitions for Android applications')
1785 self.WriteLn('include $(CLEAR_VARS)')
1786 self.WriteLn('LOCAL_MODULE := ' + module_name)
1787 self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) '
1788 '$(DEFS_$(BUILDTYPE)) '
1789 # LOCAL_CFLAGS is applied to both of C and C++. There is
1790 # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C
1792 '$(CFLAGS_C_$(BUILDTYPE)) '
1793 # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while
1794 # LOCAL_C_INCLUDES does not expect it. So put it in
1796 '$(INCS_$(BUILDTYPE))')
1797 # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred.
1798 self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))')
1799 self.WriteLn('LOCAL_C_INCLUDES :=')
1800 self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)')
1802 # Detect the C++ extension.
1803 cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0}
1804 default_cpp_ext = '.cpp'
1805 for filename in all_sources:
1806 ext = os.path.splitext(filename)[1]
1809 if cpp_ext[ext] > cpp_ext[default_cpp_ext]:
1810 default_cpp_ext = ext
1811 self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext)
1813 self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)),
1816 # Filter out those which do not match prefix and suffix and produce
1817 # the resulting list without prefix and suffix.
1818 def DepsToModules(deps, prefix, suffix):
1820 for filepath in deps:
1821 filename = os.path.basename(filepath)
1822 if filename.startswith(prefix) and filename.endswith(suffix):
1823 modules.append(filename[len(prefix):-len(suffix)])
1826 # Retrieve the default value of 'SHARED_LIB_SUFFIX'
1827 params = {'flavor': 'linux'}
1828 default_variables = {}
1829 CalculateVariables(default_variables, params)
1832 DepsToModules(link_deps,
1833 generator_default_variables['SHARED_LIB_PREFIX'],
1834 default_variables['SHARED_LIB_SUFFIX']),
1835 'LOCAL_SHARED_LIBRARIES')
1837 DepsToModules(link_deps,
1838 generator_default_variables['STATIC_LIB_PREFIX'],
1839 generator_default_variables['STATIC_LIB_SUFFIX']),
1840 'LOCAL_STATIC_LIBRARIES')
1842 if self.type == 'executable':
1843 self.WriteLn('include $(BUILD_EXECUTABLE)')
1844 elif self.type == 'shared_library':
1845 self.WriteLn('include $(BUILD_SHARED_LIBRARY)')
1846 elif self.type == 'static_library':
1847 self.WriteLn('include $(BUILD_STATIC_LIBRARY)')
1851 def WriteLn(self, text=''):
1852 self.fp.write(text + '\n')
1855 def GetSortedXcodeEnv(self, additional_settings=None):
1856 return gyp.xcode_emulation.GetSortedXcodeEnv(
1857 self.xcode_settings, "$(abs_builddir)",
1858 os.path.join("$(abs_srcdir)", self.path), "$(BUILDTYPE)",
1859 additional_settings)
1862 def GetSortedXcodePostbuildEnv(self):
1863 # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.
1864 # TODO(thakis): It would be nice to have some general mechanism instead.
1865 strip_save_file = self.xcode_settings.GetPerTargetSetting(
1866 'CHROMIUM_STRIP_SAVE_FILE', '')
1867 # Even if strip_save_file is empty, explicitly write it. Else a postbuild
1868 # might pick up an export from an earlier target.
1869 return self.GetSortedXcodeEnv(
1870 additional_settings={'CHROMIUM_STRIP_SAVE_FILE': strip_save_file})
1873 def WriteSortedXcodeEnv(self, target, env):
1877 # the escaped space does the right thing. For
1878 # export foo := a\ b
1879 # it does not -- the backslash is written to the env as literal character.
1880 # So don't escape spaces in |env[k]|.
1881 self.WriteLn('%s: export %s := %s' % (QuoteSpaces(target), k, v))
1884 def Objectify(self, path):
1885 """Convert a path to its output directory form."""
1887 path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset)
1888 if not '$(obj)' in path:
1889 path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path)
1893 def Pchify(self, path, lang):
1894 """Convert a prefix header path to its output directory form."""
1895 path = self.Absolutify(path)
1897 path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' %
1898 (self.toolset, lang))
1900 return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
1903 def Absolutify(self, path):
1904 """Convert a subdirectory-relative path into a base-relative path.
1905 Skips over paths that contain variables."""
1907 # Don't call normpath in this case, as it might collapse the
1908 # path too aggressively if it features '..'. However it's still
1909 # important to strip trailing slashes.
1910 return path.rstrip('/')
1911 return os.path.normpath(os.path.join(self.path, path))
1914 def ExpandInputRoot(self, template, expansion, dirname):
1915 if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template:
1918 'INPUT_ROOT': expansion,
1919 'INPUT_DIRNAME': dirname,
1924 def _InstallableTargetInstallPath(self):
1925 """Returns the location of the final output for an installable target."""
1926 # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files
1927 # rely on this. Emulate this behavior for mac.
1928 if (self.type == 'shared_library' and
1929 (self.flavor != 'mac' or self.toolset != 'target')):
1930 # Install all shared libs into a common directory (per toolset) for
1931 # convenient access with LD_LIBRARY_PATH.
1932 return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias)
1933 return '$(builddir)/' + self.alias
1936 def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
1938 """Write the target to regenerate the Makefile."""
1939 options = params['options']
1940 build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir)
1941 for filename in params['build_files_arg']]
1943 gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'],
1944 options.toplevel_dir)
1945 if not gyp_binary.startswith(os.sep):
1946 gyp_binary = os.path.join('.', gyp_binary)
1948 root_makefile.write(
1949 "quiet_cmd_regen_makefile = ACTION Regenerating $@\n"
1950 "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n"
1951 "%(makefile_name)s: %(deps)s\n"
1952 "\t$(call do_cmd,regen_makefile)\n\n" % {
1953 'makefile_name': makefile_name,
1954 'deps': ' '.join(map(Sourceify, build_files)),
1955 'cmd': gyp.common.EncodePOSIXShellList(
1956 [gyp_binary, '-fmake'] +
1957 gyp.RegenerateFlags(options) +
1961 def PerformBuild(data, configurations, params):
1962 options = params['options']
1963 for config in configurations:
1964 arguments = ['make']
1965 if options.toplevel_dir and options.toplevel_dir != '.':
1966 arguments += '-C', options.toplevel_dir
1967 arguments.append('BUILDTYPE=' + config)
1968 print 'Building [%s]: %s' % (config, arguments)
1969 subprocess.check_call(arguments)
1972 def GenerateOutput(target_list, target_dicts, data, params):
1973 options = params['options']
1974 flavor = gyp.common.GetFlavor(params)
1975 generator_flags = params.get('generator_flags', {})
1976 builddir_name = generator_flags.get('output_dir', 'out')
1977 android_ndk_version = generator_flags.get('android_ndk_version', None)
1978 default_target = generator_flags.get('default_target', 'all')
1980 def CalculateMakefilePath(build_file, base_name):
1981 """Determine where to write a Makefile for a given gyp file."""
1982 # Paths in gyp files are relative to the .gyp file, but we want
1983 # paths relative to the source root for the master makefile. Grab
1984 # the path of the .gyp file as the base to relativize against.
1985 # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
1986 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
1988 # We write the file in the base_path directory.
1989 output_file = os.path.join(options.depth, base_path, base_name)
1990 if options.generator_output:
1991 output_file = os.path.join(
1992 options.depth, options.generator_output, base_path, base_name)
1993 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
1994 options.toplevel_dir)
1995 return base_path, output_file
1997 # TODO: search for the first non-'Default' target. This can go
1998 # away when we add verification that all targets have the
1999 # necessary configurations.
2000 default_configuration = None
2001 toolsets = set([target_dicts[target]['toolset'] for target in target_list])
2002 for target in target_list:
2003 spec = target_dicts[target]
2004 if spec['default_configuration'] != 'Default':
2005 default_configuration = spec['default_configuration']
2007 if not default_configuration:
2008 default_configuration = 'Default'
2011 makefile_name = 'Makefile' + options.suffix
2012 makefile_path = os.path.join(options.toplevel_dir, makefile_name)
2013 if options.generator_output:
2014 global srcdir_prefix
2015 makefile_path = os.path.join(
2016 options.toplevel_dir, options.generator_output, makefile_name)
2017 srcdir = gyp.common.RelativePath(srcdir, options.generator_output)
2018 srcdir_prefix = '$(srcdir)/'
2020 flock_command= 'flock'
2022 'default_target': default_target,
2023 'builddir': builddir_name,
2024 'default_configuration': default_configuration,
2025 'flock': flock_command,
2027 'link_commands': LINK_COMMANDS_LINUX,
2028 'extra_commands': '',
2032 flock_command = './gyp-mac-tool flock'
2033 header_params.update({
2034 'flock': flock_command,
2036 'link_commands': LINK_COMMANDS_MAC,
2037 'extra_commands': SHARED_HEADER_MAC_COMMANDS,
2039 elif flavor == 'android':
2040 header_params.update({
2041 'link_commands': LINK_COMMANDS_ANDROID,
2043 elif flavor == 'solaris':
2044 header_params.update({
2045 'flock': './gyp-flock-tool flock',
2048 elif flavor == 'freebsd':
2049 # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific.
2050 header_params.update({
2053 elif flavor == 'aix':
2054 header_params.update({
2055 'link_commands': LINK_COMMANDS_AIX,
2056 'flock': './gyp-flock-tool flock',
2060 header_params.update({
2061 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'),
2062 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'),
2063 'CXX.target': GetEnvironFallback(('CXX_target', 'CXX'), '$(CXX)'),
2064 'LINK.target': GetEnvironFallback(('LINK_target', 'LINK'), '$(LINK)'),
2065 'CC.host': GetEnvironFallback(('CC_host',), 'gcc'),
2066 'AR.host': GetEnvironFallback(('AR_host',), 'ar'),
2067 'CXX.host': GetEnvironFallback(('CXX_host',), 'g++'),
2068 'LINK.host': GetEnvironFallback(('LINK_host',), '$(CXX.host)'),
2071 build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
2072 make_global_settings_array = data[build_file].get('make_global_settings', [])
2074 wrappers['LINK'] = '%s $(builddir)/linker.lock' % flock_command
2075 for key, value in make_global_settings_array:
2076 if key.endswith('_wrapper'):
2077 wrappers[key[:-len('_wrapper')]] = '$(abspath %s)' % value
2078 make_global_settings = ''
2079 for key, value in make_global_settings_array:
2080 if re.match('.*_wrapper', key):
2083 value = '$(abspath %s)' % value
2084 wrapper = wrappers.get(key)
2086 value = '%s %s' % (wrapper, value)
2088 if key in ('CC', 'CC.host', 'CXX', 'CXX.host'):
2089 make_global_settings += (
2090 'ifneq (,$(filter $(origin %s), undefined default))\n' % key)
2091 # Let gyp-time envvars win over global settings.
2092 env_key = key.replace('.', '_') # CC.host -> CC_host
2093 if env_key in os.environ:
2094 value = os.environ[env_key]
2095 make_global_settings += ' %s = %s\n' % (key, value)
2096 make_global_settings += 'endif\n'
2098 make_global_settings += '%s ?= %s\n' % (key, value)
2099 # TODO(ukai): define cmd when only wrapper is specified in
2100 # make_global_settings.
2102 header_params['make_global_settings'] = make_global_settings
2104 gyp.common.EnsureDirExists(makefile_path)
2105 root_makefile = open(makefile_path, 'w')
2106 root_makefile.write(SHARED_HEADER % header_params)
2107 # Currently any versions have the same effect, but in future the behavior
2108 # could be different.
2109 if android_ndk_version:
2110 root_makefile.write(
2111 '# Define LOCAL_PATH for build of Android applications.\n'
2112 'LOCAL_PATH := $(call my-dir)\n'
2114 for toolset in toolsets:
2115 root_makefile.write('TOOLSET := %s\n' % toolset)
2116 WriteRootHeaderSuffixRules(root_makefile)
2118 # Put build-time support tools next to the root Makefile.
2119 dest_path = os.path.dirname(makefile_path)
2120 gyp.common.CopyTool(flavor, dest_path)
2122 # Find the list of targets that derive from the gyp file(s) being built.
2123 needed_targets = set()
2124 for build_file in params['build_files']:
2125 for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
2126 needed_targets.add(target)
2129 include_list = set()
2130 for qualified_target in target_list:
2131 build_file, target, toolset = gyp.common.ParseQualifiedTarget(
2134 this_make_global_settings = data[build_file].get('make_global_settings', [])
2135 assert make_global_settings_array == this_make_global_settings, (
2136 "make_global_settings needs to be the same for all targets. %s vs. %s" %
2137 (this_make_global_settings, make_global_settings))
2139 build_files.add(gyp.common.RelativePath(build_file, options.toplevel_dir))
2140 included_files = data[build_file]['included_files']
2141 for included_file in included_files:
2142 # The included_files entries are relative to the dir of the build file
2143 # that included them, so we have to undo that and then make them relative
2145 relative_include_file = gyp.common.RelativePath(
2146 gyp.common.UnrelativePath(included_file, build_file),
2147 options.toplevel_dir)
2148 abs_include_file = os.path.abspath(relative_include_file)
2149 # If the include file is from the ~/.gyp dir, we should use absolute path
2150 # so that relocating the src dir doesn't break the path.
2151 if (params['home_dot_gyp'] and
2152 abs_include_file.startswith(params['home_dot_gyp'])):
2153 build_files.add(abs_include_file)
2155 build_files.add(relative_include_file)
2157 base_path, output_file = CalculateMakefilePath(build_file,
2158 target + '.' + toolset + options.suffix + '.mk')
2160 spec = target_dicts[qualified_target]
2161 configs = spec['configurations']
2164 gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
2166 writer = MakefileWriter(generator_flags, flavor)
2167 writer.Write(qualified_target, base_path, output_file, spec, configs,
2168 part_of_all=qualified_target in needed_targets)
2170 # Our root_makefile lives at the source root. Compute the relative path
2171 # from there to the output_file for including.
2172 mkfile_rel_path = gyp.common.RelativePath(output_file,
2173 os.path.dirname(makefile_path))
2174 include_list.add(mkfile_rel_path)
2176 # Write out per-gyp (sub-project) Makefiles.
2177 depth_rel_path = gyp.common.RelativePath(options.depth, os.getcwd())
2178 for build_file in build_files:
2179 # The paths in build_files were relativized above, so undo that before
2180 # testing against the non-relativized items in target_list and before
2181 # calculating the Makefile path.
2182 build_file = os.path.join(depth_rel_path, build_file)
2183 gyp_targets = [target_dicts[target]['target_name'] for target in target_list
2184 if target.startswith(build_file) and
2185 target in needed_targets]
2186 # Only generate Makefiles for gyp files with targets.
2189 base_path, output_file = CalculateMakefilePath(build_file,
2190 os.path.splitext(os.path.basename(build_file))[0] + '.Makefile')
2191 makefile_rel_path = gyp.common.RelativePath(os.path.dirname(makefile_path),
2192 os.path.dirname(output_file))
2193 writer.WriteSubMake(output_file, makefile_rel_path, gyp_targets,
2197 # Write out the sorted list of includes.
2198 root_makefile.write('\n')
2199 for include_file in sorted(include_list):
2200 # We wrap each .mk include in an if statement so users can tell make to
2201 # not load a file by setting NO_LOAD. The below make code says, only
2202 # load the .mk file if the .mk filename doesn't start with a token in
2204 root_makefile.write(
2205 "ifeq ($(strip $(foreach prefix,$(NO_LOAD),\\\n"
2206 " $(findstring $(join ^,$(prefix)),\\\n"
2207 " $(join ^," + include_file + ")))),)\n")
2208 root_makefile.write(" include " + include_file + "\n")
2209 root_makefile.write("endif\n")
2210 root_makefile.write('\n')
2212 if (not generator_flags.get('standalone')
2213 and generator_flags.get('auto_regeneration', True)):
2214 WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files)
2216 root_makefile.write(SHARED_FOOTER)
2218 root_makefile.close()