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',
54 generator_additional_path_sections = []
55 generator_extra_sources_for_rules = []
58 ALL_MODULES_FOOTER = """\
59 # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from
60 # all the included sub-makefiles. This is just here to clarify.
65 # This file is generated by gyp; do not edit.
69 android_standard_include_paths = set([
70 # JNI_H_INCLUDE in build/core/binary.mk
71 'dalvik/libnativehelper/include/nativehelper',
72 # from SRC_HEADERS in build/core/config.mk
73 'system/core/include',
74 'hardware/libhardware/include',
75 'hardware/libhardware_legacy/include',
76 'hardware/ril/include',
77 'dalvik/libnativehelper/include',
78 'frameworks/native/include',
79 'frameworks/native/opengl/include',
80 'frameworks/base/include',
81 'frameworks/base/opengl/include',
82 'frameworks/base/native/include',
83 'external/skia/include',
84 # TARGET_C_INCLUDES in build/core/combo/TARGET_linux-arm.mk
85 'bionic/libc/arch-arm/include',
86 'bionic/libc/include',
87 'bionic/libstdc++/include',
88 'bionic/libc/kernel/common',
89 'bionic/libc/kernel/arch-arm',
90 'bionic/libm/include',
91 'bionic/libm/include/arm',
92 'bionic/libthread_db/include',
96 # Map gyp target types to Android module classes.
98 'static_library': 'STATIC_LIBRARIES',
99 'shared_library': 'SHARED_LIBRARIES',
100 'executable': 'EXECUTABLES',
104 def IsCPPExtension(ext):
105 return make.COMPILABLE_EXTENSIONS.get(ext) == 'cxx'
109 """Convert a path to its source directory form. The Android backend does not
110 support options.generator_output, so this function is a noop."""
114 # Map from qualified target to path to output.
115 # For Android, the target of these maps is a tuple ('static', 'modulename'),
116 # ('dynamic', 'modulename'), or ('path', 'some/path') instead of a string,
117 # since we link by module.
119 # Map from qualified target to any linkable output. A subset
120 # of target_outputs. E.g. when mybinary depends on liba, we want to
121 # include liba in the linker line; when otherbinary depends on
122 # mybinary, we just want to build mybinary first.
123 target_link_deps = {}
126 class AndroidMkWriter(object):
127 """AndroidMkWriter packages up the writing of one target-specific Android.mk.
129 Its only real entry point is Write(), and is mostly used for namespacing.
132 def __init__(self, android_top_dir):
133 self.android_top_dir = android_top_dir
135 def Write(self, qualified_target, relative_target, base_path, output_filename,
136 spec, configs, part_of_all, write_alias_target):
137 """The main entry point: writes a .mk file for a single target.
140 qualified_target: target we're generating
141 relative_target: qualified target name relative to the root
142 base_path: path relative to source root we're building in, used to resolve
143 target-relative paths
144 output_filename: output .mk file name to write
145 spec, configs: gyp info
146 part_of_all: flag indicating this target is part of 'all'
147 write_alias_target: flag indicating whether to create short aliases for
150 gyp.common.EnsureDirExists(output_filename)
152 self.fp = open(output_filename, 'w')
154 self.fp.write(header)
156 self.qualified_target = qualified_target
157 self.relative_target = relative_target
158 self.path = base_path
159 self.target = spec['target_name']
160 self.type = spec['type']
161 self.toolset = spec['toolset']
163 deps, link_deps = self.ComputeDeps(spec)
165 # Some of the generation below can add extra output, sources, or
166 # link dependencies. All of the out params of the functions that
167 # follow use names like extra_foo.
171 self.android_class = MODULE_CLASSES.get(self.type, 'GYP')
172 self.android_module = self.ComputeAndroidModule(spec)
173 (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec)
174 self.output = self.output_binary = self.ComputeOutput(spec)
177 self.WriteLn('include $(CLEAR_VARS)\n')
179 # Module class and name.
180 self.WriteLn('LOCAL_MODULE_CLASS := ' + self.android_class)
181 self.WriteLn('LOCAL_MODULE := ' + self.android_module)
182 # Only emit LOCAL_MODULE_STEM if it's different to LOCAL_MODULE.
183 # The library module classes fail if the stem is set. ComputeOutputParts
184 # makes sure that stem == modulename in these cases.
185 if self.android_stem != self.android_module:
186 self.WriteLn('LOCAL_MODULE_STEM := ' + self.android_stem)
187 self.WriteLn('LOCAL_MODULE_SUFFIX := ' + self.android_suffix)
188 self.WriteLn('LOCAL_MODULE_TAGS := optional')
189 if self.toolset == 'host':
190 self.WriteLn('LOCAL_IS_HOST_MODULE := true')
192 self.WriteLn('LOCAL_MODULE_TARGET_ARCH := '
193 '$(TARGET_$(GYP_VAR_PREFIX)ARCH)')
195 # Grab output directories; needed for Actions and Rules.
196 if self.toolset == 'host':
197 self.WriteLn('gyp_intermediate_dir := '
198 '$(call local-intermediates-dir)')
200 self.WriteLn('gyp_intermediate_dir := '
201 '$(call local-intermediates-dir,,$(GYP_VAR_PREFIX))')
202 self.WriteLn('gyp_shared_intermediate_dir := '
203 '$(call intermediates-dir-for,GYP,shared,,,$(GYP_VAR_PREFIX))')
206 # List files this target depends on so that actions/rules/copies/sources
207 # can depend on the list.
208 # TODO: doesn't pull in things through transitive link deps; needed?
209 target_dependencies = [x[1] for x in deps if x[0] == 'path']
210 self.WriteLn('# Make sure our deps are built first.')
211 self.WriteList(target_dependencies, 'GYP_TARGET_DEPENDENCIES',
214 # Actions must come first, since they can generate more OBJs for use below.
215 if 'actions' in spec:
216 self.WriteActions(spec['actions'], extra_sources, extra_outputs)
218 # Rules must be early like actions.
220 self.WriteRules(spec['rules'], extra_sources, extra_outputs)
223 self.WriteCopies(spec['copies'], extra_outputs)
225 # GYP generated outputs.
226 self.WriteList(extra_outputs, 'GYP_GENERATED_OUTPUTS', local_pathify=True)
228 # Set LOCAL_ADDITIONAL_DEPENDENCIES so that Android's build rules depend
229 # on both our dependency targets and our generated files.
230 self.WriteLn('# Make sure our deps and generated files are built first.')
231 self.WriteLn('LOCAL_ADDITIONAL_DEPENDENCIES := $(GYP_TARGET_DEPENDENCIES) '
232 '$(GYP_GENERATED_OUTPUTS)')
236 if spec.get('sources', []) or extra_sources:
237 self.WriteSources(spec, configs, extra_sources)
239 self.WriteTarget(spec, configs, deps, link_deps, part_of_all,
242 # Update global list of target outputs, used in dependency tracking.
243 target_outputs[qualified_target] = ('path', self.output_binary)
245 # Update global list of link dependencies.
246 if self.type == 'static_library':
247 target_link_deps[qualified_target] = ('static', self.android_module)
248 elif self.type == 'shared_library':
249 target_link_deps[qualified_target] = ('shared', self.android_module)
252 return self.android_module
255 def WriteActions(self, actions, extra_sources, extra_outputs):
256 """Write Makefile code for any 'actions' from the gyp input.
258 extra_sources: a list that will be filled in with newly generated source
260 extra_outputs: a list that will be filled in with any outputs of these
261 actions (used to make other pieces dependent on these
264 for action in actions:
265 name = make.StringToMakefileVariable('%s_%s' % (self.relative_target,
266 action['action_name']))
267 self.WriteLn('### Rules for action "%s":' % action['action_name'])
268 inputs = action['inputs']
269 outputs = action['outputs']
271 # Build up a list of outputs.
272 # Collect the output dirs we'll need.
275 if not out.startswith('$'):
276 print ('WARNING: Action for target "%s" writes output to local path '
277 '"%s".' % (self.target, out))
278 dir = os.path.split(out)[0]
281 if int(action.get('process_outputs_as_sources', False)):
282 extra_sources += outputs
284 # Prepare the actual command.
285 command = gyp.common.EncodePOSIXShellList(action['action'])
286 if 'message' in action:
287 quiet_cmd = 'Gyp action: %s ($@)' % action['message']
289 quiet_cmd = 'Gyp action: %s ($@)' % name
291 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
293 cd_action = 'cd $(gyp_local_path)/%s; ' % self.path
294 command = cd_action + command
296 # The makefile rules are all relative to the top dir, but the gyp actions
297 # are defined relative to their containing dir. This replaces the gyp_*
298 # variables for the action rule with an absolute version so that the
299 # output goes in the right place.
300 # Only write the gyp_* rules for the "primary" output (:1);
301 # it's superfluous for the "extra outputs", and this avoids accidentally
302 # writing duplicate dummy rules for those outputs.
303 main_output = make.QuoteSpaces(self.LocalPathify(outputs[0]))
304 self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output)
305 self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output)
306 self.WriteLn('%s: gyp_intermediate_dir := '
307 '$(abspath $(gyp_intermediate_dir))' % main_output)
308 self.WriteLn('%s: gyp_shared_intermediate_dir := '
309 '$(abspath $(gyp_shared_intermediate_dir))' % main_output)
311 # Android's envsetup.sh adds a number of directories to the path including
312 # the built host binary directory. This causes actions/rules invoked by
313 # gyp to sometimes use these instead of system versions, e.g. bison.
314 # The built host binaries may not be suitable, and can cause errors.
315 # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable
317 self.WriteLn('%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))'
321 assert ' ' not in input, (
322 "Spaces in action input filenames not supported (%s)" % input)
323 for output in outputs:
324 assert ' ' not in output, (
325 "Spaces in action output filenames not supported (%s)" % output)
327 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' %
328 (main_output, ' '.join(map(self.LocalPathify, inputs))))
329 self.WriteLn('\t@echo "%s"' % quiet_cmd)
330 self.WriteLn('\t$(hide)%s\n' % command)
331 for output in outputs[1:]:
332 # Make each output depend on the main output, with an empty command
333 # to force make to notice that the mtime has changed.
334 self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output))
336 extra_outputs += outputs
342 def WriteRules(self, rules, extra_sources, extra_outputs):
343 """Write Makefile code for any 'rules' from the gyp input.
345 extra_sources: a list that will be filled in with newly generated source
347 extra_outputs: a list that will be filled in with any outputs of these
348 rules (used to make other pieces dependent on these rules)
354 if len(rule.get('rule_sources', [])) == 0:
356 name = make.StringToMakefileVariable('%s_%s' % (self.relative_target,
358 self.WriteLn('\n### Generated for rule "%s":' % name)
359 self.WriteLn('# "%s":' % rule)
361 inputs = rule.get('inputs')
362 for rule_source in rule.get('rule_sources', []):
363 (rule_source_dirname, rule_source_basename) = os.path.split(rule_source)
364 (rule_source_root, rule_source_ext) = \
365 os.path.splitext(rule_source_basename)
367 outputs = [self.ExpandInputRoot(out, rule_source_root,
369 for out in rule['outputs']]
373 if not out.startswith('$'):
374 print ('WARNING: Rule for target %s writes output to local path %s'
375 % (self.target, out))
376 dir = os.path.dirname(out)
379 extra_outputs += outputs
380 if int(rule.get('process_outputs_as_sources', False)):
381 extra_sources.extend(outputs)
384 for component in rule['action']:
385 component = self.ExpandInputRoot(component, rule_source_root,
387 if '$(RULE_SOURCES)' in component:
388 component = component.replace('$(RULE_SOURCES)',
390 components.append(component)
392 command = gyp.common.EncodePOSIXShellList(components)
393 cd_action = 'cd $(gyp_local_path)/%s; ' % self.path
394 command = cd_action + command
396 command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command
398 # We set up a rule to build the first output, and then set up
399 # a rule for each additional output to depend on the first.
400 outputs = map(self.LocalPathify, outputs)
401 main_output = outputs[0]
402 self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output)
403 self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output)
404 self.WriteLn('%s: gyp_intermediate_dir := '
405 '$(abspath $(gyp_intermediate_dir))' % main_output)
406 self.WriteLn('%s: gyp_shared_intermediate_dir := '
407 '$(abspath $(gyp_shared_intermediate_dir))' % main_output)
409 # See explanation in WriteActions.
410 self.WriteLn('%s: export PATH := '
411 '$(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output)
413 main_output_deps = self.LocalPathify(rule_source)
415 main_output_deps += ' '
416 main_output_deps += ' '.join([self.LocalPathify(f) for f in inputs])
418 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' %
419 (main_output, main_output_deps))
420 self.WriteLn('\t%s\n' % command)
421 for output in outputs[1:]:
422 # Make each output depend on the main output, with an empty command
423 # to force make to notice that the mtime has changed.
424 self.WriteLn('%s: %s ;' % (output, main_output))
430 def WriteCopies(self, copies, extra_outputs):
431 """Write Makefile code for any 'copies' from the gyp input.
433 extra_outputs: a list that will be filled in with any outputs of this action
434 (used to make other pieces dependent on this action)
436 self.WriteLn('### Generated for copy rule.')
438 variable = make.StringToMakefileVariable(self.relative_target + '_copies')
441 for path in copy['files']:
442 # The Android build system does not allow generation of files into the
443 # source tree. The destination should start with a variable, which will
444 # typically be $(gyp_intermediate_dir) or
445 # $(gyp_shared_intermediate_dir). Note that we can't use an assertion
446 # because some of the gyp tests depend on this.
447 if not copy['destination'].startswith('$'):
448 print ('WARNING: Copy rule for target %s writes output to '
449 'local path %s' % (self.target, copy['destination']))
451 # LocalPathify() calls normpath, stripping trailing slashes.
452 path = Sourceify(self.LocalPathify(path))
453 filename = os.path.split(path)[1]
454 output = Sourceify(self.LocalPathify(os.path.join(copy['destination'],
457 self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES) | $(ACP)' %
459 self.WriteLn('\t@echo Copying: $@')
460 self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
461 self.WriteLn('\t$(hide) $(ACP) -rpf $< $@')
463 outputs.append(output)
464 self.WriteLn('%s = %s' % (variable,
465 ' '.join(map(make.QuoteSpaces, outputs))))
466 extra_outputs.append('$(%s)' % variable)
470 def WriteSourceFlags(self, spec, configs):
471 """Write out the flags and include paths used to compile source files for
475 spec, configs: input from gyp.
477 for configname, config in sorted(configs.iteritems()):
478 extracted_includes = []
480 self.WriteLn('\n# Flags passed to both C and C++ files.')
481 cflags, includes_from_cflags = self.ExtractIncludesFromCFlags(
482 config.get('cflags', []) + config.get('cflags_c', []))
483 extracted_includes.extend(includes_from_cflags)
484 self.WriteList(cflags, 'MY_CFLAGS_%s' % configname)
486 self.WriteList(config.get('defines'), 'MY_DEFS_%s' % configname,
487 prefix='-D', quoter=make.EscapeCppDefine)
489 self.WriteLn('\n# Include paths placed before CFLAGS/CPPFLAGS')
490 includes = list(config.get('include_dirs', []))
491 includes.extend(extracted_includes)
492 includes = map(Sourceify, map(self.LocalPathify, includes))
493 includes = self.NormalizeIncludePaths(includes)
494 self.WriteList(includes, 'LOCAL_C_INCLUDES_%s' % configname)
496 self.WriteLn('\n# Flags passed to only C++ (and not C) files.')
497 self.WriteList(config.get('cflags_cc'), 'LOCAL_CPPFLAGS_%s' % configname)
499 self.WriteLn('\nLOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) '
500 '$(MY_DEFS_$(GYP_CONFIGURATION))')
501 # Undefine ANDROID for host modules
502 # TODO: the source code should not use macro ANDROID to tell if it's host
504 if self.toolset == 'host':
505 self.WriteLn('# Undefine ANDROID for host modules')
506 self.WriteLn('LOCAL_CFLAGS += -UANDROID')
507 self.WriteLn('LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) '
508 '$(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))')
509 self.WriteLn('LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))')
510 # Android uses separate flags for assembly file invocations, but gyp expects
511 # the same CFLAGS to be applied:
512 self.WriteLn('LOCAL_ASFLAGS := $(LOCAL_CFLAGS)')
515 def WriteSources(self, spec, configs, extra_sources):
516 """Write Makefile code for any 'sources' from the gyp input.
517 These are source files necessary to build the current target.
518 We need to handle shared_intermediate directory source files as
519 a special case by copying them to the intermediate directory and
520 treating them as a genereated sources. Otherwise the Android build
521 rules won't pick them up.
524 spec, configs: input from gyp.
525 extra_sources: Sources generated from Actions or Rules.
527 sources = filter(make.Compilable, spec.get('sources', []))
528 generated_not_sources = [x for x in extra_sources if not make.Compilable(x)]
529 extra_sources = filter(make.Compilable, extra_sources)
531 # Determine and output the C++ extension used by these sources.
532 # We simply find the first C++ file and use that extension.
533 all_sources = sources + extra_sources
534 local_cpp_extension = '.cpp'
535 for source in all_sources:
536 (root, ext) = os.path.splitext(source)
537 if IsCPPExtension(ext):
538 local_cpp_extension = ext
540 if local_cpp_extension != '.cpp':
541 self.WriteLn('LOCAL_CPP_EXTENSION := %s' % local_cpp_extension)
543 # We need to move any non-generated sources that are coming from the
544 # shared intermediate directory out of LOCAL_SRC_FILES and put them
545 # into LOCAL_GENERATED_SOURCES. We also need to move over any C++ files
546 # that don't match our local_cpp_extension, since Android will only
547 # generate Makefile rules for a single LOCAL_CPP_EXTENSION.
549 for source in sources:
550 (root, ext) = os.path.splitext(source)
551 if '$(gyp_shared_intermediate_dir)' in source:
552 extra_sources.append(source)
553 elif '$(gyp_intermediate_dir)' in source:
554 extra_sources.append(source)
555 elif IsCPPExtension(ext) and ext != local_cpp_extension:
556 extra_sources.append(source)
558 local_files.append(os.path.normpath(os.path.join(self.path, source)))
560 # For any generated source, if it is coming from the shared intermediate
561 # directory then we add a Make rule to copy them to the local intermediate
562 # directory first. This is because the Android LOCAL_GENERATED_SOURCES
563 # must be in the local module intermediate directory for the compile rules
564 # to work properly. If the file has the wrong C++ extension, then we add
565 # a rule to copy that to intermediates and use the new version.
566 final_generated_sources = []
567 # If a source file gets copied, we still need to add the orginal source
568 # directory as header search path, for GCC searches headers in the
569 # directory that contains the source file by default.
571 for source in extra_sources:
573 if not '$(gyp_intermediate_dir)/' in local_file:
574 basename = os.path.basename(local_file)
575 local_file = '$(gyp_intermediate_dir)/' + basename
576 (root, ext) = os.path.splitext(local_file)
577 if IsCPPExtension(ext) and ext != local_cpp_extension:
578 local_file = root + local_cpp_extension
579 if local_file != source:
580 self.WriteLn('%s: %s' % (local_file, self.LocalPathify(source)))
581 self.WriteLn('\tmkdir -p $(@D); cp $< $@')
582 origin_src_dirs.append(os.path.dirname(source))
583 final_generated_sources.append(local_file)
585 # We add back in all of the non-compilable stuff to make sure that the
586 # make rules have dependencies on them.
587 final_generated_sources.extend(generated_not_sources)
588 self.WriteList(final_generated_sources, 'LOCAL_GENERATED_SOURCES')
590 origin_src_dirs = gyp.common.uniquer(origin_src_dirs)
591 origin_src_dirs = map(Sourceify, map(self.LocalPathify, origin_src_dirs))
592 self.WriteList(origin_src_dirs, 'GYP_COPIED_SOURCE_ORIGIN_DIRS')
594 self.WriteList(local_files, 'LOCAL_SRC_FILES')
596 # Write out the flags used to compile the source; this must be done last
597 # so that GYP_COPIED_SOURCE_ORIGIN_DIRS can be used as an include path.
598 self.WriteSourceFlags(spec, configs)
601 def ComputeAndroidModule(self, spec):
602 """Return the Android module name used for a gyp spec.
604 We use the complete qualified target name to avoid collisions between
605 duplicate targets in different directories. We also add a suffix to
606 distinguish gyp-generated module names.
609 if int(spec.get('android_unmangled_name', 0)):
610 assert self.type != 'shared_library' or self.target.startswith('lib')
613 if self.type == 'shared_library':
614 # For reasons of convention, the Android build system requires that all
615 # shared library modules are named 'libfoo' when generating -l flags.
620 if spec['toolset'] == 'host':
621 suffix = '_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'
626 middle = make.StringToMakefileVariable('%s_%s' % (self.path, self.target))
628 middle = make.StringToMakefileVariable(self.target)
630 return ''.join([prefix, middle, suffix])
633 def ComputeOutputParts(self, spec):
634 """Return the 'output basename' of a gyp spec, split into filename + ext.
636 Android libraries must be named the same thing as their module name,
637 otherwise the linker can't find them, so product_name and so on must be
638 ignored if we are building a library, and the "lib" prepending is
639 not done for Android.
641 assert self.type != 'loadable_module' # TODO: not supported?
643 target = spec['target_name']
646 if self.type == 'static_library':
647 target = self.ComputeAndroidModule(spec)
649 elif self.type == 'shared_library':
650 target = self.ComputeAndroidModule(spec)
652 elif self.type == 'none':
653 target_ext = '.stamp'
654 elif self.type != 'executable':
655 print ("ERROR: What output file should be generated?",
656 "type", self.type, "target", target)
658 if self.type != 'static_library' and self.type != 'shared_library':
659 target_prefix = spec.get('product_prefix', target_prefix)
660 target = spec.get('product_name', target)
661 product_ext = spec.get('product_extension')
663 target_ext = '.' + product_ext
665 target_stem = target_prefix + target
666 return (target_stem, target_ext)
669 def ComputeOutputBasename(self, spec):
670 """Return the 'output basename' of a gyp spec.
672 E.g., the loadable module 'foobar' in directory 'baz' will produce
675 return ''.join(self.ComputeOutputParts(spec))
678 def ComputeOutput(self, spec):
679 """Return the 'output' (full output path) of a gyp spec.
681 E.g., the loadable module 'foobar' in directory 'baz' will produce
682 '$(obj)/baz/libfoobar.so'
684 if self.type == 'executable' and self.toolset == 'host':
685 # We install host executables into shared_intermediate_dir so they can be
686 # run by gyp rules that refer to PRODUCT_DIR.
687 path = '$(gyp_shared_intermediate_dir)'
688 elif self.type == 'shared_library':
689 if self.toolset == 'host':
690 path = '$(HOST_OUT_INTERMEDIATE_LIBRARIES)'
692 path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'
694 # Other targets just get built into their intermediate dir.
695 if self.toolset == 'host':
696 path = '$(call intermediates-dir-for,%s,%s,true)' % (self.android_class,
699 path = ('$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'
700 % (self.android_class, self.android_module))
702 assert spec.get('product_dir') is None # TODO: not supported?
703 return os.path.join(path, self.ComputeOutputBasename(spec))
705 def NormalizeIncludePaths(self, include_paths):
706 """ Normalize include_paths.
707 Convert absolute paths to relative to the Android top directory;
708 filter out include paths that are already brought in by the Android build
712 include_paths: A list of unprocessed include paths.
714 A list of normalized include paths.
717 for path in include_paths:
719 path = gyp.common.RelativePath(path, self.android_top_dir)
721 # Filter out the Android standard search path.
722 if path not in android_standard_include_paths:
723 normalized.append(path)
726 def ExtractIncludesFromCFlags(self, cflags):
727 """Extract includes "-I..." out from cflags
730 cflags: A list of compiler flags, which may be mixed with "-I.."
732 A tuple of lists: (clean_clfags, include_paths). "-I.." is trimmed.
737 if flag.startswith('-I'):
738 include_paths.append(flag[2:])
740 clean_cflags.append(flag)
742 return (clean_cflags, include_paths)
744 def ComputeAndroidLibraryModuleNames(self, libraries):
745 """Compute the Android module names from libraries, ie spec.get('libraries')
748 libraries: the value of spec.get('libraries')
750 A tuple (static_lib_modules, dynamic_lib_modules)
752 static_lib_modules = []
753 dynamic_lib_modules = []
754 for libs in libraries:
755 # Libs can have multiple words.
756 for lib in libs.split():
757 # Filter the system libraries, which are added by default by the Android
759 if (lib == '-lc' or lib == '-lstdc++' or lib == '-lm' or
760 lib.endswith('libgcc.a')):
762 match = re.search(r'([^/]+)\.a$', lib)
764 static_lib_modules.append(match.group(1))
766 match = re.search(r'([^/]+)\.so$', lib)
768 dynamic_lib_modules.append(match.group(1))
770 # "-lstlport" -> libstlport
771 if lib.startswith('-l'):
772 if lib.endswith('_static'):
773 static_lib_modules.append('lib' + lib[2:])
775 dynamic_lib_modules.append('lib' + lib[2:])
776 return (static_lib_modules, dynamic_lib_modules)
779 def ComputeDeps(self, spec):
780 """Compute the dependencies of a gyp spec.
782 Returns a tuple (deps, link_deps), where each is a list of
783 filenames that will need to be put in front of make for either
784 building (deps) or linking (link_deps).
788 if 'dependencies' in spec:
789 deps.extend([target_outputs[dep] for dep in spec['dependencies']
790 if target_outputs[dep]])
791 for dep in spec['dependencies']:
792 if dep in target_link_deps:
793 link_deps.append(target_link_deps[dep])
794 deps.extend(link_deps)
795 return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
798 def WriteTargetFlags(self, spec, configs, link_deps):
799 """Write Makefile code to specify the link flags and library dependencies.
801 spec, configs: input from gyp.
802 link_deps: link dependency list; see ComputeDeps()
804 for configname, config in sorted(configs.iteritems()):
805 ldflags = list(config.get('ldflags', []))
807 self.WriteList(ldflags, 'LOCAL_LDFLAGS_%s' % configname)
808 self.WriteLn('\nLOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))')
810 # Libraries (i.e. -lfoo)
811 libraries = gyp.common.uniquer(spec.get('libraries', []))
812 static_libs, dynamic_libs = self.ComputeAndroidLibraryModuleNames(
815 # Link dependencies (i.e. libfoo.a, libfoo.so)
816 static_link_deps = [x[1] for x in link_deps if x[0] == 'static']
817 shared_link_deps = [x[1] for x in link_deps if x[0] == 'shared']
819 self.WriteList(static_libs + static_link_deps,
820 'LOCAL_STATIC_LIBRARIES')
821 self.WriteLn('# Enable grouping to fix circular references')
822 self.WriteLn('LOCAL_GROUP_STATIC_LIBRARIES := true')
824 self.WriteList(dynamic_libs + shared_link_deps,
825 'LOCAL_SHARED_LIBRARIES')
828 def WriteTarget(self, spec, configs, deps, link_deps, part_of_all,
830 """Write Makefile code to produce the final target of the gyp spec.
832 spec, configs: input from gyp.
833 deps, link_deps: dependency lists; see ComputeDeps()
834 part_of_all: flag indicating this target is part of 'all'
835 write_alias_target: flag indicating whether to create short aliases for this
838 self.WriteLn('### Rules for final target.')
840 if self.type != 'none':
841 self.WriteTargetFlags(spec, configs, link_deps)
843 # Add to the set of targets which represent the gyp 'all' target. We use the
844 # name 'gyp_all_modules' as the Android build system doesn't allow the use
845 # of the Make target 'all' and because 'all_modules' is the equivalent of
846 # the Make target 'all' on Android.
847 if part_of_all and write_alias_target:
848 self.WriteLn('# Add target alias to "gyp_all_modules" target.')
849 self.WriteLn('.PHONY: gyp_all_modules')
850 self.WriteLn('gyp_all_modules: %s' % self.android_module)
853 # Add an alias from the gyp target name to the Android module name. This
854 # simplifies manual builds of the target, and is required by the test
856 if self.target != self.android_module and write_alias_target:
857 self.WriteLn('# Alias gyp target name.')
858 self.WriteLn('.PHONY: %s' % self.target)
859 self.WriteLn('%s: %s' % (self.target, self.android_module))
862 # Add the command to trigger build of the target type depending
863 # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY
864 # NOTE: This has to come last!
866 if self.toolset == 'host':
868 if self.type == 'static_library':
869 self.WriteLn('include $(BUILD_%sSTATIC_LIBRARY)' % modifier)
870 elif self.type == 'shared_library':
871 self.WriteLn('LOCAL_PRELINK_MODULE := false')
872 self.WriteLn('include $(BUILD_%sSHARED_LIBRARY)' % modifier)
873 elif self.type == 'executable':
874 if self.toolset == 'host':
875 self.WriteLn('LOCAL_MODULE_PATH := $(gyp_shared_intermediate_dir)')
877 # Don't install target executables for now, as it results in them being
878 # included in ROM. This can be revisited if there's a reason to install
880 self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true')
881 self.WriteLn('include $(BUILD_%sEXECUTABLE)' % modifier)
883 self.WriteLn('LOCAL_MODULE_PATH := $(PRODUCT_OUT)/gyp_stamp')
884 self.WriteLn('LOCAL_UNINSTALLABLE_MODULE := true')
885 if self.toolset == 'target':
886 self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX := $(GYP_VAR_PREFIX)')
888 self.WriteLn('include $(BUILD_SYSTEM)/base_rules.mk')
890 self.WriteLn('$(LOCAL_BUILT_MODULE): $(LOCAL_ADDITIONAL_DEPENDENCIES)')
891 self.WriteLn('\t$(hide) echo "Gyp timestamp: $@"')
892 self.WriteLn('\t$(hide) mkdir -p $(dir $@)')
893 self.WriteLn('\t$(hide) touch $@')
894 if self.toolset == 'target':
896 self.WriteLn('LOCAL_2ND_ARCH_VAR_PREFIX :=')
899 def WriteList(self, value_list, variable=None, prefix='',
900 quoter=make.QuoteIfNecessary, local_pathify=False):
901 """Write a variable definition that is a list of values.
903 E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out
905 but in a pretty-printed style.
909 value_list = [quoter(prefix + l) for l in value_list]
911 value_list = [self.LocalPathify(l) for l in value_list]
912 values = ' \\\n\t' + ' \\\n\t'.join(value_list)
913 self.fp.write('%s :=%s\n\n' % (variable, values))
916 def WriteLn(self, text=''):
917 self.fp.write(text + '\n')
920 def LocalPathify(self, path):
921 """Convert a subdirectory-relative path into a normalized path which starts
922 with the make variable $(LOCAL_PATH) (i.e. the top of the project tree).
923 Absolute paths, or paths that contain variables, are just normalized."""
924 if '$(' in path or os.path.isabs(path):
925 # path is not a file in the project tree in this case, but calling
926 # normpath is still important for trimming trailing slashes.
927 return os.path.normpath(path)
928 local_path = os.path.join('$(LOCAL_PATH)', self.path, path)
929 local_path = os.path.normpath(local_path)
930 # Check that normalizing the path didn't ../ itself out of $(LOCAL_PATH)
931 # - i.e. that the resulting path is still inside the project tree. The
932 # path may legitimately have ended up containing just $(LOCAL_PATH), though,
933 # so we don't look for a slash.
934 assert local_path.startswith('$(LOCAL_PATH)'), (
935 'Path %s attempts to escape from gyp path %s !)' % (path, self.path))
939 def ExpandInputRoot(self, template, expansion, dirname):
940 if '%(INPUT_ROOT)s' not in template and '%(INPUT_DIRNAME)s' not in template:
943 'INPUT_ROOT': expansion,
944 'INPUT_DIRNAME': dirname,
946 return os.path.normpath(path)
949 def PerformBuild(data, configurations, params):
950 # The android backend only supports the default configuration.
951 options = params['options']
952 makefile = os.path.abspath(os.path.join(options.toplevel_dir,
954 env = dict(os.environ)
955 env['ONE_SHOT_MAKEFILE'] = makefile
956 arguments = ['make', '-C', os.environ['ANDROID_BUILD_TOP'], 'gyp_all_modules']
957 print 'Building: %s' % arguments
958 subprocess.check_call(arguments, env=env)
961 def GenerateOutput(target_list, target_dicts, data, params):
962 options = params['options']
963 generator_flags = params.get('generator_flags', {})
964 builddir_name = generator_flags.get('output_dir', 'out')
965 limit_to_target_all = generator_flags.get('limit_to_target_all', False)
966 write_alias_targets = generator_flags.get('write_alias_targets', True)
967 android_top_dir = os.environ.get('ANDROID_BUILD_TOP')
968 assert android_top_dir, '$ANDROID_BUILD_TOP not set; you need to run lunch.'
970 def CalculateMakefilePath(build_file, base_name):
971 """Determine where to write a Makefile for a given gyp file."""
972 # Paths in gyp files are relative to the .gyp file, but we want
973 # paths relative to the source root for the master makefile. Grab
974 # the path of the .gyp file as the base to relativize against.
975 # E.g. "foo/bar" when we're constructing targets for "foo/bar/baz.gyp".
976 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
978 # We write the file in the base_path directory.
979 output_file = os.path.join(options.depth, base_path, base_name)
980 assert not options.generator_output, (
981 'The Android backend does not support options.generator_output.')
982 base_path = gyp.common.RelativePath(os.path.dirname(build_file),
983 options.toplevel_dir)
984 return base_path, output_file
986 # TODO: search for the first non-'Default' target. This can go
987 # away when we add verification that all targets have the
988 # necessary configurations.
989 default_configuration = None
990 toolsets = set([target_dicts[target]['toolset'] for target in target_list])
991 for target in target_list:
992 spec = target_dicts[target]
993 if spec['default_configuration'] != 'Default':
994 default_configuration = spec['default_configuration']
996 if not default_configuration:
997 default_configuration = 'Default'
1000 makefile_name = 'GypAndroid' + options.suffix + '.mk'
1001 makefile_path = os.path.join(options.toplevel_dir, makefile_name)
1002 assert not options.generator_output, (
1003 'The Android backend does not support options.generator_output.')
1004 gyp.common.EnsureDirExists(makefile_path)
1005 root_makefile = open(makefile_path, 'w')
1007 root_makefile.write(header)
1009 # We set LOCAL_PATH just once, here, to the top of the project tree. This
1010 # allows all the other paths we use to be relative to the Android.mk file,
1011 # as the Android build system expects.
1012 root_makefile.write('\nLOCAL_PATH := $(call my-dir)\n')
1014 # Find the list of targets that derive from the gyp file(s) being built.
1015 needed_targets = set()
1016 for build_file in params['build_files']:
1017 for target in gyp.common.AllTargets(target_list, target_dicts, build_file):
1018 needed_targets.add(target)
1021 include_list = set()
1022 android_modules = {}
1023 for qualified_target in target_list:
1024 build_file, target, toolset = gyp.common.ParseQualifiedTarget(
1026 relative_build_file = gyp.common.RelativePath(build_file,
1027 options.toplevel_dir)
1028 build_files.add(relative_build_file)
1029 included_files = data[build_file]['included_files']
1030 for included_file in included_files:
1031 # The included_files entries are relative to the dir of the build file
1032 # that included them, so we have to undo that and then make them relative
1034 relative_include_file = gyp.common.RelativePath(
1035 gyp.common.UnrelativePath(included_file, build_file),
1036 options.toplevel_dir)
1037 abs_include_file = os.path.abspath(relative_include_file)
1038 # If the include file is from the ~/.gyp dir, we should use absolute path
1039 # so that relocating the src dir doesn't break the path.
1040 if (params['home_dot_gyp'] and
1041 abs_include_file.startswith(params['home_dot_gyp'])):
1042 build_files.add(abs_include_file)
1044 build_files.add(relative_include_file)
1046 base_path, output_file = CalculateMakefilePath(build_file,
1047 target + '.' + toolset + options.suffix + '.mk')
1049 spec = target_dicts[qualified_target]
1050 configs = spec['configurations']
1052 part_of_all = (qualified_target in needed_targets and
1053 not int(spec.get('suppress_wildcard', False)))
1054 if limit_to_target_all and not part_of_all:
1057 relative_target = gyp.common.QualifiedTarget(relative_build_file, target,
1059 writer = AndroidMkWriter(android_top_dir)
1060 android_module = writer.Write(qualified_target, relative_target, base_path,
1061 output_file, spec, configs,
1062 part_of_all=part_of_all,
1063 write_alias_target=write_alias_targets)
1064 if android_module in android_modules:
1065 print ('ERROR: Android module names must be unique. The following '
1066 'targets both generate Android module name %s.\n %s\n %s' %
1067 (android_module, android_modules[android_module],
1070 android_modules[android_module] = qualified_target
1072 # Our root_makefile lives at the source root. Compute the relative path
1073 # from there to the output_file for including.
1074 mkfile_rel_path = gyp.common.RelativePath(output_file,
1075 os.path.dirname(makefile_path))
1076 include_list.add(mkfile_rel_path)
1078 root_makefile.write('GYP_CONFIGURATION ?= %s\n' % default_configuration)
1079 root_makefile.write('GYP_VAR_PREFIX ?=\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()