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