1 # Copyright (c) 2012 Google Inc. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
7 # This generates makefiles suitable for inclusion into the Android build system
8 # via an Android.mk file. It is based on make.py, the standard makefile
11 # The code below generates a separate .mk file for each target, but
12 # all are sourced by the top-level GypAndroid.mk. This means that all
13 # variables in .mk-files clobber one another, and furthermore that any
14 # variables set potentially clash with other Android build system variables.
15 # Try to avoid setting global variables where possible.
19 import gyp.generator.make as make # Reuse global functions from make backend.
24 generator_default_variables = {
26 'EXECUTABLE_PREFIX': '',
27 'EXECUTABLE_SUFFIX': '',
28 'STATIC_LIB_PREFIX': 'lib',
29 'SHARED_LIB_PREFIX': 'lib',
30 'STATIC_LIB_SUFFIX': '.a',
31 'SHARED_LIB_SUFFIX': '.so',
32 'INTERMEDIATE_DIR': '$(gyp_intermediate_dir)',
33 'SHARED_INTERMEDIATE_DIR': '$(gyp_shared_intermediate_dir)',
34 'PRODUCT_DIR': '$(gyp_shared_intermediate_dir)',
35 'SHARED_LIB_DIR': '$(builddir)/lib.$(TOOLSET)',
36 'LIB_DIR': '$(obj).$(TOOLSET)',
37 'RULE_INPUT_ROOT': '%(INPUT_ROOT)s', # This gets expanded by Python.
38 'RULE_INPUT_DIRNAME': '%(INPUT_DIRNAME)s', # This gets expanded by Python.
39 'RULE_INPUT_PATH': '$(RULE_SOURCES)',
40 'RULE_INPUT_EXT': '$(suffix $<)',
41 'RULE_INPUT_NAME': '$(notdir $<)',
42 'CONFIGURATION_NAME': '$(GYP_CONFIGURATION)',
45 # Make supports multiple toolsets
46 generator_supports_multiple_toolsets = True
49 # Generator-specific gyp specs.
50 generator_additional_non_configuration_keys = [
51 # Boolean to declare that this target does not want its name mangled.
52 'android_unmangled_name',
53 # Map of android build system variables to set.
54 'aosp_build_settings',
56 generator_additional_path_sections = []
57 generator_extra_sources_for_rules = []
60 ALL_MODULES_FOOTER = """\
61 # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from
62 # all the included sub-makefiles. This is just here to clarify.
67 # This file is generated by gyp; do not edit.
71 # Map gyp target types to Android module classes.
73 'static_library': 'STATIC_LIBRARIES',
74 'shared_library': 'SHARED_LIBRARIES',
75 'executable': 'EXECUTABLES',
79 def IsCPPExtension(ext):
80 return make.COMPILABLE_EXTENSIONS.get(ext) == 'cxx'
84 """Convert a path to its source directory form. The Android backend does not
85 support options.generator_output, so this function is a noop."""
89 # Map from qualified target to path to output.
90 # For Android, the target of these maps is a tuple ('static', 'modulename'),
91 # ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string,
92 # since we link by module.
94 # Map from qualified target to any linkable output. A subset
95 # of target_outputs. E.g. when mybinary depends on liba, we want to
96 # include liba in the linker line; when otherbinary depends on
97 # mybinary, we just want to build mybinary first.
101 class AndroidMkWriter(object):
102 """AndroidMkWriter packages up the writing of one target-specific Android.mk.
104 Its only real entry point is Write(), and is mostly used for namespacing.
107 def __init__(self, android_top_dir):
108 self.android_top_dir = android_top_dir
110 def Write(self, qualified_target, relative_target, base_path, output_filename,
111 spec, configs, part_of_all, write_alias_target):
112 """The main entry point: writes a .mk file for a single target.
115 qualified_target: target we're generating
116 relative_target: qualified target name relative to the root
117 base_path: path relative to source root we're building in, used to resolve
118 target-relative paths
119 output_filename: output .mk file name to write
120 spec, configs: gyp info
121 part_of_all: flag indicating this target is part of 'all'
122 write_alias_target: flag indicating whether to create short aliases for
125 gyp.common.EnsureDirExists(output_filename)
127 self.fp = open(output_filename, 'w')
129 self.fp.write(header)
131 self.qualified_target = qualified_target
132 self.relative_target = relative_target
133 self.path = base_path
134 self.target = spec['target_name']
135 self.type = spec['type']
136 self.toolset = spec['toolset']
138 deps, link_deps = self.ComputeDeps(spec)
140 # Some of the generation below can add extra output, sources, or
141 # link dependencies. All of the out params of the functions that
142 # follow use names like extra_foo.
146 self.android_class = MODULE_CLASSES.get(self.type, 'GYP')
147 self.android_module = self.ComputeAndroidModule(spec)
148 (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec)
149 self.output = self.output_binary = self.ComputeOutput(spec)
152 self.WriteLn('include $(CLEAR_VARS)\n')
154 # Module class and name.
155 self.WriteLn('LOCAL_MODULE_CLASS := ' + self.android_class)
156 self.WriteLn('LOCAL_MODULE := ' + self.android_module)
157 # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE.
158 # The library module classes fail if the stem is set. ComputeOutputParts
159 # makes sure that stem == modulename in these cases.
160 if self.android_stem != self.android_module:
161 self.WriteLn('LOCAL_MODULE_STEM := ' + self.android_stem)
162 self.WriteLn('LOCAL_MODULE_SUFFIX := ' + self.android_suffix)
163 if self.toolset == 'host':
164 self.WriteLn('LOCAL_IS_HOST_MODULE := true')
165 self.WriteLn('LOCAL_MULTILIB := $(GYP_HOST_MULTILIB)')
167 self.WriteLn('LOCAL_MODULE_TARGET_ARCH := '
168 '$(TARGET_$(GYP_VAR_PREFIX)ARCH)')
170 # Grab output directories; needed for Actions and Rules.
171 if self.toolset == 'host':
172 self.WriteLn('gyp_intermediate_dir := '
173 '$(call local-intermediates-dir,,$(GYP_HOST_VAR_PREFIX))')
175 self.WriteLn('gyp_intermediate_dir := '
176 '$(call local-intermediates-dir,,$(GYP_VAR_PREFIX))')
177 self.WriteLn('gyp_shared_intermediate_dir := '
178 '$(call intermediates-dir-for,GYP,shared,,,$(GYP_VAR_PREFIX))')
181 # List files this target depends on so that actions/rules/copies/sources
182 # can depend on the list.
183 # TODO: doesn't pull in things through transitive link deps; needed?
184 target_dependencies = [x[1] for x in deps if x[0] == 'path']
185 self.WriteLn('# Make sure our deps are built first.')
186 self.WriteList(target_dependencies, 'GYP_TARGET_DEPENDENCIES',
189 # Actions must come first, since they can generate more OBJs for use below.
190 if 'actions' in spec:
191 self.WriteActions(spec['actions'], extra_sources, extra_outputs)
193 # Rules must be early like actions.
195 self.WriteRules(spec['rules'], extra_sources, extra_outputs)
198 self.WriteCopies(spec['copies'], extra_outputs)
200 # GYP generated outputs.
201 self.WriteList(extra_outputs, 'GYP_GENERATED_OUTPUTS', local_pathify=True)
203 # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend
204 # on both our dependency targets and our generated files.
205 self.WriteLn('# Make sure our deps and generated files are built first.')
206 self.WriteLn('LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) '
207 '$(GYP_GENERATED_OUTPUTS)')
211 if spec.get('sources', []) or extra_sources:
212 self.WriteSources(spec, configs, extra_sources)
214 self.WriteTarget(spec, configs, deps, link_deps, part_of_all,
217 # Update global list of target outputs, used in dependency tracking.
218 target_outputs[qualified_target] = ('path', self.output_binary)
220 # Update global list of link dependencies.
221 if self.type == 'static_library':
222 target_link_deps[qualified_target] = ('static', self.android_module)
223 elif self.type == 'shared_library':
224 target_link_deps[qualified_target] = ('shared', self.android_module)
227 return self.android_module
230 def WriteActions(self, actions, extra_sources, extra_outputs):
231 """Write Makefile code for any 'actions' from the gyp input.
233 extra_sources: a list that will be filled in with newly generated source
235 extra_outputs: a list that will be filled in with any outputs of these
236 actions (used to make other pieces dependent on these
239 for action in actions:
240 name = make.StringToMakefileVariable('%s_%s' % (self.relative_target,
241 action['action_name']))
242 self.WriteLn('### Rules for action "%s":' % action['action_name'])
243 inputs = action['inputs']
244 outputs = action['outputs']
246 # Build up a list of outputs.
247 # Collect the output dirs we'll need.
250 if not out.startswith('$'):
251 print ('WARNING: Action for target "%s" writes output to local path '
252 '"%s".' % (self.target, out))
253 dir = os.path.split(out)[0]
256 if int(action.get('process_outputs_as_sources', False)):
257 extra_sources += outputs
259 # Prepare the actual command.
260 command = gyp.common.EncodePOSIXShellList(action['action'])
261 if 'message' in action:
262 quiet_cmd = 'Gyp action: %s ($@)' % action['message']
264 quiet_cmd = 'Gyp action: %s ($@)' % name
266 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
268 cd_action = 'cd $(gyp_local_path)/%s; ' % self.path
269 command = cd_action + command
271 # The makefile rules are all relative to the top dir, but the gyp actions
272 # are defined relative to their containing dir. This replaces the gyp_*
273 # variables for the action rule with an absolute version so that the
274 # output goes in the right place.
275 # Only write the gyp_* rules for the "primary" output (:1);
276 # it's superfluous for the "extra outputs", and this avoids accidentally
277 # writing duplicate dummy rules for those outputs.
278 main_output = make.QuoteSpaces(self.LocalPathify(outputs[0]))
279 self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output)
280 self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output)
281 self.WriteLn('%s: gyp_intermediate_dir := '
282 '$(abspath $(gyp_intermediate_dir))' % main_output)
283 self.WriteLn('%s: gyp_shared_intermediate_dir := '
284 '$(abspath $(gyp_shared_intermediate_dir))' % main_output)
286 # Android's envsetup.sh adds a number of directories to the path including
287 # the built host binary directory. This causes actions/rules invoked by
288 # gyp to sometimes use these instead of system versions, e.g. bison.
289 # The built host binaries may not be suitable, and can cause errors.
290 # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable
292 self.WriteLn('%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))'
295 # Don't allow spaces in input/output filenames, but make an exception for
296 # filenames which start with '$(' since it's okay for there to be spaces
297 # inside of make function/macro invocations.
299 if not input.startswith('$(') and ' ' in input:
300 raise gyp.common.GypError(
301 'Action input filename "%s" in target %s contains a space' %
302 (input, self.target))
303 for output in outputs:
304 if not output.startswith('$(') and ' ' in output:
305 raise gyp.common.GypError(
306 'Action output filename "%s" in target %s contains a space' %
307 (output, self.target))
309 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' %
310 (main_output, ' '.join(map(self.LocalPathify, inputs))))
311 self.WriteLn('\t@echo "%s"' % quiet_cmd)
312 self.WriteLn('\t$(hide)%s\n' % command)
313 for output in outputs[1:]:
314 # Make each output depend on the main output, with an empty command
315 # to force make to notice that the mtime has changed.
316 self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output))
318 extra_outputs += outputs
324 def WriteRules(self, rules, extra_sources, extra_outputs):
325 """Write Makefile code for any 'rules' from the gyp input.
327 extra_sources: a list that will be filled in with newly generated source
329 extra_outputs: a list that will be filled in with any outputs of these
330 rules (used to make other pieces dependent on these rules)
336 if len(rule.get('rule_sources', [])) == 0:
338 name = make.StringToMakefileVariable('%s_%s' % (self.relative_target,
340 self.WriteLn('\n### Generated for rule "%s":' % name)
341 self.WriteLn('# "%s":' % rule)
343 inputs = rule.get('inputs')
344 for rule_source in rule.get('rule_sources', []):
345 (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
346 (rule_source_root, rule_source_ext) = \
347 os.path.splitext(rule_source_basename)
349 outputs = [self.ExpandInputRoot(out, rule_source_root,
351 for out in rule['outputs']]
355 if not out.startswith('$'):
356 print ('WARNING: Rule for target %s writes output to local path %s'
357 % (self.target, out))
358 dir = os.path.dirname(out)
361 extra_outputs += outputs
362 if int(rule.get('process_outputs_as_sources', False)):
363 extra_sources.extend(outputs)
366 for component in rule['action']:
367 component = self.ExpandInputRoot(component, rule_source_root,
369 if '$(RULE_SOURCES)' in component:
370 component = component.replace('$(RULE_SOURCES)',
372 components.append(component)
374 command = gyp.common.EncodePOSIXShellList(components)
375 cd_action = 'cd $(gyp_local_path)/%s; ' % self.path
376 command = cd_action + command
378 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
380 # We set up a rule to build the first output, and then set up
381 # a rule for each additional output to depend on the first.
382 outputs = map(self.LocalPathify, outputs)
383 main_output = outputs[0]
384 self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output)
385 self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output)
386 self.WriteLn('%s: gyp_intermediate_dir := '
387 '$(abspath $(gyp_intermediate_dir))' % main_output)
388 self.WriteLn('%s: gyp_shared_intermediate_dir := '
389 '$(abspath $(gyp_shared_intermediate_dir))' % main_output)
391 # See explanation in WriteActions.
392 self.WriteLn('%s: export PATH := '
393 '$(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output)
395 main_output_deps = self.LocalPathify(rule_source)
397 main_output_deps += ' '
398 main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs])
400 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' %
401 (main_output, main_output_deps))
402 self.WriteLn('\t%s\n' % command)
403 for output in outputs[1:]:
404 # Make each output depend on the main output, with an empty command
405 # to force make to notice that the mtime has changed.
406 self.WriteLn('%s: %s ;' % (output, main_output))
412 def WriteCopies(self, copies, extra_outputs):
413 """Write Makefile code for any 'copies' from the gyp input.
415 extra_outputs: a list that will be filled in with any outputs of this action
416 (used to make other pieces dependent on this action)
418 self.WriteLn('### Generated for copy rule.')
420 variable = make.StringToMakefileVariable(self.relative_target + '_copies')
423 for path in copy['files']:
424 # The Android build system does not allow generation of files into the
425 # source tree. The destination should start with a variable, which will
426 # typically be $(gyp_intermediate_dir) or
427 # $(gyp_shared_intermediate_dir). Note that we can't use an assertion
428 # because some of the gyp tests depend on this.
429 if not copy['destination'].startswith('$'):
430 print ('WARNING: Copy rule for target %s writes output to '
431 'local path %s' % (self.target, copy['destination']))
433 # LocalPathify() calls normpath, stripping trailing slashes.
434 path = Sourceify(self.LocalPathify(path))
435 filename = os.path.split(path)[1]
436 output = Sourceify(self.LocalPathify(os.path.join(copy['destination'],
439 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' %
441 self.WriteLn('\t@echo Copying: $@')
442 self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
443 self.WriteLn('\t$(hide) $(ACP) -rpf $< $@')
445 outputs.append(output)
446 self.WriteLn('%s = %s' % (variable,
447 ' '.join(map(make.QuoteSpaces, outputs))))
448 extra_outputs.append('$(%s)' % variable)
452 def WriteSourceFlags(self, spec, configs):
453 """Write out the flags and include paths used to compile source files for
457 spec, configs: input from gyp.
459 for configname, config in sorted(configs.iteritems()):
460 extracted_includes = []
462 self.WriteLn('\n# Flags passed to both C and C++ files.')
463 cflags, includes_from_cflags = self.ExtractIncludesFromCFlags(
464 config.get('cflags', []) + config.get('cflags_c', []))
465 extracted_includes.extend(includes_from_cflags)
466 self.WriteList(cflags, 'MY_CFLAGS_%s' % configname)
468 self.WriteList(config.get('defines'), 'MY_DEFS_%s' % configname,
469 prefix='-D', quoter=make.EscapeCppDefine)
471 self.WriteLn('\n# Include paths placed before CFLAGS/CPPFLAGS')
472 includes = list(config.get('include_dirs', []))
473 includes.extend(extracted_includes)
474 includes = map(Sourceify, map(self.LocalPathify, includes))
475 includes = self.NormalizeIncludePaths(includes)
476 self.WriteList(includes, 'LOCAL_C_INCLUDES_%s' % configname)
478 self.WriteLn('\n# Flags passed to only C++ (and not C) files.')
479 self.WriteList(config.get('cflags_cc'), 'LOCAL_CPPFLAGS_%s' % configname)
481 self.WriteLn('\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) '
482 '$(MY_DEFS_$(GYP_CONFIGURATION))')
483 # Undefine ANDROID for host modules
484 # TODO: the source code should not use macro ANDROID to tell if it's host
486 if self.toolset == 'host':
487 self.WriteLn('# Undefine ANDROID for host modules')
488 self.WriteLn('LOCAL_CFLAGS += -UANDROID')
489 self.WriteLn('LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) '
490 '$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))')
491 self.WriteLn('LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))')
492 # Android uses separate flags for assembly file invocations, but gyp expects
493 # the same CFLAGS to be applied:
494 self.WriteLn('LOCAL_ASFLAGS := $(LOCAL_CFLAGS)')
497 def WriteSources(self, spec, configs, extra_sources):
498 """Write Makefile code for any 'sources' from the gyp input.
499 These are source files necessary to build the current target.
500 We need to handle shared_intermediate directory source files as
501 a special case by copying them to the intermediate directory and
502 treating them as a genereated sources. Otherwise the Android build
503 rules won't pick them up.
506 spec, configs: input from gyp.
507 extra_sources: Sources generated from Actions or Rules.
509 sources = filter(make.Compilable, spec.get('sources', []))
510 generated_not_sources = [x for x in extra_sources if not make.Compilable(x)]
511 extra_sources = filter(make.Compilable, extra_sources)
513 # Determine and output the C++ extension used by these sources.
514 # We simply find the first C++ file and use that extension.
515 all_sources = sources + extra_sources
516 local_cpp_extension = '.cpp'
517 for source in all_sources:
518 (root, ext) = os.path.splitext(source)
519 if IsCPPExtension(ext):
520 local_cpp_extension = ext
522 if local_cpp_extension != '.cpp':
523 self.WriteLn('LOCAL_CPP_EXTENSION := %s' % local_cpp_extension)
525 # We need to move any non-generated sources that are coming from the
526 # shared intermediate directory out of LOCAL_SRC_FILES and put them
527 # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files
528 # that don't match our local_cpp_extension, since Android will only
529 # generate Makefile rules for a single LOCAL_CPP_EXTENSION.
531 for source in sources:
532 (root, ext) = os.path.splitext(source)
533 if '$(gyp_shared_intermediate_dir)' in source:
534 extra_sources.append(source)
535 elif '$(gyp_intermediate_dir)' in source:
536 extra_sources.append(source)
537 elif IsCPPExtension(ext) and ext != local_cpp_extension:
538 extra_sources.append(source)
540 local_files.append(os.path.normpath(os.path.join(self.path, source)))
542 # For any generated source, if it is coming from the shared intermediate
543 # directory then we add a Make rule to copy them to the local intermediate
544 # directory first. This is because the Android LOCAL_GENERATED_SOURCES
545 # must be in the local module intermediate directory for the compile rules
546 # to work properly. If the file has the wrong C++ extension, then we add
547 # a rule to copy that to intermediates and use the new version.
548 final_generated_sources = []
549 # If a source file gets copied, we still need to add the orginal source
550 # directory as header search path, for GCC searches headers in the
551 # directory that contains the source file by default.
553 for source in extra_sources:
555 if not '$(gyp_intermediate_dir)/' in local_file:
556 basename = os.path.basename(local_file)
557 local_file = '$(gyp_intermediate_dir)/' + basename
558 (root, ext) = os.path.splitext(local_file)
559 if IsCPPExtension(ext) and ext != local_cpp_extension:
560 local_file = root + local_cpp_extension
561 if local_file != source:
562 self.WriteLn('%s: %s' % (local_file, self.LocalPathify(source)))
563 self.WriteLn('\tmkdir -p $(@D); cp $< $@')
564 origin_src_dirs.append(os.path.dirname(source))
565 final_generated_sources.append(local_file)
567 # We add back in all of the non-compilable stuff to make sure that the
568 # make rules have dependencies on them.
569 final_generated_sources.extend(generated_not_sources)
570 self.WriteList(final_generated_sources, 'LOCAL_GENERATED_SOURCES')
572 origin_src_dirs = gyp.common.uniquer(origin_src_dirs)
573 origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs))
574 self.WriteList(origin_src_dirs, 'GYP_COPIED_SOURCE_ORIGIN_DIRS')
576 self.WriteList(local_files, 'LOCAL_SRC_FILES')
578 # Write out the flags used to compile the source; this must be done last
579 # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path.
580 self.WriteSourceFlags(spec, configs)
583 def ComputeAndroidModule(self, spec):
584 """Return the Android module name used for a gyp spec.
586 We use the complete qualified target name to avoid collisions between
587 duplicate targets in different directories. We also add a suffix to
588 distinguish gyp-generated module names.
591 if int(spec.get('android_unmangled_name', 0)):
592 assert self.type != 'shared_library' or self.target.startswith('lib')
595 if self.type == 'shared_library':
596 # For reasons of convention, the Android build system requires that all
597 # shared library modules are named 'libfoo' when generating -l flags.
602 if spec['toolset'] == 'host':
603 suffix = '_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'
608 middle = make.StringToMakefileVariable('%s_%s' % (self.path, self.target))
610 middle = make.StringToMakefileVariable(self.target)
612 return ''.join([prefix, middle, suffix])
615 def ComputeOutputParts(self, spec):
616 """Return the 'output basename' of a gyp spec, split into filename + ext.
618 Android libraries must be named the same thing as their module name,
619 otherwise the linker can't find them, so product_name and so on must be
620 ignored if we are building a library, and the "lib" prepending is
621 not done for Android.
623 assert self.type != 'loadable_module' # TODO: not supported?
625 target = spec['target_name']
628 if self.type == 'static_library':
629 target = self.ComputeAndroidModule(spec)
631 elif self.type == 'shared_library':
632 target = self.ComputeAndroidModule(spec)
634 elif self.type == 'none':
635 target_ext = '.stamp'
636 elif self.type != 'executable':
637 print ("ERROR: What output file should be generated?",
638 "type", self.type, "target", target)
640 if self.type != 'static_library' and self.type != 'shared_library':
641 target_prefix = spec.get('product_prefix', target_prefix)
642 target = spec.get('product_name', target)
643 product_ext = spec.get('product_extension')
645 target_ext = '.' + product_ext
647 target_stem = target_prefix + target
648 return (target_stem, target_ext)
651 def ComputeOutputBasename(self, spec):
652 """Return the 'output basename' of a gyp spec.
654 E.g., the loadable module 'foobar' in directory 'baz' will produce
657 return ''.join(self.ComputeOutputParts(spec))
660 def ComputeOutput(self, spec):
661 """Return the 'output' (full output path) of a gyp spec.
663 E.g., the loadable module 'foobar' in directory 'baz' will produce
664 '$(obj)/baz/libfoobar.so'
666 if self.type == 'executable':
667 # We install host executables into shared_intermediate_dir so they can be
668 # run by gyp rules that refer to PRODUCT_DIR.
669 path = '$(gyp_shared_intermediate_dir)'
670 elif self.type == 'shared_library':
671 if self.toolset == 'host':
672 path = '$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'
674 path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'
676 # Other targets just get built into their intermediate dir.
677 if self.toolset == 'host':
678 path = ('$(call intermediates-dir-for,%s,%s,true,,'
679 '$(GYP_HOST_VAR_PREFIX))' % (self.android_class,
680 self.android_module))
682 path = ('$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'
683 % (self.android_class, self.android_module))
685 assert spec.get('product_dir') is None # TODO: not supported?
686 return os.path.join(path, self.ComputeOutputBasename(spec))
688 def NormalizeIncludePaths(self, include_paths):
689 """ Normalize include_paths.
690 Convert absolute paths to relative to the Android top directory.
693 include_paths: A list of unprocessed include paths.
695 A list of normalized include paths.
698 for path in include_paths:
700 path = gyp.common.RelativePath(path, self.android_top_dir)
701 normalized.append(path)
704 def ExtractIncludesFromCFlags(self, cflags):
705 """Extract includes "-I..." out from cflags
708 cflags: A list of compiler flags, which may be mixed with "-I.."
710 A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.
715 if flag.startswith('-I'):
716 include_paths.append(flag[2:])
718 clean_cflags.append(flag)
720 return (clean_cflags, include_paths)
722 def ComputeAndroidLibraryModuleNames(self, libraries):
723 """Compute the Android module names from libraries, ie spec.get('libraries')
726 libraries: the value of spec.get('libraries')
728 A tuple (static_lib_modules, dynamic_lib_modules)
730 static_lib_modules = []
731 dynamic_lib_modules = []
732 for libs in libraries:
733 # Libs can have multiple words.
734 for lib in libs.split():
735 # Filter the system libraries, which are added by default by the Android
737 if (lib == '-lc' or lib == '-lstdc++' or lib == '-lm' or
738 lib.endswith('libgcc.a')):
740 match = re.search(r'([^/]+)\.a$', lib)
742 static_lib_modules.append(match.group(1))
744 match = re.search(r'([^/]+)\.so$', lib)
746 dynamic_lib_modules.append(match.group(1))
748 # "-lstlport" -> libstlport
749 if lib.startswith('-l'):
750 if lib.endswith('_static'):
751 static_lib_modules.append('lib' + lib[2:])
753 dynamic_lib_modules.append('lib' + lib[2:])
754 return (static_lib_modules, dynamic_lib_modules)
757 def ComputeDeps(self, spec):
758 """Compute the dependencies of a gyp spec.
760 Returns a tuple (deps, link_deps), where each is a list of
761 filenames that will need to be put in front of make for either
762 building (deps) or linking (link_deps).
766 if 'dependencies' in spec:
767 deps.extend([target_outputs[dep] for dep in spec['dependencies']
768 if target_outputs[dep]])
769 for dep in spec['dependencies']:
770 if dep in target_link_deps:
771 link_deps.append(target_link_deps[dep])
772 deps.extend(link_deps)
773 return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
776 def WriteTargetFlags(self, spec, configs, link_deps):
777 """Write Makefile code to specify the link flags and library dependencies.
779 spec, configs: input from gyp.
780 link_deps: link dependency list; see ComputeDeps()
782 if self.type != 'static_library':
783 for configname, config in sorted(configs.iteritems()):
784 ldflags = list(config.get('ldflags', []))
786 self.WriteList(ldflags, 'LOCAL_LDFLAGS_%s' % configname)
787 self.WriteLn('\nLOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))')
789 # Libraries (i.e. -lfoo)
790 # These must be included even for static libraries as some of them provide
791 # implicit include paths through the build system.
792 libraries = gyp.common.uniquer(spec.get('libraries', []))
793 static_libs, dynamic_libs = self.ComputeAndroidLibraryModuleNames(
796 # Link dependencies (i.e. other gyp targets this target depends on)
797 # These need not be included for static libraries as within the gyp build
798 # we do not use the implicit include path mechanism.
799 if self.type != 'static_library':
800 static_link_deps = [x[1] for x in link_deps if x[0] == 'static']
801 shared_link_deps = [x[1] for x in link_deps if x[0] == 'shared']
803 static_link_deps = []
804 shared_link_deps = []
806 # Only write the lists if they are non-empty.
807 if static_libs or static_link_deps:
809 self.WriteList(static_libs + static_link_deps,
810 'LOCAL_STATIC_LIBRARIES')
811 self.WriteLn('# Enable grouping to fix circular references')
812 self.WriteLn('LOCAL_GROUP_STATIC_LIBRARIES := true')
813 if dynamic_libs or shared_link_deps:
815 self.WriteList(dynamic_libs + shared_link_deps,
816 'LOCAL_SHARED_LIBRARIES')
819 def WriteTarget(self, spec, configs, deps, link_deps, part_of_all,
821 """Write Makefile code to produce the final target of the gyp spec.
823 spec, configs: input from gyp.
824 deps, link_deps: dependency lists; see ComputeDeps()
825 part_of_all: flag indicating this target is part of 'all'
826 write_alias_target: flag indicating whether to create short aliases for this
829 self.WriteLn('### Rules for final target.')
831 if self.type != 'none':
832 self.WriteTargetFlags(spec, configs, link_deps)
834 settings = spec.get('aosp_build_settings', {})
836 self.WriteLn('### Set directly by aosp_build_settings.')
837 for k, v in settings.iteritems():
838 if isinstance(v, list):
841 self.WriteLn('%s := %s' % (k, make.QuoteIfNecessary(v)))
844 # Add to the set of targets which represent the gyp 'all' target. We use the
845 # name 'gyp_all_modules' as the Android build system doesn't allow the use
846 # of the Make target 'all' and because 'all_modules' is the equivalent of
847 # the Make target 'all' on Android.
848 if part_of_all and write_alias_target:
849 self.WriteLn('# Add target alias to "gyp_all_modules" target.')
850 self.WriteLn('.PHONY: gyp_all_modules')
851 self.WriteLn('gyp_all_modules: %s' % self.android_module)
854 # Add an alias from the gyp target name to the Android module name. This
855 # simplifies manual builds of the target, and is required by the test
857 if self.target != self.android_module and write_alias_target:
858 self.WriteLn('# Alias gyp target name.')
859 self.WriteLn('.PHONY: %s' % self.target)
860 self.WriteLn('%s: %s' % (self.target, self.android_module))
863 # Add the command to trigger build of the target type depending
864 # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY
865 # NOTE: This has to come last!
867 if self.toolset == 'host':
869 if self.type == 'static_library':
870 self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier)
871 elif self.type == 'shared_library':
872 self.WriteLn('LOCAL_PRELINK_MODULE := false')
873 self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier)
874 elif self.type == 'executable':
875 # Executables are for build and test purposes only, so they're installed
876 # to a directory that doesn't get included in the system image.
877 self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)')
878 self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier)
880 self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp')
881 self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true')
882 if self.toolset == 'target':
883 self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)')
885 self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_HOST_VAR_PREFIX)')
887 self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk')
889 self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)')
890 self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"')
891 self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
892 self.WriteLn('\t$(hide) touch $@')
894 self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX :=')
897 def WriteList(self, value_list, variable=None, prefix='',
898 quoter=make.QuoteIfNecessary, local_pathify=False):
899 """Write a variable definition that is a list of values.
901 E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
903 but in a pretty-printed style.
907 value_list = [quoter(prefix + l) for l in value_list]
909 value_list = [self.LocalPathify(l) for l in value_list]
910 values = ' \\\n\t' + ' \\\n\t'.join(value_list)
911 self.fp.write('%s :=%s\n\n' % (variable, values))
914 def WriteLn(self, text=''):
915 self.fp.write(text + '\n')
918 def LocalPathify(self, path):
919 """Convert a subdirectory-relative path into a normalized path which starts
920 with the make variable $(LOCAL_PATH) (i.e. the top of the project tree).
921 Absolute paths, or paths that contain variables, are just normalized."""
922 if '$(' in path or os.path.isabs(path):
923 # path is not a file in the project tree in this case, but calling
924 # normpath is still important for trimming trailing slashes.
925 return os.path.normpath(path)
926 local_path = os.path.join('$(LOCAL_PATH)', self.path, path)
927 local_path = os.path.normpath(local_path)
928 # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH)
929 # - i.e. that the resulting path is still inside the project tree. The
930 # path may legitimately have ended up containing just $(LOCAL_PATH), though,
931 # so we don't look for a slash.
932 assert local_path.startswith('$(LOCAL_PATH)'), (
933 'Path %s attempts to escape from gyp path %s !)' % (path, self.path))
937 def ExpandInputRoot(self, template, expansion, dirname):
938 if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template:
941 'INPUT_ROOT': expansion,
942 'INPUT_DIRNAME': dirname,
944 return os.path.normpath(path)
947 def PerformBuild(data, configurations, params):
948 # The android backend only supports the default configuration.
949 options = params['options']
950 makefile = os.path.abspath(os.path.join(options.toplevel_dir,
952 env = dict(os.environ)
953 env['ONE_SHOT_MAKEFILE'] = makefile
954 arguments = ['make', '-C', os.environ['ANDROID_BUILD_TOP'], 'gyp_all_modules']
955 print 'Building: %s' % arguments
956 subprocess.check_call(arguments, env=env)
959 def GenerateOutput(target_list, target_dicts, data, params):
960 options = params['options']
961 generator_flags = params.get('generator_flags', {})
962 builddir_name = generator_flags.get('output_dir', 'out')
963 limit_to_target_all = generator_flags.get('limit_to_target_all', False)
964 write_alias_targets = generator_flags.get('write_alias_targets', True)
965 android_top_dir = os.environ.get('ANDROID_BUILD_TOP')
966 assert android_top_dir, '$ANDROID_BUILD_TOP not set; you need to run lunch.'
968 def CalculateMakefilePath(build_file, base_name):
969 """Determine where to write a Makefile for a given gyp file."""
970 # Paths in gyp files are relative to the .gyp file, but we want
971 # paths relative to the source root for the master makefile. Grab
972 # the path of the .gyp file as the base to relativize against.
973 # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
974 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
976 # We write the file in the base_path directory.
977 output_file = os.path.join(options.depth, base_path, base_name)
978 assert not options.generator_output, (
979 'The Android backend does not support options.generator_output.')
980 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
981 options.toplevel_dir)
982 return base_path, output_file
984 # TODO: search for the first non-'Default' target. This can go
985 # away when we add verification that all targets have the
986 # necessary configurations.
987 default_configuration = None
988 toolsets = set([target_dicts[target]['toolset'] for target in target_list])
989 for target in target_list:
990 spec = target_dicts[target]
991 if spec['default_configuration'] != 'Default':
992 default_configuration = spec['default_configuration']
994 if not default_configuration:
995 default_configuration = 'Default'
998 makefile_name = 'GypAndroid' + options.suffix + '.mk'
999 makefile_path = os.path.join(options.toplevel_dir, makefile_name)
1000 assert not options.generator_output, (
1001 'The Android backend does not support options.generator_output.')
1002 gyp.common.EnsureDirExists(makefile_path)
1003 root_makefile = open(makefile_path, 'w')
1005 root_makefile.write(header)
1007 # We set LOCAL_PATH just once, here, to the top of the project tree. This
1008 # allows all the other paths we use to be relative to the Android.mk file,
1009 # as the Android build system expects.
1010 root_makefile.write('\nLOCAL_PATH := $(call my-dir)\n')
1012 # Find the list of targets that derive from the gyp file(s) being built.
1013 needed_targets = set()
1014 for build_file in params['build_files']:
1015 for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
1016 needed_targets.add(target)
1019 include_list = set()
1020 android_modules = {}
1021 for qualified_target in target_list:
1022 build_file, target, toolset = gyp.common.ParseQualifiedTarget(
1024 relative_build_file = gyp.common.RelativePath(build_file,
1025 options.toplevel_dir)
1026 build_files.add(relative_build_file)
1027 included_files = data[build_file]['included_files']
1028 for included_file in included_files:
1029 # The included_files entries are relative to the dir of the build file
1030 # that included them, so we have to undo that and then make them relative
1032 relative_include_file = gyp.common.RelativePath(
1033 gyp.common.UnrelativePath(included_file, build_file),
1034 options.toplevel_dir)
1035 abs_include_file = os.path.abspath(relative_include_file)
1036 # If the include file is from the ~/.gyp dir, we should use absolute path
1037 # so that relocating the src dir doesn't break the path.
1038 if (params['home_dot_gyp'] and
1039 abs_include_file.startswith(params['home_dot_gyp'])):
1040 build_files.add(abs_include_file)
1042 build_files.add(relative_include_file)
1044 base_path, output_file = CalculateMakefilePath(build_file,
1045 target + '.' + toolset + options.suffix + '.mk')
1047 spec = target_dicts[qualified_target]
1048 configs = spec['configurations']
1050 part_of_all = (qualified_target in needed_targets and
1051 not int(spec.get('suppress_wildcard', False)))
1052 if limit_to_target_all and not part_of_all:
1055 relative_target = gyp.common.QualifiedTarget(relative_build_file, target,
1057 writer = AndroidMkWriter(android_top_dir)
1058 android_module = writer.Write(qualified_target, relative_target, base_path,
1059 output_file, spec, configs,
1060 part_of_all=part_of_all,
1061 write_alias_target=write_alias_targets)
1062 if android_module in android_modules:
1063 print ('ERROR: Android module names must be unique. The following '
1064 'targets both generate Android module name %s.\n %s\n %s' %
1065 (android_module, android_modules[android_module],
1068 android_modules[android_module] = qualified_target
1070 # Our root_makefile lives at the source root. Compute the relative path
1071 # from there to the output_file for including.
1072 mkfile_rel_path = gyp.common.RelativePath(output_file,
1073 os.path.dirname(makefile_path))
1074 include_list.add(mkfile_rel_path)
1076 root_makefile.write('GYP_CONFIGURATION ?= %s\n' % default_configuration)
1077 root_makefile.write('GYP_VAR_PREFIX ?=\n')
1078 root_makefile.write('GYP_HOST_VAR_PREFIX ?=\n')
1079 root_makefile.write('GYP_HOST_MULTILIB ?=\n')
1081 # Write out the sorted list of includes.
1082 root_makefile.write('\n')
1083 for include_file in sorted(include_list):
1084 root_makefile.write('include $(LOCAL_PATH)/' + include_file + '\n')
1085 root_makefile.write('\n')
1087 if write_alias_targets:
1088 root_makefile.write(ALL_MODULES_FOOTER)
1090 root_makefile.close()