blob: f71e00183cf7d0f9f4c81d6bf960c74cbeb3a17b [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 = []
179
180 def to_string(self, output):
181 if self.comment:
182 output.append('// %s' % self.comment)
183 output.append('%s {' % self.type)
184 self._output_field(output, 'name')
185 self._output_field(output, 'srcs')
186 self._output_field(output, 'shared_libs')
187 self._output_field(output, 'static_libs')
188 self._output_field(output, 'tools')
189 self._output_field(output, 'cmd', sort=False)
Primiano Tucci6aa75572018-03-21 05:33:14 -0700190 self._output_field(output, 'host_supported')
Primiano Tucci6067e732018-01-08 16:19:40 +0000191 self._output_field(output, 'init_rc')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000192 self._output_field(output, 'out')
193 self._output_field(output, 'export_include_dirs')
194 self._output_field(output, 'generated_headers')
Lalit Magantic5bcd792018-01-12 18:38:11 +0000195 self._output_field(output, 'export_generated_headers')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000196 self._output_field(output, 'defaults')
197 self._output_field(output, 'cflags')
198 self._output_field(output, 'local_include_dirs')
Logan Chien9bfaaf92018-02-13 18:49:24 +0800199 if any(name in library_not_in_pdk for name in self.shared_libs):
200 output.append(' product_variables: {')
201 output.append(' pdk: {')
202 output.append(' enabled: false,')
203 output.append(' },')
204 output.append(' },')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000205 output.append('}')
206 output.append('')
207
208 def _output_field(self, output, name, sort=True):
209 value = getattr(self, name)
210 if not value:
211 return
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000212 if isinstance(value, set):
Logan Chien9bfaaf92018-02-13 18:49:24 +0800213 value = sorted(value)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000214 if isinstance(value, list):
215 output.append(' %s: [' % name)
216 for item in sorted(value) if sort else value:
217 output.append(' "%s",' % item)
218 output.append(' ],')
Primiano Tucci6aa75572018-03-21 05:33:14 -0700219 return
220 if isinstance(value, bool):
221 output.append(' %s: true,' % name)
222 return
223 output.append(' %s: "%s",' % (name, value))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000224
225
226class Blueprint(object):
227 """In-memory representation of an Android.bp file."""
228
229 def __init__(self):
230 self.modules = {}
231
232 def add_module(self, module):
233 """Adds a new module to the blueprint, replacing any existing module
234 with the same name.
235
236 Args:
237 module: Module instance.
238 """
239 self.modules[module.name] = module
240
241 def to_string(self, output):
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000242 for m in sorted(self.modules.itervalues(), key=lambda m: m.name):
Sami Kyostila865d1d32017-12-12 18:37:04 +0000243 m.to_string(output)
244
245
246def label_to_path(label):
247 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
248 assert label.startswith('//')
249 return label[2:]
250
251
252def label_to_module_name(label):
253 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Primiano Tucci4e49c022017-12-21 18:22:44 +0100254 module = re.sub(r'^//:?', '', label)
255 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
256 if not module.startswith(module_prefix) and label not in default_targets:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000257 return module_prefix + module
258 return module
259
260
261def label_without_toolchain(label):
262 """Strips the toolchain from a GN label.
263
264 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
265 gcc_like_host) without the parenthesised toolchain part.
266 """
267 return label.split('(')[0]
268
269
270def is_supported_source_file(name):
271 """Returns True if |name| can appear in a 'srcs' list."""
272 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
273
274
275def is_generated_by_action(desc, label):
276 """Checks if a label is generated by an action.
277
278 Returns True if a GN output label |label| is an output for any action,
279 i.e., the file is generated dynamically.
280 """
281 for target in desc.itervalues():
282 if target['type'] == 'action' and label in target['outputs']:
283 return True
284 return False
285
286
287def apply_module_dependency(blueprint, desc, module, dep_name):
288 """Recursively collect dependencies for a given module.
289
290 Walk the transitive dependencies for a GN target and apply them to a given
291 module. This effectively flattens the dependency tree so that |module|
292 directly contains all the sources, libraries, etc. in the corresponding GN
293 dependency tree.
294
295 Args:
296 blueprint: Blueprint instance which is being generated.
297 desc: JSON GN description.
298 module: Module to which dependencies should be added.
299 dep_name: GN target of the dependency.
300 """
Sami Kyostila865d1d32017-12-12 18:37:04 +0000301 # If the dependency refers to a library which we can replace with an Android
302 # equivalent, stop recursing and patch the dependency in.
303 if label_without_toolchain(dep_name) in builtin_deps:
304 builtin_deps[label_without_toolchain(dep_name)](module)
305 return
306
307 # Similarly some shared libraries are directly mapped to Android
308 # equivalents.
309 target = desc[dep_name]
310 for lib in target.get('libs', []):
311 android_lib = 'lib' + lib
312 if lib in library_whitelist and not android_lib in module.shared_libs:
313 module.shared_libs.append(android_lib)
314
315 type = target['type']
316 if type == 'action':
317 create_modules_from_target(blueprint, desc, dep_name)
318 # Depend both on the generated sources and headers -- see
319 # make_genrules_for_action.
320 module.srcs.append(':' + label_to_module_name(dep_name))
321 module.generated_headers.append(
322 label_to_module_name(dep_name) + '_headers')
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000323 elif type == 'static_library' and label_to_module_name(
324 dep_name) != module.name:
325 create_modules_from_target(blueprint, desc, dep_name)
326 module.static_libs.append(label_to_module_name(dep_name))
Primiano Tucci6067e732018-01-08 16:19:40 +0000327 elif type == 'shared_library' and label_to_module_name(
328 dep_name) != module.name:
329 module.shared_libs.append(label_to_module_name(dep_name))
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000330 elif type in ['group', 'source_set', 'executable', 'static_library'
331 ] and 'sources' in target:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000332 # Ignore source files that are generated by actions since they will be
333 # implicitly added by the genrule dependencies.
334 module.srcs.extend(
335 label_to_path(src) for src in target['sources']
336 if is_supported_source_file(src)
337 and not is_generated_by_action(desc, src))
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000338 module.cflags |= _get_cflags(target)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000339
340
341def make_genrules_for_action(blueprint, desc, target_name):
342 """Generate genrules for a GN action.
343
344 GN actions are used to dynamically generate files during the build. The
345 Soong equivalent is a genrule. This function turns a specific kind of
346 genrule which turns .proto files into source and header files into a pair
Sami Kyostila71625d72017-12-18 10:29:49 +0000347 equivalent genrules.
Sami Kyostila865d1d32017-12-12 18:37:04 +0000348
349 Args:
350 blueprint: Blueprint instance which is being generated.
351 desc: JSON GN description.
352 target_name: GN target for genrule generation.
353
354 Returns:
355 A (source_genrule, header_genrule) module tuple.
356 """
357 target = desc[target_name]
358
359 # We only support genrules which call protoc (with or without a plugin) to
360 # turn .proto files into header and source files.
361 args = target['args']
362 if not args[0].endswith('/protoc'):
363 raise Error('Unsupported action in target %s: %s' % (target_name,
364 target['args']))
Primiano Tucci20b760c2018-01-19 12:36:12 +0000365 parser = ThrowingArgumentParser('Action in target %s (%s)' %
366 (target_name, ' '.join(target['args'])))
367 parser.add_argument('--proto_path')
368 parser.add_argument('--cpp_out')
369 parser.add_argument('--plugin')
370 parser.add_argument('--plugin_out')
371 parser.add_argument('protos', nargs=argparse.REMAINDER)
372 args = parser.parse_args(args[1:])
373
374 # Depending on whether we are using the default protoc C++ generator or the
375 # protozero plugin, the output dir is passed as:
376 # --cpp_out=gen/xxx or
377 # --plugin_out=:gen/xxx or
378 # --plugin_out=wrapper_namespace=pbzero:gen/xxx
379 gen_dir = args.cpp_out if args.cpp_out else args.plugin_out.split(':')[1]
380 assert gen_dir.startswith('gen/')
381 gen_dir = gen_dir[4:]
382 cpp_out_dir = ('$(genDir)/%s/%s' % (tree_path, gen_dir)).rstrip('/')
383
384 # TODO(skyostil): Is there a way to avoid hardcoding the tree path here?
385 # TODO(skyostil): Find a way to avoid creating the directory.
386 cmd = [
387 'mkdir -p %s &&' % cpp_out_dir,
388 '$(location aprotoc)',
389 '--cpp_out=%s' % cpp_out_dir
390 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000391
392 # We create two genrules for each action: one for the protobuf headers and
393 # another for the sources. This is because the module that depends on the
394 # generated files needs to declare two different types of dependencies --
395 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
396 # valid to generate .h files from a source dependency and vice versa.
Sami Kyostila71625d72017-12-18 10:29:49 +0000397 source_module = Module('genrule', label_to_module_name(target_name))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000398 source_module.srcs.extend(label_to_path(src) for src in target['sources'])
399 source_module.tools = ['aprotoc']
400
Sami Kyostila71625d72017-12-18 10:29:49 +0000401 header_module = Module('genrule',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000402 label_to_module_name(target_name) + '_headers')
403 header_module.srcs = source_module.srcs[:]
404 header_module.tools = source_module.tools[:]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000405 header_module.export_include_dirs = [gen_dir or '.']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000406
Primiano Tucci20b760c2018-01-19 12:36:12 +0000407 # In GN builds the proto path is always relative to the output directory
408 # (out/tmp.xxx).
409 assert args.proto_path.startswith('../../')
410 cmd += [ '--proto_path=%s/%s' % (tree_path, args.proto_path[6:])]
411
Sami Kyostila865d1d32017-12-12 18:37:04 +0000412 namespaces = ['pb']
Sami Kyostila865d1d32017-12-12 18:37:04 +0000413 if args.plugin:
414 _, plugin = os.path.split(args.plugin)
415 # TODO(skyostil): Can we detect this some other way?
416 if plugin == 'ipc_plugin':
417 namespaces.append('ipc')
418 elif plugin == 'protoc_plugin':
419 namespaces = ['pbzero']
420 for dep in target['deps']:
421 if desc[dep]['type'] != 'executable':
422 continue
423 _, executable = os.path.split(desc[dep]['outputs'][0])
424 if executable == plugin:
425 cmd += [
426 '--plugin=protoc-gen-plugin=$(location %s)' %
427 label_to_module_name(dep)
428 ]
429 source_module.tools.append(label_to_module_name(dep))
430 # Also make sure the module for the tool is generated.
431 create_modules_from_target(blueprint, desc, dep)
432 break
433 else:
434 raise Error('Unrecognized protoc plugin in target %s: %s' %
435 (target_name, args[i]))
436 if args.plugin_out:
437 plugin_args = args.plugin_out.split(':')[0]
Primiano Tucci20b760c2018-01-19 12:36:12 +0000438 cmd += ['--plugin_out=%s:%s' % (plugin_args, cpp_out_dir)]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000439
440 cmd += ['$(in)']
441 source_module.cmd = ' '.join(cmd)
442 header_module.cmd = source_module.cmd
443 header_module.tools = source_module.tools[:]
444
445 for ns in namespaces:
446 source_module.out += [
447 '%s/%s' % (tree_path, src.replace('.proto', '.%s.cc' % ns))
448 for src in source_module.srcs
449 ]
450 header_module.out += [
451 '%s/%s' % (tree_path, src.replace('.proto', '.%s.h' % ns))
452 for src in header_module.srcs
453 ]
454 return source_module, header_module
455
456
Florian Mayer3d5e7e62018-01-19 15:22:46 +0000457def _get_cflags(target):
458 cflags = set(flag for flag in target.get('cflags', [])
459 if re.match(cflag_whitelist, flag))
460 cflags |= set("-D%s" % define for define in target.get('defines', [])
461 if re.match(define_whitelist, define))
462 return cflags
463
464
Sami Kyostila865d1d32017-12-12 18:37:04 +0000465def create_modules_from_target(blueprint, desc, target_name):
466 """Generate module(s) for a given GN target.
467
468 Given a GN target name, generate one or more corresponding modules into a
469 blueprint.
470
471 Args:
472 blueprint: Blueprint instance which is being generated.
473 desc: JSON GN description.
474 target_name: GN target for module generation.
475 """
476 target = desc[target_name]
477 if target['type'] == 'executable':
Primiano Tucci21c19d82018-03-29 12:35:08 +0100478 if 'host' in target['toolchain'] or target_name in target_host_only:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000479 module_type = 'cc_binary_host'
480 elif target.get('testonly'):
481 module_type = 'cc_test'
482 else:
483 module_type = 'cc_binary'
484 modules = [Module(module_type, label_to_module_name(target_name))]
485 elif target['type'] == 'action':
486 modules = make_genrules_for_action(blueprint, desc, target_name)
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000487 elif target['type'] == 'static_library':
Lalit Magantic5bcd792018-01-12 18:38:11 +0000488 module = Module('cc_library_static', label_to_module_name(target_name))
489 module.export_include_dirs = ['include']
490 modules = [module]
Primiano Tucci6067e732018-01-08 16:19:40 +0000491 elif target['type'] == 'shared_library':
492 modules = [
493 Module('cc_library_shared', label_to_module_name(target_name))
494 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000495 else:
496 raise Error('Unknown target type: %s' % target['type'])
497
498 for module in modules:
499 module.comment = 'GN target: %s' % target_name
Primiano Tucci6067e732018-01-08 16:19:40 +0000500 if target_name in target_initrc:
501 module.init_rc = [target_initrc[target_name]]
Primiano Tucci6aa75572018-03-21 05:33:14 -0700502 if target_name in target_host_supported:
503 module.host_supported = True
Primiano Tucci6067e732018-01-08 16:19:40 +0000504
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000505 # Don't try to inject library/source dependencies into genrules because
506 # they are not compiled in the traditional sense.
Sami Kyostila71625d72017-12-18 10:29:49 +0000507 if module.type != 'genrule':
Sami Kyostila865d1d32017-12-12 18:37:04 +0000508 module.defaults = [defaults_module]
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000509 apply_module_dependency(blueprint, desc, module, target_name)
510 for dep in resolve_dependencies(desc, target_name):
511 apply_module_dependency(blueprint, desc, module, dep)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000512
Lalit Magantic5bcd792018-01-12 18:38:11 +0000513 # If the module is a static library, export all the generated headers.
514 if module.type == 'cc_library_static':
515 module.export_generated_headers = module.generated_headers
516
Sami Kyostila865d1d32017-12-12 18:37:04 +0000517 blueprint.add_module(module)
518
519
520def resolve_dependencies(desc, target_name):
521 """Return the transitive set of dependent-on targets for a GN target.
522
523 Args:
524 blueprint: Blueprint instance which is being generated.
525 desc: JSON GN description.
526
527 Returns:
528 A set of transitive dependencies in the form of GN targets.
529 """
530
531 if label_without_toolchain(target_name) in builtin_deps:
532 return set()
533 target = desc[target_name]
534 resolved_deps = set()
535 for dep in target.get('deps', []):
536 resolved_deps.add(dep)
537 # Ignore the transitive dependencies of actions because they are
538 # explicitly converted to genrules.
539 if desc[dep]['type'] == 'action':
540 continue
Primiano Tucci6067e732018-01-08 16:19:40 +0000541 # Dependencies on shared libraries shouldn't propagate any transitive
542 # dependencies but only depend on the shared library target
543 if desc[dep]['type'] == 'shared_library':
544 continue
Sami Kyostila865d1d32017-12-12 18:37:04 +0000545 resolved_deps.update(resolve_dependencies(desc, dep))
546 return resolved_deps
547
548
549def create_blueprint_for_targets(desc, targets):
550 """Generate a blueprint for a list of GN targets."""
551 blueprint = Blueprint()
552
553 # Default settings used by all modules.
554 defaults = Module('cc_defaults', defaults_module)
555 defaults.local_include_dirs = ['include']
556 defaults.cflags = [
557 '-Wno-error=return-type',
558 '-Wno-sign-compare',
559 '-Wno-sign-promo',
560 '-Wno-unused-parameter',
Florian Mayercc424fd2018-01-15 11:19:01 +0000561 '-fvisibility=hidden',
Florian Mayerc2a38ea2018-01-19 11:48:43 +0000562 '-Oz',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000563 ]
564
565 blueprint.add_module(defaults)
566 for target in targets:
567 create_modules_from_target(blueprint, desc, target)
568 return blueprint
569
570
Sami Kyostilab27619f2017-12-13 19:22:16 +0000571def repo_root():
572 """Returns an absolute path to the repository root."""
573
574 return os.path.join(
575 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
576
577
578def create_build_description():
579 """Creates the JSON build description by running GN."""
580
581 out = os.path.join(repo_root(), 'out', 'tmp.gen_android_bp')
582 try:
583 try:
584 os.makedirs(out)
585 except OSError as e:
586 if e.errno != errno.EEXIST:
587 raise
588 subprocess.check_output(
589 ['gn', 'gen', out, '--args=%s' % gn_args], cwd=repo_root())
590 desc = subprocess.check_output(
591 ['gn', 'desc', out, '--format=json', '--all-toolchains', '//*'],
592 cwd=repo_root())
593 return json.loads(desc)
594 finally:
595 shutil.rmtree(out)
596
597
Sami Kyostila865d1d32017-12-12 18:37:04 +0000598def main():
599 parser = argparse.ArgumentParser(
600 description='Generate Android.bp from a GN description.')
601 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000602 '--desc',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000603 help=
604 'GN description (e.g., gn desc out --format=json --all-toolchains "//*"'
605 )
606 parser.add_argument(
Lalit Magantic5bcd792018-01-12 18:38:11 +0000607 '--extras',
608 help='Extra targets to include at the end of the Blueprint file',
609 default=os.path.join(repo_root(), 'Android.bp.extras'),
610 )
611 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000612 '--output',
613 help='Blueprint file to create',
614 default=os.path.join(repo_root(), 'Android.bp'),
615 )
616 parser.add_argument(
Sami Kyostila865d1d32017-12-12 18:37:04 +0000617 'targets',
618 nargs=argparse.REMAINDER,
619 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")')
620 args = parser.parse_args()
621
Sami Kyostilab27619f2017-12-13 19:22:16 +0000622 if args.desc:
623 with open(args.desc) as f:
624 desc = json.load(f)
625 else:
626 desc = create_build_description()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000627
Sami Kyostilab27619f2017-12-13 19:22:16 +0000628 blueprint = create_blueprint_for_targets(desc, args.targets
629 or default_targets)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000630 output = [
631 """// Copyright (C) 2017 The Android Open Source Project
632//
633// Licensed under the Apache License, Version 2.0 (the "License");
634// you may not use this file except in compliance with the License.
635// You may obtain a copy of the License at
636//
637// http://www.apache.org/licenses/LICENSE-2.0
638//
639// Unless required by applicable law or agreed to in writing, software
640// distributed under the License is distributed on an "AS IS" BASIS,
641// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
642// See the License for the specific language governing permissions and
643// limitations under the License.
644//
645// This file is automatically generated by %s. Do not edit.
646""" % (__file__)
647 ]
648 blueprint.to_string(output)
Lalit Magantic5bcd792018-01-12 18:38:11 +0000649 with open(args.extras, 'r') as r:
650 for line in r:
651 output.append(line.rstrip("\n\r"))
Sami Kyostilab27619f2017-12-13 19:22:16 +0000652 with open(args.output, 'w') as f:
653 f.write('\n'.join(output))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000654
655
656if __name__ == '__main__':
657 sys.exit(main())