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