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