blob: cacb051450bdc67cb93e0d5263de5bc25431adbe [file] [log] [blame]
Patrick Rohr92d74122022-10-21 15:50:52 -07001#!/usr/bin/env python3
2# Copyright (C) 2022 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 collections
30import json
31import os
32import re
33import sys
34
35import gn_utils
36
Patrick Rohr92d74122022-10-21 15:50:52 -070037ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
38
Patrick Rohr92d74122022-10-21 15:50:52 -070039# Defines a custom init_rc argument to be applied to the corresponding output
40# blueprint target.
41target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070042 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070043}
44
45target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070046 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070047]
48
Patrick Rohr92d74122022-10-21 15:50:52 -070049# Proto target groups which will be made public.
50proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070051 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070052}
53
54# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070055module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070056
57# Shared libraries which are directly translated to Android system equivalents.
58shared_library_allowlist = [
59 'android',
60 'android.hardware.atrace@1.0',
61 'android.hardware.health@2.0',
62 'android.hardware.health-V1-ndk',
63 'android.hardware.power.stats@1.0',
64 "android.hardware.power.stats-V1-cpp",
65 'base',
66 'binder',
67 'binder_ndk',
68 'cutils',
69 'hidlbase',
70 'hidltransport',
71 'hwbinder',
72 'incident',
73 'log',
74 'services',
75 'statssocket',
76 "tracingproxy",
77 'utils',
78]
79
80# Static libraries which are directly translated to Android system equivalents.
81static_library_allowlist = [
82 'statslog_perfetto',
83]
84
85# Name of the module which settings such as compiler flags for all other
86# modules.
87defaults_module = module_prefix + 'defaults'
88
89# Location of the project in the Android source tree.
90tree_path = 'external/perfetto'
91
92# Path for the protobuf sources in the standalone build.
93buildtools_protobuf_src = '//buildtools/protobuf/src'
94
95# Location of the protobuf src dir in the Android source tree.
96android_protobuf_src = 'external/protobuf/src'
97
98# Compiler flags which are passed through to the blueprint.
99cflag_allowlist = r'^-DPERFETTO.*$'
100
101# Compiler defines which are passed through to the blueprint.
102define_allowlist = r'^(GOOGLE_PROTO.*)|(ZLIB_.*)|(USE_MMAP)|(HAVE_HIDDEN)$'
103
Patrick Rohr92d74122022-10-21 15:50:52 -0700104# Additional arguments to apply to Android.bp rules.
105additional_args = {
Patrick Rohr29ba3052022-10-25 11:30:49 -0700106 # TODO: remove if this is not useful for the cronet build.
107 # Consider using additional_args for overriding the genrule cmd property for gn actions.
Patrick Rohr92d74122022-10-21 15:50:52 -0700108}
109
110
111def enable_gtest_and_gmock(module):
112 module.static_libs.add('libgmock')
113 module.static_libs.add('libgtest')
114 if module.name != 'perfetto_gtest_logcat_printer':
115 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
116
117
118def enable_protobuf_full(module):
119 if module.type == 'cc_binary_host':
120 module.static_libs.add('libprotobuf-cpp-full')
121 elif module.host_supported:
122 module.host.static_libs.add('libprotobuf-cpp-full')
123 module.android.shared_libs.add('libprotobuf-cpp-full')
124 else:
125 module.shared_libs.add('libprotobuf-cpp-full')
126
127
128def enable_protobuf_lite(module):
129 module.shared_libs.add('libprotobuf-cpp-lite')
130
131
132def enable_protoc_lib(module):
133 if module.type == 'cc_binary_host':
134 module.static_libs.add('libprotoc')
135 else:
136 module.shared_libs.add('libprotoc')
137
138
139def enable_libunwindstack(module):
140 if module.name != 'heapprofd_standalone_client':
141 module.shared_libs.add('libunwindstack')
142 module.shared_libs.add('libprocinfo')
143 module.shared_libs.add('libbase')
144 else:
145 module.static_libs.add('libunwindstack')
146 module.static_libs.add('libprocinfo')
147 module.static_libs.add('libbase')
148 module.static_libs.add('liblzma')
149 module.static_libs.add('libdexfile_support')
150 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
151
152
153def enable_libunwind(module):
154 # libunwind is disabled on Darwin so we cannot depend on it.
155 pass
156
157
158def enable_sqlite(module):
159 if module.type == 'cc_binary_host':
160 module.static_libs.add('libsqlite')
161 module.static_libs.add('sqlite_ext_percentile')
162 elif module.host_supported:
163 # Copy what the sqlite3 command line tool does.
164 module.android.shared_libs.add('libsqlite')
165 module.android.shared_libs.add('libicu')
166 module.android.shared_libs.add('liblog')
167 module.android.shared_libs.add('libutils')
168 module.android.static_libs.add('sqlite_ext_percentile')
169 module.host.static_libs.add('libsqlite')
170 module.host.static_libs.add('sqlite_ext_percentile')
171 else:
172 module.shared_libs.add('libsqlite')
173 module.shared_libs.add('libicu')
174 module.shared_libs.add('liblog')
175 module.shared_libs.add('libutils')
176 module.static_libs.add('sqlite_ext_percentile')
177
178
179def enable_zlib(module):
180 if module.type == 'cc_binary_host':
181 module.static_libs.add('libz')
182 elif module.host_supported:
183 module.android.shared_libs.add('libz')
184 module.host.static_libs.add('libz')
185 else:
186 module.shared_libs.add('libz')
187
188
189def enable_uapi_headers(module):
190 module.include_dirs.add('bionic/libc/kernel')
191
192
193def enable_bionic_libc_platform_headers_on_android(module):
194 module.header_libs.add('bionic_libc_platform_headers')
195
196
197# Android equivalents for third-party libraries that the upstream project
198# depends on.
199builtin_deps = {
200 '//gn:default_deps':
201 lambda x: None,
202 '//gn:gtest_main':
203 lambda x: None,
204 '//gn:protoc':
205 lambda x: None,
206 '//gn:gtest_and_gmock':
207 enable_gtest_and_gmock,
208 '//gn:libunwind':
209 enable_libunwind,
210 '//gn:protobuf_full':
211 enable_protobuf_full,
212 '//gn:protobuf_lite':
213 enable_protobuf_lite,
214 '//gn:protoc_lib':
215 enable_protoc_lib,
216 '//gn:libunwindstack':
217 enable_libunwindstack,
218 '//gn:sqlite':
219 enable_sqlite,
220 '//gn:zlib':
221 enable_zlib,
222 '//gn:bionic_kernel_uapi_headers':
223 enable_uapi_headers,
224 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
225 enable_bionic_libc_platform_headers_on_android,
226}
227
228# ----------------------------------------------------------------------------
229# End of configuration.
230# ----------------------------------------------------------------------------
231
232
233class Error(Exception):
234 pass
235
236
237class ThrowingArgumentParser(argparse.ArgumentParser):
238
239 def __init__(self, context):
240 super(ThrowingArgumentParser, self).__init__()
241 self.context = context
242
243 def error(self, message):
244 raise Error('%s: %s' % (self.context, message))
245
246
247def write_blueprint_key_value(output, name, value, sort=True):
248 """Writes a Blueprint key-value pair to the output"""
249
250 if isinstance(value, bool):
251 if value:
252 output.append(' %s: true,' % name)
253 else:
254 output.append(' %s: false,' % name)
255 return
256 if not value:
257 return
258 if isinstance(value, set):
259 value = sorted(value)
260 if isinstance(value, list):
261 output.append(' %s: [' % name)
262 for item in sorted(value) if sort else value:
263 output.append(' "%s",' % item)
264 output.append(' ],')
265 return
266 if isinstance(value, Target):
267 value.to_string(output)
268 return
269 if isinstance(value, dict):
270 kv_output = []
271 for k, v in value.items():
272 write_blueprint_key_value(kv_output, k, v)
273
274 output.append(' %s: {' % name)
275 for line in kv_output:
276 output.append(' %s' % line)
277 output.append(' },')
278 return
279 output.append(' %s: "%s",' % (name, value))
280
281
282class Target(object):
283 """A target-scoped part of a module"""
284
285 def __init__(self, name):
286 self.name = name
287 self.shared_libs = set()
288 self.static_libs = set()
289 self.whole_static_libs = set()
290 self.cflags = set()
291 self.dist = dict()
292 self.strip = dict()
293 self.stl = None
294
295 def to_string(self, output):
296 nested_out = []
297 self._output_field(nested_out, 'shared_libs')
298 self._output_field(nested_out, 'static_libs')
299 self._output_field(nested_out, 'whole_static_libs')
300 self._output_field(nested_out, 'cflags')
301 self._output_field(nested_out, 'stl')
302 self._output_field(nested_out, 'dist')
303 self._output_field(nested_out, 'strip')
304
305 if nested_out:
306 output.append(' %s: {' % self.name)
307 for line in nested_out:
308 output.append(' %s' % line)
309 output.append(' },')
310
311 def _output_field(self, output, name, sort=True):
312 value = getattr(self, name)
313 return write_blueprint_key_value(output, name, value, sort)
314
315
316class Module(object):
317 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
318
319 def __init__(self, mod_type, name, gn_target):
320 self.type = mod_type
321 self.gn_target = gn_target
322 self.name = name
323 self.srcs = set()
324 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
325 self.shared_libs = set()
326 self.static_libs = set()
327 self.whole_static_libs = set()
328 self.runtime_libs = set()
329 self.tools = set()
330 self.cmd = None
331 self.host_supported = False
332 self.vendor_available = False
333 self.init_rc = set()
334 self.out = set()
335 self.export_include_dirs = set()
336 self.generated_headers = set()
337 self.export_generated_headers = set()
338 self.defaults = set()
339 self.cflags = set()
340 self.include_dirs = set()
Patrick Rohr344b2472022-10-25 11:32:15 -0700341 self.local_include_dirs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700342 self.header_libs = set()
343 self.required = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700344 self.tool_files = None
345 self.android = Target('android')
346 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700347 self.stl = None
348 self.dist = dict()
349 self.strip = dict()
350 self.data = set()
351 self.apex_available = set()
352 self.min_sdk_version = None
353 self.proto = dict()
354 # The genrule_XXX below are properties that must to be propagated back
355 # on the module(s) that depend on the genrule.
356 self.genrule_headers = set()
357 self.genrule_srcs = set()
358 self.genrule_shared_libs = set()
359 self.version_script = None
360 self.test_suites = set()
361 self.test_config = None
362 self.stubs = {}
363
364 def to_string(self, output):
365 if self.comment:
366 output.append('// %s' % self.comment)
367 output.append('%s {' % self.type)
368 self._output_field(output, 'name')
369 self._output_field(output, 'srcs')
370 self._output_field(output, 'shared_libs')
371 self._output_field(output, 'static_libs')
372 self._output_field(output, 'whole_static_libs')
373 self._output_field(output, 'runtime_libs')
374 self._output_field(output, 'tools')
375 self._output_field(output, 'cmd', sort=False)
376 if self.host_supported:
377 self._output_field(output, 'host_supported')
378 if self.vendor_available:
379 self._output_field(output, 'vendor_available')
380 self._output_field(output, 'init_rc')
381 self._output_field(output, 'out')
382 self._output_field(output, 'export_include_dirs')
383 self._output_field(output, 'generated_headers')
384 self._output_field(output, 'export_generated_headers')
385 self._output_field(output, 'defaults')
386 self._output_field(output, 'cflags')
387 self._output_field(output, 'include_dirs')
Patrick Rohr344b2472022-10-25 11:32:15 -0700388 self._output_field(output, 'local_include_dirs')
Patrick Rohr92d74122022-10-21 15:50:52 -0700389 self._output_field(output, 'header_libs')
390 self._output_field(output, 'required')
391 self._output_field(output, 'dist')
392 self._output_field(output, 'strip')
393 self._output_field(output, 'tool_files')
394 self._output_field(output, 'data')
395 self._output_field(output, 'stl')
396 self._output_field(output, 'apex_available')
397 self._output_field(output, 'min_sdk_version')
398 self._output_field(output, 'version_script')
399 self._output_field(output, 'test_suites')
400 self._output_field(output, 'test_config')
401 self._output_field(output, 'stubs')
402 self._output_field(output, 'proto')
403
404 target_out = []
405 self._output_field(target_out, 'android')
406 self._output_field(target_out, 'host')
407 if target_out:
408 output.append(' target: {')
409 for line in target_out:
410 output.append(' %s' % line)
411 output.append(' },')
412
Patrick Rohr92d74122022-10-21 15:50:52 -0700413 output.append('}')
414 output.append('')
415
416 def add_android_static_lib(self, lib):
417 if self.type == 'cc_binary_host':
418 raise Exception('Adding Android static lib for host tool is unsupported')
419 elif self.host_supported:
420 self.android.static_libs.add(lib)
421 else:
422 self.static_libs.add(lib)
423
424 def add_android_shared_lib(self, lib):
425 if self.type == 'cc_binary_host':
426 raise Exception('Adding Android shared lib for host tool is unsupported')
427 elif self.host_supported:
428 self.android.shared_libs.add(lib)
429 else:
430 self.shared_libs.add(lib)
431
432 def _output_field(self, output, name, sort=True):
433 value = getattr(self, name)
434 return write_blueprint_key_value(output, name, value, sort)
435
436
437class Blueprint(object):
438 """In-memory representation of an Android.bp file."""
439
440 def __init__(self):
441 self.modules = {}
442
443 def add_module(self, module):
444 """Adds a new module to the blueprint, replacing any existing module
445 with the same name.
446
447 Args:
448 module: Module instance.
449 """
450 self.modules[module.name] = module
451
452 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700453 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700454 m.to_string(output)
455
456
457def label_to_module_name(label):
458 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
459 # If the label is explicibly listed in the default target list, don't prefix
460 # its name and return just the target name. This is so tools like
461 # "traceconv" stay as such in the Android tree.
462 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700463 module = re.sub(r'^//:?', '', label_without_toolchain)
464 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
465 if not module.startswith(module_prefix):
466 return module_prefix + module
467 return module
468
469
470def is_supported_source_file(name):
471 """Returns True if |name| can appear in a 'srcs' list."""
472 return os.path.splitext(name)[1] in ['.c', '.cc', '.proto']
473
474
475def create_proto_modules(blueprint, gn, target):
476 """Generate genrules for a proto GN target.
477
478 GN actions are used to dynamically generate files during the build. The
479 Soong equivalent is a genrule. This function turns a specific kind of
480 genrule which turns .proto files into source and header files into a pair
481 equivalent genrules.
482
483 Args:
484 blueprint: Blueprint instance which is being generated.
485 target: gn_utils.Target object.
486
487 Returns:
488 The source_genrule module.
489 """
490 assert (target.type == 'proto_library')
491
492 tools = {'aprotoc'}
493 cpp_out_dir = '$(genDir)/%s/' % tree_path
494 target_module_name = label_to_module_name(target.name)
495
496 # In GN builds the proto path is always relative to the output directory
497 # (out/tmp.xxx).
498 cmd = ['mkdir -p %s &&' % cpp_out_dir, '$(location aprotoc)']
499 cmd += ['--proto_path=%s' % tree_path]
500
501 if buildtools_protobuf_src in target.proto_paths:
502 cmd += ['--proto_path=%s' % android_protobuf_src]
503
504 # We don't generate any targets for source_set proto modules because
505 # they will be inlined into other modules if required.
506 if target.proto_plugin == 'source_set':
507 return None
508
509 # Descriptor targets only generate a single target.
510 if target.proto_plugin == 'descriptor':
511 out = '{}.bin'.format(target_module_name)
512
513 cmd += ['--descriptor_set_out=$(out)']
514 cmd += ['$(in)']
515
516 descriptor_module = Module('genrule', target_module_name, target.name)
517 descriptor_module.cmd = ' '.join(cmd)
518 descriptor_module.out = [out]
519 descriptor_module.tools = tools
520 blueprint.add_module(descriptor_module)
521
522 # Recursively extract the .proto files of all the dependencies and
523 # add them to srcs.
524 descriptor_module.srcs.update(
525 gn_utils.label_to_path(src) for src in target.sources)
526 for dep in target.transitive_proto_deps:
527 current_target = gn.get_target(dep)
528 descriptor_module.srcs.update(
529 gn_utils.label_to_path(src) for src in current_target.sources)
530
531 return descriptor_module
532
533 # We create two genrules for each proto target: one for the headers and
534 # another for the sources. This is because the module that depends on the
535 # generated files needs to declare two different types of dependencies --
536 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
537 # valid to generate .h files from a source dependency and vice versa.
538 source_module_name = target_module_name + '_gen'
539 source_module = Module('genrule', source_module_name, target.name)
540 blueprint.add_module(source_module)
541 source_module.srcs.update(
542 gn_utils.label_to_path(src) for src in target.sources)
543
544 header_module = Module('genrule', source_module_name + '_headers',
545 target.name)
546 blueprint.add_module(header_module)
547 header_module.srcs = set(source_module.srcs)
548
549 # TODO(primiano): at some point we should remove this. This was introduced
550 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
551 # avoid doing multi-repo changes and allow old clients in the android tree
552 # to still do the old #include "perfetto/..." rather than
553 # #include "protos/perfetto/...".
554 header_module.export_include_dirs = {'.', 'protos'}
555
556 source_module.genrule_srcs.add(':' + source_module.name)
557 source_module.genrule_headers.add(header_module.name)
558
559 if target.proto_plugin == 'proto':
560 suffixes = ['pb']
561 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
562 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
563 elif target.proto_plugin == 'protozero':
564 suffixes = ['pbzero']
565 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
566 tools.add(plugin.name)
567 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
568 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
569 elif target.proto_plugin == 'cppgen':
570 suffixes = ['gen']
571 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
572 tools.add(plugin.name)
573 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
574 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
575 elif target.proto_plugin == 'ipc':
576 suffixes = ['ipc']
577 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
578 tools.add(plugin.name)
579 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
580 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
581 else:
582 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
583
584 cmd += ['$(in)']
585 source_module.cmd = ' '.join(cmd)
586 header_module.cmd = source_module.cmd
587 source_module.tools = tools
588 header_module.tools = tools
589
590 for sfx in suffixes:
591 source_module.out.update('%s/%s' %
592 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
593 for src in source_module.srcs)
594 header_module.out.update('%s/%s' %
595 (tree_path, src.replace('.proto', '.%s.h' % sfx))
596 for src in header_module.srcs)
597 return source_module
598
599
600def create_amalgamated_sql_metrics_module(blueprint, target):
601 bp_module_name = label_to_module_name(target.name)
602 module = Module('genrule', bp_module_name, target.name)
603 module.tool_files = [
604 'tools/gen_amalgamated_sql_metrics.py',
605 ]
606 module.cmd = ' '.join([
607 '$(location tools/gen_amalgamated_sql_metrics.py)',
608 '--cpp_out=$(out)',
609 '$(in)',
610 ])
611 module.genrule_headers.add(module.name)
612 module.out.update(target.outputs)
613 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
614 blueprint.add_module(module)
615 return module
616
617
618def create_cc_proto_descriptor_module(blueprint, target):
619 bp_module_name = label_to_module_name(target.name)
620 module = Module('genrule', bp_module_name, target.name)
621 module.tool_files = [
622 'tools/gen_cc_proto_descriptor.py',
623 ]
624 module.cmd = ' '.join([
625 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
626 '--cpp_out=$(out)', '$(in)'
627 ])
628 module.genrule_headers.add(module.name)
629 module.srcs.update(
630 ':' + label_to_module_name(dep) for dep in target.proto_deps)
631 module.srcs.update(
632 gn_utils.label_to_path(src)
633 for src in target.inputs
634 if "tmp.gn_utils" not in src)
635 module.out.update(target.outputs)
636 blueprint.add_module(module)
637 return module
638
639
640def create_gen_version_module(blueprint, target, bp_module_name):
641 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
642 script_path = gn_utils.label_to_path(target.script)
643 module.genrule_headers.add(bp_module_name)
644 module.tool_files = [script_path]
645 module.out.update(target.outputs)
646 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
647 module.cmd = ' '.join([
648 'python3 $(location %s)' % script_path, '--no_git',
649 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
650 ])
651 blueprint.add_module(module)
652 return module
653
654
655def create_proto_group_modules(blueprint, gn, module_name, target_names):
656 # TODO(lalitm): today, we're only adding a Java lite module because that's
657 # the only one used in practice. In the future, if we need other target types
658 # (e.g. C++, Java full etc.) add them here.
659 bp_module_name = label_to_module_name(module_name) + '_java_protos'
660 module = Module('java_library', bp_module_name, bp_module_name)
661 module.comment = f'''GN: [{', '.join(target_names)}]'''
662 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
663
664 for name in target_names:
665 target = gn.get_target(name)
666 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
667 for dep_label in target.transitive_proto_deps:
668 dep = gn.get_target(dep_label)
669 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
670
671 blueprint.add_module(module)
672
673
674def _get_cflags(target):
675 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
676 cflags |= set("-D%s" % define
677 for define in target.defines
678 if re.match(define_allowlist, define))
679 return cflags
680
681
682def create_modules_from_target(blueprint, gn, gn_target_name):
683 """Generate module(s) for a given GN target.
684
685 Given a GN target name, generate one or more corresponding modules into a
686 blueprint. The only case when this generates >1 module is proto libraries.
687
688 Args:
689 blueprint: Blueprint instance which is being generated.
690 gn: gn_utils.GnParser object.
691 gn_target_name: GN target for module generation.
692 """
693 bp_module_name = label_to_module_name(gn_target_name)
694 if bp_module_name in blueprint.modules:
695 return blueprint.modules[bp_module_name]
696 target = gn.get_target(gn_target_name)
697
698 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
699 if target.type == 'executable':
700 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
701 module_type = 'cc_binary_host'
702 elif target.testonly:
703 module_type = 'cc_test'
704 else:
705 module_type = 'cc_binary'
706 module = Module(module_type, bp_module_name, gn_target_name)
707 elif target.type == 'static_library':
708 module = Module('cc_library_static', bp_module_name, gn_target_name)
709 elif target.type == 'shared_library':
710 module = Module('cc_library_shared', bp_module_name, gn_target_name)
711 elif target.type == 'source_set':
712 module = Module('filegroup', bp_module_name, gn_target_name)
713 elif target.type == 'group':
714 # "group" targets are resolved recursively by gn_utils.get_target().
715 # There's nothing we need to do at this level for them.
716 return None
717 elif target.type == 'proto_library':
718 module = create_proto_modules(blueprint, gn, target)
719 if module is None:
720 return None
721 elif target.type == 'action':
722 if 'gen_amalgamated_sql_metrics' in target.name:
723 module = create_amalgamated_sql_metrics_module(blueprint, target)
724 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
725 module = create_cc_proto_descriptor_module(blueprint, target)
726 elif target.type == 'action' and \
727 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
728 module = create_gen_version_module(blueprint, target, bp_module_name)
729 else:
730 raise Error('Unhandled action: {}'.format(target.name))
731 else:
732 raise Error('Unknown target %s (%s)' % (target.name, target.type))
733
734 blueprint.add_module(module)
735 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -0700736 module.init_rc = target_initrc.get(target.name, [])
737 module.srcs.update(
738 gn_utils.label_to_path(src)
739 for src in target.sources
740 if is_supported_source_file(src))
741
742 if target.type in gn_utils.LINKER_UNIT_TYPES:
743 module.cflags.update(_get_cflags(target))
Patrick Rohr344b2472022-10-25 11:32:15 -0700744 module.local_include_dirs.update(gn_utils.label_to_path(it) for it in target.include_dirs)
Patrick Rohr92d74122022-10-21 15:50:52 -0700745
746 module_is_compiled = module.type not in ('genrule', 'filegroup')
747 if module_is_compiled:
748 # Don't try to inject library/source dependencies into genrules or
749 # filegroups because they are not compiled in the traditional sense.
750 module.defaults = [defaults_module]
751 for lib in target.libs:
752 # Generally library names should be mangled as 'libXXX', unless they
753 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
754 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
755 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
756 else 'lib' + lib
757 if lib in shared_library_allowlist:
758 module.add_android_shared_lib(android_lib)
759 if lib in static_library_allowlist:
760 module.add_android_static_lib(android_lib)
761
762 # If the module is a static library, export all the generated headers.
763 if module.type == 'cc_library_static':
764 module.export_generated_headers = module.generated_headers
765
766 # Merge in additional hardcoded arguments.
767 for key, add_val in additional_args.get(module.name, []):
768 curr = getattr(module, key)
769 if add_val and isinstance(add_val, set) and isinstance(curr, set):
770 curr.update(add_val)
771 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
772 setattr(module, key, add_val)
773 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
774 setattr(module, key, add_val)
775 elif isinstance(add_val, dict) and isinstance(curr, dict):
776 curr.update(add_val)
777 elif isinstance(add_val, dict) and isinstance(curr, Target):
778 curr.__dict__.update(add_val)
779 else:
780 raise Error('Unimplemented type %r of additional_args: %r' %
781 (type(add_val), key))
782
783 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
784 all_deps = target.deps | target.source_set_deps | target.transitive_proto_deps
785 for dep_name in all_deps:
786 # If the dependency refers to a library which we can replace with an
787 # Android equivalent, stop recursing and patch the dependency in.
788 # Don't recurse into //buildtools, builtin_deps are intercepted at
789 # the //gn:xxx level.
790 if dep_name.startswith('//buildtools'):
791 continue
792
793 # Ignore the dependency on the gen_buildflags genrule. That is run
794 # separately in this generator and the generated file is copied over
795 # into the repo (see usage of |buildflags_dir| in this script).
796 if dep_name.startswith(gn_utils.BUILDFLAGS_TARGET):
797 continue
798
799 dep_module = create_modules_from_target(blueprint, gn, dep_name)
800
801 # For filegroups and genrule, recurse but don't apply the deps.
802 if not module_is_compiled:
803 continue
804
805 # |builtin_deps| override GN deps with Android-specific ones. See the
806 # config in the top of this file.
807 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
808 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
809 continue
810
811 # Don't recurse in any other //gn dep if not handled by builtin_deps.
812 if dep_name.startswith('//gn:'):
813 continue
814
815 if dep_module is None:
816 continue
817 if dep_module.type == 'cc_library_shared':
818 module.shared_libs.add(dep_module.name)
819 elif dep_module.type == 'cc_library_static':
820 module.static_libs.add(dep_module.name)
821 elif dep_module.type == 'filegroup':
822 module.srcs.add(':' + dep_module.name)
823 elif dep_module.type == 'genrule':
824 module.generated_headers.update(dep_module.genrule_headers)
825 module.srcs.update(dep_module.genrule_srcs)
826 module.shared_libs.update(dep_module.genrule_shared_libs)
827 elif dep_module.type == 'cc_binary':
828 continue # Ignore executables deps (used by cmdline integration tests).
829 else:
830 raise Error('Unknown dep %s (%s) for target %s' %
831 (dep_module.name, dep_module.type, module.name))
832
833 return module
834
835
836def create_blueprint_for_targets(gn, desc, targets):
837 """Generate a blueprint for a list of GN targets."""
838 blueprint = Blueprint()
839
840 # Default settings used by all modules.
841 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -0700842 defaults.cflags = [
843 '-Wno-error=return-type',
844 '-Wno-sign-compare',
845 '-Wno-sign-promo',
846 '-Wno-unused-parameter',
847 '-fvisibility=hidden',
848 '-O2',
849 ]
Patrick Rohr92d74122022-10-21 15:50:52 -0700850 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -0700851
Patrick Rohr92d74122022-10-21 15:50:52 -0700852 for target in targets:
853 create_modules_from_target(blueprint, gn, target)
854 return blueprint
855
856
857def main():
858 parser = argparse.ArgumentParser(
859 description='Generate Android.bp from a GN description.')
860 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -0700861 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -0700862 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
863 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -0700864 )
865 parser.add_argument(
866 '--extras',
867 help='Extra targets to include at the end of the Blueprint file',
868 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
869 )
870 parser.add_argument(
871 '--output',
872 help='Blueprint file to create',
873 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
874 )
875 parser.add_argument(
876 'targets',
877 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -0700878 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
879 )
Patrick Rohr92d74122022-10-21 15:50:52 -0700880 args = parser.parse_args()
881
Patrick Rohr3db246a2022-10-25 10:25:17 -0700882 with open(args.desc) as f:
883 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -0700884
885 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -0700886 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -0700887 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
888 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
889
Patrick Rohr92d74122022-10-21 15:50:52 -0700890 # Add any proto groups to the blueprint.
891 for l_name, t_names in proto_groups.items():
892 create_proto_group_modules(blueprint, gn, l_name, t_names)
893
894 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -0700895 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -0700896//
897// Licensed under the Apache License, Version 2.0 (the "License");
898// you may not use this file except in compliance with the License.
899// You may obtain a copy of the License at
900//
901// http://www.apache.org/licenses/LICENSE-2.0
902//
903// Unless required by applicable law or agreed to in writing, software
904// distributed under the License is distributed on an "AS IS" BASIS,
905// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
906// See the License for the specific language governing permissions and
907// limitations under the License.
908//
909// This file is automatically generated by %s. Do not edit.
910""" % (tool_name)
911 ]
912 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -0700913 if os.path.exists(args.extras):
914 with open(args.extras, 'r') as r:
915 for line in r:
916 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -0700917
918 out_files = []
919
920 # Generate the Android.bp file.
921 out_files.append(args.output + '.swp')
922 with open(out_files[-1], 'w') as f:
923 f.write('\n'.join(output))
924 # Text files should have a trailing EOL.
925 f.write('\n')
926
Patrick Rohr94693eb2022-10-25 10:09:16 -0700927 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -0700928
929
930if __name__ == '__main__':
931 sys.exit(main())