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