7bef217f674c0a46d8b380be652ed616b3d5ecb0
[platform/upstream/nodejs.git] / tools / gyp / pylib / gyp / generator / make.py
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.
4
5 # Notes:
6 #
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.
10 #
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
16 # .mk files.
17 #
18 # TODOs:
19 #
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.
23
24 import os
25 import re
26 import sys
27 import subprocess
28 import gyp
29 import gyp.common
30 import gyp.xcode_emulation
31 from gyp.common import GetEnvironFallback
32
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)',
48 }
49
50 # Make supports multiple toolsets
51 generator_supports_multiple_toolsets = True
52
53 # Request sorted dependencies in the order from dependents to dependencies.
54 generator_wants_sorted_dependencies = False
55
56 # Placates pylint.
57 generator_additional_non_configuration_keys = []
58 generator_additional_path_sections = []
59 generator_extra_sources_for_rules = []
60
61
62 def CalculateVariables(default_variables, params):
63   """Calculate additional variables for use in the build (called by gyp)."""
64   flavor = gyp.common.GetFlavor(params)
65   if flavor == 'mac':
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'])
72
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'})
86   else:
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)')
94
95
96 def CalculateGeneratorInputInfo(params):
97   """Calculate the generator specific info that gets fed to input (called by
98   gyp)."""
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
105
106
107 def ensure_directory_exists(path):
108   dir = os.path.dirname(path)
109   if dir and not os.path.exists(dir):
110     os.makedirs(dir)
111
112
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
118 # file for
119 #     Chromium\ Framework.framework/foo
120 # is for example
121 #     out/Release/.deps/out/Release/Chromium?Framework.framework/foo
122 # This is the replacement character.
123 SPACE_REPLACEMENT = '?'
124
125
126 LINK_COMMANDS_LINUX = """\
127 quiet_cmd_alink = AR($(TOOLSET)) $@
128 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
129
130 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
131 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
132
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)
138
139 # We support two kinds of shared objects (.so):
140 # 1) shared_library, which is just bundling together many dependent libraries
141 # into a link line.
142 # 2) loadable_module, which is generating a module intended for dlopen().
143 #
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
147 # outermost module.
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
150 # normal linking.)
151
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)
157
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)
160 """
161
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,$^)
165
166 quiet_cmd_link = LINK($(TOOLSET)) $@
167 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
168
169 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
170 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
171
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)
174 """
175
176 LINK_COMMANDS_ANDROID = """\
177 quiet_cmd_alink = AR($(TOOLSET)) $@
178 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
179
180 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
181 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
182
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)
190
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)
196
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)
201 """
202
203
204 LINK_COMMANDS_AIX = """\
205 quiet_cmd_alink = AR($(TOOLSET)) $@
206 cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
207
208 quiet_cmd_alink_thin = AR($(TOOLSET)) $@
209 cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
210
211 quiet_cmd_link = LINK($(TOOLSET)) $@
212 cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
213
214 quiet_cmd_solink = SOLINK($(TOOLSET)) $@
215 cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
216
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)
219 """
220
221
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.
227
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.
231 MAKEFLAGS=-r
232
233 # The source directory tree.
234 srcdir := %(srcdir)s
235 abs_srcdir := $(abspath $(srcdir))
236
237 # The name of the builddir.
238 builddir_name ?= %(builddir)s
239
240 # The V=1 flag on command line makes us verbosely print command lines.
241 ifdef V
242   quiet=
243 else
244   quiet=quiet_
245 endif
246
247 # Specify BUILDTYPE=Release on the command line for a release build.
248 BUILDTYPE ?= %(default_configuration)s
249
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
256
257 # Object output directory.
258 obj := $(builddir)/obj
259 abs_obj := $(abspath $(obj))
260
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.
263 all_deps :=
264
265 %(make_global_settings)s
266
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)
273 AR.target ?= $(AR)
274
275 # C++ apps need to be linked with g++.
276 #
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:
280 #
281 #   export LINK=g++
282 #
283 # This will allow make to invoke N linker processes as specified in -jN.
284 LINK ?= %(flock)s $(builddir)/linker.lock $(CXX.target)
285
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
289 CFLAGS.host ?=
290 CXX.host ?= %(CXX.host)s
291 CXXFLAGS.host ?=
292 LINK.host ?= %(LINK.host)s
293 LDFLAGS.host ?=
294 AR.host ?= %(AR.host)s
295
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."
300 empty :=
301 space := $(empty) $(empty)
302
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)))
307
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
314
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
318 # the form:
319 #   foobar.o: DEP1 DEP2
320 # into
321 #   path/to/foobar.o: DEP1 DEP2
322 # (2) we want missing files not to cause us to fail to build.
323 # We want to rewrite
324 #   foobar.o: DEP1 DEP2 \\
325 #               DEP3
326 # to
327 #   DEP1:
328 #   DEP2:
329 #   DEP3:
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."""
335 r"""
336 define fixup_dep
337 # The depfile may not exist if the input file didn't have any #includes.
338 touch $(depfile).raw
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 |\
346   grep -v '^$$'                             |\
347   sed -e 1d -e 's|$$|:|'                     \
348     >> $(depfile)
349 rm $(depfile).raw
350 endef
351 """
352 """
353 # Command definitions:
354 # - cmd_foo is the actual command to run;
355 # - quiet_cmd_foo is the brief-output summary of the command.
356
357 quiet_cmd_cc = CC($(TOOLSET)) $@
358 cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
359
360 quiet_cmd_cxx = CXX($(TOOLSET)) $@
361 cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
362 %(extra_commands)s
363 quiet_cmd_touch = TOUCH $@
364 cmd_touch = touch $@
365
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 "$<" "$@")
369
370 %(link_commands)s
371 """
372
373 r"""
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))'
388 """
389 """
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))))
404
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 $|,$?))
411
412 # Helper that executes all postbuilds until one fails.
413 define do_postbuilds
414   @E=0;\\
415   for p in $(POSTBUILDS); do\\
416     eval $$p;\\
417     E=$$?;\\
418     if [ $$E -ne 0 ]; then\\
419       break;\\
420     fi;\\
421   done;\\
422   if [ $$E -ne 0 ]; then\\
423     rm -rf "$@";\\
424     exit $$E;\\
425   fi
426 endef
427
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 + \
435                                      """ characters.
436 define do_cmd
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))),
441     @$(cmd_$(1))
442     @echo "  $(quiet_cmd_$(1)): Finished",
443     @$(cmd_$(1))
444   )
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)
449   )
450 )
451 endef
452
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
456 %(default_target)s:
457
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.
461 %%.d: ;
462
463 # Use FORCE_DO_CMD to force a target to run.  Should be coupled with
464 # do_cmd.
465 .PHONY: FORCE_DO_CMD
466 FORCE_DO_CMD:
467
468 """)
469
470 SHARED_HEADER_MAC_COMMANDS = """
471 quiet_cmd_objc = CXX($(TOOLSET)) $@
472 cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
473
474 quiet_cmd_objcxx = CXX($(TOOLSET)) $@
475 cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
476
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 $@ $<
486
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
489 # already.
490 quiet_cmd_mac_tool = MACTOOL $(4) $<
491 cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
492
493 quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
494 cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
495
496 quiet_cmd_infoplist = INFOPLIST $@
497 cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
498 """
499
500
501 def WriteRootHeaderSuffixRules(writer):
502   extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower)
503
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])
508
509   writer.write('\n# Try building from generated source, too.\n')
510   for ext in extensions:
511     writer.write(
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])
514   writer.write('\n')
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])
518   writer.write('\n')
519
520
521 SHARED_HEADER_SUFFIX_RULES_COMMENT1 = ("""\
522 # Suffix rules, putting all outputs into $(obj).
523 """)
524
525
526 SHARED_HEADER_SUFFIX_RULES_COMMENT2 = ("""\
527 # Try building from generated source, too.
528 """)
529
530
531 SHARED_FOOTER = """\
532 # "all" is a concatenation of the "all" targets from all the included
533 # sub-makefiles. This is just here to clarify.
534 all:
535
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))
539 ifneq ($(d_files),)
540   include $(d_files)
541 endif
542 """
543
544 header = """\
545 # This file is generated by gyp; do not edit.
546
547 """
548
549 # Maps every compilable file extension to the do_cmd that compiles it.
550 COMPILABLE_EXTENSIONS = {
551   '.c': 'cc',
552   '.cc': 'cxx',
553   '.cpp': 'cxx',
554   '.cxx': 'cxx',
555   '.s': 'cc',
556   '.S': 'cc',
557 }
558
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):
562     if res:
563       return True
564   return False
565
566
567 def Linkable(filename):
568   """Return true if the file is linkable (should be on the link line)."""
569   return filename.endswith('.o')
570
571
572 def Target(filename):
573   """Translate a compilable filename to its .o target."""
574   return os.path.splitext(filename)[0] + '.o'
575
576
577 def EscapeShellArgument(s):
578   """Quotes an argument so that it will be interpreted literally by a POSIX
579      shell. Taken from
580      http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
581      """
582   return "'" + s.replace("'", "'\\''") + "'"
583
584
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('$', '$$')
589
590
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'\#')
598
599
600 def QuoteIfNecessary(string):
601   """TODO: Should this ideally be replaced with one or more of the above
602      functions?"""
603   if '"' in string:
604     string = '"' + string.replace('"', '\\"') + '"'
605   return string
606
607
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)
611
612
613 srcdir_prefix = ''
614 def Sourceify(path):
615   """Convert a path to its source directory form."""
616   if '$(' in path:
617     return path
618   if os.path.isabs(path):
619     return path
620   return srcdir_prefix + path
621
622
623 def QuoteSpaces(s, quote=r'\ '):
624   return s.replace(' ', quote)
625
626
627 # Map from qualified target to path to output.
628 target_outputs = {}
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 = {}
634
635
636 class MakefileWriter:
637   """MakefileWriter packages up the writing of one target-specific foobar.mk.
638
639   Its only real entry point is Write(), and is mostly used for namespacing.
640   """
641
642   def __init__(self, generator_flags, flavor):
643     self.generator_flags = generator_flags
644     self.flavor = flavor
645
646     self.suffix_rules_srcdir = {}
647     self.suffix_rules_objdir1 = {}
648     self.suffix_rules_objdir2 = {}
649
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
655         @$(call do_cmd,%s,1)
656 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
657
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
661         @$(call do_cmd,%s,1)
662 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
663       self.suffix_rules_objdir2.update({ext: ("""\
664 $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(obj)/%%%s FORCE_DO_CMD
665         @$(call do_cmd,%s,1)
666 """ % (ext, COMPILABLE_EXTENSIONS[ext]))})
667
668
669   def Write(self, qualified_target, base_path, output_filename, spec, configs,
670             part_of_all):
671     """The main entry point: writes a .mk file for a single target.
672
673     Arguments:
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'
680     """
681     ensure_directory_exists(output_filename)
682
683     self.fp = open(output_filename, 'w')
684
685     self.fp.write(header)
686
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']
692
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)
696     else:
697       self.xcode_settings = None
698
699     deps, link_deps = self.ComputeDeps(spec)
700
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.
704     extra_outputs = []
705     extra_sources = []
706     extra_link_deps = []
707     extra_mac_bundle_resources = []
708     mac_bundle_deps = []
709
710     if self.is_mac_bundle:
711       self.output = self.ComputeMacBundleOutput(spec)
712       self.output_binary = self.ComputeMacBundleBinaryOutput(spec)
713     else:
714       self.output = self.output_binary = self.ComputeOutput(spec)
715
716     self.is_standalone_static_library = bool(
717         spec.get('standalone_static_library', 0))
718     self._INSTALLABLE_TARGETS = ('executable', 'loadable_module',
719                                  'shared_library')
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()
724     else:
725       self.alias = self.output
726       install_path = self.output
727
728     self.WriteLn("TOOLSET := " + self.toolset)
729     self.WriteLn("TARGET := " + self.target)
730
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)
735
736     # Rules must be early like actions.
737     if 'rules' in spec:
738       self.WriteRules(spec['rules'], extra_sources, extra_outputs,
739                       extra_mac_bundle_resources, part_of_all)
740
741     if 'copies' in spec:
742       self.WriteCopies(spec['copies'], extra_outputs, part_of_all)
743
744     # Bundle resources.
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)
750
751     # Sources.
752     all_sources = spec.get('sources', []) + extra_sources
753     if all_sources:
754       self.WriteSources(
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)),
759               self.Pchify))
760       sources = filter(Compilable, all_sources)
761       if 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')
775
776         # Add dependency from bundle to bundle binary.
777         if self.is_mac_bundle:
778           mac_bundle_deps.append(self.output_binary)
779
780     self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps,
781                      mac_bundle_deps, extra_outputs, part_of_all)
782
783     # Update global list of target outputs, used in dependency tracking.
784     target_outputs[qualified_target] = install_path
785
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
789
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)
794
795     self.fp.close()
796
797
798   def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
799     """Write a "sub-project" Makefile.
800
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).
803
804     Arguments:
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
809     """
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')
818     self.WriteLn('all:')
819     if makefile_path:
820       makefile_path = ' -C ' + makefile_path
821     self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
822     self.fp.close()
823
824
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.
828
829     extra_sources: a list that will be filled in with newly generated source
830                    files, if any
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
833                    actions)
834     part_of_all: flag indicating this target is part of 'all'
835     """
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']
843
844       # Build up a list of outputs.
845       # Collect the output dirs we'll need.
846       dirs = set()
847       for out in outputs:
848         dir = os.path.split(out)[0]
849         if dir:
850           dirs.add(dir)
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
855
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']))
864       else:
865         self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name))
866       if len(dirs) > 0:
867         command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
868
869       cd_action = 'cd %s; ' % Sourceify(self.path or '.')
870
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)
876
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
881       # target libraries.
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; '
886                    '%s%s'
887                    % (name, cd_action, command))
888       self.WriteLn()
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())
901
902       for input in inputs:
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)
908
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]
912
913       self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)),
914                       part_of_all=part_of_all, command=name)
915
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)
920       self.WriteLn()
921
922     self.WriteLn()
923
924
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.
928
929     extra_sources: a list that will be filled in with newly generated source
930                    files, if any
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'
934     """
935     env = self.GetSortedXcodeEnv()
936     for rule in rules:
937       name = StringToMakefileVariable('%s_%s' % (self.qualified_target,
938                                                  rule['rule_name']))
939       count = 0
940       self.WriteLn('### Generated for rule %s:' % name)
941
942       all_outputs = []
943
944       for rule_source in rule.get('rule_sources', []):
945         dirs = set()
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)
949
950         outputs = [self.ExpandInputRoot(out, rule_source_root,
951                                         rule_source_dirname)
952                    for out in rule['outputs']]
953
954         for out in outputs:
955           dir = os.path.dirname(out)
956           if dir:
957             dirs.add(dir)
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)]
965
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
972           # amount of pain.
973           actions += ['@touch --no-create $@']
974
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]
978
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
990         # before checking.
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))
997
998         action = [self.ExpandInputRoot(ac, rule_source_root,
999                                        rule_source_dirname)
1000                   for ac in rule['action']]
1001         mkdirs = ''
1002         if len(dirs) > 0:
1003           mkdirs = 'mkdir -p %s; ' % ' '.join(dirs)
1004         cd_action = 'cd %s; ' % Sourceify(self.path or '.')
1005
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)
1016
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
1021         # target libraries.
1022         # TODO(piman): when everything is cross-compile safe, remove lib.target
1023         self.WriteLn(
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" % {
1028           'action': action,
1029           'cd_action': cd_action,
1030           'count': count,
1031           'mkdirs': mkdirs,
1032           'name': name,
1033         })
1034         self.WriteLn(
1035             'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % {
1036           'count': count,
1037           'name': name,
1038         })
1039         self.WriteLn()
1040         count += 1
1041
1042       outputs_variable = 'rule_%s_outputs' % name
1043       self.WriteList(all_outputs, outputs_variable)
1044       extra_outputs.append('$(%s)' % outputs_variable)
1045
1046       self.WriteLn('### Finished generating for rule: %s' % name)
1047       self.WriteLn()
1048     self.WriteLn('### Finished generating for all rules')
1049     self.WriteLn('')
1050
1051
1052   def WriteCopies(self, copies, extra_outputs, part_of_all):
1053     """Write Makefile code for any 'copies' from the gyp input.
1054
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'
1058     """
1059     self.WriteLn('### Generated for copy rule.')
1060
1061     variable = StringToMakefileVariable(self.qualified_target + '_copies')
1062     outputs = []
1063     for copy in 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'],
1069                                                         filename)))
1070
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)
1087     self.WriteLn()
1088
1089
1090   def WriteMacBundleResources(self, resources, bundle_deps):
1091     """Writes Makefile code for 'mac_bundle_resources'."""
1092     self.WriteLn('### Generated for mac_bundle_resources')
1093
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',
1098                       part_of_all=True)
1099       bundle_deps.append(output)
1100
1101
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)))
1107     if not info_plist:
1108       return
1109     if defines:
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',
1125                     part_of_all=True)
1126     bundle_deps.append(out)
1127
1128
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.
1134
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'
1141     """
1142
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)
1148
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)
1155       else:
1156         cflags = config.get('cflags')
1157         cflags_c = config.get('cflags_c')
1158         cflags_cc = config.get('cflags_cc')
1159
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')
1172       if includes:
1173         includes = map(Sourceify, map(self.Absolutify, includes))
1174       self.WriteList(includes, 'INCS_%s' % configname, prefix='-I')
1175
1176     compilable = filter(Compilable, sources)
1177     objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable)))
1178     self.WriteList(objs, 'OBJS')
1179
1180     for obj in 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)')
1186     self.WriteLn()
1187
1188     # Make sure our dependencies are built first.
1189     if deps:
1190       self.WriteMakeRule(['$(OBJS)'], deps,
1191                          comment = 'Make sure our dependencies are built '
1192                                    'before any of us.',
1193                          order_only = True)
1194
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.
1198     if extra_outputs:
1199       self.WriteMakeRule(['$(OBJS)'], extra_outputs,
1200                          comment = 'Make sure our actions/rules run '
1201                                    'before any of us.',
1202                          order_only = True)
1203
1204     pchdeps = precompiled_header.GetObjDependencies(compilable, objs )
1205     if pchdeps:
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')
1210
1211     if objs:
1212       extra_link_deps.append('$(OBJS)')
1213       self.WriteLn("""\
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))")
1244
1245     self.WritePchTargets(precompiled_header.GetPchBuildCommands())
1246
1247     # If there are any object files in our input file list, link them into our
1248     # output.
1249     extra_link_deps += filter(Linkable, sources)
1250
1251     self.WriteLn()
1252
1253   def WritePchTargets(self, pch_commands):
1254     """Writes make rules to compile prefix headers."""
1255     if not pch_commands:
1256       return
1257
1258     for gch, lang_flag, lang, input in pch_commands:
1259       extra_flags = {
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))',
1264       }[lang]
1265       var_name = {
1266         'c': 'GYP_PCH_CFLAGS',
1267         'cc': 'GYP_PCH_CXXFLAGS',
1268         'm': 'GYP_PCH_OBJCFLAGS',
1269         'mm': 'GYP_PCH_OBJCXXFLAGS',
1270       }[lang]
1271       self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) +
1272                    "$(DEFS_$(BUILDTYPE)) "
1273                    "$(INCS_$(BUILDTYPE)) "
1274                    "$(CFLAGS_$(BUILDTYPE)) " +
1275                    extra_flags)
1276
1277       self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input))
1278       self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang)
1279       self.WriteLn('')
1280       assert ' ' not in gch, (
1281           "Spaces in gch filenames not supported (%s)"  % gch)
1282       self.WriteLn('all_deps += %s' % gch)
1283       self.WriteLn('')
1284
1285
1286   def ComputeOutputBasename(self, spec):
1287     """Return the 'output basename' of a gyp spec.
1288
1289     E.g., the loadable module 'foobar' in directory 'baz' will produce
1290       'libfoobar.so'
1291     """
1292     assert not self.is_mac_bundle
1293
1294     if self.flavor == 'mac' and self.type in (
1295         'static_library', 'executable', 'shared_library', 'loadable_module'):
1296       return self.xcode_settings.GetExecutablePath()
1297
1298     target = spec['target_name']
1299     target_prefix = ''
1300     target_ext = ''
1301     if self.type == 'static_library':
1302       if target[:3] == 'lib':
1303         target = target[3:]
1304       target_prefix = 'lib'
1305       target_ext = '.a'
1306     elif self.type in ('loadable_module', 'shared_library'):
1307       if target[:3] == 'lib':
1308         target = target[3:]
1309       target_prefix = 'lib'
1310       target_ext = '.so'
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)
1316
1317     target_prefix = spec.get('product_prefix', target_prefix)
1318     target = spec.get('product_name', target)
1319     product_ext = spec.get('product_extension')
1320     if product_ext:
1321       target_ext = '.' + product_ext
1322
1323     return target_prefix + target + target_ext
1324
1325
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')
1329
1330
1331   def ComputeOutput(self, spec):
1332     """Return the 'output' (full output path) of a gyp spec.
1333
1334     E.g., the loadable module 'foobar' in directory 'baz' will produce
1335       '$(obj)/baz/libfoobar.so'
1336     """
1337     assert not self.is_mac_bundle
1338
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))
1344
1345
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())
1351
1352
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())
1357
1358
1359   def ComputeDeps(self, spec):
1360     """Compute the dependencies of a gyp spec.
1361
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).
1365     """
1366     deps = []
1367     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))
1379
1380
1381   def WriteDependencyOnExtraOutputs(self, target, extra_outputs):
1382     self.WriteMakeRule([self.output_binary], extra_outputs,
1383                        comment = 'Build our special outputs first.',
1384                        order_only = True)
1385
1386
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.
1390
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'
1395     """
1396
1397     self.WriteLn('### Rules for final target.')
1398
1399     if extra_outputs:
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.'),
1404                          order_only = True)
1405
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)))
1414
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(
1418               configname,
1419               QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build,
1420                                                         self.output))),
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
1425         else:
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/' %
1433                            self.toolset)
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')
1441       if 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))
1450
1451       if self.flavor == 'mac':
1452         self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' %
1453             QuoteSpaces(self.output_binary))
1454
1455     # Postbuild actions. Like actions, but implicitly depend on the target's
1456     # output.
1457     postbuilds = []
1458     if self.flavor == 'mac':
1459       if target_postbuilds:
1460         postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))')
1461       postbuilds.extend(
1462           gyp.xcode_emulation.GetSpecPostbuildCommands(spec))
1463
1464     if postbuilds:
1465       # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),
1466       # so we must output its definition first, since we declare variables
1467       # using ":=".
1468       self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv())
1469
1470       for configname in target_postbuilds:
1471         self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' %
1472             (QuoteSpaces(self.output),
1473              configname,
1474              gyp.common.EncodePOSIXShellList(target_postbuilds[configname])))
1475
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)))
1485
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)
1493
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))
1498
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())
1504
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.
1507       if postbuilds:
1508         self.WriteLn('\t@$(call do_postbuilds)')
1509       postbuilds = []  # Don't write postbuilds for target's output.
1510
1511       # Needed by test/mac/gyptest-rebuild.py.
1512       self.WriteLn('\t@true  # No-op, used by tests')
1513
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))
1520
1521     if postbuilds:
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')
1526
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)
1534       else:
1535         self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all,
1536                         postbuilds=postbuilds)
1537
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)
1546       else:
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)
1562       else:
1563         self.WriteDoCmd(
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)
1570     else:
1571       print "WARNING: no output for", self.type, target
1572
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)
1579       if part_of_all:
1580         self.WriteMakeRule(['all'], [self.target],
1581                            comment = 'Add target alias to "all" target.',
1582                            phony = True)
1583
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'
1594       else:
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)
1603
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)
1617       if part_of_all:
1618         self.WriteMakeRule(['all'], [install_path],
1619                            comment = 'Add %s to "all" target.' % file_desc,
1620                            phony = True)
1621
1622
1623   def WriteList(self, value_list, variable=None, prefix='',
1624                 quoter=QuoteIfNecessary):
1625     """Write a variable definition that is a list of values.
1626
1627     E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
1628          foo = blaha blahb
1629     but in a pretty-printed style.
1630     """
1631     values = ''
1632     if value_list:
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))
1636
1637
1638   def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None,
1639                  postbuilds=False):
1640     """Write a Makefile rule that uses do_cmd.
1641
1642     This makes the outputs dependent on the command line that was run,
1643     as well as support the V= make command line flag.
1644     """
1645     suffix = ''
1646     if postbuilds:
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)],
1651                        comment = comment,
1652                        force = True)
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
1656     # other functions.
1657     outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs]
1658     self.WriteLn('all_deps += %s' % ' '.join(outputs))
1659
1660
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.
1664
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
1675     """
1676     outputs = map(QuoteSpaces, outputs)
1677     inputs = map(QuoteSpaces, inputs)
1678
1679     if comment:
1680       self.WriteLn('# ' + comment)
1681     if phony:
1682       self.WriteLn('.PHONY: ' + ' '.join(outputs))
1683     # TODO(evanm): just make order_only a list of deps instead of these hacks.
1684     if order_only:
1685       order_insert = '| '
1686       pick_output = ' '.join(outputs)
1687     else:
1688       order_insert = ''
1689       pick_output = outputs[0]
1690     if force:
1691       force_append = ' FORCE_DO_CMD'
1692     else:
1693       force_append = ''
1694     if actions:
1695       self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0])
1696     self.WriteLn('%s: %s%s%s' % (pick_output, order_insert, ' '.join(inputs),
1697                                  force_append))
1698     if actions:
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
1703       #   foo bar: baz
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
1707       # the files.
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
1711       # the action.
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:])))
1721     self.WriteLn()
1722
1723
1724   def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps):
1725     """Write a set of LOCAL_XXX definitions for Android NDK.
1726
1727     These variable definitions will be used by Android NDK but do nothing for
1728     non-Android applications.
1729
1730     Arguments:
1731       module_name: Android NDK module name, which must be unique among all
1732           module names.
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.
1736     """
1737     if self.type not in ('executable', 'shared_library', 'static_library'):
1738       return
1739
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
1747                  # sources.
1748                  '$(CFLAGS_C_$(BUILDTYPE)) '
1749                  # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while
1750                  # LOCAL_C_INCLUDES does not expect it.  So put it in
1751                  # LOCAL_CFLAGS.
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)')
1757
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]
1763       if ext in cpp_ext:
1764         cpp_ext[ext] += 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)
1768
1769     self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)),
1770                    'LOCAL_SRC_FILES')
1771
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):
1775       modules = []
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)])
1780       return modules
1781
1782     # Retrieve the default value of 'SHARED_LIB_SUFFIX'
1783     params = {'flavor': 'linux'}
1784     default_variables = {}
1785     CalculateVariables(default_variables, params)
1786
1787     self.WriteList(
1788         DepsToModules(link_deps,
1789                       generator_default_variables['SHARED_LIB_PREFIX'],
1790                       default_variables['SHARED_LIB_SUFFIX']),
1791         'LOCAL_SHARED_LIBRARIES')
1792     self.WriteList(
1793         DepsToModules(link_deps,
1794                       generator_default_variables['STATIC_LIB_PREFIX'],
1795                       generator_default_variables['STATIC_LIB_SUFFIX']),
1796         'LOCAL_STATIC_LIBRARIES')
1797
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)')
1804     self.WriteLn()
1805
1806
1807   def WriteLn(self, text=''):
1808     self.fp.write(text + '\n')
1809
1810
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)
1816
1817
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})
1827
1828
1829   def WriteSortedXcodeEnv(self, target, env):
1830     for k, v in env:
1831       # For
1832       #  foo := a\ b
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))
1838
1839
1840   def Objectify(self, path):
1841     """Convert a path to its output directory form."""
1842     if '$(' in path:
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)
1846     return path
1847
1848
1849   def Pchify(self, path, lang):
1850     """Convert a prefix header path to its output directory form."""
1851     path = self.Absolutify(path)
1852     if '$(' in path:
1853       path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' %
1854                           (self.toolset, lang))
1855       return path
1856     return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
1857
1858
1859   def Absolutify(self, path):
1860     """Convert a subdirectory-relative path into a base-relative path.
1861     Skips over paths that contain variables."""
1862     if '$(' in path:
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))
1868
1869
1870   def ExpandInputRoot(self, template, expansion, dirname):
1871     if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template:
1872       return template
1873     path = template % {
1874         'INPUT_ROOT': expansion,
1875         'INPUT_DIRNAME': dirname,
1876         }
1877     return path
1878
1879
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
1890
1891
1892 def WriteAutoRegenerationRule(params, root_makefile, makefile_name,
1893                               build_files):
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']]
1898
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)
1903
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) +
1914                      build_files_args)})
1915
1916
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)
1926
1927
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')
1935
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),
1943                                         options.depth)
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
1951
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']
1961       break
1962   if not default_configuration:
1963     default_configuration = 'Default'
1964
1965   srcdir = '.'
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)/'
1973
1974   flock_command= 'flock'
1975   header_params = {
1976       'default_target': default_target,
1977       'builddir': builddir_name,
1978       'default_configuration': default_configuration,
1979       'flock': flock_command,
1980       'flock_index': 1,
1981       'link_commands': LINK_COMMANDS_LINUX,
1982       'extra_commands': '',
1983       'srcdir': srcdir,
1984     }
1985   if flavor == 'mac':
1986     flock_command = './gyp-mac-tool flock'
1987     header_params.update({
1988         'flock': flock_command,
1989         'flock_index': 2,
1990         'link_commands': LINK_COMMANDS_MAC,
1991         'extra_commands': SHARED_HEADER_MAC_COMMANDS,
1992     })
1993   elif flavor == 'android':
1994     header_params.update({
1995         'link_commands': LINK_COMMANDS_ANDROID,
1996     })
1997   elif flavor == 'solaris':
1998     header_params.update({
1999         'flock': './gyp-flock-tool flock',
2000         'flock_index': 2,
2001     })
2002   elif flavor == 'freebsd':
2003     # Note: OpenBSD has sysutils/flock. lockf seems to be FreeBSD specific.
2004     header_params.update({
2005         'flock': 'lockf',
2006     })
2007   elif flavor == 'aix':
2008     header_params.update({
2009         'link_commands': LINK_COMMANDS_AIX,
2010         'flock': './gyp-flock-tool flock',
2011         'flock_index': 2,
2012     })
2013
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)'),
2023   })
2024
2025   build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
2026   make_global_settings_array = data[build_file].get('make_global_settings', [])
2027   wrappers = {}
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):
2035       continue
2036     if value[0] != '$':
2037       value = '$(abspath %s)' % value
2038     wrapper = wrappers.get(key)
2039     if wrapper:
2040       value = '%s %s' % (wrapper, value)
2041       del wrappers[key]
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'
2050     else:
2051       make_global_settings += '%s ?= %s\n' % (key, value)
2052   # TODO(ukai): define cmd when only wrapper is specified in
2053   # make_global_settings.
2054
2055   header_params['make_global_settings'] = make_global_settings
2056
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'
2066         '\n')
2067   for toolset in toolsets:
2068     root_makefile.write('TOOLSET := %s\n' % toolset)
2069     WriteRootHeaderSuffixRules(root_makefile)
2070
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)
2074
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)
2080
2081   build_files = set()
2082   include_list = set()
2083   for qualified_target in target_list:
2084     build_file, target, toolset = gyp.common.ParseQualifiedTarget(
2085         qualified_target)
2086
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.")
2090
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
2096       # to the root dir.
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)
2106       else:
2107         build_files.add(relative_include_file)
2108
2109     base_path, output_file = CalculateMakefilePath(build_file,
2110         target + '.' + toolset + options.suffix + '.mk')
2111
2112     spec = target_dicts[qualified_target]
2113     configs = spec['configurations']
2114
2115     if flavor == 'mac':
2116       gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
2117
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)
2121
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)
2127
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.
2139     if not gyp_targets:
2140       continue
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,
2146                         builddir_name)
2147
2148
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
2155     # NO_LOAD.
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')
2163
2164   if (not generator_flags.get('standalone')
2165       and generator_flags.get('auto_regeneration', True)):
2166     WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files)
2167
2168   root_makefile.write(SHARED_FOOTER)
2169
2170   root_makefile.close()