blob: 728ed238b0993555aa2cdcc84145e0d02017168a [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 Tucci4e49c022017-12-21 18:22:44 +010046]
Sami Kyostilab27619f2017-12-13 19:22:16 +000047
Primiano Tucci6067e732018-01-08 16:19:40 +000048# Defines a custom init_rc argument to be applied to the corresponding output
49# blueprint target.
Primiano Tucci5a304532018-01-09 14:15:43 +000050target_initrc = {
51 '//:traced': 'perfetto.rc',
52}
Primiano Tucci6067e732018-01-08 16:19:40 +000053
Primiano Tucci6aa75572018-03-21 05:33:14 -070054target_host_supported = [
55 '//:perfetto_trace_protos',
56]
57
Sami Kyostilab27619f2017-12-13 19:22:16 +000058# Arguments for the GN output directory.
Primiano Tucciedf099c2018-01-08 18:27:56 +000059gn_args = 'target_os="android" target_cpu="arm" is_debug=false build_with_android=true'
Sami Kyostilab27619f2017-12-13 19:22:16 +000060
Sami Kyostila865d1d32017-12-12 18:37:04 +000061# All module names are prefixed with this string to avoid collisions.
62module_prefix = 'perfetto_'
63
64# Shared libraries which are directly translated to Android system equivalents.
65library_whitelist = [
66 'android',
Sami Kyostilab5b71692018-01-12 12:16:44 +000067 'binder',
Sami Kyostila865d1d32017-12-12 18:37:04 +000068 'log',
Sami Kyostilab5b71692018-01-12 12:16:44 +000069 'services',
Primiano Tucciedf099c2018-01-08 18:27:56 +000070 'utils',
Sami Kyostila865d1d32017-12-12 18:37:04 +000071]
72
73# Name of the module which settings such as compiler flags for all other
74# modules.
75defaults_module = module_prefix + 'defaults'
76
77# Location of the project in the Android source tree.
78tree_path = 'external/perfetto'
79
Primiano Tucciedf099c2018-01-08 18:27:56 +000080# Compiler flags which are passed through to the blueprint.
81cflag_whitelist = r'^-DPERFETTO.*$'
82
Florian Mayer3d5e7e62018-01-19 15:22:46 +000083# Compiler defines which are passed through to the blueprint.
84define_whitelist = r'^GOOGLE_PROTO.*$'
85
Logan Chien9bfaaf92018-02-13 18:49:24 +080086# Shared libraries which are not in PDK.
87library_not_in_pdk = {
88 'libandroid',
89 'libservices',
90}
91
Sami Kyostila865d1d32017-12-12 18:37:04 +000092
93def enable_gmock(module):
94 module.static_libs.append('libgmock')
95
96
Hector Dearman3e712a02017-12-19 16:39:59 +000097def enable_gtest_prod(module):
98 module.static_libs.append('libgtest_prod')
99
100
Sami Kyostila865d1d32017-12-12 18:37:04 +0000101def enable_gtest(module):
102 assert module.type == 'cc_test'
103
104
105def enable_protobuf_full(module):
106 module.shared_libs.append('libprotobuf-cpp-full')
107
108
109def enable_protobuf_lite(module):
110 module.shared_libs.append('libprotobuf-cpp-lite')
111
112
113def enable_protoc_lib(module):
114 module.shared_libs.append('libprotoc')
115
116
117def enable_libunwind(module):
Sami Kyostilafc074d42017-12-15 10:33:42 +0000118 # libunwind is disabled on Darwin so we cannot depend on it.
119 pass
Sami Kyostila865d1d32017-12-12 18:37:04 +0000120
121
122# Android equivalents for third-party libraries that the upstream project
123# depends on.
124builtin_deps = {
125 '//buildtools:gmock': enable_gmock,
126 '//buildtools:gtest': enable_gtest,
Hector Dearman3e712a02017-12-19 16:39:59 +0000127 '//gn:gtest_prod_config': enable_gtest_prod,
Sami Kyostila865d1d32017-12-12 18:37:04 +0000128 '//buildtools:gtest_main': enable_gtest,
129 '//buildtools:libunwind': enable_libunwind,
130 '//buildtools:protobuf_full': enable_protobuf_full,
131 '//buildtools:protobuf_lite': enable_protobuf_lite,
132 '//buildtools:protoc_lib': enable_protoc_lib,
133}
134
135# ----------------------------------------------------------------------------
136# End of configuration.
137# ----------------------------------------------------------------------------
138
139
140class Error(Exception):
141 pass
142
143
144class ThrowingArgumentParser(argparse.ArgumentParser):
145 def __init__(self, context):
146 super(ThrowingArgumentParser, self).__init__()
147 self.context = context
148
149 def error(self, message):
150 raise Error('%s: %s' % (self.context, message))
151
152
153class Module(object):
154 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
155
156 def __init__(self, mod_type, name):
157 self.type = mod_type
158 self.name = name
159 self.srcs = []
160 self.comment = None
161 self.shared_libs = []
162 self.static_libs = []
163 self.tools = []
164 self.cmd = None
Primiano Tucci6aa75572018-03-21 05:33:14 -0700165 self.host_supported = False
Primiano Tucci6067e732018-01-08 16:19:40 +0000166 self.init_rc = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000167 self.out = []
168 self.export_include_dirs = []
169 self.generated_headers = []
Lalit Magantic5bcd792018-01-12 18:38:11 +0000170 self.export_generated_headers = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000171 self.defaults = []
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000172 self.cflags = set()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000173 self.local_include_dirs = []
174
175 def to_string(self, output):
176 if self.comment:
177 output.append('// %s' % self.comment)
178 output.append('%s {' % self.type)
179 self._output_field(output, 'name')
180 self._output_field(output, 'srcs')
181 self._output_field(output, 'shared_libs')
182 self._output_field(output, 'static_libs')
183 self._output_field(output, 'tools')
184 self._output_field(output, 'cmd', sort=False)
Primiano Tucci6aa75572018-03-21 05:33:14 -0700185 self._output_field(output, 'host_supported')
Primiano Tucci6067e732018-01-08 16:19:40 +0000186 self._output_field(output, 'init_rc')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000187 self._output_field(output, 'out')
188 self._output_field(output, 'export_include_dirs')
189 self._output_field(output, 'generated_headers')
Lalit Magantic5bcd792018-01-12 18:38:11 +0000190 self._output_field(output, 'export_generated_headers')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000191 self._output_field(output, 'defaults')
192 self._output_field(output, 'cflags')
193 self._output_field(output, 'local_include_dirs')
Logan Chien9bfaaf92018-02-13 18:49:24 +0800194 if any(name in library_not_in_pdk for name in self.shared_libs):
195 output.append(' product_variables: {')
196 output.append(' pdk: {')
197 output.append(' enabled: false,')
198 output.append(' },')
199 output.append(' },')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000200 output.append('}')
201 output.append('')
202
203 def _output_field(self, output, name, sort=True):
204 value = getattr(self, name)
205 if not value:
206 return
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000207 if isinstance(value, set):
Logan Chien9bfaaf92018-02-13 18:49:24 +0800208 value = sorted(value)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000209 if isinstance(value, list):
210 output.append(' %s: [' % name)
211 for item in sorted(value) if sort else value:
212 output.append(' "%s",' % item)
213 output.append(' ],')
Primiano Tucci6aa75572018-03-21 05:33:14 -0700214 return
215 if isinstance(value, bool):
216 output.append(' %s: true,' % name)
217 return
218 output.append(' %s: "%s",' % (name, value))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000219
220
221class Blueprint(object):
222 """In-memory representation of an Android.bp file."""
223
224 def __init__(self):
225 self.modules = {}
226
227 def add_module(self, module):
228 """Adds a new module to the blueprint, replacing any existing module
229 with the same name.
230
231 Args:
232 module: Module instance.
233 """
234 self.modules[module.name] = module
235
236 def to_string(self, output):
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000237 for m in sorted(self.modules.itervalues(), key=lambda m: m.name):
Sami Kyostila865d1d32017-12-12 18:37:04 +0000238 m.to_string(output)
239
240
241def label_to_path(label):
242 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
243 assert label.startswith('//')
244 return label[2:]
245
246
247def label_to_module_name(label):
248 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Primiano Tucci4e49c022017-12-21 18:22:44 +0100249 module = re.sub(r'^//:?', '', label)
250 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
251 if not module.startswith(module_prefix) and label not in default_targets:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000252 return module_prefix + module
253 return module
254
255
256def label_without_toolchain(label):
257 """Strips the toolchain from a GN label.
258
259 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
260 gcc_like_host) without the parenthesised toolchain part.
261 """
262 return label.split('(')[0]
263
264
265def is_supported_source_file(name):
266 """Returns True if |name| can appear in a 'srcs' list."""
267 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
268
269
270def is_generated_by_action(desc, label):
271 """Checks if a label is generated by an action.
272
273 Returns True if a GN output label |label| is an output for any action,
274 i.e., the file is generated dynamically.
275 """
276 for target in desc.itervalues():
277 if target['type'] == 'action' and label in target['outputs']:
278 return True
279 return False
280
281
282def apply_module_dependency(blueprint, desc, module, dep_name):
283 """Recursively collect dependencies for a given module.
284
285 Walk the transitive dependencies for a GN target and apply them to a given
286 module. This effectively flattens the dependency tree so that |module|
287 directly contains all the sources, libraries, etc. in the corresponding GN
288 dependency tree.
289
290 Args:
291 blueprint: Blueprint instance which is being generated.
292 desc: JSON GN description.
293 module: Module to which dependencies should be added.
294 dep_name: GN target of the dependency.
295 """
Sami Kyostila865d1d32017-12-12 18:37:04 +0000296 # If the dependency refers to a library which we can replace with an Android
297 # equivalent, stop recursing and patch the dependency in.
298 if label_without_toolchain(dep_name) in builtin_deps:
299 builtin_deps[label_without_toolchain(dep_name)](module)
300 return
301
302 # Similarly some shared libraries are directly mapped to Android
303 # equivalents.
304 target = desc[dep_name]
305 for lib in target.get('libs', []):
306 android_lib = 'lib' + lib
307 if lib in library_whitelist and not android_lib in module.shared_libs:
308 module.shared_libs.append(android_lib)
309
310 type = target['type']
311 if type == 'action':
312 create_modules_from_target(blueprint, desc, dep_name)
313 # Depend both on the generated sources and headers -- see
314 # make_genrules_for_action.
315 module.srcs.append(':' + label_to_module_name(dep_name))
316 module.generated_headers.append(
317 label_to_module_name(dep_name) + '_headers')
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000318 elif type == 'static_library' and label_to_module_name(
319 dep_name) != module.name:
320 create_modules_from_target(blueprint, desc, dep_name)
321 module.static_libs.append(label_to_module_name(dep_name))
Primiano Tucci6067e732018-01-08 16:19:40 +0000322 elif type == 'shared_library' and label_to_module_name(
323 dep_name) != module.name:
324 module.shared_libs.append(label_to_module_name(dep_name))
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000325 elif type in ['group', 'source_set', 'executable', 'static_library'
326 ] and 'sources' in target:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000327 # Ignore source files that are generated by actions since they will be
328 # implicitly added by the genrule dependencies.
329 module.srcs.extend(
330 label_to_path(src) for src in target['sources']
331 if is_supported_source_file(src)
332 and not is_generated_by_action(desc, src))
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000333 module.cflags |= _get_cflags(target)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000334
335
336def make_genrules_for_action(blueprint, desc, target_name):
337 """Generate genrules for a GN action.
338
339 GN actions are used to dynamically generate files during the build. The
340 Soong equivalent is a genrule. This function turns a specific kind of
341 genrule which turns .proto files into source and header files into a pair
Sami Kyostila71625d72017-12-18 10:29:49 +0000342 equivalent genrules.
Sami Kyostila865d1d32017-12-12 18:37:04 +0000343
344 Args:
345 blueprint: Blueprint instance which is being generated.
346 desc: JSON GN description.
347 target_name: GN target for genrule generation.
348
349 Returns:
350 A (source_genrule, header_genrule) module tuple.
351 """
352 target = desc[target_name]
353
354 # We only support genrules which call protoc (with or without a plugin) to
355 # turn .proto files into header and source files.
356 args = target['args']
357 if not args[0].endswith('/protoc'):
358 raise Error('Unsupported action in target %s: %s' % (target_name,
359 target['args']))
Primiano Tucci20b760c2018-01-19 12:36:12 +0000360 parser = ThrowingArgumentParser('Action in target %s (%s)' %
361 (target_name, ' '.join(target['args'])))
362 parser.add_argument('--proto_path')
363 parser.add_argument('--cpp_out')
364 parser.add_argument('--plugin')
365 parser.add_argument('--plugin_out')
366 parser.add_argument('protos', nargs=argparse.REMAINDER)
367 args = parser.parse_args(args[1:])
368
369 # Depending on whether we are using the default protoc C++ generator or the
370 # protozero plugin, the output dir is passed as:
371 # --cpp_out=gen/xxx or
372 # --plugin_out=:gen/xxx or
373 # --plugin_out=wrapper_namespace=pbzero:gen/xxx
374 gen_dir = args.cpp_out if args.cpp_out else args.plugin_out.split(':')[1]
375 assert gen_dir.startswith('gen/')
376 gen_dir = gen_dir[4:]
377 cpp_out_dir = ('$(genDir)/%s/%s' % (tree_path, gen_dir)).rstrip('/')
378
379 # TODO(skyostil): Is there a way to avoid hardcoding the tree path here?
380 # TODO(skyostil): Find a way to avoid creating the directory.
381 cmd = [
382 'mkdir -p %s &&' % cpp_out_dir,
383 '$(location aprotoc)',
384 '--cpp_out=%s' % cpp_out_dir
385 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000386
387 # We create two genrules for each action: one for the protobuf headers and
388 # another for the sources. This is because the module that depends on the
389 # generated files needs to declare two different types of dependencies --
390 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
391 # valid to generate .h files from a source dependency and vice versa.
Sami Kyostila71625d72017-12-18 10:29:49 +0000392 source_module = Module('genrule', label_to_module_name(target_name))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000393 source_module.srcs.extend(label_to_path(src) for src in target['sources'])
394 source_module.tools = ['aprotoc']
395
Sami Kyostila71625d72017-12-18 10:29:49 +0000396 header_module = Module('genrule',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000397 label_to_module_name(target_name) + '_headers')
398 header_module.srcs = source_module.srcs[:]
399 header_module.tools = source_module.tools[:]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000400 header_module.export_include_dirs = [gen_dir or '.']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000401
Primiano Tucci20b760c2018-01-19 12:36:12 +0000402 # In GN builds the proto path is always relative to the output directory
403 # (out/tmp.xxx).
404 assert args.proto_path.startswith('../../')
405 cmd += [ '--proto_path=%s/%s' % (tree_path, args.proto_path[6:])]
406
Sami Kyostila865d1d32017-12-12 18:37:04 +0000407 namespaces = ['pb']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000408 if args.plugin:
409 _, plugin = os.path.split(args.plugin)
410 # TODO(skyostil): Can we detect this some other way?
411 if plugin == 'ipc_plugin':
412 namespaces.append('ipc')
413 elif plugin == 'protoc_plugin':
414 namespaces = ['pbzero']
415 for dep in target['deps']:
416 if desc[dep]['type'] != 'executable':
417 continue
418 _, executable = os.path.split(desc[dep]['outputs'][0])
419 if executable == plugin:
420 cmd += [
421 '--plugin=protoc-gen-plugin=$(location %s)' %
422 label_to_module_name(dep)
423 ]
424 source_module.tools.append(label_to_module_name(dep))
425 # Also make sure the module for the tool is generated.
426 create_modules_from_target(blueprint, desc, dep)
427 break
428 else:
429 raise Error('Unrecognized protoc plugin in target %s: %s' %
430 (target_name, args[i]))
431 if args.plugin_out:
432 plugin_args = args.plugin_out.split(':')[0]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000433 cmd += ['--plugin_out=%s:%s' % (plugin_args, cpp_out_dir)]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000434
435 cmd += ['$(in)']
436 source_module.cmd = ' '.join(cmd)
437 header_module.cmd = source_module.cmd
438 header_module.tools = source_module.tools[:]
439
440 for ns in namespaces:
441 source_module.out += [
442 '%s/%s' % (tree_path, src.replace('.proto', '.%s.cc' % ns))
443 for src in source_module.srcs
444 ]
445 header_module.out += [
446 '%s/%s' % (tree_path, src.replace('.proto', '.%s.h' % ns))
447 for src in header_module.srcs
448 ]
449 return source_module, header_module
450
451
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000452def _get_cflags(target):
453 cflags = set(flag for flag in target.get('cflags', [])
454 if re.match(cflag_whitelist, flag))
455 cflags |= set("-D%s" % define for define in target.get('defines', [])
456 if re.match(define_whitelist, define))
457 return cflags
458
459
Sami Kyostila865d1d32017-12-12 18:37:04 +0000460def create_modules_from_target(blueprint, desc, target_name):
461 """Generate module(s) for a given GN target.
462
463 Given a GN target name, generate one or more corresponding modules into a
464 blueprint.
465
466 Args:
467 blueprint: Blueprint instance which is being generated.
468 desc: JSON GN description.
469 target_name: GN target for module generation.
470 """
471 target = desc[target_name]
472 if target['type'] == 'executable':
473 if 'host' in target['toolchain']:
474 module_type = 'cc_binary_host'
475 elif target.get('testonly'):
476 module_type = 'cc_test'
477 else:
478 module_type = 'cc_binary'
479 modules = [Module(module_type, label_to_module_name(target_name))]
480 elif target['type'] == 'action':
481 modules = make_genrules_for_action(blueprint, desc, target_name)
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000482 elif target['type'] == 'static_library':
Lalit Magantic5bcd792018-01-12 18:38:11 +0000483 module = Module('cc_library_static', label_to_module_name(target_name))
484 module.export_include_dirs = ['include']
485 modules = [module]
Primiano Tucci6067e732018-01-08 16:19:40 +0000486 elif target['type'] == 'shared_library':
487 modules = [
488 Module('cc_library_shared', label_to_module_name(target_name))
489 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000490 else:
491 raise Error('Unknown target type: %s' % target['type'])
492
493 for module in modules:
494 module.comment = 'GN target: %s' % target_name
Primiano Tucci6067e732018-01-08 16:19:40 +0000495 if target_name in target_initrc:
496 module.init_rc = [target_initrc[target_name]]
Primiano Tucci6aa75572018-03-21 05:33:14 -0700497 if target_name in target_host_supported:
498 module.host_supported = True
Primiano Tucci6067e732018-01-08 16:19:40 +0000499
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000500 # Don't try to inject library/source dependencies into genrules because
501 # they are not compiled in the traditional sense.
Sami Kyostila71625d72017-12-18 10:29:49 +0000502 if module.type != 'genrule':
Sami Kyostila865d1d32017-12-12 18:37:04 +0000503 module.defaults = [defaults_module]
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000504 apply_module_dependency(blueprint, desc, module, target_name)
505 for dep in resolve_dependencies(desc, target_name):
506 apply_module_dependency(blueprint, desc, module, dep)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000507
Lalit Magantic5bcd792018-01-12 18:38:11 +0000508 # If the module is a static library, export all the generated headers.
509 if module.type == 'cc_library_static':
510 module.export_generated_headers = module.generated_headers
511
Sami Kyostila865d1d32017-12-12 18:37:04 +0000512 blueprint.add_module(module)
513
514
515def resolve_dependencies(desc, target_name):
516 """Return the transitive set of dependent-on targets for a GN target.
517
518 Args:
519 blueprint: Blueprint instance which is being generated.
520 desc: JSON GN description.
521
522 Returns:
523 A set of transitive dependencies in the form of GN targets.
524 """
525
526 if label_without_toolchain(target_name) in builtin_deps:
527 return set()
528 target = desc[target_name]
529 resolved_deps = set()
530 for dep in target.get('deps', []):
531 resolved_deps.add(dep)
532 # Ignore the transitive dependencies of actions because they are
533 # explicitly converted to genrules.
534 if desc[dep]['type'] == 'action':
535 continue
Primiano Tucci6067e732018-01-08 16:19:40 +0000536 # Dependencies on shared libraries shouldn't propagate any transitive
537 # dependencies but only depend on the shared library target
538 if desc[dep]['type'] == 'shared_library':
539 continue
Sami Kyostila865d1d32017-12-12 18:37:04 +0000540 resolved_deps.update(resolve_dependencies(desc, dep))
541 return resolved_deps
542
543
544def create_blueprint_for_targets(desc, targets):
545 """Generate a blueprint for a list of GN targets."""
546 blueprint = Blueprint()
547
548 # Default settings used by all modules.
549 defaults = Module('cc_defaults', defaults_module)
550 defaults.local_include_dirs = ['include']
551 defaults.cflags = [
552 '-Wno-error=return-type',
553 '-Wno-sign-compare',
554 '-Wno-sign-promo',
555 '-Wno-unused-parameter',
Florian Mayercc424fd2018-01-15 11:19:01 +0000556 '-fvisibility=hidden',
Florian Mayerc2a38ea2018-01-19 11:48:43 +0000557 '-Oz',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000558 ]
559
560 blueprint.add_module(defaults)
561 for target in targets:
562 create_modules_from_target(blueprint, desc, target)
563 return blueprint
564
565
Sami Kyostilab27619f2017-12-13 19:22:16 +0000566def repo_root():
567 """Returns an absolute path to the repository root."""
568
569 return os.path.join(
570 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
571
572
573def create_build_description():
574 """Creates the JSON build description by running GN."""
575
576 out = os.path.join(repo_root(), 'out', 'tmp.gen_android_bp')
577 try:
578 try:
579 os.makedirs(out)
580 except OSError as e:
581 if e.errno != errno.EEXIST:
582 raise
583 subprocess.check_output(
584 ['gn', 'gen', out, '--args=%s' % gn_args], cwd=repo_root())
585 desc = subprocess.check_output(
586 ['gn', 'desc', out, '--format=json', '--all-toolchains', '//*'],
587 cwd=repo_root())
588 return json.loads(desc)
589 finally:
590 shutil.rmtree(out)
591
592
Sami Kyostila865d1d32017-12-12 18:37:04 +0000593def main():
594 parser = argparse.ArgumentParser(
595 description='Generate Android.bp from a GN description.')
596 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000597 '--desc',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000598 help=
599 'GN description (e.g., gn desc out --format=json --all-toolchains "//*"'
600 )
601 parser.add_argument(
Lalit Magantic5bcd792018-01-12 18:38:11 +0000602 '--extras',
603 help='Extra targets to include at the end of the Blueprint file',
604 default=os.path.join(repo_root(), 'Android.bp.extras'),
605 )
606 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000607 '--output',
608 help='Blueprint file to create',
609 default=os.path.join(repo_root(), 'Android.bp'),
610 )
611 parser.add_argument(
Sami Kyostila865d1d32017-12-12 18:37:04 +0000612 'targets',
613 nargs=argparse.REMAINDER,
614 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")')
615 args = parser.parse_args()
616
Sami Kyostilab27619f2017-12-13 19:22:16 +0000617 if args.desc:
618 with open(args.desc) as f:
619 desc = json.load(f)
620 else:
621 desc = create_build_description()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000622
Sami Kyostilab27619f2017-12-13 19:22:16 +0000623 blueprint = create_blueprint_for_targets(desc, args.targets
624 or default_targets)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000625 output = [
626 """// Copyright (C) 2017 The Android Open Source Project
627//
628// Licensed under the Apache License, Version 2.0 (the "License");
629// you may not use this file except in compliance with the License.
630// You may obtain a copy of the License at
631//
632// http://www.apache.org/licenses/LICENSE-2.0
633//
634// Unless required by applicable law or agreed to in writing, software
635// distributed under the License is distributed on an "AS IS" BASIS,
636// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
637// See the License for the specific language governing permissions and
638// limitations under the License.
639//
640// This file is automatically generated by %s. Do not edit.
641""" % (__file__)
642 ]
643 blueprint.to_string(output)
Lalit Magantic5bcd792018-01-12 18:38:11 +0000644 with open(args.extras, 'r') as r:
645 for line in r:
646 output.append(line.rstrip("\n\r"))
Sami Kyostilab27619f2017-12-13 19:22:16 +0000647 with open(args.output, 'w') as f:
648 f.write('\n'.join(output))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000649
650
651if __name__ == '__main__':
652 sys.exit(main())