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