blob: 88b2b5a3b7558091e177eb4e73ef74b6bcf9a643 [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
Patrick Rohr16228942022-10-26 14:00:26 -070031import logging as log
Patrick Rohr92d74122022-10-21 15:50:52 -070032import os
33import re
34import sys
35
36import gn_utils
37
Patrick Rohr92d74122022-10-21 15:50:52 -070038ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
39
Patrick Rohr92d74122022-10-21 15:50:52 -070040# Defines a custom init_rc argument to be applied to the corresponding output
41# blueprint target.
42target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070043 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070044}
45
46target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070047 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070048]
49
Patrick Rohr92d74122022-10-21 15:50:52 -070050# Proto target groups which will be made public.
51proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070052 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070053}
54
55# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070056module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070057
58# Shared libraries which are directly translated to Android system equivalents.
59shared_library_allowlist = [
60 'android',
61 'android.hardware.atrace@1.0',
62 'android.hardware.health@2.0',
63 'android.hardware.health-V1-ndk',
64 'android.hardware.power.stats@1.0',
65 "android.hardware.power.stats-V1-cpp",
66 'base',
67 'binder',
68 'binder_ndk',
69 'cutils',
70 'hidlbase',
71 'hidltransport',
72 'hwbinder',
73 'incident',
74 'log',
75 'services',
76 'statssocket',
77 "tracingproxy",
78 'utils',
79]
80
81# Static libraries which are directly translated to Android system equivalents.
82static_library_allowlist = [
83 'statslog_perfetto',
84]
85
86# Name of the module which settings such as compiler flags for all other
87# modules.
88defaults_module = module_prefix + 'defaults'
89
90# Location of the project in the Android source tree.
91tree_path = 'external/perfetto'
92
93# Path for the protobuf sources in the standalone build.
94buildtools_protobuf_src = '//buildtools/protobuf/src'
95
96# Location of the protobuf src dir in the Android source tree.
97android_protobuf_src = 'external/protobuf/src'
98
99# Compiler flags which are passed through to the blueprint.
100cflag_allowlist = r'^-DPERFETTO.*$'
101
Patrick Rohr92d74122022-10-21 15:50:52 -0700102# Additional arguments to apply to Android.bp rules.
103additional_args = {
Patrick Rohr29ba3052022-10-25 11:30:49 -0700104 # TODO: remove if this is not useful for the cronet build.
105 # Consider using additional_args for overriding the genrule cmd property for gn actions.
Patrick Rohr92d74122022-10-21 15:50:52 -0700106}
107
108
109def enable_gtest_and_gmock(module):
110 module.static_libs.add('libgmock')
111 module.static_libs.add('libgtest')
112 if module.name != 'perfetto_gtest_logcat_printer':
113 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
114
115
116def enable_protobuf_full(module):
117 if module.type == 'cc_binary_host':
118 module.static_libs.add('libprotobuf-cpp-full')
119 elif module.host_supported:
120 module.host.static_libs.add('libprotobuf-cpp-full')
121 module.android.shared_libs.add('libprotobuf-cpp-full')
122 else:
123 module.shared_libs.add('libprotobuf-cpp-full')
124
125
126def enable_protobuf_lite(module):
127 module.shared_libs.add('libprotobuf-cpp-lite')
128
129
130def enable_protoc_lib(module):
131 if module.type == 'cc_binary_host':
132 module.static_libs.add('libprotoc')
133 else:
134 module.shared_libs.add('libprotoc')
135
136
137def enable_libunwindstack(module):
138 if module.name != 'heapprofd_standalone_client':
139 module.shared_libs.add('libunwindstack')
140 module.shared_libs.add('libprocinfo')
141 module.shared_libs.add('libbase')
142 else:
143 module.static_libs.add('libunwindstack')
144 module.static_libs.add('libprocinfo')
145 module.static_libs.add('libbase')
146 module.static_libs.add('liblzma')
147 module.static_libs.add('libdexfile_support')
148 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
149
150
151def enable_libunwind(module):
152 # libunwind is disabled on Darwin so we cannot depend on it.
153 pass
154
155
156def enable_sqlite(module):
157 if module.type == 'cc_binary_host':
158 module.static_libs.add('libsqlite')
159 module.static_libs.add('sqlite_ext_percentile')
160 elif module.host_supported:
161 # Copy what the sqlite3 command line tool does.
162 module.android.shared_libs.add('libsqlite')
163 module.android.shared_libs.add('libicu')
164 module.android.shared_libs.add('liblog')
165 module.android.shared_libs.add('libutils')
166 module.android.static_libs.add('sqlite_ext_percentile')
167 module.host.static_libs.add('libsqlite')
168 module.host.static_libs.add('sqlite_ext_percentile')
169 else:
170 module.shared_libs.add('libsqlite')
171 module.shared_libs.add('libicu')
172 module.shared_libs.add('liblog')
173 module.shared_libs.add('libutils')
174 module.static_libs.add('sqlite_ext_percentile')
175
176
177def enable_zlib(module):
178 if module.type == 'cc_binary_host':
179 module.static_libs.add('libz')
180 elif module.host_supported:
181 module.android.shared_libs.add('libz')
182 module.host.static_libs.add('libz')
183 else:
184 module.shared_libs.add('libz')
185
186
187def enable_uapi_headers(module):
188 module.include_dirs.add('bionic/libc/kernel')
189
190
191def enable_bionic_libc_platform_headers_on_android(module):
192 module.header_libs.add('bionic_libc_platform_headers')
193
194
195# Android equivalents for third-party libraries that the upstream project
196# depends on.
197builtin_deps = {
198 '//gn:default_deps':
199 lambda x: None,
200 '//gn:gtest_main':
201 lambda x: None,
202 '//gn:protoc':
203 lambda x: None,
204 '//gn:gtest_and_gmock':
205 enable_gtest_and_gmock,
206 '//gn:libunwind':
207 enable_libunwind,
208 '//gn:protobuf_full':
209 enable_protobuf_full,
210 '//gn:protobuf_lite':
211 enable_protobuf_lite,
212 '//gn:protoc_lib':
213 enable_protoc_lib,
214 '//gn:libunwindstack':
215 enable_libunwindstack,
216 '//gn:sqlite':
217 enable_sqlite,
218 '//gn:zlib':
219 enable_zlib,
220 '//gn:bionic_kernel_uapi_headers':
221 enable_uapi_headers,
222 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
223 enable_bionic_libc_platform_headers_on_android,
224}
225
226# ----------------------------------------------------------------------------
227# End of configuration.
228# ----------------------------------------------------------------------------
229
230
231class Error(Exception):
232 pass
233
234
235class ThrowingArgumentParser(argparse.ArgumentParser):
236
237 def __init__(self, context):
238 super(ThrowingArgumentParser, self).__init__()
239 self.context = context
240
241 def error(self, message):
242 raise Error('%s: %s' % (self.context, message))
243
244
245def write_blueprint_key_value(output, name, value, sort=True):
246 """Writes a Blueprint key-value pair to the output"""
247
248 if isinstance(value, bool):
249 if value:
250 output.append(' %s: true,' % name)
251 else:
252 output.append(' %s: false,' % name)
253 return
254 if not value:
255 return
256 if isinstance(value, set):
257 value = sorted(value)
258 if isinstance(value, list):
259 output.append(' %s: [' % name)
260 for item in sorted(value) if sort else value:
261 output.append(' "%s",' % item)
262 output.append(' ],')
263 return
264 if isinstance(value, Target):
265 value.to_string(output)
266 return
267 if isinstance(value, dict):
268 kv_output = []
269 for k, v in value.items():
270 write_blueprint_key_value(kv_output, k, v)
271
272 output.append(' %s: {' % name)
273 for line in kv_output:
274 output.append(' %s' % line)
275 output.append(' },')
276 return
277 output.append(' %s: "%s",' % (name, value))
278
279
280class Target(object):
281 """A target-scoped part of a module"""
282
283 def __init__(self, name):
284 self.name = name
285 self.shared_libs = set()
286 self.static_libs = set()
287 self.whole_static_libs = set()
288 self.cflags = set()
289 self.dist = dict()
290 self.strip = dict()
291 self.stl = None
292
293 def to_string(self, output):
294 nested_out = []
295 self._output_field(nested_out, 'shared_libs')
296 self._output_field(nested_out, 'static_libs')
297 self._output_field(nested_out, 'whole_static_libs')
298 self._output_field(nested_out, 'cflags')
299 self._output_field(nested_out, 'stl')
300 self._output_field(nested_out, 'dist')
301 self._output_field(nested_out, 'strip')
302
303 if nested_out:
304 output.append(' %s: {' % self.name)
305 for line in nested_out:
306 output.append(' %s' % line)
307 output.append(' },')
308
309 def _output_field(self, output, name, sort=True):
310 value = getattr(self, name)
311 return write_blueprint_key_value(output, name, value, sort)
312
313
314class Module(object):
315 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
316
317 def __init__(self, mod_type, name, gn_target):
318 self.type = mod_type
319 self.gn_target = gn_target
320 self.name = name
321 self.srcs = set()
322 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
323 self.shared_libs = set()
324 self.static_libs = set()
325 self.whole_static_libs = set()
326 self.runtime_libs = set()
327 self.tools = set()
328 self.cmd = None
329 self.host_supported = False
330 self.vendor_available = False
331 self.init_rc = set()
332 self.out = set()
333 self.export_include_dirs = set()
334 self.generated_headers = set()
335 self.export_generated_headers = set()
336 self.defaults = set()
337 self.cflags = set()
338 self.include_dirs = set()
Patrick Rohr344b2472022-10-25 11:32:15 -0700339 self.local_include_dirs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700340 self.header_libs = set()
341 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700342 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700343 self.android = Target('android')
344 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700345 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700346 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700347 self.dist = dict()
348 self.strip = dict()
349 self.data = set()
350 self.apex_available = set()
351 self.min_sdk_version = None
352 self.proto = dict()
353 # The genrule_XXX below are properties that must to be propagated back
354 # on the module(s) that depend on the genrule.
355 self.genrule_headers = set()
356 self.genrule_srcs = set()
357 self.genrule_shared_libs = set()
358 self.version_script = None
359 self.test_suites = set()
360 self.test_config = None
361 self.stubs = {}
362
363 def to_string(self, output):
364 if self.comment:
365 output.append('// %s' % self.comment)
366 output.append('%s {' % self.type)
367 self._output_field(output, 'name')
368 self._output_field(output, 'srcs')
369 self._output_field(output, 'shared_libs')
370 self._output_field(output, 'static_libs')
371 self._output_field(output, 'whole_static_libs')
372 self._output_field(output, 'runtime_libs')
373 self._output_field(output, 'tools')
374 self._output_field(output, 'cmd', sort=False)
375 if self.host_supported:
376 self._output_field(output, 'host_supported')
377 if self.vendor_available:
378 self._output_field(output, 'vendor_available')
379 self._output_field(output, 'init_rc')
380 self._output_field(output, 'out')
381 self._output_field(output, 'export_include_dirs')
382 self._output_field(output, 'generated_headers')
383 self._output_field(output, 'export_generated_headers')
384 self._output_field(output, 'defaults')
385 self._output_field(output, 'cflags')
386 self._output_field(output, 'include_dirs')
Patrick Rohr344b2472022-10-25 11:32:15 -0700387 self._output_field(output, 'local_include_dirs')
Patrick Rohr92d74122022-10-21 15:50:52 -0700388 self._output_field(output, 'header_libs')
389 self._output_field(output, 'required')
390 self._output_field(output, 'dist')
391 self._output_field(output, 'strip')
392 self._output_field(output, 'tool_files')
393 self._output_field(output, 'data')
394 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700395 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700396 self._output_field(output, 'apex_available')
397 self._output_field(output, 'min_sdk_version')
398 self._output_field(output, 'version_script')
399 self._output_field(output, 'test_suites')
400 self._output_field(output, 'test_config')
401 self._output_field(output, 'stubs')
402 self._output_field(output, 'proto')
403
404 target_out = []
405 self._output_field(target_out, 'android')
406 self._output_field(target_out, 'host')
407 if target_out:
408 output.append(' target: {')
409 for line in target_out:
410 output.append(' %s' % line)
411 output.append(' },')
412
Patrick Rohr92d74122022-10-21 15:50:52 -0700413 output.append('}')
414 output.append('')
415
416 def add_android_static_lib(self, lib):
417 if self.type == 'cc_binary_host':
418 raise Exception('Adding Android static lib for host tool is unsupported')
419 elif self.host_supported:
420 self.android.static_libs.add(lib)
421 else:
422 self.static_libs.add(lib)
423
424 def add_android_shared_lib(self, lib):
425 if self.type == 'cc_binary_host':
426 raise Exception('Adding Android shared lib for host tool is unsupported')
427 elif self.host_supported:
428 self.android.shared_libs.add(lib)
429 else:
430 self.shared_libs.add(lib)
431
432 def _output_field(self, output, name, sort=True):
433 value = getattr(self, name)
434 return write_blueprint_key_value(output, name, value, sort)
435
436
437class Blueprint(object):
438 """In-memory representation of an Android.bp file."""
439
440 def __init__(self):
441 self.modules = {}
442
443 def add_module(self, module):
444 """Adds a new module to the blueprint, replacing any existing module
445 with the same name.
446
447 Args:
448 module: Module instance.
449 """
450 self.modules[module.name] = module
451
452 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700453 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700454 m.to_string(output)
455
456
457def label_to_module_name(label):
458 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
459 # If the label is explicibly listed in the default target list, don't prefix
460 # its name and return just the target name. This is so tools like
461 # "traceconv" stay as such in the Android tree.
462 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700463 module = re.sub(r'^//:?', '', label_without_toolchain)
464 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
465 if not module.startswith(module_prefix):
466 return module_prefix + module
467 return module
468
469
470def is_supported_source_file(name):
471 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrd604f9f2022-10-27 13:56:42 -0700472 return os.path.splitext(name)[1] in ['.c', '.cc', '.java', '.proto']
Patrick Rohr92d74122022-10-21 15:50:52 -0700473
474
475def create_proto_modules(blueprint, gn, target):
476 """Generate genrules for a proto GN target.
477
478 GN actions are used to dynamically generate files during the build. The
479 Soong equivalent is a genrule. This function turns a specific kind of
480 genrule which turns .proto files into source and header files into a pair
481 equivalent genrules.
482
483 Args:
484 blueprint: Blueprint instance which is being generated.
485 target: gn_utils.Target object.
486
487 Returns:
488 The source_genrule module.
489 """
490 assert (target.type == 'proto_library')
491
492 tools = {'aprotoc'}
493 cpp_out_dir = '$(genDir)/%s/' % tree_path
494 target_module_name = label_to_module_name(target.name)
495
496 # In GN builds the proto path is always relative to the output directory
497 # (out/tmp.xxx).
498 cmd = ['mkdir -p %s &&' % cpp_out_dir, '$(location aprotoc)']
499 cmd += ['--proto_path=%s' % tree_path]
500
501 if buildtools_protobuf_src in target.proto_paths:
502 cmd += ['--proto_path=%s' % android_protobuf_src]
503
504 # We don't generate any targets for source_set proto modules because
505 # they will be inlined into other modules if required.
506 if target.proto_plugin == 'source_set':
507 return None
508
509 # Descriptor targets only generate a single target.
510 if target.proto_plugin == 'descriptor':
511 out = '{}.bin'.format(target_module_name)
512
513 cmd += ['--descriptor_set_out=$(out)']
514 cmd += ['$(in)']
515
516 descriptor_module = Module('genrule', target_module_name, target.name)
517 descriptor_module.cmd = ' '.join(cmd)
518 descriptor_module.out = [out]
519 descriptor_module.tools = tools
520 blueprint.add_module(descriptor_module)
521
522 # Recursively extract the .proto files of all the dependencies and
523 # add them to srcs.
524 descriptor_module.srcs.update(
525 gn_utils.label_to_path(src) for src in target.sources)
526 for dep in target.transitive_proto_deps:
527 current_target = gn.get_target(dep)
528 descriptor_module.srcs.update(
529 gn_utils.label_to_path(src) for src in current_target.sources)
530
531 return descriptor_module
532
533 # We create two genrules for each proto target: one for the headers and
534 # another for the sources. This is because the module that depends on the
535 # generated files needs to declare two different types of dependencies --
536 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
537 # valid to generate .h files from a source dependency and vice versa.
538 source_module_name = target_module_name + '_gen'
539 source_module = Module('genrule', source_module_name, target.name)
540 blueprint.add_module(source_module)
541 source_module.srcs.update(
542 gn_utils.label_to_path(src) for src in target.sources)
543
544 header_module = Module('genrule', source_module_name + '_headers',
545 target.name)
546 blueprint.add_module(header_module)
547 header_module.srcs = set(source_module.srcs)
548
549 # TODO(primiano): at some point we should remove this. This was introduced
550 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
551 # avoid doing multi-repo changes and allow old clients in the android tree
552 # to still do the old #include "perfetto/..." rather than
553 # #include "protos/perfetto/...".
554 header_module.export_include_dirs = {'.', 'protos'}
555
556 source_module.genrule_srcs.add(':' + source_module.name)
557 source_module.genrule_headers.add(header_module.name)
558
559 if target.proto_plugin == 'proto':
560 suffixes = ['pb']
561 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
562 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
563 elif target.proto_plugin == 'protozero':
564 suffixes = ['pbzero']
565 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
566 tools.add(plugin.name)
567 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
568 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
569 elif target.proto_plugin == 'cppgen':
570 suffixes = ['gen']
571 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
572 tools.add(plugin.name)
573 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
574 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
575 elif target.proto_plugin == 'ipc':
576 suffixes = ['ipc']
577 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
578 tools.add(plugin.name)
579 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
580 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
581 else:
582 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
583
584 cmd += ['$(in)']
585 source_module.cmd = ' '.join(cmd)
586 header_module.cmd = source_module.cmd
587 source_module.tools = tools
588 header_module.tools = tools
589
590 for sfx in suffixes:
591 source_module.out.update('%s/%s' %
592 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
593 for src in source_module.srcs)
594 header_module.out.update('%s/%s' %
595 (tree_path, src.replace('.proto', '.%s.h' % sfx))
596 for src in header_module.srcs)
597 return source_module
598
599
600def create_amalgamated_sql_metrics_module(blueprint, target):
601 bp_module_name = label_to_module_name(target.name)
602 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700603 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700604 module.cmd = ' '.join([
605 '$(location tools/gen_amalgamated_sql_metrics.py)',
606 '--cpp_out=$(out)',
607 '$(in)',
608 ])
609 module.genrule_headers.add(module.name)
610 module.out.update(target.outputs)
611 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
612 blueprint.add_module(module)
613 return module
614
615
616def create_cc_proto_descriptor_module(blueprint, target):
617 bp_module_name = label_to_module_name(target.name)
618 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700619 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700620 module.cmd = ' '.join([
621 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
622 '--cpp_out=$(out)', '$(in)'
623 ])
624 module.genrule_headers.add(module.name)
625 module.srcs.update(
626 ':' + label_to_module_name(dep) for dep in target.proto_deps)
627 module.srcs.update(
628 gn_utils.label_to_path(src)
629 for src in target.inputs
630 if "tmp.gn_utils" not in src)
631 module.out.update(target.outputs)
632 blueprint.add_module(module)
633 return module
634
635
636def create_gen_version_module(blueprint, target, bp_module_name):
637 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
638 script_path = gn_utils.label_to_path(target.script)
639 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700640 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700641 module.out.update(target.outputs)
642 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
643 module.cmd = ' '.join([
644 'python3 $(location %s)' % script_path, '--no_git',
645 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
646 ])
647 blueprint.add_module(module)
648 return module
649
650
651def create_proto_group_modules(blueprint, gn, module_name, target_names):
652 # TODO(lalitm): today, we're only adding a Java lite module because that's
653 # the only one used in practice. In the future, if we need other target types
654 # (e.g. C++, Java full etc.) add them here.
655 bp_module_name = label_to_module_name(module_name) + '_java_protos'
656 module = Module('java_library', bp_module_name, bp_module_name)
657 module.comment = f'''GN: [{', '.join(target_names)}]'''
658 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
659
660 for name in target_names:
661 target = gn.get_target(name)
662 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
663 for dep_label in target.transitive_proto_deps:
664 dep = gn.get_target(dep_label)
665 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
666
667 blueprint.add_module(module)
668
Motomu Utsumibf569d42022-10-28 16:47:34 +0900669# There may be a better way to do target specific modification
670# Target specific modification before create_action_module
671def pre_create_action_module(target):
Patrick Rohr9b99a982022-10-28 11:00:57 -0700672 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
673 # TODO: we may want to only do this for python scripts arguments. If argparse
674 # is used, this transformation is safe.
675 target.args = [str for it in target.args for str in it.split('=')]
676
Motomu Utsumibf569d42022-10-28 16:47:34 +0900677 if target.script == "//build/write_buildflag_header.py":
678 # write_buildflag_header.py writes result to args.genDir/args.output
679 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700680 for i, val in enumerate(target.args):
681 if val == '--gen-dir':
682 target.args[i + 1] = '.'
Motomu Utsumibf569d42022-10-28 16:47:34 +0900683 break
Patrick Rohr0db9f852022-10-27 13:49:57 -0700684
Patrick Rohr8acccca2022-10-28 10:39:06 -0700685 elif target.script == '//base/android/jni_generator/jni_generator.py':
686 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900687 if val == '--output_dir':
688 # replace --output_dir gen/... with --output_dir $(genDir)/...
Patrick Rohr8acccca2022-10-28 10:39:06 -0700689 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
690 if val == '--input_file':
691 # --input_file supports both .class specifiers or source files as arguments.
692 # Only source files need to be wrapped inside a $(location <label>) tag.
693 if re.match('.*\.class$', target.args[i + 1]):
694 continue
695 # replace --input_file ../../... with --input_file $(location ...)
696 # TODO: put inside function
697 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
698 target.args[i + 1] = '$(location %s)' % filename
699
700
Patrick Rohre1a853e2022-10-26 12:31:39 -0700701def create_action_module(blueprint, target):
702 bp_module_name = label_to_module_name(target.name)
703 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700704 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700705 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700706
Motomu Utsumi83c3da22022-10-28 15:56:21 +0900707 # Replace arg by {$out} if possible
708 if len(target.outputs) == 1:
709 out = list(target.outputs)[0]
Motomu Utsumie0d20212022-10-28 17:06:46 +0900710 target.args = ['$(out)' if arg == out or arg == 'gen/' + out else arg for arg in target.args]
Motomu Utsumi83c3da22022-10-28 15:56:21 +0900711
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700712 # Handle passing parameters via response file by piping them into the script
713 # and reading them from /dev/stdin.
714 response_file = '{{response_file_name}}'
715 use_response_file = response_file in target.args
716 if use_response_file:
717 # Replace {{response_file_contents}} with /dev/stdin
718 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
719
Patrick Rohr9b99a982022-10-28 11:00:57 -0700720 # put all args on a new line for better diffs.
721 NEWLINE = ' " +\n "'
722 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700723 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700724
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700725 if use_response_file:
726 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700727 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700728
Patrick Rohr67f4d432022-10-26 16:04:15 -0700729 if all(os.path.splitext(it)[1] == '.h' for it in target.outputs):
730 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700731
Patrick Rohr0db9f852022-10-27 13:49:57 -0700732 # gn treats inputs and sources for actions equally.
733 # soong only supports source files inside srcs, non-source files are added as
734 # tool_files dependency.
735 for it in target.sources or target.inputs:
736 if is_supported_source_file(it):
737 module.srcs.add(gn_utils.label_to_path(it))
738 else:
739 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700740
Patrick Rohr15a2c302022-10-26 15:08:57 -0700741 # Actions using template "action_with_pydeps" also put script inside inputs.
742 # TODO: it might make sense to filter inputs inside GnParser.
743 if script in module.srcs:
744 module.srcs.remove(script)
745
Patrick Rohre1a853e2022-10-26 12:31:39 -0700746 module.out.update(target.outputs)
747 blueprint.add_module(module)
748 return module
749
750
Patrick Rohr92d74122022-10-21 15:50:52 -0700751
752def _get_cflags(target):
753 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900754 # Consider proper allowlist or denylist if needed
755 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700756 return cflags
757
758
759def create_modules_from_target(blueprint, gn, gn_target_name):
760 """Generate module(s) for a given GN target.
761
762 Given a GN target name, generate one or more corresponding modules into a
763 blueprint. The only case when this generates >1 module is proto libraries.
764
765 Args:
766 blueprint: Blueprint instance which is being generated.
767 gn: gn_utils.GnParser object.
768 gn_target_name: GN target for module generation.
769 """
770 bp_module_name = label_to_module_name(gn_target_name)
771 if bp_module_name in blueprint.modules:
772 return blueprint.modules[bp_module_name]
773 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -0700774 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -0700775
776 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
777 if target.type == 'executable':
778 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
779 module_type = 'cc_binary_host'
780 elif target.testonly:
781 module_type = 'cc_test'
782 else:
783 module_type = 'cc_binary'
784 module = Module(module_type, bp_module_name, gn_target_name)
785 elif target.type == 'static_library':
786 module = Module('cc_library_static', bp_module_name, gn_target_name)
787 elif target.type == 'shared_library':
788 module = Module('cc_library_shared', bp_module_name, gn_target_name)
789 elif target.type == 'source_set':
790 module = Module('filegroup', bp_module_name, gn_target_name)
791 elif target.type == 'group':
792 # "group" targets are resolved recursively by gn_utils.get_target().
793 # There's nothing we need to do at this level for them.
794 return None
795 elif target.type == 'proto_library':
796 module = create_proto_modules(blueprint, gn, target)
797 if module is None:
798 return None
799 elif target.type == 'action':
800 if 'gen_amalgamated_sql_metrics' in target.name:
801 module = create_amalgamated_sql_metrics_module(blueprint, target)
802 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
803 module = create_cc_proto_descriptor_module(blueprint, target)
804 elif target.type == 'action' and \
805 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
806 module = create_gen_version_module(blueprint, target, bp_module_name)
807 else:
Motomu Utsumibf569d42022-10-28 16:47:34 +0900808 pre_create_action_module(target)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700809 module = create_action_module(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -0700810 elif target.type == 'copy':
811 # TODO: careful now! copy targets are not supported yet, but this will stop
812 # traversing the dependency tree. For //base:base, this is not a big
813 # problem as libicu contains the only copy target which happens to be a
814 # leaf node.
815 return None
Patrick Rohr92d74122022-10-21 15:50:52 -0700816 else:
817 raise Error('Unknown target %s (%s)' % (target.name, target.type))
818
819 blueprint.add_module(module)
820 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -0700821 module.init_rc = target_initrc.get(target.name, [])
822 module.srcs.update(
823 gn_utils.label_to_path(src)
824 for src in target.sources
825 if is_supported_source_file(src))
826
827 if target.type in gn_utils.LINKER_UNIT_TYPES:
828 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -0700829 # HACK! We may have to link against chromium's sysroot instead, but this
830 # seems to work for //base:base.
831 # TODO: implement proper cflag parsing.
832 for flag in target.cflags:
833 if '--sysroot=' in flag:
834 module.header_libs.add('jni_headers')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700835 if '-std=' in flag:
836 module.cpp_std = flag[len('-std='):]
837
Patrick Rohr344b2472022-10-25 11:32:15 -0700838 module.local_include_dirs.update(gn_utils.label_to_path(it) for it in target.include_dirs)
Patrick Rohr92d74122022-10-21 15:50:52 -0700839
840 module_is_compiled = module.type not in ('genrule', 'filegroup')
841 if module_is_compiled:
842 # Don't try to inject library/source dependencies into genrules or
843 # filegroups because they are not compiled in the traditional sense.
844 module.defaults = [defaults_module]
845 for lib in target.libs:
846 # Generally library names should be mangled as 'libXXX', unless they
847 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
848 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
849 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
850 else 'lib' + lib
851 if lib in shared_library_allowlist:
852 module.add_android_shared_lib(android_lib)
853 if lib in static_library_allowlist:
854 module.add_android_static_lib(android_lib)
855
856 # If the module is a static library, export all the generated headers.
857 if module.type == 'cc_library_static':
858 module.export_generated_headers = module.generated_headers
859
860 # Merge in additional hardcoded arguments.
861 for key, add_val in additional_args.get(module.name, []):
862 curr = getattr(module, key)
863 if add_val and isinstance(add_val, set) and isinstance(curr, set):
864 curr.update(add_val)
865 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
866 setattr(module, key, add_val)
867 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
868 setattr(module, key, add_val)
869 elif isinstance(add_val, dict) and isinstance(curr, dict):
870 curr.update(add_val)
871 elif isinstance(add_val, dict) and isinstance(curr, Target):
872 curr.__dict__.update(add_val)
873 else:
874 raise Error('Unimplemented type %r of additional_args: %r' %
875 (type(add_val), key))
876
877 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
878 all_deps = target.deps | target.source_set_deps | target.transitive_proto_deps
879 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -0700880 # |builtin_deps| override GN deps with Android-specific ones. See the
881 # config in the top of this file.
882 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
883 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
884 continue
885
Patrick Rohr92d74122022-10-21 15:50:52 -0700886 dep_module = create_modules_from_target(blueprint, gn, dep_name)
887
888 # For filegroups and genrule, recurse but don't apply the deps.
889 if not module_is_compiled:
890 continue
891
Patrick Rohr92d74122022-10-21 15:50:52 -0700892 if dep_module is None:
893 continue
894 if dep_module.type == 'cc_library_shared':
895 module.shared_libs.add(dep_module.name)
896 elif dep_module.type == 'cc_library_static':
897 module.static_libs.add(dep_module.name)
898 elif dep_module.type == 'filegroup':
899 module.srcs.add(':' + dep_module.name)
900 elif dep_module.type == 'genrule':
901 module.generated_headers.update(dep_module.genrule_headers)
902 module.srcs.update(dep_module.genrule_srcs)
903 module.shared_libs.update(dep_module.genrule_shared_libs)
904 elif dep_module.type == 'cc_binary':
905 continue # Ignore executables deps (used by cmdline integration tests).
906 else:
907 raise Error('Unknown dep %s (%s) for target %s' %
908 (dep_module.name, dep_module.type, module.name))
909
910 return module
911
912
913def create_blueprint_for_targets(gn, desc, targets):
914 """Generate a blueprint for a list of GN targets."""
915 blueprint = Blueprint()
916
917 # Default settings used by all modules.
918 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -0700919 defaults.cflags = [
920 '-Wno-error=return-type',
921 '-Wno-sign-compare',
922 '-Wno-sign-promo',
923 '-Wno-unused-parameter',
924 '-fvisibility=hidden',
925 '-O2',
926 ]
Patrick Rohr92d74122022-10-21 15:50:52 -0700927 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -0700928
Patrick Rohr92d74122022-10-21 15:50:52 -0700929 for target in targets:
930 create_modules_from_target(blueprint, gn, target)
931 return blueprint
932
933
934def main():
935 parser = argparse.ArgumentParser(
936 description='Generate Android.bp from a GN description.')
937 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -0700938 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -0700939 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
940 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -0700941 )
942 parser.add_argument(
943 '--extras',
944 help='Extra targets to include at the end of the Blueprint file',
945 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
946 )
947 parser.add_argument(
948 '--output',
949 help='Blueprint file to create',
950 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
951 )
952 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -0700953 '-v',
954 '--verbose',
955 help='Print debug logs.',
956 action='store_true',
957 )
958 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -0700959 'targets',
960 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -0700961 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
962 )
Patrick Rohr92d74122022-10-21 15:50:52 -0700963 args = parser.parse_args()
964
Patrick Rohr16228942022-10-26 14:00:26 -0700965 if args.verbose:
966 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
967
Patrick Rohr3db246a2022-10-25 10:25:17 -0700968 with open(args.desc) as f:
969 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -0700970
971 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -0700972 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -0700973 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
974 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
975
Patrick Rohr92d74122022-10-21 15:50:52 -0700976 # Add any proto groups to the blueprint.
977 for l_name, t_names in proto_groups.items():
978 create_proto_group_modules(blueprint, gn, l_name, t_names)
979
980 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -0700981 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -0700982//
983// Licensed under the Apache License, Version 2.0 (the "License");
984// you may not use this file except in compliance with the License.
985// You may obtain a copy of the License at
986//
987// http://www.apache.org/licenses/LICENSE-2.0
988//
989// Unless required by applicable law or agreed to in writing, software
990// distributed under the License is distributed on an "AS IS" BASIS,
991// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
992// See the License for the specific language governing permissions and
993// limitations under the License.
994//
995// This file is automatically generated by %s. Do not edit.
996""" % (tool_name)
997 ]
998 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -0700999 if os.path.exists(args.extras):
1000 with open(args.extras, 'r') as r:
1001 for line in r:
1002 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001003
1004 out_files = []
1005
1006 # Generate the Android.bp file.
1007 out_files.append(args.output + '.swp')
1008 with open(out_files[-1], 'w') as f:
1009 f.write('\n'.join(output))
1010 # Text files should have a trailing EOL.
1011 f.write('\n')
1012
Patrick Rohr94693eb2022-10-25 10:09:16 -07001013 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001014
1015
1016if __name__ == '__main__':
1017 sys.exit(main())