blob: 3c7b96b093cb339dbdedd0b7be821286c8e329fa [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
29import json
30import os
31import re
Sami Kyostilab27619f2017-12-13 19:22:16 +000032import shutil
33import subprocess
Sami Kyostila865d1d32017-12-12 18:37:04 +000034import sys
35
Sami Kyostilab27619f2017-12-13 19:22:16 +000036# Default targets to translate to the blueprint file.
Primiano Tucci4e49c022017-12-21 18:22:44 +010037default_targets = [
38 '//:perfetto_tests',
39 '//:traced',
Primiano Tucci6067e732018-01-08 16:19:40 +000040 '//:traced_probes',
41 '//:libtraced_shared',
Primiano Tucci4e49c022017-12-21 18:22:44 +010042 '//src/tracing:consumer_cmd',
43]
Sami Kyostilab27619f2017-12-13 19:22:16 +000044
Primiano Tucci6067e732018-01-08 16:19:40 +000045# Defines a custom init_rc argument to be applied to the corresponding output
46# blueprint target.
47target_initrc = {} # TODO(primiano): populate in upcoming CLs.
48
Sami Kyostilab27619f2017-12-13 19:22:16 +000049# Arguments for the GN output directory.
50gn_args = 'target_os="android" target_cpu="arm" is_debug=false'
51
Sami Kyostila865d1d32017-12-12 18:37:04 +000052# All module names are prefixed with this string to avoid collisions.
53module_prefix = 'perfetto_'
54
55# Shared libraries which are directly translated to Android system equivalents.
56library_whitelist = [
57 'android',
58 'log',
59]
60
61# Name of the module which settings such as compiler flags for all other
62# modules.
63defaults_module = module_prefix + 'defaults'
64
65# Location of the project in the Android source tree.
66tree_path = 'external/perfetto'
67
68
69def enable_gmock(module):
70 module.static_libs.append('libgmock')
71
72
Hector Dearman3e712a02017-12-19 16:39:59 +000073def enable_gtest_prod(module):
74 module.static_libs.append('libgtest_prod')
75
76
Sami Kyostila865d1d32017-12-12 18:37:04 +000077def enable_gtest(module):
78 assert module.type == 'cc_test'
79
80
81def enable_protobuf_full(module):
82 module.shared_libs.append('libprotobuf-cpp-full')
83
84
85def enable_protobuf_lite(module):
86 module.shared_libs.append('libprotobuf-cpp-lite')
87
88
89def enable_protoc_lib(module):
90 module.shared_libs.append('libprotoc')
91
92
93def enable_libunwind(module):
Sami Kyostilafc074d42017-12-15 10:33:42 +000094 # libunwind is disabled on Darwin so we cannot depend on it.
95 pass
Sami Kyostila865d1d32017-12-12 18:37:04 +000096
97
98# Android equivalents for third-party libraries that the upstream project
99# depends on.
100builtin_deps = {
101 '//buildtools:gmock': enable_gmock,
102 '//buildtools:gtest': enable_gtest,
Hector Dearman3e712a02017-12-19 16:39:59 +0000103 '//gn:gtest_prod_config': enable_gtest_prod,
Sami Kyostila865d1d32017-12-12 18:37:04 +0000104 '//buildtools:gtest_main': enable_gtest,
105 '//buildtools:libunwind': enable_libunwind,
106 '//buildtools:protobuf_full': enable_protobuf_full,
107 '//buildtools:protobuf_lite': enable_protobuf_lite,
108 '//buildtools:protoc_lib': enable_protoc_lib,
109}
110
111# ----------------------------------------------------------------------------
112# End of configuration.
113# ----------------------------------------------------------------------------
114
115
116class Error(Exception):
117 pass
118
119
120class ThrowingArgumentParser(argparse.ArgumentParser):
121 def __init__(self, context):
122 super(ThrowingArgumentParser, self).__init__()
123 self.context = context
124
125 def error(self, message):
126 raise Error('%s: %s' % (self.context, message))
127
128
129class Module(object):
130 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
131
132 def __init__(self, mod_type, name):
133 self.type = mod_type
134 self.name = name
135 self.srcs = []
136 self.comment = None
137 self.shared_libs = []
138 self.static_libs = []
139 self.tools = []
140 self.cmd = None
Primiano Tucci6067e732018-01-08 16:19:40 +0000141 self.init_rc = []
Sami Kyostila865d1d32017-12-12 18:37:04 +0000142 self.out = []
143 self.export_include_dirs = []
144 self.generated_headers = []
145 self.defaults = []
146 self.cflags = []
147 self.local_include_dirs = []
148
149 def to_string(self, output):
150 if self.comment:
151 output.append('// %s' % self.comment)
152 output.append('%s {' % self.type)
153 self._output_field(output, 'name')
154 self._output_field(output, 'srcs')
155 self._output_field(output, 'shared_libs')
156 self._output_field(output, 'static_libs')
157 self._output_field(output, 'tools')
158 self._output_field(output, 'cmd', sort=False)
Primiano Tucci6067e732018-01-08 16:19:40 +0000159 self._output_field(output, 'init_rc')
Sami Kyostila865d1d32017-12-12 18:37:04 +0000160 self._output_field(output, 'out')
161 self._output_field(output, 'export_include_dirs')
162 self._output_field(output, 'generated_headers')
163 self._output_field(output, 'defaults')
164 self._output_field(output, 'cflags')
165 self._output_field(output, 'local_include_dirs')
166 output.append('}')
167 output.append('')
168
169 def _output_field(self, output, name, sort=True):
170 value = getattr(self, name)
171 if not value:
172 return
173 if isinstance(value, list):
174 output.append(' %s: [' % name)
175 for item in sorted(value) if sort else value:
176 output.append(' "%s",' % item)
177 output.append(' ],')
178 else:
179 output.append(' %s: "%s",' % (name, value))
180
181
182class Blueprint(object):
183 """In-memory representation of an Android.bp file."""
184
185 def __init__(self):
186 self.modules = {}
187
188 def add_module(self, module):
189 """Adds a new module to the blueprint, replacing any existing module
190 with the same name.
191
192 Args:
193 module: Module instance.
194 """
195 self.modules[module.name] = module
196
197 def to_string(self, output):
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000198 for m in sorted(self.modules.itervalues(), key=lambda m: m.name):
Sami Kyostila865d1d32017-12-12 18:37:04 +0000199 m.to_string(output)
200
201
202def label_to_path(label):
203 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
204 assert label.startswith('//')
205 return label[2:]
206
207
208def label_to_module_name(label):
209 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Primiano Tucci4e49c022017-12-21 18:22:44 +0100210 module = re.sub(r'^//:?', '', label)
211 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
212 if not module.startswith(module_prefix) and label not in default_targets:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000213 return module_prefix + module
214 return module
215
216
217def label_without_toolchain(label):
218 """Strips the toolchain from a GN label.
219
220 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
221 gcc_like_host) without the parenthesised toolchain part.
222 """
223 return label.split('(')[0]
224
225
226def is_supported_source_file(name):
227 """Returns True if |name| can appear in a 'srcs' list."""
228 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
229
230
231def is_generated_by_action(desc, label):
232 """Checks if a label is generated by an action.
233
234 Returns True if a GN output label |label| is an output for any action,
235 i.e., the file is generated dynamically.
236 """
237 for target in desc.itervalues():
238 if target['type'] == 'action' and label in target['outputs']:
239 return True
240 return False
241
242
243def apply_module_dependency(blueprint, desc, module, dep_name):
244 """Recursively collect dependencies for a given module.
245
246 Walk the transitive dependencies for a GN target and apply them to a given
247 module. This effectively flattens the dependency tree so that |module|
248 directly contains all the sources, libraries, etc. in the corresponding GN
249 dependency tree.
250
251 Args:
252 blueprint: Blueprint instance which is being generated.
253 desc: JSON GN description.
254 module: Module to which dependencies should be added.
255 dep_name: GN target of the dependency.
256 """
Sami Kyostila865d1d32017-12-12 18:37:04 +0000257 # If the dependency refers to a library which we can replace with an Android
258 # equivalent, stop recursing and patch the dependency in.
259 if label_without_toolchain(dep_name) in builtin_deps:
260 builtin_deps[label_without_toolchain(dep_name)](module)
261 return
262
263 # Similarly some shared libraries are directly mapped to Android
264 # equivalents.
265 target = desc[dep_name]
266 for lib in target.get('libs', []):
267 android_lib = 'lib' + lib
268 if lib in library_whitelist and not android_lib in module.shared_libs:
269 module.shared_libs.append(android_lib)
270
271 type = target['type']
272 if type == 'action':
273 create_modules_from_target(blueprint, desc, dep_name)
274 # Depend both on the generated sources and headers -- see
275 # make_genrules_for_action.
276 module.srcs.append(':' + label_to_module_name(dep_name))
277 module.generated_headers.append(
278 label_to_module_name(dep_name) + '_headers')
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000279 elif type == 'static_library' and label_to_module_name(
280 dep_name) != module.name:
281 create_modules_from_target(blueprint, desc, dep_name)
282 module.static_libs.append(label_to_module_name(dep_name))
Primiano Tucci6067e732018-01-08 16:19:40 +0000283 elif type == 'shared_library' and label_to_module_name(
284 dep_name) != module.name:
285 module.shared_libs.append(label_to_module_name(dep_name))
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000286 elif type in ['group', 'source_set', 'executable', 'static_library'
287 ] and 'sources' in target:
Sami Kyostila865d1d32017-12-12 18:37:04 +0000288 # Ignore source files that are generated by actions since they will be
289 # implicitly added by the genrule dependencies.
290 module.srcs.extend(
291 label_to_path(src) for src in target['sources']
292 if is_supported_source_file(src)
293 and not is_generated_by_action(desc, src))
294
295
296def make_genrules_for_action(blueprint, desc, target_name):
297 """Generate genrules for a GN action.
298
299 GN actions are used to dynamically generate files during the build. The
300 Soong equivalent is a genrule. This function turns a specific kind of
301 genrule which turns .proto files into source and header files into a pair
Sami Kyostila71625d72017-12-18 10:29:49 +0000302 equivalent genrules.
Sami Kyostila865d1d32017-12-12 18:37:04 +0000303
304 Args:
305 blueprint: Blueprint instance which is being generated.
306 desc: JSON GN description.
307 target_name: GN target for genrule generation.
308
309 Returns:
310 A (source_genrule, header_genrule) module tuple.
311 """
312 target = desc[target_name]
313
314 # We only support genrules which call protoc (with or without a plugin) to
315 # turn .proto files into header and source files.
316 args = target['args']
317 if not args[0].endswith('/protoc'):
318 raise Error('Unsupported action in target %s: %s' % (target_name,
319 target['args']))
320
321 # We create two genrules for each action: one for the protobuf headers and
322 # another for the sources. This is because the module that depends on the
323 # generated files needs to declare two different types of dependencies --
324 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
325 # valid to generate .h files from a source dependency and vice versa.
Sami Kyostila71625d72017-12-18 10:29:49 +0000326 source_module = Module('genrule', label_to_module_name(target_name))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000327 source_module.srcs.extend(label_to_path(src) for src in target['sources'])
328 source_module.tools = ['aprotoc']
329
Sami Kyostila71625d72017-12-18 10:29:49 +0000330 header_module = Module('genrule',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000331 label_to_module_name(target_name) + '_headers')
332 header_module.srcs = source_module.srcs[:]
333 header_module.tools = source_module.tools[:]
334 header_module.export_include_dirs = ['.']
335
336 # TODO(skyostil): Is there a way to avoid hardcoding the tree path here?
337 # TODO(skyostil): Find a way to avoid creating the directory.
338 cmd = [
339 'mkdir -p $(genDir)/%s &&' % tree_path, '$(location aprotoc)',
340 '--cpp_out=$(genDir)/%s' % tree_path,
341 '--proto_path=%s' % tree_path
342 ]
343 namespaces = ['pb']
344
345 parser = ThrowingArgumentParser('Action in target %s (%s)' %
346 (target_name, ' '.join(target['args'])))
347 parser.add_argument('--proto_path')
348 parser.add_argument('--cpp_out')
349 parser.add_argument('--plugin')
350 parser.add_argument('--plugin_out')
351 parser.add_argument('protos', nargs=argparse.REMAINDER)
352
353 args = parser.parse_args(args[1:])
354 if args.plugin:
355 _, plugin = os.path.split(args.plugin)
356 # TODO(skyostil): Can we detect this some other way?
357 if plugin == 'ipc_plugin':
358 namespaces.append('ipc')
359 elif plugin == 'protoc_plugin':
360 namespaces = ['pbzero']
361 for dep in target['deps']:
362 if desc[dep]['type'] != 'executable':
363 continue
364 _, executable = os.path.split(desc[dep]['outputs'][0])
365 if executable == plugin:
366 cmd += [
367 '--plugin=protoc-gen-plugin=$(location %s)' %
368 label_to_module_name(dep)
369 ]
370 source_module.tools.append(label_to_module_name(dep))
371 # Also make sure the module for the tool is generated.
372 create_modules_from_target(blueprint, desc, dep)
373 break
374 else:
375 raise Error('Unrecognized protoc plugin in target %s: %s' %
376 (target_name, args[i]))
377 if args.plugin_out:
378 plugin_args = args.plugin_out.split(':')[0]
379 cmd += ['--plugin_out=%s:$(genDir)/%s' % (plugin_args, tree_path)]
380
381 cmd += ['$(in)']
382 source_module.cmd = ' '.join(cmd)
383 header_module.cmd = source_module.cmd
384 header_module.tools = source_module.tools[:]
385
386 for ns in namespaces:
387 source_module.out += [
388 '%s/%s' % (tree_path, src.replace('.proto', '.%s.cc' % ns))
389 for src in source_module.srcs
390 ]
391 header_module.out += [
392 '%s/%s' % (tree_path, src.replace('.proto', '.%s.h' % ns))
393 for src in header_module.srcs
394 ]
395 return source_module, header_module
396
397
398def create_modules_from_target(blueprint, desc, target_name):
399 """Generate module(s) for a given GN target.
400
401 Given a GN target name, generate one or more corresponding modules into a
402 blueprint.
403
404 Args:
405 blueprint: Blueprint instance which is being generated.
406 desc: JSON GN description.
407 target_name: GN target for module generation.
408 """
409 target = desc[target_name]
410 if target['type'] == 'executable':
411 if 'host' in target['toolchain']:
412 module_type = 'cc_binary_host'
413 elif target.get('testonly'):
414 module_type = 'cc_test'
415 else:
416 module_type = 'cc_binary'
417 modules = [Module(module_type, label_to_module_name(target_name))]
418 elif target['type'] == 'action':
419 modules = make_genrules_for_action(blueprint, desc, target_name)
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000420 elif target['type'] == 'static_library':
421 modules = [
422 Module('cc_library_static', label_to_module_name(target_name))
423 ]
Primiano Tucci6067e732018-01-08 16:19:40 +0000424 elif target['type'] == 'shared_library':
425 modules = [
426 Module('cc_library_shared', label_to_module_name(target_name))
427 ]
Sami Kyostila865d1d32017-12-12 18:37:04 +0000428 else:
429 raise Error('Unknown target type: %s' % target['type'])
430
431 for module in modules:
432 module.comment = 'GN target: %s' % target_name
Primiano Tucci6067e732018-01-08 16:19:40 +0000433 if target_name in target_initrc:
434 module.init_rc = [target_initrc[target_name]]
435
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000436 # Don't try to inject library/source dependencies into genrules because
437 # they are not compiled in the traditional sense.
Sami Kyostila71625d72017-12-18 10:29:49 +0000438 if module.type != 'genrule':
Sami Kyostila865d1d32017-12-12 18:37:04 +0000439 module.defaults = [defaults_module]
Sami Kyostilaebba0fe2017-12-19 14:01:52 +0000440 apply_module_dependency(blueprint, desc, module, target_name)
441 for dep in resolve_dependencies(desc, target_name):
442 apply_module_dependency(blueprint, desc, module, dep)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000443
444 blueprint.add_module(module)
445
446
447def resolve_dependencies(desc, target_name):
448 """Return the transitive set of dependent-on targets for a GN target.
449
450 Args:
451 blueprint: Blueprint instance which is being generated.
452 desc: JSON GN description.
453
454 Returns:
455 A set of transitive dependencies in the form of GN targets.
456 """
457
458 if label_without_toolchain(target_name) in builtin_deps:
459 return set()
460 target = desc[target_name]
461 resolved_deps = set()
462 for dep in target.get('deps', []):
463 resolved_deps.add(dep)
464 # Ignore the transitive dependencies of actions because they are
465 # explicitly converted to genrules.
466 if desc[dep]['type'] == 'action':
467 continue
Primiano Tucci6067e732018-01-08 16:19:40 +0000468 # Dependencies on shared libraries shouldn't propagate any transitive
469 # dependencies but only depend on the shared library target
470 if desc[dep]['type'] == 'shared_library':
471 continue
Sami Kyostila865d1d32017-12-12 18:37:04 +0000472 resolved_deps.update(resolve_dependencies(desc, dep))
473 return resolved_deps
474
475
476def create_blueprint_for_targets(desc, targets):
477 """Generate a blueprint for a list of GN targets."""
478 blueprint = Blueprint()
479
480 # Default settings used by all modules.
481 defaults = Module('cc_defaults', defaults_module)
482 defaults.local_include_dirs = ['include']
483 defaults.cflags = [
484 '-Wno-error=return-type',
485 '-Wno-sign-compare',
486 '-Wno-sign-promo',
487 '-Wno-unused-parameter',
488 ]
489
490 blueprint.add_module(defaults)
491 for target in targets:
492 create_modules_from_target(blueprint, desc, target)
493 return blueprint
494
495
Sami Kyostilab27619f2017-12-13 19:22:16 +0000496def repo_root():
497 """Returns an absolute path to the repository root."""
498
499 return os.path.join(
500 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
501
502
503def create_build_description():
504 """Creates the JSON build description by running GN."""
505
506 out = os.path.join(repo_root(), 'out', 'tmp.gen_android_bp')
507 try:
508 try:
509 os.makedirs(out)
510 except OSError as e:
511 if e.errno != errno.EEXIST:
512 raise
513 subprocess.check_output(
514 ['gn', 'gen', out, '--args=%s' % gn_args], cwd=repo_root())
515 desc = subprocess.check_output(
516 ['gn', 'desc', out, '--format=json', '--all-toolchains', '//*'],
517 cwd=repo_root())
518 return json.loads(desc)
519 finally:
520 shutil.rmtree(out)
521
522
Sami Kyostila865d1d32017-12-12 18:37:04 +0000523def main():
524 parser = argparse.ArgumentParser(
525 description='Generate Android.bp from a GN description.')
526 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000527 '--desc',
Sami Kyostila865d1d32017-12-12 18:37:04 +0000528 help=
529 'GN description (e.g., gn desc out --format=json --all-toolchains "//*"'
530 )
531 parser.add_argument(
Sami Kyostilab27619f2017-12-13 19:22:16 +0000532 '--output',
533 help='Blueprint file to create',
534 default=os.path.join(repo_root(), 'Android.bp'),
535 )
536 parser.add_argument(
Sami Kyostila865d1d32017-12-12 18:37:04 +0000537 'targets',
538 nargs=argparse.REMAINDER,
539 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")')
540 args = parser.parse_args()
541
Sami Kyostilab27619f2017-12-13 19:22:16 +0000542 if args.desc:
543 with open(args.desc) as f:
544 desc = json.load(f)
545 else:
546 desc = create_build_description()
Sami Kyostila865d1d32017-12-12 18:37:04 +0000547
Sami Kyostilab27619f2017-12-13 19:22:16 +0000548 blueprint = create_blueprint_for_targets(desc, args.targets
549 or default_targets)
Sami Kyostila865d1d32017-12-12 18:37:04 +0000550 output = [
551 """// Copyright (C) 2017 The Android Open Source Project
552//
553// Licensed under the Apache License, Version 2.0 (the "License");
554// you may not use this file except in compliance with the License.
555// You may obtain a copy of the License at
556//
557// http://www.apache.org/licenses/LICENSE-2.0
558//
559// Unless required by applicable law or agreed to in writing, software
560// distributed under the License is distributed on an "AS IS" BASIS,
561// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
562// See the License for the specific language governing permissions and
563// limitations under the License.
564//
565// This file is automatically generated by %s. Do not edit.
566""" % (__file__)
567 ]
568 blueprint.to_string(output)
Sami Kyostilab27619f2017-12-13 19:22:16 +0000569 with open(args.output, 'w') as f:
570 f.write('\n'.join(output))
Sami Kyostila865d1d32017-12-12 18:37:04 +0000571
572
573if __name__ == '__main__':
574 sys.exit(main())