blob: c6dccbb84fa63db93aa6cb661f0734e94fb6a686 [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 Rohr3a2c3dd2022-11-29 22:29:36 -080032import operator
Patrick Rohr92d74122022-10-21 15:50:52 -070033import os
34import re
35import sys
Motomu Utsumic6277d92022-11-07 15:15:17 +090036import copy
Patrick Rohr92d74122022-10-21 15:50:52 -070037
38import gn_utils
39
Patrick Rohr92d74122022-10-21 15:50:52 -070040ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
41
Patrick Rohr06296362022-11-10 21:37:33 -080042# Default targets to translate to the blueprint file.
43default_targets = [
44 '//components/cronet/android:cronet',
Motomu Utsumiabbfdc32022-11-25 12:19:23 +090045 '//components/cronet:cronet_package',
Patrick Rohr06296362022-11-10 21:37:33 -080046]
47
Patrick Rohr92d74122022-10-21 15:50:52 -070048# Defines a custom init_rc argument to be applied to the corresponding output
49# blueprint target.
50target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070051 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070052}
53
54target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070055 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070056]
57
Patrick Rohr92d74122022-10-21 15:50:52 -070058# Proto target groups which will be made public.
59proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070060 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070061}
62
63# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070064module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070065
66# Shared libraries which are directly translated to Android system equivalents.
67shared_library_allowlist = [
68 'android',
69 'android.hardware.atrace@1.0',
70 'android.hardware.health@2.0',
71 'android.hardware.health-V1-ndk',
72 'android.hardware.power.stats@1.0',
73 "android.hardware.power.stats-V1-cpp",
74 'base',
75 'binder',
76 'binder_ndk',
77 'cutils',
78 'hidlbase',
79 'hidltransport',
80 'hwbinder',
81 'incident',
82 'log',
83 'services',
84 'statssocket',
85 "tracingproxy",
86 'utils',
87]
88
89# Static libraries which are directly translated to Android system equivalents.
90static_library_allowlist = [
91 'statslog_perfetto',
92]
93
Patrick Rohrd9dd3b92022-11-09 16:15:30 -080094# Include directories that will be removed from all targets.
95local_include_dirs_denylist = [
Patrick Rohrd9dd3b92022-11-09 16:15:30 -080096]
97
Patrick Rohr92d74122022-10-21 15:50:52 -070098# Name of the module which settings such as compiler flags for all other
99# modules.
100defaults_module = module_prefix + 'defaults'
101
102# Location of the project in the Android source tree.
Patrick Rohr76ceeb52022-11-07 14:18:58 -0800103tree_path = 'external/chromium_org'
Patrick Rohr92d74122022-10-21 15:50:52 -0700104
105# Path for the protobuf sources in the standalone build.
106buildtools_protobuf_src = '//buildtools/protobuf/src'
107
108# Location of the protobuf src dir in the Android source tree.
109android_protobuf_src = 'external/protobuf/src'
110
111# Compiler flags which are passed through to the blueprint.
Motomu Utsumic8b7bea2022-11-16 18:12:44 +0900112cflag_allowlist = [
Motomu Utsumicf68d732022-11-16 18:15:21 +0900113 # needed for zlib:zlib
114 "-mpclmul",
115 # needed for zlib:zlib
116 "-mssse3",
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000117 # needed for zlib:zlib
118 "-msse3",
119 # needed for zlib:zlib
120 "-msse4.2",
Motomu Utsumic8b7bea2022-11-16 18:12:44 +0900121]
Patrick Rohr92d74122022-10-21 15:50:52 -0700122
Patrick Rohr92d74122022-10-21 15:50:52 -0700123# Additional arguments to apply to Android.bp rules.
124additional_args = {
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800125 # TODO: remove if not needed.
Patrick Rohrd90025f2022-11-11 14:18:35 -0800126 'cronet_aml_components_cronet_android_cronet': [
127 ('linker_scripts', {
128 'base/android/library_loader/anchor_functions.lds',
129 }),
130 ],
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800131 'cronet_aml_net_net': [
Patrick Rohr9f4d3e32022-11-09 16:37:31 -0800132 ('export_static_lib_headers', {
133 'cronet_aml_net_third_party_quiche_quiche',
134 'cronet_aml_crypto_crypto',
135 }),
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000136 ],
Patrick Rohr92d74122022-10-21 15:50:52 -0700137}
138
Patrick Rohr92d74122022-10-21 15:50:52 -0700139# Android equivalents for third-party libraries that the upstream project
140# depends on.
141builtin_deps = {
Patrick Rohr14ee0932022-11-15 12:10:27 -0800142 '//net/tools/root_store_tool:root_store_tool':
143 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700144}
145
146# ----------------------------------------------------------------------------
147# End of configuration.
148# ----------------------------------------------------------------------------
149
150
151class Error(Exception):
152 pass
153
154
155class ThrowingArgumentParser(argparse.ArgumentParser):
156
157 def __init__(self, context):
158 super(ThrowingArgumentParser, self).__init__()
159 self.context = context
160
161 def error(self, message):
162 raise Error('%s: %s' % (self.context, message))
163
164
165def write_blueprint_key_value(output, name, value, sort=True):
166 """Writes a Blueprint key-value pair to the output"""
167
168 if isinstance(value, bool):
169 if value:
170 output.append(' %s: true,' % name)
171 else:
172 output.append(' %s: false,' % name)
173 return
174 if not value:
175 return
176 if isinstance(value, set):
177 value = sorted(value)
178 if isinstance(value, list):
179 output.append(' %s: [' % name)
180 for item in sorted(value) if sort else value:
181 output.append(' "%s",' % item)
182 output.append(' ],')
183 return
184 if isinstance(value, Target):
185 value.to_string(output)
186 return
187 if isinstance(value, dict):
188 kv_output = []
189 for k, v in value.items():
190 write_blueprint_key_value(kv_output, k, v)
191
192 output.append(' %s: {' % name)
193 for line in kv_output:
194 output.append(' %s' % line)
195 output.append(' },')
196 return
197 output.append(' %s: "%s",' % (name, value))
198
199
200class Target(object):
201 """A target-scoped part of a module"""
202
203 def __init__(self, name):
204 self.name = name
Patrick Rohr5d399b32022-11-16 10:19:55 -0800205 self.srcs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700206 self.shared_libs = set()
207 self.static_libs = set()
208 self.whole_static_libs = set()
Patrick Rohrc03f1bb2022-11-18 16:13:17 -0800209 self.header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700210 self.cflags = set()
211 self.dist = dict()
212 self.strip = dict()
213 self.stl = None
Motomu Utsumi50ad2172022-11-17 22:29:53 +0900214 self.cppflags = set()
Patrick Rohr3cd5ffb2022-11-18 17:40:55 -0800215 self.local_include_dirs = set()
Patrick Rohr81435162022-11-17 19:34:32 -0800216 self.export_system_include_dirs = set()
Mohannad Farrag631443e2022-11-21 16:17:01 +0000217 self.generated_headers = set()
218 self.export_generated_headers = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700219
220 def to_string(self, output):
221 nested_out = []
Patrick Rohr5d399b32022-11-16 10:19:55 -0800222 self._output_field(nested_out, 'srcs')
Patrick Rohr92d74122022-10-21 15:50:52 -0700223 self._output_field(nested_out, 'shared_libs')
224 self._output_field(nested_out, 'static_libs')
225 self._output_field(nested_out, 'whole_static_libs')
Patrick Rohrc03f1bb2022-11-18 16:13:17 -0800226 self._output_field(nested_out, 'header_libs')
Patrick Rohr92d74122022-10-21 15:50:52 -0700227 self._output_field(nested_out, 'cflags')
228 self._output_field(nested_out, 'stl')
229 self._output_field(nested_out, 'dist')
230 self._output_field(nested_out, 'strip')
Motomu Utsumi50ad2172022-11-17 22:29:53 +0900231 self._output_field(nested_out, 'cppflags')
232 self._output_field(nested_out, 'local_include_dirs')
Patrick Rohr81435162022-11-17 19:34:32 -0800233 self._output_field(nested_out, 'export_system_include_dirs')
Mohannad Farrag631443e2022-11-21 16:17:01 +0000234 self._output_field(nested_out, 'generated_headers')
235 self._output_field(nested_out, 'export_generated_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -0700236
237 if nested_out:
238 output.append(' %s: {' % self.name)
239 for line in nested_out:
240 output.append(' %s' % line)
241 output.append(' },')
242
243 def _output_field(self, output, name, sort=True):
244 value = getattr(self, name)
245 return write_blueprint_key_value(output, name, value, sort)
246
247
248class Module(object):
249 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
250
251 def __init__(self, mod_type, name, gn_target):
252 self.type = mod_type
253 self.gn_target = gn_target
254 self.name = name
255 self.srcs = set()
Patrick Rohr07876662022-11-15 22:55:23 -0800256 self.comment = 'GN: ' + gn_target
Patrick Rohr92d74122022-10-21 15:50:52 -0700257 self.shared_libs = set()
258 self.static_libs = set()
259 self.whole_static_libs = set()
260 self.runtime_libs = set()
261 self.tools = set()
262 self.cmd = None
263 self.host_supported = False
Patrick Rohrcdda6322022-11-15 22:44:16 -0800264 self.device_supported = True
Patrick Rohr92d74122022-10-21 15:50:52 -0700265 self.vendor_available = False
266 self.init_rc = set()
267 self.out = set()
268 self.export_include_dirs = set()
269 self.generated_headers = set()
270 self.export_generated_headers = set()
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800271 self.export_static_lib_headers = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700272 self.defaults = set()
273 self.cflags = set()
274 self.include_dirs = set()
Patrick Rohr3cd5ffb2022-11-18 17:40:55 -0800275 self.local_include_dirs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700276 self.header_libs = set()
277 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700278 self.tool_files = set()
Patrick Rohrbfdc5fd2022-11-16 10:03:49 -0800279 # target contains a dict of Targets indexed by os_arch.
280 # example: { 'android_x86': Target('android_x86')
281 self.target = dict()
282 self.target['android'] = Target('android')
Patrick Rohr82e40742022-11-16 10:20:39 -0800283 self.target['android_x86'] = Target('android_x86')
284 self.target['android_x86_64'] = Target('android_x86_64')
285 self.target['android_arm'] = Target('android_arm')
286 self.target['android_arm64'] = Target('android_arm64')
Patrick Rohrbfdc5fd2022-11-16 10:03:49 -0800287 self.target['host'] = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700288 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700289 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700290 self.dist = dict()
291 self.strip = dict()
292 self.data = set()
293 self.apex_available = set()
294 self.min_sdk_version = None
295 self.proto = dict()
Patrick Rohrd90025f2022-11-11 14:18:35 -0800296 self.linker_scripts = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700297 # The genrule_XXX below are properties that must to be propagated back
298 # on the module(s) that depend on the genrule.
299 self.genrule_headers = set()
300 self.genrule_srcs = set()
301 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700302 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700303 self.version_script = None
304 self.test_suites = set()
305 self.test_config = None
306 self.stubs = {}
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000307 self.cppflags = set()
308 self.rtti = False
Patrick Rohr92d74122022-10-21 15:50:52 -0700309
310 def to_string(self, output):
311 if self.comment:
312 output.append('// %s' % self.comment)
313 output.append('%s {' % self.type)
314 self._output_field(output, 'name')
315 self._output_field(output, 'srcs')
316 self._output_field(output, 'shared_libs')
317 self._output_field(output, 'static_libs')
318 self._output_field(output, 'whole_static_libs')
319 self._output_field(output, 'runtime_libs')
320 self._output_field(output, 'tools')
321 self._output_field(output, 'cmd', sort=False)
322 if self.host_supported:
323 self._output_field(output, 'host_supported')
Patrick Rohrcdda6322022-11-15 22:44:16 -0800324 if not self.device_supported:
325 self._output_field(output, 'device_supported')
Patrick Rohr92d74122022-10-21 15:50:52 -0700326 if self.vendor_available:
327 self._output_field(output, 'vendor_available')
328 self._output_field(output, 'init_rc')
329 self._output_field(output, 'out')
330 self._output_field(output, 'export_include_dirs')
331 self._output_field(output, 'generated_headers')
332 self._output_field(output, 'export_generated_headers')
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800333 self._output_field(output, 'export_static_lib_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -0700334 self._output_field(output, 'defaults')
335 self._output_field(output, 'cflags')
336 self._output_field(output, 'include_dirs')
Patrick Rohr3cd5ffb2022-11-18 17:40:55 -0800337 self._output_field(output, 'local_include_dirs')
Patrick Rohr92d74122022-10-21 15:50:52 -0700338 self._output_field(output, 'header_libs')
339 self._output_field(output, 'required')
340 self._output_field(output, 'dist')
341 self._output_field(output, 'strip')
342 self._output_field(output, 'tool_files')
343 self._output_field(output, 'data')
344 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700345 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700346 self._output_field(output, 'apex_available')
347 self._output_field(output, 'min_sdk_version')
348 self._output_field(output, 'version_script')
349 self._output_field(output, 'test_suites')
350 self._output_field(output, 'test_config')
351 self._output_field(output, 'stubs')
352 self._output_field(output, 'proto')
Patrick Rohrd90025f2022-11-11 14:18:35 -0800353 self._output_field(output, 'linker_scripts')
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000354 self._output_field(output, 'cppflags')
355 if self.rtti:
356 self._output_field(output, 'rtti')
Patrick Rohr92d74122022-10-21 15:50:52 -0700357
358 target_out = []
Patrick Rohr09ee70e2022-11-16 15:20:03 -0800359 for arch, target in sorted(self.target.items()):
Patrick Rohrbfdc5fd2022-11-16 10:03:49 -0800360 # _output_field calls getattr(self, arch).
361 setattr(self, arch, target)
362 self._output_field(target_out, arch)
363
Patrick Rohr92d74122022-10-21 15:50:52 -0700364 if target_out:
365 output.append(' target: {')
366 for line in target_out:
367 output.append(' %s' % line)
368 output.append(' },')
369
Patrick Rohr92d74122022-10-21 15:50:52 -0700370 output.append('}')
371 output.append('')
372
373 def add_android_static_lib(self, lib):
374 if self.type == 'cc_binary_host':
375 raise Exception('Adding Android static lib for host tool is unsupported')
376 elif self.host_supported:
Patrick Rohrbfdc5fd2022-11-16 10:03:49 -0800377 self.target['android'].static_libs.add(lib)
Patrick Rohr92d74122022-10-21 15:50:52 -0700378 else:
379 self.static_libs.add(lib)
380
381 def add_android_shared_lib(self, lib):
382 if self.type == 'cc_binary_host':
383 raise Exception('Adding Android shared lib for host tool is unsupported')
384 elif self.host_supported:
Patrick Rohrbfdc5fd2022-11-16 10:03:49 -0800385 self.target['android'].shared_libs.add(lib)
Patrick Rohr92d74122022-10-21 15:50:52 -0700386 else:
387 self.shared_libs.add(lib)
388
389 def _output_field(self, output, name, sort=True):
390 value = getattr(self, name)
391 return write_blueprint_key_value(output, name, value, sort)
392
Patrick Rohra6ce0232022-11-16 22:09:01 -0800393 def is_compiled(self):
Mohannad Farragf2391cc2022-11-29 13:26:32 +0000394 return self.type not in ('cc_genrule', 'filegroup', 'cc_defaults')
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000395
396 def is_genrule(self):
397 return self.type == "cc_genrule"
Patrick Rohra6ce0232022-11-16 22:09:01 -0800398
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000399 def has_input_files(self):
400 for target in self.target.values():
401 if len(target.srcs) > 0:
402 return True
403 return len(self.srcs) > 0 or any([len(target.srcs) > 0 for target in self.target.values()])
404
Mohannad Farragf2391cc2022-11-29 13:26:32 +0000405 def merge_attribute(self, key, source_module, allowed_archs, source_key = None):
406 """
407 Merges the value of the attribute `source_key` for the `dep_module` with
408 the value of the attribute `key` for this module. If the value of the
409 `source_key` is equal to None. Then `key` is used for both modules.
410
411 This merges the attribute for both non-arch and archs
412 specified in `allowed_archs`.
413 :param key: The attribute used for merging in the calling module. Also
414 used for `dep_module` if the `source_key` is None.
415 :param source_module: The module where data is propagated from.
416 :param allowed_archs: A list of archs to merge the attribute on.
417 :param source_key: if the attribute merged from the `dep_module`
418 is different from the `key`
419 """
420 if not source_key:
421 source_key = key
422 self.__dict__[key].update(source_module.__dict__[source_key])
423 for arch_name in source_module.target.keys():
424 if arch_name in allowed_archs:
425 self.target[arch_name].__dict__[key].update(
426 source_module.target[arch_name].__dict__[source_key])
Patrick Rohr92d74122022-10-21 15:50:52 -0700427
428class Blueprint(object):
429 """In-memory representation of an Android.bp file."""
430
431 def __init__(self):
432 self.modules = {}
433
434 def add_module(self, module):
435 """Adds a new module to the blueprint, replacing any existing module
436 with the same name.
437
438 Args:
439 module: Module instance.
440 """
441 self.modules[module.name] = module
442
443 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700444 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700445 m.to_string(output)
446
447
448def label_to_module_name(label):
449 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
Patrick Rohr07876662022-11-15 22:55:23 -0800450 module = re.sub(r'^//:?', '', label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700451 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
Motomu Utsumi3fde1482022-11-14 15:55:21 +0900452
Patrick Rohr92d74122022-10-21 15:50:52 -0700453 if not module.startswith(module_prefix):
454 return module_prefix + module
455 return module
456
457
458def is_supported_source_file(name):
459 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrf9f3a992022-11-10 19:40:32 -0800460 return os.path.splitext(name)[1] in ['.c', '.cc', '.cpp', '.java', '.proto', '.S']
Patrick Rohr92d74122022-10-21 15:50:52 -0700461
462
463def create_proto_modules(blueprint, gn, target):
464 """Generate genrules for a proto GN target.
465
466 GN actions are used to dynamically generate files during the build. The
467 Soong equivalent is a genrule. This function turns a specific kind of
468 genrule which turns .proto files into source and header files into a pair
469 equivalent genrules.
470
471 Args:
472 blueprint: Blueprint instance which is being generated.
473 target: gn_utils.Target object.
474
475 Returns:
476 The source_genrule module.
477 """
478 assert (target.type == 'proto_library')
479
Motomu Utsumibd4013f2022-11-17 16:06:05 +0900480 protoc_gn_target_name = gn.get_target('//third_party/protobuf:protoc').name
Motomu Utsumid58c1dc2022-11-16 18:04:46 +0900481 protoc_module_name = label_to_module_name(protoc_gn_target_name)
482 tools = {protoc_module_name}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900483 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700484 target_module_name = label_to_module_name(target.name)
485
486 # In GN builds the proto path is always relative to the output directory
487 # (out/tmp.xxx).
Motomu Utsumid58c1dc2022-11-16 18:04:46 +0900488 cmd = ['$(location %s)' % protoc_module_name]
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900489 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700490
491 if buildtools_protobuf_src in target.proto_paths:
492 cmd += ['--proto_path=%s' % android_protobuf_src]
493
494 # We don't generate any targets for source_set proto modules because
495 # they will be inlined into other modules if required.
496 if target.proto_plugin == 'source_set':
497 return None
498
499 # Descriptor targets only generate a single target.
500 if target.proto_plugin == 'descriptor':
501 out = '{}.bin'.format(target_module_name)
502
503 cmd += ['--descriptor_set_out=$(out)']
504 cmd += ['$(in)']
505
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000506 descriptor_module = Module('cc_genrule', target_module_name, target.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700507 descriptor_module.cmd = ' '.join(cmd)
508 descriptor_module.out = [out]
509 descriptor_module.tools = tools
510 blueprint.add_module(descriptor_module)
511
512 # Recursively extract the .proto files of all the dependencies and
513 # add them to srcs.
514 descriptor_module.srcs.update(
515 gn_utils.label_to_path(src) for src in target.sources)
516 for dep in target.transitive_proto_deps:
517 current_target = gn.get_target(dep)
518 descriptor_module.srcs.update(
519 gn_utils.label_to_path(src) for src in current_target.sources)
520
521 return descriptor_module
522
523 # We create two genrules for each proto target: one for the headers and
524 # another for the sources. This is because the module that depends on the
525 # generated files needs to declare two different types of dependencies --
526 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
527 # valid to generate .h files from a source dependency and vice versa.
528 source_module_name = target_module_name + '_gen'
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000529 source_module = Module('cc_genrule', source_module_name, target.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700530 blueprint.add_module(source_module)
531 source_module.srcs.update(
532 gn_utils.label_to_path(src) for src in target.sources)
533
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000534 header_module = Module('cc_genrule', source_module_name + '_headers',
Patrick Rohr92d74122022-10-21 15:50:52 -0700535 target.name)
536 blueprint.add_module(header_module)
537 header_module.srcs = set(source_module.srcs)
538
539 # TODO(primiano): at some point we should remove this. This was introduced
540 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
541 # avoid doing multi-repo changes and allow old clients in the android tree
542 # to still do the old #include "perfetto/..." rather than
543 # #include "protos/perfetto/...".
544 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800545 # Since the .cc file and .h get created by a different gerule target, they
546 # are not put in the same intermediate path, so local includes do not work
547 # without explictily exporting the include dir.
548 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700549
550 source_module.genrule_srcs.add(':' + source_module.name)
551 source_module.genrule_headers.add(header_module.name)
552
553 if target.proto_plugin == 'proto':
554 suffixes = ['pb']
555 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
556 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
557 elif target.proto_plugin == 'protozero':
558 suffixes = ['pbzero']
559 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
560 tools.add(plugin.name)
561 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
562 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
563 elif target.proto_plugin == 'cppgen':
564 suffixes = ['gen']
565 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
566 tools.add(plugin.name)
567 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
568 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
569 elif target.proto_plugin == 'ipc':
570 suffixes = ['ipc']
571 plugin = create_modules_from_target(blueprint, gn, ipc_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 else:
576 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
577
578 cmd += ['$(in)']
579 source_module.cmd = ' '.join(cmd)
580 header_module.cmd = source_module.cmd
581 source_module.tools = tools
582 header_module.tools = tools
583
584 for sfx in suffixes:
585 source_module.out.update('%s/%s' %
586 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
587 for src in source_module.srcs)
588 header_module.out.update('%s/%s' %
589 (tree_path, src.replace('.proto', '.%s.h' % sfx))
590 for src in header_module.srcs)
591 return source_module
592
593
Patrick Rohr92d74122022-10-21 15:50:52 -0700594def create_proto_group_modules(blueprint, gn, module_name, target_names):
595 # TODO(lalitm): today, we're only adding a Java lite module because that's
596 # the only one used in practice. In the future, if we need other target types
597 # (e.g. C++, Java full etc.) add them here.
598 bp_module_name = label_to_module_name(module_name) + '_java_protos'
599 module = Module('java_library', bp_module_name, bp_module_name)
600 module.comment = f'''GN: [{', '.join(target_names)}]'''
601 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
602
603 for name in target_names:
604 target = gn.get_target(name)
605 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
606 for dep_label in target.transitive_proto_deps:
607 dep = gn.get_target(dep_label)
608 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
609
610 blueprint.add_module(module)
611
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800612
613class ActionSanitizer():
614 def __init__(self, target):
Patrick Rohr9e414b52022-11-29 22:12:18 -0800615 # Just to be on the safe side, create a deep-copy.
616 self.target = copy.deepcopy(target)
617 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
618 self.target.args = [str for it in target.args for str in it.split('=')]
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800619
620 def _has_arg(self, arg):
621 return arg in self.target.args
622
Patrick Rohr3a2c3dd2022-11-29 22:29:36 -0800623 # Whether an arg has multiple occurences (see argparse action='append')
624 def _is_append_arg(self, arg):
625 return operator.countOf(arg, self.target.args) > 1
626
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800627 def _has_arg_value(self, arg):
Patrick Rohr3a2c3dd2022-11-29 22:29:36 -0800628 # TODO: we'll probably need a set of helper functions to deal with append
629 # args as well.
630 assert(not self._is_append_arg(arg))
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800631 i = self.target.args.index(arg)
632 return not self.target.args[i + 1].startswith('--')
633
634 def _get_arg_value(self, arg):
Patrick Rohr3a2c3dd2022-11-29 22:29:36 -0800635 assert(self._has_arg_value(arg))
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800636 i = self.target.args.index(arg)
637 return self.target.args[i + 1]
638
639 def _set_arg_value(self, arg, value):
640 assert(self._has_arg_value(arg))
641 i = self.target.args.index(arg)
642 self.target.args[i + 1] = value
643
644 def _delete_arg(self, arg):
Patrick Rohr3a2c3dd2022-11-29 22:29:36 -0800645 assert(not self._is_append_arg(arg))
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800646 hasValue = self._has_arg_value(arg)
647 i = self.target.index(arg)
648 self.target.args.pop(i)
649 if hasValue:
650 self.target.args.pop(i)
651
Patrick Rohr73ef7ae2022-11-29 22:33:09 -0800652 # wrap filename in location tag.
653 def _location_tag(self, filename):
654 return '$(location %s)' % filename
655
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800656 def get_args(self):
Patrick Rohr48fa74d2022-11-29 22:15:29 -0800657 if self.target.script == "//build/write_buildflag_header.py":
658 # write_buildflag_header.py writes result to args.genDir/args.output
659 # So, override args.genDir by '.' so that args.output=$(out) works
660 self._set_arg_value('--gen-dir', '.')
661 self._set_arg_value('--output', '$(out)')
662
Patrick Rohr9e414b52022-11-29 22:12:18 -0800663 return self.target.args
Patrick Rohrf6de33f2022-11-29 22:02:55 -0800664
665
Mohannad Farragbab6c892022-11-02 14:09:46 +0000666def create_action_foreach_modules(blueprint, target):
667 """ The following assumes that rebase_path exists in the args.
668 The args of an action_foreach contains hints about which output files are generated
669 by which source files.
670 This is copied directly from the args
671 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
672 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
673 """
674 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900675 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000676 # don't add script arg for the first source -- create_action_module
677 # already does this.
678 if i != 0:
679 new_args.append('&& python3 $(location %s)' %
680 gn_utils.label_to_path(target.script))
681 for arg in target.args:
682 if '{{source}}' in arg:
683 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
684 elif '{{source_name_part}}' in arg:
685 source_name_part = src.split("/")[-1] # Get the file name only
686 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
687 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
688 # file_name represent the output file name. But we need the whole path
689 # This can be found from target.outputs.
690 for out in target.outputs:
691 if out.endswith(file_name):
692 new_args.append('$(location %s)' % out)
693 else:
694 new_args.append(arg)
695
696 target.args = new_args
697 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900698
Patrick Rohr7be99032022-10-31 11:54:19 -0700699def create_action_module(blueprint, target):
700 bp_module_name = label_to_module_name(target.name)
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000701 module = Module('cc_genrule', bp_module_name, target.name)
Patrick Rohr7be99032022-10-31 11:54:19 -0700702
Patrick Rohr9e414b52022-11-29 22:12:18 -0800703 sanitizer = ActionSanitizer(target)
704 target.args = sanitizer.get_args()
Patrick Rohr9b99a982022-10-28 11:00:57 -0700705
Patrick Rohr48fa74d2022-11-29 22:15:29 -0800706 if target.script == '//build/write_build_date_header.py':
Patrick Rohrfa972402022-11-01 11:54:35 -0700707 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700708
Patrick Rohr8acccca2022-10-28 10:39:06 -0700709 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohr131ba282022-10-31 16:36:20 -0700710 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700711 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900712 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700713 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
714 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700715 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700716 # --input_file supports both .class specifiers or source files as arguments.
717 # Only source files need to be wrapped inside a $(location <label>) tag.
718 if re.match('.*\.class$', target.args[i + 1]):
719 continue
720 # replace --input_file ../../... with --input_file $(location ...)
721 # TODO: put inside function
722 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
723 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700724 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700725 # delete all leading ../
726 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700727 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700728 # this is not needed for aosp builds.
729 target.args[i] = ''
730 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700731 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700732 # delete leading ../../ and add path to javap
733 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
734 target.args[i + 1] = '$(location %s)' % filename
735 needs_javap = True
736
737 if needs_javap:
738 target.args.append('--javap')
739 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700740 # fix target.output directory to match #include statements.
741 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700742
Patrick Rohrf6d2b612022-11-09 12:30:26 -0800743 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
744 # jni_registration_generator.py pulls in some config dependencies that we
745 # do not handle. Remove them.
746 # TODO: find a better way to do this.
747 target.deps.clear()
748
Motomu Utsumied009082022-11-10 16:26:44 +0900749 target.inputs = [file for file in target.inputs if not file.startswith('//out/')]
Motomu Utsumi6b4acaa2022-11-10 16:13:24 +0900750 for i, val in enumerate(target.args):
751 if val in ['--depfile', '--srcjar-path', '--header-path']:
752 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900753 if val == '--sources-files':
754 target.args[i + 1] = '$(genDir)/java.sources'
Motomu Utsumi47d122f2022-11-10 17:32:23 +0900755 elif val == '--sources-exclusions':
756 # update_jni_registration_module removes them from the srcs of the module
757 # It might be better to remove sources by '--sources-exclusions'
758 target.args[i] = ''
759 target.args[i + 1] = ''
Motomu Utsumia0cc6662022-11-09 15:22:27 +0900760 elif target.script == "//net/tools/dafsa/make_dafsa.py":
761 # This script generates .cc files but source (registry_controlled_domain.cc) in the target that
762 # depends on this target includes .cc file this script generates.
763 module.genrule_headers.add(module.name)
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900764 elif target.script == "//build/util/version.py":
Motomu Utsumib0a49e42022-11-09 18:12:27 +0900765 # android_chrome_version.py is not specified in anywhere but version.py imports this file
766 module.tool_files.add('build/util/android_chrome_version.py')
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900767 for i, val in enumerate(target.args):
768 if val.startswith('../../'):
769 filename = re.sub('^\.\./\.\./', '', val)
770 target.args[i] = '$(location %s)' % filename
Motomu Utsumiee279c52022-11-09 17:46:27 +0900771 elif val == '-e':
772 # arg for -e EVAL option should be passed in -e PATCH_HI=int(PATCH)//256 format.
773 target.args[i + 1] = '%s=\'%s\'' % (target.args[i + 1], target.args[i + 2])
774 target.args[i + 2] = ''
Motomu Utsumi438f2c22022-11-09 18:16:40 +0900775 elif val == '-o':
776 target.args[i + 1] = '$(out)'
Patrick Rohr245df582022-11-01 16:59:45 -0700777
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700778 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700779 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700780
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700781 # Handle passing parameters via response file by piping them into the script
782 # and reading them from /dev/stdin.
783 response_file = '{{response_file_name}}'
784 use_response_file = response_file in target.args
785 if use_response_file:
786 # Replace {{response_file_contents}} with /dev/stdin
787 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
788
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700789 # escape " and \$ in target.args.
790 # once all actions are properly implemented, this may not be necessary anymore.
791 # TODO: is this the right place to do this?
792 target.args = [arg.replace('"', r'\"') for arg in target.args]
793 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
794
Patrick Rohr9b99a982022-10-28 11:00:57 -0700795 # put all args on a new line for better diffs.
796 NEWLINE = ' " +\n "'
797 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700798 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700799
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700800 if use_response_file:
801 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700802 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700803
Motomu Utsumi7e983832022-11-10 16:04:46 +0900804 if any(os.path.splitext(it)[1] == '.h' for it in target.outputs):
Patrick Rohr67f4d432022-10-26 16:04:15 -0700805 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700806
Patrick Rohr0db9f852022-10-27 13:49:57 -0700807 # gn treats inputs and sources for actions equally.
808 # soong only supports source files inside srcs, non-source files are added as
809 # tool_files dependency.
810 for it in target.sources or target.inputs:
811 if is_supported_source_file(it):
812 module.srcs.add(gn_utils.label_to_path(it))
813 else:
814 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700815
Patrick Rohr15a2c302022-10-26 15:08:57 -0700816 # Actions using template "action_with_pydeps" also put script inside inputs.
817 # TODO: it might make sense to filter inputs inside GnParser.
818 if script in module.srcs:
819 module.srcs.remove(script)
820
Patrick Rohre1a853e2022-10-26 12:31:39 -0700821 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900822
Motomu Utsumi4b35a322022-11-25 11:55:37 +0900823 if target.script == "//base/android/jni_generator/jni_generator.py":
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000824 # android_jar.classes should be part of the tools as it list implicit classes
825 # for the script to generate JNI headers.
826 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900827 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
Motomu Utsumi9ca466b2022-11-10 17:12:29 +0900828 # jni_registration_generator.py doesn't work with python2
829 module.cmd = "python3 " + module.cmd
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900830 # Path in the original sources file does not work in genrule.
831 # So creating sources file in cmd based on the srcs of this target.
832 # Adding ../$(current_dir)/ to the head because jni_registration_generator.py uses the files
833 # whose path startswith(..)
834 commands = ["current_dir=`basename \\\`pwd\\\``;",
835 "for f in $(in);",
836 "do",
837 "echo \\\"../$$current_dir/$$f\\\" >> $(genDir)/java.sources;",
838 "done;",
839 module.cmd]
Motomu Utsumi2a892d22022-11-10 18:03:20 +0900840
841 # .h file jni_registration_generator.py generates has #define with directory name.
842 # With the genrule env that contains "." which is invalid. So replace that at the end of cmd.
Mohannad Farrag7c0f0982022-11-10 14:39:49 +0000843 commands.append(";sed -i -e 's/OUT_SOONG_.TEMP_SBOX_.*_OUT/GEN/g' ")
Motomu Utsumi2a892d22022-11-10 18:03:20 +0900844 commands.append("$(genDir)/components/cronet/android/cronet_jni_registration.h")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900845 module.cmd = NEWLINE.join(commands)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900846
Patrick Rohre1a853e2022-10-26 12:31:39 -0700847 blueprint.add_module(module)
848 return module
849
850
Patrick Rohr92d74122022-10-21 15:50:52 -0700851
Motomu Utsumic34b1372022-11-17 22:15:51 +0900852def _get_cflags(cflags, defines):
853 cflags = {flag for flag in cflags if flag in cflag_allowlist}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900854 # Consider proper allowlist or denylist if needed
Motomu Utsumic34b1372022-11-17 22:15:51 +0900855 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700856 return cflags
857
Motomu Utsumic34b1372022-11-17 22:15:51 +0900858def set_module_flags(module, cflags, defines):
859 module.cflags.update(_get_cflags(cflags, defines))
860 # TODO: implement proper cflag parsing.
861 for flag in cflags:
862 if '-std=' in flag:
863 module.cpp_std = flag[len('-std='):]
Motomu Utsumic34b1372022-11-17 22:15:51 +0900864 if '-fexceptions' in flag:
865 module.cppflags.add('-fexceptions')
Patrick Rohr92d74122022-10-21 15:50:52 -0700866
Mohannad Farrag631443e2022-11-21 16:17:01 +0000867def add_genrule_per_arch(module, dep_module, type):
868 module.generated_headers.update(dep_module.genrule_headers)
869 # If the module is a static library, export all the generated headers.
870 if type == 'cc_library_static':
871 module.export_generated_headers.update(dep_module.genrule_headers)
872 module.srcs.update(dep_module.genrule_srcs)
873 module.shared_libs.update(dep_module.genrule_shared_libs)
874 module.header_libs.update(dep_module.genrule_header_libs)
875
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900876def set_module_include_dirs(module, cflags, include_dirs):
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900877 for flag in cflags:
878 if '-isystem' in flag:
Patrick Rohr3cd5ffb2022-11-18 17:40:55 -0800879 module.local_include_dirs.add(flag[len('-isystem../../'):])
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900880
881 # Adding local_include_dirs is necessary due to source_sets / filegroups
882 # which do not properly propagate include directories.
883 # Filter any directory inside //out as a) this directory does not exist for
884 # aosp / soong builds and b) the include directory should already be
885 # configured via library dependency.
Patrick Rohr3cd5ffb2022-11-18 17:40:55 -0800886 module.local_include_dirs.update([gn_utils.label_to_path(d)
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900887 for d in include_dirs
888 if not re.match('^//out/.*', d)])
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900889
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900890
Patrick Rohr92d74122022-10-21 15:50:52 -0700891def create_modules_from_target(blueprint, gn, gn_target_name):
892 """Generate module(s) for a given GN target.
893
894 Given a GN target name, generate one or more corresponding modules into a
895 blueprint. The only case when this generates >1 module is proto libraries.
896
897 Args:
898 blueprint: Blueprint instance which is being generated.
899 gn: gn_utils.GnParser object.
900 gn_target_name: GN target for module generation.
901 """
902 bp_module_name = label_to_module_name(gn_target_name)
903 if bp_module_name in blueprint.modules:
904 return blueprint.modules[bp_module_name]
905 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -0700906 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -0700907
Patrick Rohr92d74122022-10-21 15:50:52 -0700908 if target.type == 'executable':
Patrick Rohrc8f41cd2022-11-15 22:46:10 -0800909 if target.testonly:
Patrick Rohr92d74122022-10-21 15:50:52 -0700910 module_type = 'cc_test'
911 else:
Patrick Rohrc8f41cd2022-11-15 22:46:10 -0800912 # Can be used for both host and device targets.
Patrick Rohr92d74122022-10-21 15:50:52 -0700913 module_type = 'cc_binary'
914 module = Module(module_type, bp_module_name, gn_target_name)
915 elif target.type == 'static_library':
916 module = Module('cc_library_static', bp_module_name, gn_target_name)
917 elif target.type == 'shared_library':
918 module = Module('cc_library_shared', bp_module_name, gn_target_name)
919 elif target.type == 'source_set':
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000920 module = Module('cc_object', bp_module_name, gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700921 elif target.type == 'group':
922 # "group" targets are resolved recursively by gn_utils.get_target().
923 # There's nothing we need to do at this level for them.
924 return None
925 elif target.type == 'proto_library':
926 module = create_proto_modules(blueprint, gn, target)
927 if module is None:
928 return None
929 elif target.type == 'action':
Motomu Utsumi7f765cf2022-11-25 13:42:42 +0900930 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +0000931 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +0000932 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -0700933 elif target.type == 'copy':
934 # TODO: careful now! copy targets are not supported yet, but this will stop
935 # traversing the dependency tree. For //base:base, this is not a big
936 # problem as libicu contains the only copy target which happens to be a
937 # leaf node.
938 return None
Patrick Rohrad440602022-11-10 22:09:04 -0800939 elif target.type == 'java_group':
940 # Java targets are handled outside of create_modules_from_target.
941 return None
Patrick Rohr92d74122022-10-21 15:50:52 -0700942 else:
943 raise Error('Unknown target %s (%s)' % (target.name, target.type))
944
945 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -0700946 module.init_rc = target_initrc.get(target.name, [])
947 module.srcs.update(
948 gn_utils.label_to_path(src)
949 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +0900950 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -0700951
Patrick Rohr3b5ff762022-11-16 10:22:16 -0800952 # Add arch-specific properties
953 for arch_name, arch in target.arch.items():
Motomu Utsumi40f95c52022-11-17 19:39:13 +0900954 module.target[arch_name].srcs.update(
955 gn_utils.label_to_path(src)
956 for src in arch.sources
957 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr3b5ff762022-11-16 10:22:16 -0800958
Mohannad Farragbaf0d572022-11-22 11:53:54 +0000959 module.rtti = target.rtti
960
Patrick Rohr92d74122022-10-21 15:50:52 -0700961 if target.type in gn_utils.LINKER_UNIT_TYPES:
Motomu Utsumic34b1372022-11-17 22:15:51 +0900962 set_module_flags(module, target.cflags, target.defines)
Motomu Utsumi88efbb42022-11-17 22:18:15 +0900963 set_module_include_dirs(module, target.cflags, target.include_dirs)
Motomu Utsumif0f47682022-11-17 22:34:39 +0900964 # TODO: set_module_xxx is confusing, apply similar function to module and target in better way.
965 for arch_name, arch in target.arch.items():
966 set_module_flags(module.target[arch_name], arch.cflags, arch.defines)
Motomu Utsumi3371d682022-11-28 16:56:52 +0900967 # -Xclang -target-feature -Xclang +mte are used to enable MTE (Memory Tagging Extensions).
968 # Flags which does not start with '-' could not be in the cflags so enabling MTE by
969 # -march and -mcpu Feature Modifiers. MTE is only available on arm64. This is needed for
970 # building //base/allocator/partition_allocator:partition_alloc for arm64.
971 if '+mte' in arch.cflags and arch_name == 'android_arm64':
972 module.target[arch_name].cflags.add('-march=armv8-a+memtag')
Motomu Utsumif0f47682022-11-17 22:34:39 +0900973 set_module_include_dirs(module.target[arch_name], arch.cflags, arch.include_dirs)
Patrick Rohr92d74122022-10-21 15:50:52 -0700974
Mohannad Farragf2391cc2022-11-29 13:26:32 +0000975 module.host_supported = target.host_supported()
976 module.device_supported = target.device_supported()
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000977
Mohannad Farragf2391cc2022-11-29 13:26:32 +0000978 if module.is_compiled():
Patrick Rohr92d74122022-10-21 15:50:52 -0700979 # Don't try to inject library/source dependencies into genrules or
980 # filegroups because they are not compiled in the traditional sense.
981 module.defaults = [defaults_module]
982 for lib in target.libs:
983 # Generally library names should be mangled as 'libXXX', unless they
984 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
985 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
986 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
987 else 'lib' + lib
988 if lib in shared_library_allowlist:
989 module.add_android_shared_lib(android_lib)
990 if lib in static_library_allowlist:
991 module.add_android_static_lib(android_lib)
992
Patrick Rohrd9dd3b92022-11-09 16:15:30 -0800993 # Remove prohibited include directories
994 module.local_include_dirs = [d for d in module.local_include_dirs
995 if d not in local_include_dirs_denylist]
996
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000997 # If the module is a static library, export all the generated headers.
998 if module.type == 'cc_library_static':
999 module.export_generated_headers = module.generated_headers
1000
Patrick Rohr92d74122022-10-21 15:50:52 -07001001 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001002 # Currently, only one module is generated from target even target has multiple toolchains.
1003 # And module is generated based on the first visited target.
1004 # Sort deps before iteration to make result deterministic.
1005 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001006 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001007 # |builtin_deps| override GN deps with Android-specific ones. See the
1008 # config in the top of this file.
Patrick Rohr07876662022-11-15 22:55:23 -08001009 if dep_name in builtin_deps:
1010 builtin_deps[dep_name](module)
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001011 continue
1012
Patrick Rohr92d74122022-10-21 15:50:52 -07001013 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1014
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001015 if dep_module is None:
1016 continue
Motomu Utsumie246feb2022-11-01 17:25:56 +09001017 # TODO: Proper dependency check for genrule.
1018 # Currently, only propagating genrule dependencies.
1019 # Also, currently, all the dependencies are propagated upwards.
1020 # in gn, public_deps should be propagated but deps should not.
1021 # Not sure this information is available in the desc.json.
1022 # Following rule works for adding android_runtime_jni_headers to base:base.
1023 # If this doesn't work for other target, hardcoding for specific target
1024 # might be better.
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001025 if module.is_genrule() and dep_module.is_genrule():
1026 module.genrule_headers.add(dep_module.name)
1027 module.genrule_headers.update(dep_module.genrule_headers)
Motomu Utsumie246feb2022-11-01 17:25:56 +09001028
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001029 # For filegroups, and genrule, recurse but don't apply the
Patrick Rohra6ce0232022-11-16 22:09:01 -08001030 # deps.
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001031 if not module.is_compiled() or module.is_genrule():
Patrick Rohr92d74122022-10-21 15:50:52 -07001032 continue
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001033
Patrick Rohr92d74122022-10-21 15:50:52 -07001034 if dep_module.type == 'cc_library_shared':
1035 module.shared_libs.add(dep_module.name)
1036 elif dep_module.type == 'cc_library_static':
1037 module.static_libs.add(dep_module.name)
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001038 elif dep_module.type == 'cc_object':
Mohannad Farragf2391cc2022-11-29 13:26:32 +00001039 module.merge_attribute('generated_headers', dep_module, target.arch.keys())
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001040 if module.type != 'cc_object':
1041 if dep_module.has_input_files():
1042 # Only add it as part of srcs if the dep_module has input files otherwise
1043 # this would throw an error.
1044 module.srcs.add(":" + dep_module.name)
Mohannad Farragf2391cc2022-11-29 13:26:32 +00001045 module.merge_attribute('export_generated_headers', dep_module,
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001046 target.arch.keys(), 'generated_headers')
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001047 elif dep_module.type == 'cc_genrule':
Mohannad Farragf2391cc2022-11-29 13:26:32 +00001048 module.merge_attribute('generated_headers', dep_module, [], 'genrule_headers')
1049 module.merge_attribute('srcs', dep_module, [], 'genrule_srcs')
1050 module.merge_attribute('shared_libs', dep_module, [], 'genrule_shared_libs')
1051 module.merge_attribute('header_libs', dep_module, [], 'genrule_header_libs')
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001052 if module.type not in ["cc_object"]:
Mohannad Farragf2391cc2022-11-29 13:26:32 +00001053 module.merge_attribute('export_generated_headers', dep_module, [],
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001054 'genrule_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -07001055 elif dep_module.type == 'cc_binary':
1056 continue # Ignore executables deps (used by cmdline integration tests).
1057 else:
1058 raise Error('Unknown dep %s (%s) for target %s' %
1059 (dep_module.name, dep_module.type, module.name))
1060
Patrick Rohrb51878f2022-11-16 23:49:03 -08001061 for arch_name, arch in target.arch.items():
1062 for dep_name in arch.deps:
1063 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1064 # Arch-specific dependencies currently only include cc_library_static.
1065 # Revisit this approach once we need to support more target types.
1066 if dep_module.type == 'cc_library_static':
1067 module.target[arch_name].static_libs.add(dep_module.name)
Mohannad Farrag1de6cb12022-11-28 12:27:26 +00001068 elif dep_module.type == 'cc_genrule':
1069 if dep_module.name.endswith(arch_name):
1070 module.target[arch_name].generated_headers.update(dep_module.genrule_headers)
1071 module.target[arch_name].srcs.update(dep_module.genrule_srcs)
1072 module.target[arch_name].shared_libs.update(dep_module.genrule_shared_libs)
1073 module.target[arch_name].header_libs.update(dep_module.genrule_header_libs)
1074 if module.type not in ["cc_object"]:
1075 module.target[arch_name].export_generated_headers.update(
1076 dep_module.genrule_headers)
Patrick Rohrb51878f2022-11-16 23:49:03 -08001077 else:
1078 raise Error('Unsupported arch-specific dependency %s of target %s with type %s' %
1079 (dep_module.name, target.name, dep_module.type))
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001080 for dep_name in arch.source_set_deps:
1081 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1082 if dep_module.type == 'cc_object':
1083 if module.type != 'cc_object':
1084 # We only want to bubble up cc_objects for modules that are not cc_objects
1085 # otherwise they'd be recompiled and that would cause multiple symbol redefinitions.
1086 if dep_module.has_input_files():
1087 # Only add it as part of srcs if the dep_module has input files otherwise
1088 # this would throw an error.
1089 module.target[arch_name].srcs.add(":" + dep_module.name)
1090 else:
1091 raise Error('Unsupported arch-specific dependency %s of target %s with type %s' %
1092 (dep_module.name, target.name, dep_module.type))
Patrick Rohr92d74122022-10-21 15:50:52 -07001093 return module
1094
Patrick Rohrb18aca22022-11-04 15:07:32 -07001095def create_java_module(blueprint, gn):
1096 bp_module_name = module_prefix + 'java'
1097 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001098 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001099 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001100
Patrick Rohr6ef22722022-11-18 18:24:01 -08001101def update_jni_registration_module(module, gn):
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001102 # TODO: deny list is in the arg of jni_registration_generator.py. Should not be hardcoded
1103 deny_list = [
1104 '//base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java',
1105 '//base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java',
1106 '//base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java',
1107 '//base/android/java/src/org/chromium/base/SysUtils.java']
1108
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001109 # TODO: java_sources might not contain all the required java files
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001110 module.srcs.update([gn_utils.label_to_path(source)
1111 for source in gn.java_sources if source not in deny_list])
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001112
Motomu Utsumia71281c2022-11-18 15:19:00 +09001113def create_blueprint_for_targets(gn, targets):
Patrick Rohr92d74122022-10-21 15:50:52 -07001114 """Generate a blueprint for a list of GN targets."""
1115 blueprint = Blueprint()
1116
1117 # Default settings used by all modules.
1118 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001119 defaults.cflags = [
Patrick Rohr3ce74772022-11-11 14:19:58 -08001120 '-DGOOGLE_PROTOBUF_NO_RTTI',
Patrick Rohr92d74122022-10-21 15:50:52 -07001121 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001122 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001123 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001124 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001125 '-Wno-sign-compare',
1126 '-Wno-sign-promo',
1127 '-Wno-unused-parameter',
Mohannad Farrag54d52442022-11-21 16:27:02 +00001128 '-Wno-null-pointer-subtraction', # Needed to libevent
Mohannad Farragd98a96d2022-11-10 14:56:19 +00001129 '-Wno-deprecated-non-prototype', # needed for zlib
Patrick Rohr92d74122022-10-21 15:50:52 -07001130 '-fvisibility=hidden',
Motomu Utsumiba020942022-11-14 15:15:41 +09001131 '-Wno-ambiguous-reversed-operator', # needed for icui18n
Motomu Utsumib1ec8782022-11-14 15:25:57 +09001132 '-Wno-unreachable-code-loop-increment', # needed for icui18n
Patrick Rohr92d74122022-10-21 15:50:52 -07001133 '-O2',
Mohannad Farrag7f29d832022-11-23 19:52:41 +00001134 '-fPIC',
Patrick Rohr92d74122022-10-21 15:50:52 -07001135 ]
Patrick Rohrc03f1bb2022-11-18 16:13:17 -08001136 # Chromium builds do not add a dependency for headers found inside the
1137 # sysroot, so they are added globally via defaults.
1138 defaults.target['android'].header_libs = [
1139 'media_ndk_headers',
1140 'jni_headers',
1141 ]
Patrick Rohr5446df82022-11-18 14:54:55 -08001142 defaults.target['host'].cflags = [
1143 # -DANDROID is added by default but target.defines contain -DANDROID if
1144 # it's required. So adding -UANDROID to cancel default -DANDROID if it's
1145 # not specified.
1146 # Note: -DANDROID is not consistently applied across the chromium code
1147 # base, so it is removed unconditionally for host targets.
1148 '-UANDROID',
1149 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001150 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001151 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001152
Patrick Rohr92d74122022-10-21 15:50:52 -07001153 for target in targets:
1154 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001155
1156 create_java_module(blueprint, gn)
Patrick Rohr6ef22722022-11-18 18:24:01 -08001157 for module in blueprint.modules.values():
1158 if 'cronet_jni_registration' in module.name:
1159 update_jni_registration_module(module, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001160
1161 # Merge in additional hardcoded arguments.
1162 for module in blueprint.modules.values():
1163 for key, add_val in additional_args.get(module.name, []):
1164 curr = getattr(module, key)
1165 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1166 curr.update(add_val)
1167 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1168 setattr(module, key, add_val)
1169 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1170 setattr(module, key, add_val)
1171 elif isinstance(add_val, dict) and isinstance(curr, dict):
1172 curr.update(add_val)
1173 elif isinstance(add_val, dict) and isinstance(curr, Target):
1174 curr.__dict__.update(add_val)
1175 else:
1176 raise Error('Unimplemented type %r of additional_args: %r' %
1177 (type(add_val), key))
1178
Patrick Rohr92d74122022-10-21 15:50:52 -07001179 return blueprint
1180
1181
1182def main():
1183 parser = argparse.ArgumentParser(
1184 description='Generate Android.bp from a GN description.')
1185 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001186 '--desc',
Motomu Utsumi879dec82022-11-18 15:25:12 +09001187 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*".' +
1188 'You can specify multiple --desc options for different target_cpu',
1189 required=True,
1190 action='append'
Patrick Rohr92d74122022-10-21 15:50:52 -07001191 )
1192 parser.add_argument(
1193 '--extras',
1194 help='Extra targets to include at the end of the Blueprint file',
1195 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1196 )
1197 parser.add_argument(
1198 '--output',
1199 help='Blueprint file to create',
1200 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1201 )
1202 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001203 '-v',
1204 '--verbose',
1205 help='Print debug logs.',
1206 action='store_true',
1207 )
1208 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001209 'targets',
1210 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001211 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1212 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001213 args = parser.parse_args()
1214
Patrick Rohr16228942022-10-26 14:00:26 -07001215 if args.verbose:
1216 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1217
Patrick Rohrd0077b72022-11-15 12:43:26 -08001218 targets = args.targets or default_targets
Motomu Utsumi879dec82022-11-18 15:25:12 +09001219 gn = gn_utils.GnParser()
1220 for desc_file in args.desc:
1221 with open(desc_file) as f:
1222 desc = json.load(f)
1223 for target in targets:
1224 gn.parse_gn_desc(desc, target)
Motomu Utsumia71281c2022-11-18 15:19:00 +09001225 blueprint = create_blueprint_for_targets(gn, targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001226 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1227 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1228
Patrick Rohr92d74122022-10-21 15:50:52 -07001229 # Add any proto groups to the blueprint.
1230 for l_name, t_names in proto_groups.items():
1231 create_proto_group_modules(blueprint, gn, l_name, t_names)
1232
1233 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001234 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001235//
1236// Licensed under the Apache License, Version 2.0 (the "License");
1237// you may not use this file except in compliance with the License.
1238// You may obtain a copy of the License at
1239//
1240// http://www.apache.org/licenses/LICENSE-2.0
1241//
1242// Unless required by applicable law or agreed to in writing, software
1243// distributed under the License is distributed on an "AS IS" BASIS,
1244// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1245// See the License for the specific language governing permissions and
1246// limitations under the License.
1247//
1248// This file is automatically generated by %s. Do not edit.
1249""" % (tool_name)
1250 ]
1251 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001252 if os.path.exists(args.extras):
1253 with open(args.extras, 'r') as r:
1254 for line in r:
1255 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001256
1257 out_files = []
1258
1259 # Generate the Android.bp file.
1260 out_files.append(args.output + '.swp')
1261 with open(out_files[-1], 'w') as f:
1262 f.write('\n'.join(output))
1263 # Text files should have a trailing EOL.
1264 f.write('\n')
1265
Patrick Rohr94693eb2022-10-25 10:09:16 -07001266 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001267
1268
1269if __name__ == '__main__':
1270 sys.exit(main())