blob: d48c91ccaf29d95a4b94a25a680edeb0b6d8b80d [file] [log] [blame]
Sami Kyostila865d1d32017-12-12 18:37:04 +00001#!/usr/bin/env python
2# Copyright (C) 2017 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16# This tool translates a collection of BUILD.gn files into a mostly equivalent
17# Android.bp file for the Android Soong build system. The input to the tool is a
18# JSON description of the GN build definition generated with the following
19# command:
20#
21# gn desc out --format=json --all-toolchains "//*" > desc.json
22#
23# The tool is then given a list of GN labels for which to generate Android.bp
24# build rules. The dependencies for the GN labels are squashed to the generated
25# Android.bp target, except for actions which get their own genrule. Some
26# libraries are also mapped to their Android equivalents -- see |builtin_deps|.
27
28import argparse
Primiano Tucciedf099c2018-01-08 18:27:56 +000029import errno
Sami Kyostila865d1d32017-12-12 18:37:04 +000030import json
31import os
32import re
Sami Kyostilab27619f2017-12-13 19:22:16 +000033import shutil
34import subprocess
Sami Kyostila865d1d32017-12-12 18:37:04 +000035import sys
36
Sami Kyostilab27619f2017-12-13 19:22:16 +000037# Default targets to translate to the blueprint file.
Primiano Tucci4e49c022017-12-21 18:22:44 +010038default_targets = [
Primiano Tucciedf099c2018-01-08 18:27:56 +000039 '//:libtraced_shared',
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000040 '//:perfetto_integrationtests',
Primiano Tucci6aa75572018-03-21 05:33:14 -070041 '//:perfetto_trace_protos',
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000042 '//:perfetto_unittests',
Primiano Tucci3b729102018-01-08 18:16:36 +000043 '//:perfetto',
Primiano Tucci4e49c022017-12-21 18:22:44 +010044 '//:traced',
Primiano Tucci6067e732018-01-08 16:19:40 +000045 '//:traced_probes',
Primiano Tucci21c19d82018-03-29 12:35:08 +010046 '//:trace_to_text',
Primiano Tucci4e49c022017-12-21 18:22:44 +010047]
Sami Kyostilab27619f2017-12-13 19:22:16 +000048
Primiano Tucci6067e732018-01-08 16:19:40 +000049# Defines a custom init_rc argument to be applied to the corresponding output
50# blueprint target.
Primiano Tucci5a304532018-01-09 14:15:43 +000051target_initrc = {
52 '//:traced': 'perfetto.rc',
53}
Primiano Tucci6067e732018-01-08 16:19:40 +000054
Primiano Tucci6aa75572018-03-21 05:33:14 -070055target_host_supported = [
56 '//:perfetto_trace_protos',
57]
58
Primiano Tucci21c19d82018-03-29 12:35:08 +010059target_host_only = [
60 '//:trace_to_text',
61]
62
Sami Kyostilab27619f2017-12-13 19:22:16 +000063# Arguments for the GN output directory.
Primiano Tucciedf099c2018-01-08 18:27:56 +000064gn_args = 'target_os="android" target_cpu="arm" is_debug=false build_with_android=true'
Sami Kyostilab27619f2017-12-13 19:22:16 +000065
Sami Kyostila865d1d32017-12-12 18:37:04 +000066# All module names are prefixed with this string to avoid collisions.
67module_prefix = 'perfetto_'
68
69# Shared libraries which are directly translated to Android system equivalents.
70library_whitelist = [
71 'android',
Sami Kyostilab5b71692018-01-12 12:16:44 +000072 'binder',
Sami Kyostila865d1d32017-12-12 18:37:04 +000073 'log',
Sami Kyostilab5b71692018-01-12 12:16:44 +000074 'services',
Primiano Tucciedf099c2018-01-08 18:27:56 +000075 'utils',
Sami Kyostila865d1d32017-12-12 18:37:04 +000076]
77
78# Name of the module which settings such as compiler flags for all other
79# modules.
80defaults_module = module_prefix + 'defaults'
81
82# Location of the project in the Android source tree.
83tree_path = 'external/perfetto'
84
Primiano Tucciedf099c2018-01-08 18:27:56 +000085# Compiler flags which are passed through to the blueprint.
86cflag_whitelist = r'^-DPERFETTO.*$'
87
Florian Mayer3d5e7e62018-01-19 15:22:46 +000088# Compiler defines which are passed through to the blueprint.
89define_whitelist = r'^GOOGLE_PROTO.*$'
90
Logan Chien9bfaaf92018-02-13 18:49:24 +080091# Shared libraries which are not in PDK.
92library_not_in_pdk = {
93 'libandroid',
94 'libservices',
95}
96
Sami Kyostila865d1d32017-12-12 18:37:04 +000097
98def enable_gmock(module):
99 module.static_libs.append('libgmock')
100
101
Hector Dearman3e712a02017-12-19 16:39:59 +0000102def enable_gtest_prod(module):
103 module.static_libs.append('libgtest_prod')
104
105
Sami Kyostila865d1d32017-12-12 18:37:04 +0000106def enable_gtest(module):
107 assert module.type == 'cc_test'
108
109
110def enable_protobuf_full(module):
111 module.shared_libs.append('libprotobuf-cpp-full')
112
113
114def enable_protobuf_lite(module):
115 module.shared_libs.append('libprotobuf-cpp-lite')
116
117
118def enable_protoc_lib(module):
119 module.shared_libs.append('libprotoc')
120
121
122def enable_libunwind(module):
Sami Kyostilafc074d42017-12-15 10:33:42 +0000123 # libunwind is disabled on Darwin so we cannot depend on it.
124 pass
Sami Kyostila865d1d32017-12-12 18:37:04 +0000125
126
127# Android equivalents for third-party libraries that the upstream project
128# depends on.
129builtin_deps = {
130 '//buildtools:gmock': enable_gmock,
131 '//buildtools:gtest': enable_gtest,
Hector Dearman3e712a02017-12-19 16:39:59 +0000132 '//gn:gtest_prod_config': enable_gtest_prod,
Sami Kyostila865d1d32017-12-12 18:37:04 +0000133 '//buildtools:gtest_main': enable_gtest,
134 '//buildtools:libunwind': enable_libunwind,
135 '//buildtools:protobuf_full': enable_protobuf_full,
136 '//buildtools:protobuf_lite': enable_protobuf_lite,
137 '//buildtools:protoc_lib': enable_protoc_lib,
138}
139
140# ----------------------------------------------------------------------------
141# End of configuration.
142# ----------------------------------------------------------------------------
143
144
145class Error(Exception):
146 pass
147
148
149class ThrowingArgumentParser(argparse.ArgumentParser):
150 def __init__(self, context):
151 super(ThrowingArgumentParser, self).__init__()
152 self.context = context
153
154 def error(self, message):
155 raise Error('%s: %s' % (self.context, message))
156
157
158class Module(object):
159 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
160
161 def __init__(self, mod_type, name):
162 self.type = mod_type
163 self.name = name
164 self.srcs = []
165 self.comment = None
166 self.shared_libs = []
167 self.static_libs = []
168 self.tools = []
169 self.cmd = None
Primiano Tucci6aa75572018-03-21 05:33:14 -0700170 self.host_supported = False
Primiano Tucci6067e732018-01-08 16:19:40 +0000171 self.init_rc = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000172 self.out = []
173 self.export_include_dirs = []
174 self.generated_headers = []
Lalit Magantic5bcd792018-01-12 18:38:11 +0000175 self.export_generated_headers = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000176 self.defaults = []
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000177 self.cflags = set()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000178 self.local_include_dirs = []
Lalit Maganti41844ed2018-05-23 14:41:43 +0100179 self.user_debug_flag = False
Sami Kyostila865d1d32017-12-12 18:37:04 +0000180
181 def to_string(self, output):
182 if self.comment:
183 output.append('// %s' % self.comment)
184 output.append('%s {' % self.type)
185 self._output_field(output, 'name')
186 self._output_field(output, 'srcs')
187 self._output_field(output, 'shared_libs')
188 self._output_field(output, 'static_libs')
189 self._output_field(output, 'tools')
190 self._output_field(output, 'cmd', sort=False)
Primiano Tucci6aa75572018-03-21 05:33:14 -0700191 self._output_field(output, 'host_supported')
Primiano Tucci6067e732018-01-08 16:19:40 +0000192 self._output_field(output, 'init_rc')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000193 self._output_field(output, 'out')
194 self._output_field(output, 'export_include_dirs')
195 self._output_field(output, 'generated_headers')
Lalit Magantic5bcd792018-01-12 18:38:11 +0000196 self._output_field(output, 'export_generated_headers')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000197 self._output_field(output, 'defaults')
198 self._output_field(output, 'cflags')
199 self._output_field(output, 'local_include_dirs')
Lalit Maganti41844ed2018-05-23 14:41:43 +0100200
201 disable_pdk = any(name in library_not_in_pdk for name in self.shared_libs)
202 if self.user_debug_flag or disable_pdk:
Logan Chien9bfaaf92018-02-13 18:49:24 +0800203 output.append(' product_variables: {')
Lalit Maganti41844ed2018-05-23 14:41:43 +0100204 if disable_pdk:
205 output.append(' pdk: {')
206 output.append(' enabled: false,')
207 output.append(' },')
208 if self.user_debug_flag:
209 output.append(' debuggable: {')
210 output.append(' cflags: ["-DPERFETTO_BUILD_WITH_ANDROID_USERDEBUG"],')
211 output.append(' },')
Logan Chien9bfaaf92018-02-13 18:49:24 +0800212 output.append(' },')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000213 output.append('}')
214 output.append('')
215
216 def _output_field(self, output, name, sort=True):
217 value = getattr(self, name)
218 if not value:
219 return
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000220 if isinstance(value, set):
Logan Chien9bfaaf92018-02-13 18:49:24 +0800221 value = sorted(value)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000222 if isinstance(value, list):
223 output.append(' %s: [' % name)
224 for item in sorted(value) if sort else value:
225 output.append(' "%s",' % item)
226 output.append(' ],')
Primiano Tucci6aa75572018-03-21 05:33:14 -0700227 return
228 if isinstance(value, bool):
229 output.append(' %s: true,' % name)
230 return
231 output.append(' %s: "%s",' % (name, value))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000232
233
234class Blueprint(object):
235 """In-memory representation of an Android.bp file."""
236
237 def __init__(self):
238 self.modules = {}
239
240 def add_module(self, module):
241 """Adds a new module to the blueprint, replacing any existing module
242 with the same name.
243
244 Args:
245 module: Module instance.
246 """
247 self.modules[module.name] = module
248
249 def to_string(self, output):
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000250 for m in sorted(self.modules.itervalues(), key=lambda m: m.name):
Sami Kyostila865d1d32017-12-12 18:37:04 +0000251 m.to_string(output)
252
253
254def label_to_path(label):
255 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
256 assert label.startswith('//')
257 return label[2:]
258
259
260def label_to_module_name(label):
261 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Primiano Tucci4e49c022017-12-21 18:22:44 +0100262 module = re.sub(r'^//:?', '', label)
263 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
264 if not module.startswith(module_prefix) and label not in default_targets:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000265 return module_prefix + module
266 return module
267
268
269def label_without_toolchain(label):
270 """Strips the toolchain from a GN label.
271
272 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
273 gcc_like_host) without the parenthesised toolchain part.
274 """
275 return label.split('(')[0]
276
277
278def is_supported_source_file(name):
279 """Returns True if |name| can appear in a 'srcs' list."""
280 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
281
282
283def is_generated_by_action(desc, label):
284 """Checks if a label is generated by an action.
285
286 Returns True if a GN output label |label| is an output for any action,
287 i.e., the file is generated dynamically.
288 """
289 for target in desc.itervalues():
290 if target['type'] == 'action' and label in target['outputs']:
291 return True
292 return False
293
294
295def apply_module_dependency(blueprint, desc, module, dep_name):
296 """Recursively collect dependencies for a given module.
297
298 Walk the transitive dependencies for a GN target and apply them to a given
299 module. This effectively flattens the dependency tree so that |module|
300 directly contains all the sources, libraries, etc. in the corresponding GN
301 dependency tree.
302
303 Args:
304 blueprint: Blueprint instance which is being generated.
305 desc: JSON GN description.
306 module: Module to which dependencies should be added.
307 dep_name: GN target of the dependency.
308 """
Sami Kyostila865d1d32017-12-12 18:37:04 +0000309 # If the dependency refers to a library which we can replace with an Android
310 # equivalent, stop recursing and patch the dependency in.
311 if label_without_toolchain(dep_name) in builtin_deps:
312 builtin_deps[label_without_toolchain(dep_name)](module)
313 return
314
315 # Similarly some shared libraries are directly mapped to Android
316 # equivalents.
317 target = desc[dep_name]
318 for lib in target.get('libs', []):
319 android_lib = 'lib' + lib
320 if lib in library_whitelist and not android_lib in module.shared_libs:
321 module.shared_libs.append(android_lib)
322
323 type = target['type']
324 if type == 'action':
325 create_modules_from_target(blueprint, desc, dep_name)
326 # Depend both on the generated sources and headers -- see
327 # make_genrules_for_action.
328 module.srcs.append(':' + label_to_module_name(dep_name))
329 module.generated_headers.append(
330 label_to_module_name(dep_name) + '_headers')
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000331 elif type == 'static_library' and label_to_module_name(
332 dep_name) != module.name:
333 create_modules_from_target(blueprint, desc, dep_name)
334 module.static_libs.append(label_to_module_name(dep_name))
Primiano Tucci6067e732018-01-08 16:19:40 +0000335 elif type == 'shared_library' and label_to_module_name(
336 dep_name) != module.name:
337 module.shared_libs.append(label_to_module_name(dep_name))
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000338 elif type in ['group', 'source_set', 'executable', 'static_library'
339 ] and 'sources' in target:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000340 # Ignore source files that are generated by actions since they will be
341 # implicitly added by the genrule dependencies.
342 module.srcs.extend(
343 label_to_path(src) for src in target['sources']
344 if is_supported_source_file(src)
345 and not is_generated_by_action(desc, src))
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000346 module.cflags |= _get_cflags(target)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000347
348
349def make_genrules_for_action(blueprint, desc, target_name):
350 """Generate genrules for a GN action.
351
352 GN actions are used to dynamically generate files during the build. The
353 Soong equivalent is a genrule. This function turns a specific kind of
354 genrule which turns .proto files into source and header files into a pair
Sami Kyostila71625d72017-12-18 10:29:49 +0000355 equivalent genrules.
Sami Kyostila865d1d32017-12-12 18:37:04 +0000356
357 Args:
358 blueprint: Blueprint instance which is being generated.
359 desc: JSON GN description.
360 target_name: GN target for genrule generation.
361
362 Returns:
363 A (source_genrule, header_genrule) module tuple.
364 """
365 target = desc[target_name]
366
367 # We only support genrules which call protoc (with or without a plugin) to
368 # turn .proto files into header and source files.
369 args = target['args']
370 if not args[0].endswith('/protoc'):
371 raise Error('Unsupported action in target %s: %s' % (target_name,
372 target['args']))
Primiano Tucci20b760c2018-01-19 12:36:12 +0000373 parser = ThrowingArgumentParser('Action in target %s (%s)' %
374 (target_name, ' '.join(target['args'])))
375 parser.add_argument('--proto_path')
376 parser.add_argument('--cpp_out')
377 parser.add_argument('--plugin')
378 parser.add_argument('--plugin_out')
379 parser.add_argument('protos', nargs=argparse.REMAINDER)
380 args = parser.parse_args(args[1:])
381
382 # Depending on whether we are using the default protoc C++ generator or the
383 # protozero plugin, the output dir is passed as:
384 # --cpp_out=gen/xxx or
385 # --plugin_out=:gen/xxx or
386 # --plugin_out=wrapper_namespace=pbzero:gen/xxx
387 gen_dir = args.cpp_out if args.cpp_out else args.plugin_out.split(':')[1]
388 assert gen_dir.startswith('gen/')
389 gen_dir = gen_dir[4:]
390 cpp_out_dir = ('$(genDir)/%s/%s' % (tree_path, gen_dir)).rstrip('/')
391
392 # TODO(skyostil): Is there a way to avoid hardcoding the tree path here?
393 # TODO(skyostil): Find a way to avoid creating the directory.
394 cmd = [
395 'mkdir -p %s &&' % cpp_out_dir,
396 '$(location aprotoc)',
397 '--cpp_out=%s' % cpp_out_dir
398 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000399
400 # We create two genrules for each action: one for the protobuf headers and
401 # another for the sources. This is because the module that depends on the
402 # generated files needs to declare two different types of dependencies --
403 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
404 # valid to generate .h files from a source dependency and vice versa.
Sami Kyostila71625d72017-12-18 10:29:49 +0000405 source_module = Module('genrule', label_to_module_name(target_name))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000406 source_module.srcs.extend(label_to_path(src) for src in target['sources'])
407 source_module.tools = ['aprotoc']
408
Sami Kyostila71625d72017-12-18 10:29:49 +0000409 header_module = Module('genrule',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000410 label_to_module_name(target_name) + '_headers')
411 header_module.srcs = source_module.srcs[:]
412 header_module.tools = source_module.tools[:]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000413 header_module.export_include_dirs = [gen_dir or '.']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000414
Primiano Tucci20b760c2018-01-19 12:36:12 +0000415 # In GN builds the proto path is always relative to the output directory
416 # (out/tmp.xxx).
417 assert args.proto_path.startswith('../../')
418 cmd += [ '--proto_path=%s/%s' % (tree_path, args.proto_path[6:])]
419
Sami Kyostila865d1d32017-12-12 18:37:04 +0000420 namespaces = ['pb']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000421 if args.plugin:
422 _, plugin = os.path.split(args.plugin)
423 # TODO(skyostil): Can we detect this some other way?
424 if plugin == 'ipc_plugin':
425 namespaces.append('ipc')
426 elif plugin == 'protoc_plugin':
427 namespaces = ['pbzero']
428 for dep in target['deps']:
429 if desc[dep]['type'] != 'executable':
430 continue
431 _, executable = os.path.split(desc[dep]['outputs'][0])
432 if executable == plugin:
433 cmd += [
434 '--plugin=protoc-gen-plugin=$(location %s)' %
435 label_to_module_name(dep)
436 ]
437 source_module.tools.append(label_to_module_name(dep))
438 # Also make sure the module for the tool is generated.
439 create_modules_from_target(blueprint, desc, dep)
440 break
441 else:
442 raise Error('Unrecognized protoc plugin in target %s: %s' %
443 (target_name, args[i]))
444 if args.plugin_out:
445 plugin_args = args.plugin_out.split(':')[0]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000446 cmd += ['--plugin_out=%s:%s' % (plugin_args, cpp_out_dir)]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000447
448 cmd += ['$(in)']
449 source_module.cmd = ' '.join(cmd)
450 header_module.cmd = source_module.cmd
451 header_module.tools = source_module.tools[:]
452
453 for ns in namespaces:
454 source_module.out += [
455 '%s/%s' % (tree_path, src.replace('.proto', '.%s.cc' % ns))
456 for src in source_module.srcs
457 ]
458 header_module.out += [
459 '%s/%s' % (tree_path, src.replace('.proto', '.%s.h' % ns))
460 for src in header_module.srcs
461 ]
462 return source_module, header_module
463
464
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000465def _get_cflags(target):
466 cflags = set(flag for flag in target.get('cflags', [])
467 if re.match(cflag_whitelist, flag))
468 cflags |= set("-D%s" % define for define in target.get('defines', [])
469 if re.match(define_whitelist, define))
470 return cflags
471
472
Sami Kyostila865d1d32017-12-12 18:37:04 +0000473def create_modules_from_target(blueprint, desc, target_name):
474 """Generate module(s) for a given GN target.
475
476 Given a GN target name, generate one or more corresponding modules into a
477 blueprint.
478
479 Args:
480 blueprint: Blueprint instance which is being generated.
481 desc: JSON GN description.
482 target_name: GN target for module generation.
483 """
484 target = desc[target_name]
485 if target['type'] == 'executable':
Primiano Tucci21c19d82018-03-29 12:35:08 +0100486 if 'host' in target['toolchain'] or target_name in target_host_only:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000487 module_type = 'cc_binary_host'
488 elif target.get('testonly'):
489 module_type = 'cc_test'
490 else:
491 module_type = 'cc_binary'
492 modules = [Module(module_type, label_to_module_name(target_name))]
493 elif target['type'] == 'action':
494 modules = make_genrules_for_action(blueprint, desc, target_name)
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000495 elif target['type'] == 'static_library':
Lalit Magantic5bcd792018-01-12 18:38:11 +0000496 module = Module('cc_library_static', label_to_module_name(target_name))
497 module.export_include_dirs = ['include']
498 modules = [module]
Primiano Tucci6067e732018-01-08 16:19:40 +0000499 elif target['type'] == 'shared_library':
500 modules = [
501 Module('cc_library_shared', label_to_module_name(target_name))
502 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000503 else:
504 raise Error('Unknown target type: %s' % target['type'])
505
506 for module in modules:
507 module.comment = 'GN target: %s' % target_name
Primiano Tucci6067e732018-01-08 16:19:40 +0000508 if target_name in target_initrc:
509 module.init_rc = [target_initrc[target_name]]
Primiano Tucci6aa75572018-03-21 05:33:14 -0700510 if target_name in target_host_supported:
511 module.host_supported = True
Primiano Tucci6067e732018-01-08 16:19:40 +0000512
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000513 # Don't try to inject library/source dependencies into genrules because
514 # they are not compiled in the traditional sense.
Sami Kyostila71625d72017-12-18 10:29:49 +0000515 if module.type != 'genrule':
Sami Kyostila865d1d32017-12-12 18:37:04 +0000516 module.defaults = [defaults_module]
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000517 apply_module_dependency(blueprint, desc, module, target_name)
518 for dep in resolve_dependencies(desc, target_name):
519 apply_module_dependency(blueprint, desc, module, dep)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000520
Lalit Magantic5bcd792018-01-12 18:38:11 +0000521 # If the module is a static library, export all the generated headers.
522 if module.type == 'cc_library_static':
523 module.export_generated_headers = module.generated_headers
524
Sami Kyostila865d1d32017-12-12 18:37:04 +0000525 blueprint.add_module(module)
526
527
528def resolve_dependencies(desc, target_name):
529 """Return the transitive set of dependent-on targets for a GN target.
530
531 Args:
532 blueprint: Blueprint instance which is being generated.
533 desc: JSON GN description.
534
535 Returns:
536 A set of transitive dependencies in the form of GN targets.
537 """
538
539 if label_without_toolchain(target_name) in builtin_deps:
540 return set()
541 target = desc[target_name]
542 resolved_deps = set()
543 for dep in target.get('deps', []):
544 resolved_deps.add(dep)
545 # Ignore the transitive dependencies of actions because they are
546 # explicitly converted to genrules.
547 if desc[dep]['type'] == 'action':
548 continue
Primiano Tucci6067e732018-01-08 16:19:40 +0000549 # Dependencies on shared libraries shouldn't propagate any transitive
550 # dependencies but only depend on the shared library target
551 if desc[dep]['type'] == 'shared_library':
552 continue
Sami Kyostila865d1d32017-12-12 18:37:04 +0000553 resolved_deps.update(resolve_dependencies(desc, dep))
554 return resolved_deps
555
556
557def create_blueprint_for_targets(desc, targets):
558 """Generate a blueprint for a list of GN targets."""
559 blueprint = Blueprint()
560
561 # Default settings used by all modules.
562 defaults = Module('cc_defaults', defaults_module)
563 defaults.local_include_dirs = ['include']
564 defaults.cflags = [
565 '-Wno-error=return-type',
566 '-Wno-sign-compare',
567 '-Wno-sign-promo',
568 '-Wno-unused-parameter',
Florian Mayercc424fd2018-01-15 11:19:01 +0000569 '-fvisibility=hidden',
Florian Mayerc2a38ea2018-01-19 11:48:43 +0000570 '-Oz',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000571 ]
Lalit Maganti41844ed2018-05-23 14:41:43 +0100572 defaults.user_debug_flag = True
Sami Kyostila865d1d32017-12-12 18:37:04 +0000573
574 blueprint.add_module(defaults)
575 for target in targets:
576 create_modules_from_target(blueprint, desc, target)
577 return blueprint
578
579
Sami Kyostilab27619f2017-12-13 19:22:16 +0000580def repo_root():
581 """Returns an absolute path to the repository root."""
582
583 return os.path.join(
584 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
585
586
587def create_build_description():
588 """Creates the JSON build description by running GN."""
589
590 out = os.path.join(repo_root(), 'out', 'tmp.gen_android_bp')
591 try:
592 try:
593 os.makedirs(out)
594 except OSError as e:
595 if e.errno != errno.EEXIST:
596 raise
597 subprocess.check_output(
598 ['gn', 'gen', out, '--args=%s' % gn_args], cwd=repo_root())
599 desc = subprocess.check_output(
600 ['gn', 'desc', out, '--format=json', '--all-toolchains', '//*'],
601 cwd=repo_root())
602 return json.loads(desc)
603 finally:
604 shutil.rmtree(out)
605
606
Sami Kyostila865d1d32017-12-12 18:37:04 +0000607def main():
608 parser = argparse.ArgumentParser(
609 description='Generate Android.bp from a GN description.')
610 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000611 '--desc',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000612 help=
613 'GN description (e.g., gn desc out --format=json --all-toolchains "//*"'
614 )
615 parser.add_argument(
Lalit Magantic5bcd792018-01-12 18:38:11 +0000616 '--extras',
617 help='Extra targets to include at the end of the Blueprint file',
618 default=os.path.join(repo_root(), 'Android.bp.extras'),
619 )
620 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000621 '--output',
622 help='Blueprint file to create',
623 default=os.path.join(repo_root(), 'Android.bp'),
624 )
625 parser.add_argument(
Sami Kyostila865d1d32017-12-12 18:37:04 +0000626 'targets',
627 nargs=argparse.REMAINDER,
628 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")')
629 args = parser.parse_args()
630
Sami Kyostilab27619f2017-12-13 19:22:16 +0000631 if args.desc:
632 with open(args.desc) as f:
633 desc = json.load(f)
634 else:
635 desc = create_build_description()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000636
Sami Kyostilab27619f2017-12-13 19:22:16 +0000637 blueprint = create_blueprint_for_targets(desc, args.targets
638 or default_targets)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000639 output = [
640 """// Copyright (C) 2017 The Android Open Source Project
641//
642// Licensed under the Apache License, Version 2.0 (the "License");
643// you may not use this file except in compliance with the License.
644// You may obtain a copy of the License at
645//
646// http://www.apache.org/licenses/LICENSE-2.0
647//
648// Unless required by applicable law or agreed to in writing, software
649// distributed under the License is distributed on an "AS IS" BASIS,
650// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
651// See the License for the specific language governing permissions and
652// limitations under the License.
653//
654// This file is automatically generated by %s. Do not edit.
655""" % (__file__)
656 ]
657 blueprint.to_string(output)
Lalit Magantic5bcd792018-01-12 18:38:11 +0000658 with open(args.extras, 'r') as r:
659 for line in r:
660 output.append(line.rstrip("\n\r"))
Sami Kyostilab27619f2017-12-13 19:22:16 +0000661 with open(args.output, 'w') as f:
662 f.write('\n'.join(output))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000663
664
665if __name__ == '__main__':
666 sys.exit(main())