blob: 4fbcd720728380c84c57c7848aa559922114c185 [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
Motomu Utsumic6277d92022-11-07 15:15:17 +090035import copy
Patrick Rohr92d74122022-10-21 15:50:52 -070036
37import gn_utils
38
Patrick Rohr92d74122022-10-21 15:50:52 -070039ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
40
Patrick Rohr06296362022-11-10 21:37:33 -080041# Default targets to translate to the blueprint file.
42default_targets = [
43 '//components/cronet/android:cronet',
44]
45
Patrick Rohr92d74122022-10-21 15:50:52 -070046# Defines a custom init_rc argument to be applied to the corresponding output
47# blueprint target.
48target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070049 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070050}
51
52target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070053 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070054]
55
Patrick Rohr92d74122022-10-21 15:50:52 -070056# Proto target groups which will be made public.
57proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070058 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070059}
60
61# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070062module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070063
64# Shared libraries which are directly translated to Android system equivalents.
65shared_library_allowlist = [
66 'android',
67 'android.hardware.atrace@1.0',
68 'android.hardware.health@2.0',
69 'android.hardware.health-V1-ndk',
70 'android.hardware.power.stats@1.0',
71 "android.hardware.power.stats-V1-cpp",
72 'base',
73 'binder',
74 'binder_ndk',
75 'cutils',
76 'hidlbase',
77 'hidltransport',
78 'hwbinder',
79 'incident',
80 'log',
81 'services',
82 'statssocket',
83 "tracingproxy",
84 'utils',
85]
86
87# Static libraries which are directly translated to Android system equivalents.
88static_library_allowlist = [
89 'statslog_perfetto',
90]
91
Patrick Rohrd9dd3b92022-11-09 16:15:30 -080092# Include directories that will be removed from all targets.
93local_include_dirs_denylist = [
94 'third_party/protobuf/src/',
95]
96
Patrick Rohr92d74122022-10-21 15:50:52 -070097# Name of the module which settings such as compiler flags for all other
98# modules.
99defaults_module = module_prefix + 'defaults'
100
101# Location of the project in the Android source tree.
Patrick Rohr76ceeb52022-11-07 14:18:58 -0800102tree_path = 'external/chromium_org'
Patrick Rohr92d74122022-10-21 15:50:52 -0700103
104# Path for the protobuf sources in the standalone build.
105buildtools_protobuf_src = '//buildtools/protobuf/src'
106
107# Location of the protobuf src dir in the Android source tree.
108android_protobuf_src = 'external/protobuf/src'
109
110# Compiler flags which are passed through to the blueprint.
111cflag_allowlist = r'^-DPERFETTO.*$'
112
Patrick Rohr92d74122022-10-21 15:50:52 -0700113# Additional arguments to apply to Android.bp rules.
114additional_args = {
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800115 # TODO: remove if not needed.
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800116 'cronet_aml_net_net': [
Patrick Rohr9f4d3e32022-11-09 16:37:31 -0800117 ('export_static_lib_headers', {
118 'cronet_aml_net_third_party_quiche_quiche',
119 'cronet_aml_crypto_crypto',
120 }),
Mohannad Farrage7d29312022-11-10 17:39:16 +0000121 ('whole_static_libs', {
122 'cronet_aml_net_third_party_quiche_quiche',
123 'cronet_aml_base_base',
124 "cronet_aml_crypto_crypto",
Patrick Rohrcc83af22022-11-10 20:00:58 -0800125 "libssl",
Mohannad Farrage7d29312022-11-10 17:39:16 +0000126 }),
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000127 ],
128 'cronet_aml_components_cronet_android_cronet': [
129 ('rtti', True),
130 ('cppflags', {
131 # TODO: figure out if there is no way around this and if this is
132 # allowed for platform code.
133 "-fexceptions",
134 })
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800135 ]
Patrick Rohr92d74122022-10-21 15:50:52 -0700136}
137
138
139def enable_gtest_and_gmock(module):
140 module.static_libs.add('libgmock')
141 module.static_libs.add('libgtest')
142 if module.name != 'perfetto_gtest_logcat_printer':
143 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
144
145
146def enable_protobuf_full(module):
147 if module.type == 'cc_binary_host':
148 module.static_libs.add('libprotobuf-cpp-full')
149 elif module.host_supported:
150 module.host.static_libs.add('libprotobuf-cpp-full')
151 module.android.shared_libs.add('libprotobuf-cpp-full')
Patrick Rohr84b16402022-11-08 19:01:01 -0800152 elif module.type not in ['genrule', 'filegroup']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700153 module.shared_libs.add('libprotobuf-cpp-full')
154
155
156def enable_protobuf_lite(module):
Patrick Rohr84b16402022-11-08 19:01:01 -0800157 if module.type not in ['genrule', 'filegroup']:
158 module.shared_libs.add('libprotobuf-cpp-lite')
Patrick Rohr92d74122022-10-21 15:50:52 -0700159
160
161def enable_protoc_lib(module):
162 if module.type == 'cc_binary_host':
163 module.static_libs.add('libprotoc')
164 else:
165 module.shared_libs.add('libprotoc')
166
167
168def enable_libunwindstack(module):
169 if module.name != 'heapprofd_standalone_client':
170 module.shared_libs.add('libunwindstack')
171 module.shared_libs.add('libprocinfo')
172 module.shared_libs.add('libbase')
173 else:
174 module.static_libs.add('libunwindstack')
175 module.static_libs.add('libprocinfo')
176 module.static_libs.add('libbase')
177 module.static_libs.add('liblzma')
178 module.static_libs.add('libdexfile_support')
179 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
180
181
182def enable_libunwind(module):
183 # libunwind is disabled on Darwin so we cannot depend on it.
184 pass
185
186
187def enable_sqlite(module):
188 if module.type == 'cc_binary_host':
189 module.static_libs.add('libsqlite')
190 module.static_libs.add('sqlite_ext_percentile')
191 elif module.host_supported:
192 # Copy what the sqlite3 command line tool does.
193 module.android.shared_libs.add('libsqlite')
194 module.android.shared_libs.add('libicu')
195 module.android.shared_libs.add('liblog')
196 module.android.shared_libs.add('libutils')
197 module.android.static_libs.add('sqlite_ext_percentile')
198 module.host.static_libs.add('libsqlite')
199 module.host.static_libs.add('sqlite_ext_percentile')
200 else:
201 module.shared_libs.add('libsqlite')
202 module.shared_libs.add('libicu')
203 module.shared_libs.add('liblog')
204 module.shared_libs.add('libutils')
205 module.static_libs.add('sqlite_ext_percentile')
206
207
208def enable_zlib(module):
209 if module.type == 'cc_binary_host':
210 module.static_libs.add('libz')
211 elif module.host_supported:
212 module.android.shared_libs.add('libz')
213 module.host.static_libs.add('libz')
214 else:
215 module.shared_libs.add('libz')
216
217
218def enable_uapi_headers(module):
219 module.include_dirs.add('bionic/libc/kernel')
220
221
222def enable_bionic_libc_platform_headers_on_android(module):
223 module.header_libs.add('bionic_libc_platform_headers')
224
225
Patrick Rohrcc83af22022-11-10 20:00:58 -0800226def enable_boringssl(module):
227 if module.type not in ['genrule', 'filegroup']:
228 module.static_libs.add('libssl')
229
230
Patrick Rohr92d74122022-10-21 15:50:52 -0700231# Android equivalents for third-party libraries that the upstream project
232# depends on.
233builtin_deps = {
234 '//gn:default_deps':
235 lambda x: None,
236 '//gn:gtest_main':
237 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700238 '//gn:gtest_and_gmock':
239 enable_gtest_and_gmock,
240 '//gn:libunwind':
241 enable_libunwind,
Patrick Rohr92d74122022-10-21 15:50:52 -0700242 '//gn:libunwindstack':
243 enable_libunwindstack,
244 '//gn:sqlite':
245 enable_sqlite,
246 '//gn:zlib':
247 enable_zlib,
248 '//gn:bionic_kernel_uapi_headers':
249 enable_uapi_headers,
250 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
251 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900252 '//third_party/protobuf:protoc':
253 lambda x: None,
Patrick Rohr84b16402022-11-08 19:01:01 -0800254 '//third_party/protobuf:protobuf_full':
255 enable_protobuf_full,
256 '//third_party/protobuf:protobuf_lite':
257 enable_protobuf_lite,
258 '//third_party/protobuf:protoc_lib':
259 enable_protoc_lib,
Patrick Rohrcc83af22022-11-10 20:00:58 -0800260 '//third_party/boringssl:boringssl':
261 enable_boringssl,
Patrick Rohr92d74122022-10-21 15:50:52 -0700262}
263
264# ----------------------------------------------------------------------------
265# End of configuration.
266# ----------------------------------------------------------------------------
267
268
269class Error(Exception):
270 pass
271
272
273class ThrowingArgumentParser(argparse.ArgumentParser):
274
275 def __init__(self, context):
276 super(ThrowingArgumentParser, self).__init__()
277 self.context = context
278
279 def error(self, message):
280 raise Error('%s: %s' % (self.context, message))
281
282
283def write_blueprint_key_value(output, name, value, sort=True):
284 """Writes a Blueprint key-value pair to the output"""
285
286 if isinstance(value, bool):
287 if value:
288 output.append(' %s: true,' % name)
289 else:
290 output.append(' %s: false,' % name)
291 return
292 if not value:
293 return
294 if isinstance(value, set):
295 value = sorted(value)
296 if isinstance(value, list):
297 output.append(' %s: [' % name)
298 for item in sorted(value) if sort else value:
299 output.append(' "%s",' % item)
300 output.append(' ],')
301 return
302 if isinstance(value, Target):
303 value.to_string(output)
304 return
305 if isinstance(value, dict):
306 kv_output = []
307 for k, v in value.items():
308 write_blueprint_key_value(kv_output, k, v)
309
310 output.append(' %s: {' % name)
311 for line in kv_output:
312 output.append(' %s' % line)
313 output.append(' },')
314 return
315 output.append(' %s: "%s",' % (name, value))
316
317
318class Target(object):
319 """A target-scoped part of a module"""
320
321 def __init__(self, name):
322 self.name = name
323 self.shared_libs = set()
324 self.static_libs = set()
325 self.whole_static_libs = set()
326 self.cflags = set()
327 self.dist = dict()
328 self.strip = dict()
329 self.stl = None
330
331 def to_string(self, output):
332 nested_out = []
333 self._output_field(nested_out, 'shared_libs')
334 self._output_field(nested_out, 'static_libs')
335 self._output_field(nested_out, 'whole_static_libs')
336 self._output_field(nested_out, 'cflags')
337 self._output_field(nested_out, 'stl')
338 self._output_field(nested_out, 'dist')
339 self._output_field(nested_out, 'strip')
340
341 if nested_out:
342 output.append(' %s: {' % self.name)
343 for line in nested_out:
344 output.append(' %s' % line)
345 output.append(' },')
346
347 def _output_field(self, output, name, sort=True):
348 value = getattr(self, name)
349 return write_blueprint_key_value(output, name, value, sort)
350
351
352class Module(object):
353 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
354
355 def __init__(self, mod_type, name, gn_target):
356 self.type = mod_type
357 self.gn_target = gn_target
358 self.name = name
359 self.srcs = set()
360 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
361 self.shared_libs = set()
362 self.static_libs = set()
363 self.whole_static_libs = set()
364 self.runtime_libs = set()
365 self.tools = set()
366 self.cmd = None
367 self.host_supported = False
368 self.vendor_available = False
369 self.init_rc = set()
370 self.out = set()
371 self.export_include_dirs = set()
372 self.generated_headers = set()
373 self.export_generated_headers = set()
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800374 self.export_static_lib_headers = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700375 self.defaults = set()
376 self.cflags = set()
377 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900378 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700379 self.header_libs = set()
380 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700381 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700382 self.android = Target('android')
383 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700384 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700385 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700386 self.dist = dict()
387 self.strip = dict()
388 self.data = set()
389 self.apex_available = set()
390 self.min_sdk_version = None
391 self.proto = dict()
392 # The genrule_XXX below are properties that must to be propagated back
393 # on the module(s) that depend on the genrule.
394 self.genrule_headers = set()
395 self.genrule_srcs = set()
396 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700397 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700398 self.version_script = None
399 self.test_suites = set()
400 self.test_config = None
401 self.stubs = {}
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000402 self.cppflags = set()
403 self.rtti = False
Patrick Rohr92d74122022-10-21 15:50:52 -0700404
405 def to_string(self, output):
406 if self.comment:
407 output.append('// %s' % self.comment)
408 output.append('%s {' % self.type)
409 self._output_field(output, 'name')
410 self._output_field(output, 'srcs')
411 self._output_field(output, 'shared_libs')
412 self._output_field(output, 'static_libs')
413 self._output_field(output, 'whole_static_libs')
414 self._output_field(output, 'runtime_libs')
415 self._output_field(output, 'tools')
416 self._output_field(output, 'cmd', sort=False)
417 if self.host_supported:
418 self._output_field(output, 'host_supported')
419 if self.vendor_available:
420 self._output_field(output, 'vendor_available')
421 self._output_field(output, 'init_rc')
422 self._output_field(output, 'out')
423 self._output_field(output, 'export_include_dirs')
424 self._output_field(output, 'generated_headers')
425 self._output_field(output, 'export_generated_headers')
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800426 self._output_field(output, 'export_static_lib_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -0700427 self._output_field(output, 'defaults')
428 self._output_field(output, 'cflags')
429 self._output_field(output, 'include_dirs')
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900430 self._output_field(output, 'local_include_dirs', sort=False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700431 self._output_field(output, 'header_libs')
432 self._output_field(output, 'required')
433 self._output_field(output, 'dist')
434 self._output_field(output, 'strip')
435 self._output_field(output, 'tool_files')
436 self._output_field(output, 'data')
437 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700438 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700439 self._output_field(output, 'apex_available')
440 self._output_field(output, 'min_sdk_version')
441 self._output_field(output, 'version_script')
442 self._output_field(output, 'test_suites')
443 self._output_field(output, 'test_config')
444 self._output_field(output, 'stubs')
445 self._output_field(output, 'proto')
Mohannad Farrag37388fa2022-11-10 20:42:13 +0000446 self._output_field(output, 'cppflags')
447 if self.rtti:
448 self._output_field(output, 'rtti')
Patrick Rohr92d74122022-10-21 15:50:52 -0700449
450 target_out = []
451 self._output_field(target_out, 'android')
452 self._output_field(target_out, 'host')
453 if target_out:
454 output.append(' target: {')
455 for line in target_out:
456 output.append(' %s' % line)
457 output.append(' },')
458
Patrick Rohr92d74122022-10-21 15:50:52 -0700459 output.append('}')
460 output.append('')
461
462 def add_android_static_lib(self, lib):
463 if self.type == 'cc_binary_host':
464 raise Exception('Adding Android static lib for host tool is unsupported')
465 elif self.host_supported:
466 self.android.static_libs.add(lib)
467 else:
468 self.static_libs.add(lib)
469
470 def add_android_shared_lib(self, lib):
471 if self.type == 'cc_binary_host':
472 raise Exception('Adding Android shared lib for host tool is unsupported')
473 elif self.host_supported:
474 self.android.shared_libs.add(lib)
475 else:
476 self.shared_libs.add(lib)
477
478 def _output_field(self, output, name, sort=True):
479 value = getattr(self, name)
480 return write_blueprint_key_value(output, name, value, sort)
481
482
483class Blueprint(object):
484 """In-memory representation of an Android.bp file."""
485
486 def __init__(self):
487 self.modules = {}
488
489 def add_module(self, module):
490 """Adds a new module to the blueprint, replacing any existing module
491 with the same name.
492
493 Args:
494 module: Module instance.
495 """
496 self.modules[module.name] = module
497
498 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700499 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700500 m.to_string(output)
501
502
503def label_to_module_name(label):
504 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
505 # If the label is explicibly listed in the default target list, don't prefix
506 # its name and return just the target name. This is so tools like
507 # "traceconv" stay as such in the Android tree.
508 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700509 module = re.sub(r'^//:?', '', label_without_toolchain)
510 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
511 if not module.startswith(module_prefix):
512 return module_prefix + module
513 return module
514
515
516def is_supported_source_file(name):
517 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrf9f3a992022-11-10 19:40:32 -0800518 return os.path.splitext(name)[1] in ['.c', '.cc', '.cpp', '.java', '.proto', '.S']
Patrick Rohr92d74122022-10-21 15:50:52 -0700519
520
521def create_proto_modules(blueprint, gn, target):
522 """Generate genrules for a proto GN target.
523
524 GN actions are used to dynamically generate files during the build. The
525 Soong equivalent is a genrule. This function turns a specific kind of
526 genrule which turns .proto files into source and header files into a pair
527 equivalent genrules.
528
529 Args:
530 blueprint: Blueprint instance which is being generated.
531 target: gn_utils.Target object.
532
533 Returns:
534 The source_genrule module.
535 """
536 assert (target.type == 'proto_library')
537
538 tools = {'aprotoc'}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900539 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700540 target_module_name = label_to_module_name(target.name)
541
542 # In GN builds the proto path is always relative to the output directory
543 # (out/tmp.xxx).
Motomu Utsumie8457452022-11-08 18:47:51 +0900544 cmd = ['$(location aprotoc)']
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900545 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700546
547 if buildtools_protobuf_src in target.proto_paths:
548 cmd += ['--proto_path=%s' % android_protobuf_src]
549
550 # We don't generate any targets for source_set proto modules because
551 # they will be inlined into other modules if required.
552 if target.proto_plugin == 'source_set':
553 return None
554
555 # Descriptor targets only generate a single target.
556 if target.proto_plugin == 'descriptor':
557 out = '{}.bin'.format(target_module_name)
558
559 cmd += ['--descriptor_set_out=$(out)']
560 cmd += ['$(in)']
561
562 descriptor_module = Module('genrule', target_module_name, target.name)
563 descriptor_module.cmd = ' '.join(cmd)
564 descriptor_module.out = [out]
565 descriptor_module.tools = tools
566 blueprint.add_module(descriptor_module)
567
568 # Recursively extract the .proto files of all the dependencies and
569 # add them to srcs.
570 descriptor_module.srcs.update(
571 gn_utils.label_to_path(src) for src in target.sources)
572 for dep in target.transitive_proto_deps:
573 current_target = gn.get_target(dep)
574 descriptor_module.srcs.update(
575 gn_utils.label_to_path(src) for src in current_target.sources)
576
577 return descriptor_module
578
579 # We create two genrules for each proto target: one for the headers and
580 # another for the sources. This is because the module that depends on the
581 # generated files needs to declare two different types of dependencies --
582 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
583 # valid to generate .h files from a source dependency and vice versa.
584 source_module_name = target_module_name + '_gen'
585 source_module = Module('genrule', source_module_name, target.name)
586 blueprint.add_module(source_module)
587 source_module.srcs.update(
588 gn_utils.label_to_path(src) for src in target.sources)
589
590 header_module = Module('genrule', source_module_name + '_headers',
591 target.name)
592 blueprint.add_module(header_module)
593 header_module.srcs = set(source_module.srcs)
594
595 # TODO(primiano): at some point we should remove this. This was introduced
596 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
597 # avoid doing multi-repo changes and allow old clients in the android tree
598 # to still do the old #include "perfetto/..." rather than
599 # #include "protos/perfetto/...".
600 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800601 # Since the .cc file and .h get created by a different gerule target, they
602 # are not put in the same intermediate path, so local includes do not work
603 # without explictily exporting the include dir.
604 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700605
606 source_module.genrule_srcs.add(':' + source_module.name)
607 source_module.genrule_headers.add(header_module.name)
608
609 if target.proto_plugin == 'proto':
610 suffixes = ['pb']
611 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
612 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
613 elif target.proto_plugin == 'protozero':
614 suffixes = ['pbzero']
615 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
616 tools.add(plugin.name)
617 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
618 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
619 elif target.proto_plugin == 'cppgen':
620 suffixes = ['gen']
621 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
622 tools.add(plugin.name)
623 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
624 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
625 elif target.proto_plugin == 'ipc':
626 suffixes = ['ipc']
627 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
628 tools.add(plugin.name)
629 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
630 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
631 else:
632 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
633
634 cmd += ['$(in)']
635 source_module.cmd = ' '.join(cmd)
636 header_module.cmd = source_module.cmd
637 source_module.tools = tools
638 header_module.tools = tools
639
640 for sfx in suffixes:
641 source_module.out.update('%s/%s' %
642 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
643 for src in source_module.srcs)
644 header_module.out.update('%s/%s' %
645 (tree_path, src.replace('.proto', '.%s.h' % sfx))
646 for src in header_module.srcs)
647 return source_module
648
649
650def create_amalgamated_sql_metrics_module(blueprint, target):
651 bp_module_name = label_to_module_name(target.name)
652 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700653 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700654 module.cmd = ' '.join([
655 '$(location tools/gen_amalgamated_sql_metrics.py)',
656 '--cpp_out=$(out)',
657 '$(in)',
658 ])
659 module.genrule_headers.add(module.name)
660 module.out.update(target.outputs)
661 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
662 blueprint.add_module(module)
663 return module
664
665
666def create_cc_proto_descriptor_module(blueprint, target):
667 bp_module_name = label_to_module_name(target.name)
668 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700669 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700670 module.cmd = ' '.join([
671 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
672 '--cpp_out=$(out)', '$(in)'
673 ])
674 module.genrule_headers.add(module.name)
675 module.srcs.update(
676 ':' + label_to_module_name(dep) for dep in target.proto_deps)
677 module.srcs.update(
678 gn_utils.label_to_path(src)
679 for src in target.inputs
680 if "tmp.gn_utils" not in src)
681 module.out.update(target.outputs)
682 blueprint.add_module(module)
683 return module
684
685
686def create_gen_version_module(blueprint, target, bp_module_name):
687 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
688 script_path = gn_utils.label_to_path(target.script)
689 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700690 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700691 module.out.update(target.outputs)
692 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
693 module.cmd = ' '.join([
694 'python3 $(location %s)' % script_path, '--no_git',
695 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
696 ])
697 blueprint.add_module(module)
698 return module
699
700
701def create_proto_group_modules(blueprint, gn, module_name, target_names):
702 # TODO(lalitm): today, we're only adding a Java lite module because that's
703 # the only one used in practice. In the future, if we need other target types
704 # (e.g. C++, Java full etc.) add them here.
705 bp_module_name = label_to_module_name(module_name) + '_java_protos'
706 module = Module('java_library', bp_module_name, bp_module_name)
707 module.comment = f'''GN: [{', '.join(target_names)}]'''
708 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
709
710 for name in target_names:
711 target = gn.get_target(name)
712 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
713 for dep_label in target.transitive_proto_deps:
714 dep = gn.get_target(dep_label)
715 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
716
717 blueprint.add_module(module)
718
Motomu Utsumia6c33152022-11-02 18:21:55 +0900719# HACK: Need to support build_cofig_gen flexibly instead of hardcoding
720# build_config_gen generates srcjar by executing gcc via gcc_preprocess.py but gcc is not
721# available in genrule sandbox. Also gcc path is not configurable.
722# Under the //net:net, gcc_preprocess.py is only used for build_config_gen.
723# So, for now, hardcoding BuildConfig.java and generates srcjar by soong_zip.
724def override_build_config_gen(module):
725 module.tool_files.clear()
726 module.tools.add("soong_zip")
727 cmd = [
728 "echo",
729 "\\\"package org.chromium.build;\\n",
730 "public class BuildConfig {\\n",
731 "public static boolean IS_MULTIDEX_ENABLED ;\\n",
732 "public static boolean ENABLE_ASSERTS = true;\\n",
733 "public static boolean IS_UBSAN ;\\n",
734 "public static boolean IS_CHROME_BRANDED ;\\n",
735 "public static int R_STRING_PRODUCT_VERSION ;\\n",
736 "public static int MIN_SDK_VERSION = 1;\\n",
737 "public static boolean BUNDLES_SUPPORTED ;\\n",
738 "public static boolean IS_INCREMENTAL_INSTALL ;\\n",
739 "public static boolean ISOLATED_SPLITS_ENABLED ;\\n",
740 "public static boolean IS_FOR_TEST ;\\n",
741 "}\\n\\\"",
742 "> $(genDir)/BuildConfig.java &&",
743 "$(location soong_zip) -o $(out) -srcjar -f $(genDir)/BuildConfig.java"
744 ]
745 NEWLINE = ' " +\n "'
746 module.cmd = NEWLINE.join(cmd)
747 return module
748
Mohannad Farragbab6c892022-11-02 14:09:46 +0000749def create_action_foreach_modules(blueprint, target):
750 """ The following assumes that rebase_path exists in the args.
751 The args of an action_foreach contains hints about which output files are generated
752 by which source files.
753 This is copied directly from the args
754 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
755 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
756 """
757 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900758 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000759 # don't add script arg for the first source -- create_action_module
760 # already does this.
761 if i != 0:
762 new_args.append('&& python3 $(location %s)' %
763 gn_utils.label_to_path(target.script))
764 for arg in target.args:
765 if '{{source}}' in arg:
766 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
767 elif '{{source_name_part}}' in arg:
768 source_name_part = src.split("/")[-1] # Get the file name only
769 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
770 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
771 # file_name represent the output file name. But we need the whole path
772 # This can be found from target.outputs.
773 for out in target.outputs:
774 if out.endswith(file_name):
775 new_args.append('$(location %s)' % out)
776 else:
777 new_args.append(arg)
778
779 target.args = new_args
780 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900781
Patrick Rohr7be99032022-10-31 11:54:19 -0700782def create_action_module(blueprint, target):
783 bp_module_name = label_to_module_name(target.name)
784 module = Module('genrule', bp_module_name, target.name)
785
Patrick Rohr9b99a982022-10-28 11:00:57 -0700786 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
787 # TODO: we may want to only do this for python scripts arguments. If argparse
788 # is used, this transformation is safe.
789 target.args = [str for it in target.args for str in it.split('=')]
790
Motomu Utsumibf569d42022-10-28 16:47:34 +0900791 if target.script == "//build/write_buildflag_header.py":
792 # write_buildflag_header.py writes result to args.genDir/args.output
793 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700794 for i, val in enumerate(target.args):
795 if val == '--gen-dir':
796 target.args[i + 1] = '.'
Patrick Rohrfa972402022-11-01 11:54:35 -0700797 elif val == '--output':
798 target.args[i + 1] = '$(out)'
799
800 elif target.script == '//build/write_build_date_header.py':
801 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700802
Patrick Rohr8acccca2022-10-28 10:39:06 -0700803 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohrc5cc21a2022-10-31 11:57:49 -0700804 # chromium builds against a prebuilt ndk that contains the jni_headers, so
805 # a dependency is never explicitly created.
806 module.genrule_header_libs.add('jni_headers')
Patrick Rohr131ba282022-10-31 16:36:20 -0700807 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700808 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900809 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700810 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
811 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700812 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700813 # --input_file supports both .class specifiers or source files as arguments.
814 # Only source files need to be wrapped inside a $(location <label>) tag.
815 if re.match('.*\.class$', target.args[i + 1]):
816 continue
817 # replace --input_file ../../... with --input_file $(location ...)
818 # TODO: put inside function
819 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
820 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700821 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700822 # delete all leading ../
823 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700824 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700825 # this is not needed for aosp builds.
826 target.args[i] = ''
827 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700828 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700829 # delete leading ../../ and add path to javap
830 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
831 target.args[i + 1] = '$(location %s)' % filename
832 needs_javap = True
833
834 if needs_javap:
835 target.args.append('--javap')
836 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700837 # fix target.output directory to match #include statements.
838 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700839
Patrick Rohrf6d2b612022-11-09 12:30:26 -0800840 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
841 # jni_registration_generator.py pulls in some config dependencies that we
842 # do not handle. Remove them.
843 # TODO: find a better way to do this.
844 target.deps.clear()
845
Motomu Utsumied009082022-11-10 16:26:44 +0900846 target.inputs = [file for file in target.inputs if not file.startswith('//out/')]
Motomu Utsumi6b4acaa2022-11-10 16:13:24 +0900847 for i, val in enumerate(target.args):
848 if val in ['--depfile', '--srcjar-path', '--header-path']:
849 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900850 if val == '--sources-files':
851 target.args[i + 1] = '$(genDir)/java.sources'
Motomu Utsumi47d122f2022-11-10 17:32:23 +0900852 elif val == '--sources-exclusions':
853 # update_jni_registration_module removes them from the srcs of the module
854 # It might be better to remove sources by '--sources-exclusions'
855 target.args[i] = ''
856 target.args[i + 1] = ''
Motomu Utsumi6b4acaa2022-11-10 16:13:24 +0900857
Patrick Rohr245df582022-11-01 16:59:45 -0700858 elif target.script == '//build/android/gyp/write_build_config.py':
859 for i, val in enumerate(target.args):
860 if val == '--depfile':
861 # Depfile is not used, so no need to generate it.
862 target.args[i] = ''
863 target.args[i + 1] = ''
864 elif val in ['--deps-configs', '--bundled-srcjars']:
865 args = target.args[i + 1]
866 if args == '[]':
867 continue
868 # strip surrounding [] and split by ", "
869 args = args.strip('[]').split(', ')
870 # strip surrounding ""
871 args = [arg.strip('"') for arg in args]
872 # remove leading gen/
873 args = [re.sub('^gen/', '', arg) for arg in args]
874 # wrap filename in \"$(location filename)\"
875 args = ['\"$(location %s)\"' % arg for arg in args]
876 # join args with ", " and wrap in []
877 target.args[i + 1] = '[%s]' % ', '.join(args)
878
879 elif val == '--public-deps-configs':
880 # TODO: implement.
881 pass
882
883 elif val == '--build-config':
884 # json output of this script
885 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
886
887 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
888 '--device-jar-path', '--host-jar-path']:
889 # jar path can be within sources (../../) or output generated by
890 # another genrule (obj/)
891 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
892 filename = re.sub('^obj/', '', target.args[i + 1])
893 target.args[i + 1] = '$(location %s)' % filename
894
895 elif val == '--proguard-configs':
896 args = target.args[i + 1]
897 if args == '[]':
898 continue
899 # TODO: consider adding helpers to deal with argument lists
900 # strip surrounding [] and split by ", ", then strip surrounding ""
901 args = args.strip('[]').split(', ')
902 args = [arg.strip('"') for arg in args]
903 # remove leading ../../
904 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
905 # add dependency on proguard config file, so a $(location) wrapper can be used.
906 module.tool_files.update(args)
907 # wrap filename in \"$(location filename)\"
908 args = ['$(location %s)' % arg for arg in args]
909 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900910 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
911 for i, val in enumerate(target.args):
912 if val == '--output':
913 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900914 elif target.script == "//tools/grit/stamp_grit_sources.py":
915 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
916 # Directory that contains grit scripts
917 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
918 # Path to the stamp file
919 target.args[1] = '$(out)'
920 # Script tries to create args[2] file but this is not in the output.
921 # Specifying file under $(genDir) so that parent directory exists.
922 # If this file is used by other module, we may need to add this file to the outputs.
923 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000924 elif target.script == "//tools/grit/grit.py":
925 for i, val in enumerate(target.args):
926 if val == '-i':
927 # Delete leading ../..
928 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
929 target.args[i + 1] = '$(location %s)' % filename
930 elif val == '-o':
931 filename = re.sub('^gen/', '', target.args[i + 1])
932 if filename == "net":
933 # This is a directory not a file
934 target.args[i + 1] = '$(genDir)/net'
935 else:
936 # This is an output fil
937 target.args[i + 1] = '$(location %s)' % filename
938 elif val == '--depfile':
939 # The depfile is replaced by adding /tools/**/*.py to the tools_files
940 # This is basically just globbing all the needed sources by hardcoding.
941 module.tool_files.update([
942 "tools/grit/**/*.py",
943 "third_party/six/src/six.py" # This is not picked up by default. Must be added
944 ])
945
946 # Delete the depfile argument
947 target.args[i] = ' '
948 target.args[i + 1] = ' '
949 elif val == '--input':
950 # Delete leading ../..
951 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
952 # This is an output file so use $(location %s)
953 target.args[i + 1] = '$(location %s)' % filename
Motomu Utsumia0cc6662022-11-09 15:22:27 +0900954 elif target.script == "//net/tools/dafsa/make_dafsa.py":
955 # This script generates .cc files but source (registry_controlled_domain.cc) in the target that
956 # depends on this target includes .cc file this script generates.
957 module.genrule_headers.add(module.name)
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900958 elif target.script == "//build/util/version.py":
Motomu Utsumib0a49e42022-11-09 18:12:27 +0900959 # android_chrome_version.py is not specified in anywhere but version.py imports this file
960 module.tool_files.add('build/util/android_chrome_version.py')
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900961 for i, val in enumerate(target.args):
962 if val.startswith('../../'):
963 filename = re.sub('^\.\./\.\./', '', val)
964 target.args[i] = '$(location %s)' % filename
Motomu Utsumiee279c52022-11-09 17:46:27 +0900965 elif val == '-e':
966 # arg for -e EVAL option should be passed in -e PATCH_HI=int(PATCH)//256 format.
967 target.args[i + 1] = '%s=\'%s\'' % (target.args[i + 1], target.args[i + 2])
968 target.args[i + 2] = ''
Motomu Utsumi438f2c22022-11-09 18:16:40 +0900969 elif val == '-o':
970 target.args[i + 1] = '$(out)'
Patrick Rohr245df582022-11-01 16:59:45 -0700971
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700972 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700973 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700974
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700975 # Handle passing parameters via response file by piping them into the script
976 # and reading them from /dev/stdin.
977 response_file = '{{response_file_name}}'
978 use_response_file = response_file in target.args
979 if use_response_file:
980 # Replace {{response_file_contents}} with /dev/stdin
981 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
982
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700983 # escape " and \$ in target.args.
984 # once all actions are properly implemented, this may not be necessary anymore.
985 # TODO: is this the right place to do this?
986 target.args = [arg.replace('"', r'\"') for arg in target.args]
987 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
988
Patrick Rohr9b99a982022-10-28 11:00:57 -0700989 # put all args on a new line for better diffs.
990 NEWLINE = ' " +\n "'
991 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700992 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700993
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700994 if use_response_file:
995 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700996 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700997
Motomu Utsumi7e983832022-11-10 16:04:46 +0900998 if any(os.path.splitext(it)[1] == '.h' for it in target.outputs):
Patrick Rohr67f4d432022-10-26 16:04:15 -0700999 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -07001000
Patrick Rohr0db9f852022-10-27 13:49:57 -07001001 # gn treats inputs and sources for actions equally.
1002 # soong only supports source files inside srcs, non-source files are added as
1003 # tool_files dependency.
1004 for it in target.sources or target.inputs:
1005 if is_supported_source_file(it):
1006 module.srcs.add(gn_utils.label_to_path(it))
1007 else:
1008 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -07001009
Patrick Rohr15a2c302022-10-26 15:08:57 -07001010 # Actions using template "action_with_pydeps" also put script inside inputs.
1011 # TODO: it might make sense to filter inputs inside GnParser.
1012 if script in module.srcs:
1013 module.srcs.remove(script)
1014
Patrick Rohre1a853e2022-10-26 12:31:39 -07001015 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +09001016
1017 if target.name == "//build/android:build_config_gen":
1018 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +09001019 elif target.script == "//tools/grit/stamp_grit_sources.py":
1020 # stamp_grit_sources.py is not executable
1021 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +00001022 elif target.script == "//base/android/jni_generator/jni_generator.py":
1023 # android_jar.classes should be part of the tools as it list implicit classes
1024 # for the script to generate JNI headers.
1025 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001026 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
Motomu Utsumi9ca466b2022-11-10 17:12:29 +09001027 # jni_registration_generator.py doesn't work with python2
1028 module.cmd = "python3 " + module.cmd
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001029 # Path in the original sources file does not work in genrule.
1030 # So creating sources file in cmd based on the srcs of this target.
1031 # Adding ../$(current_dir)/ to the head because jni_registration_generator.py uses the files
1032 # whose path startswith(..)
1033 commands = ["current_dir=`basename \\\`pwd\\\``;",
1034 "for f in $(in);",
1035 "do",
1036 "echo \\\"../$$current_dir/$$f\\\" >> $(genDir)/java.sources;",
1037 "done;",
1038 module.cmd]
Motomu Utsumi2a892d22022-11-10 18:03:20 +09001039
1040 # .h file jni_registration_generator.py generates has #define with directory name.
1041 # With the genrule env that contains "." which is invalid. So replace that at the end of cmd.
Mohannad Farrag7c0f0982022-11-10 14:39:49 +00001042 commands.append(";sed -i -e 's/OUT_SOONG_.TEMP_SBOX_.*_OUT/GEN/g' ")
Motomu Utsumi2a892d22022-11-10 18:03:20 +09001043 commands.append("$(genDir)/components/cronet/android/cronet_jni_registration.h")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001044 module.cmd = NEWLINE.join(commands)
Motomu Utsumia6c33152022-11-02 18:21:55 +09001045
Patrick Rohre1a853e2022-10-26 12:31:39 -07001046 blueprint.add_module(module)
1047 return module
1048
1049
Patrick Rohr92d74122022-10-21 15:50:52 -07001050
1051def _get_cflags(target):
1052 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +09001053 # Consider proper allowlist or denylist if needed
1054 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -07001055 return cflags
1056
1057
1058def create_modules_from_target(blueprint, gn, gn_target_name):
1059 """Generate module(s) for a given GN target.
1060
1061 Given a GN target name, generate one or more corresponding modules into a
1062 blueprint. The only case when this generates >1 module is proto libraries.
1063
1064 Args:
1065 blueprint: Blueprint instance which is being generated.
1066 gn: gn_utils.GnParser object.
1067 gn_target_name: GN target for module generation.
1068 """
1069 bp_module_name = label_to_module_name(gn_target_name)
1070 if bp_module_name in blueprint.modules:
1071 return blueprint.modules[bp_module_name]
1072 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -07001073 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -07001074
1075 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
1076 if target.type == 'executable':
1077 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
1078 module_type = 'cc_binary_host'
1079 elif target.testonly:
1080 module_type = 'cc_test'
1081 else:
1082 module_type = 'cc_binary'
1083 module = Module(module_type, bp_module_name, gn_target_name)
1084 elif target.type == 'static_library':
1085 module = Module('cc_library_static', bp_module_name, gn_target_name)
1086 elif target.type == 'shared_library':
1087 module = Module('cc_library_shared', bp_module_name, gn_target_name)
1088 elif target.type == 'source_set':
1089 module = Module('filegroup', bp_module_name, gn_target_name)
1090 elif target.type == 'group':
1091 # "group" targets are resolved recursively by gn_utils.get_target().
1092 # There's nothing we need to do at this level for them.
1093 return None
1094 elif target.type == 'proto_library':
1095 module = create_proto_modules(blueprint, gn, target)
1096 if module is None:
1097 return None
1098 elif target.type == 'action':
1099 if 'gen_amalgamated_sql_metrics' in target.name:
1100 module = create_amalgamated_sql_metrics_module(blueprint, target)
1101 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1102 module = create_cc_proto_descriptor_module(blueprint, target)
1103 elif target.type == 'action' and \
1104 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1105 module = create_gen_version_module(blueprint, target, bp_module_name)
1106 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001107 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001108 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001109 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001110 elif target.type == 'copy':
1111 # TODO: careful now! copy targets are not supported yet, but this will stop
1112 # traversing the dependency tree. For //base:base, this is not a big
1113 # problem as libicu contains the only copy target which happens to be a
1114 # leaf node.
1115 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001116 else:
1117 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1118
1119 blueprint.add_module(module)
1120 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001121 module.init_rc = target_initrc.get(target.name, [])
1122 module.srcs.update(
1123 gn_utils.label_to_path(src)
1124 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001125 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001126
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001127 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001128 if target.type in gn_utils.LINKER_UNIT_TYPES:
1129 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001130 # TODO: implement proper cflag parsing.
1131 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001132 if '-std=' in flag:
1133 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001134 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001135 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001136
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001137 # Adding local_include_dirs is necessary due to source_sets / filegroups
1138 # which do not properly propagate include directories.
1139 # Filter any directory inside //out as a) this directory does not exist for
1140 # aosp / soong builds and b) the include directory should already be
1141 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001142 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001143 for d in target.include_dirs
1144 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001145 module.local_include_dirs = sorted(list(local_include_dirs_set))
1146
1147 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1148 # in //base:base needs to have sysroot include after icu/source/common
1149 # include. So adding sysroot include at the end.
1150 for flag in target.cflags:
1151 if '--sysroot' in flag:
1152 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001153
1154 module_is_compiled = module.type not in ('genrule', 'filegroup')
1155 if module_is_compiled:
1156 # Don't try to inject library/source dependencies into genrules or
1157 # filegroups because they are not compiled in the traditional sense.
1158 module.defaults = [defaults_module]
1159 for lib in target.libs:
1160 # Generally library names should be mangled as 'libXXX', unless they
1161 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1162 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1163 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1164 else 'lib' + lib
1165 if lib in shared_library_allowlist:
1166 module.add_android_shared_lib(android_lib)
1167 if lib in static_library_allowlist:
1168 module.add_android_static_lib(android_lib)
1169
Patrick Rohrd9dd3b92022-11-09 16:15:30 -08001170 # Remove prohibited include directories
1171 module.local_include_dirs = [d for d in module.local_include_dirs
1172 if d not in local_include_dirs_denylist]
1173
1174
Patrick Rohr92d74122022-10-21 15:50:52 -07001175 # If the module is a static library, export all the generated headers.
1176 if module.type == 'cc_library_static':
1177 module.export_generated_headers = module.generated_headers
1178
Patrick Rohr92d74122022-10-21 15:50:52 -07001179 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001180 # Currently, only one module is generated from target even target has multiple toolchains.
1181 # And module is generated based on the first visited target.
1182 # Sort deps before iteration to make result deterministic.
1183 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001184 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001185 # |builtin_deps| override GN deps with Android-specific ones. See the
1186 # config in the top of this file.
1187 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1188 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1189 continue
1190
Patrick Rohr92d74122022-10-21 15:50:52 -07001191 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1192
Motomu Utsumie246feb2022-11-01 17:25:56 +09001193 # TODO: Proper dependency check for genrule.
1194 # Currently, only propagating genrule dependencies.
1195 # Also, currently, all the dependencies are propagated upwards.
1196 # in gn, public_deps should be propagated but deps should not.
1197 # Not sure this information is available in the desc.json.
1198 # Following rule works for adding android_runtime_jni_headers to base:base.
1199 # If this doesn't work for other target, hardcoding for specific target
1200 # might be better.
1201 if module.type == "genrule" and dep_module.type == "genrule":
1202 module.genrule_headers.add(dep_module.name)
1203 module.genrule_headers.update(dep_module.genrule_headers)
1204
Patrick Rohr92d74122022-10-21 15:50:52 -07001205 # For filegroups and genrule, recurse but don't apply the deps.
1206 if not module_is_compiled:
1207 continue
1208
Patrick Rohr92d74122022-10-21 15:50:52 -07001209 if dep_module is None:
1210 continue
1211 if dep_module.type == 'cc_library_shared':
1212 module.shared_libs.add(dep_module.name)
1213 elif dep_module.type == 'cc_library_static':
1214 module.static_libs.add(dep_module.name)
1215 elif dep_module.type == 'filegroup':
1216 module.srcs.add(':' + dep_module.name)
1217 elif dep_module.type == 'genrule':
1218 module.generated_headers.update(dep_module.genrule_headers)
1219 module.srcs.update(dep_module.genrule_srcs)
1220 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001221 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001222 elif dep_module.type == 'cc_binary':
1223 continue # Ignore executables deps (used by cmdline integration tests).
1224 else:
1225 raise Error('Unknown dep %s (%s) for target %s' %
1226 (dep_module.name, dep_module.type, module.name))
1227
1228 return module
1229
Patrick Rohrb18aca22022-11-04 15:07:32 -07001230def create_java_module(blueprint, gn):
1231 bp_module_name = module_prefix + 'java'
1232 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001233 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001234 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001235
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001236def update_jni_registration_module(blueprint, gn):
1237 bp_module_name = label_to_module_name('//components/cronet/android:cronet_jni_registration')
Patrick Rohr7f225422022-11-10 21:38:38 -08001238 if bp_module_name not in blueprint.modules:
1239 # To support building targets that might not create the cronet_jni_registration.
1240 return
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001241 module = blueprint.modules[bp_module_name]
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001242
1243 # TODO: deny list is in the arg of jni_registration_generator.py. Should not be hardcoded
1244 deny_list = [
1245 '//base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java',
1246 '//base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java',
1247 '//base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java',
1248 '//base/android/java/src/org/chromium/base/SysUtils.java']
1249
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001250 # TODO: java_sources might not contain all the required java files
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001251 module.srcs.update([gn_utils.label_to_path(source)
1252 for source in gn.java_sources if source not in deny_list])
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001253
Motomu Utsumi79bd0c82022-11-10 17:52:24 +09001254 # TODO: Remove hardcoded file addition to srcs
1255 # jni_registration_generator.py generates empty .h file if native methods are not found in the
1256 # java files. But android:cronet depends on `RegisterNonMainDexNatives` which is in the template
1257 # of .h file. To make script generate non empty .h file, adding java file which contains native
1258 # method. Once all the required java files are added to the srcs, this can be removed.
1259 module.srcs.update([
1260 "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java"])
1261
Patrick Rohr92d74122022-10-21 15:50:52 -07001262def create_blueprint_for_targets(gn, desc, targets):
1263 """Generate a blueprint for a list of GN targets."""
1264 blueprint = Blueprint()
1265
1266 # Default settings used by all modules.
1267 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001268 defaults.cflags = [
1269 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001270 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001271 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001272 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001273 '-Wno-sign-compare',
1274 '-Wno-sign-promo',
1275 '-Wno-unused-parameter',
Mohannad Farragd98a96d2022-11-10 14:56:19 +00001276 '-Wno-deprecated-non-prototype', # needed for zlib
Patrick Rohr92d74122022-10-21 15:50:52 -07001277 '-fvisibility=hidden',
1278 '-O2',
1279 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001280 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001281 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001282
Patrick Rohr92d74122022-10-21 15:50:52 -07001283 for target in targets:
1284 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001285
1286 create_java_module(blueprint, gn)
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001287 update_jni_registration_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001288
1289 # Merge in additional hardcoded arguments.
1290 for module in blueprint.modules.values():
1291 for key, add_val in additional_args.get(module.name, []):
1292 curr = getattr(module, key)
1293 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1294 curr.update(add_val)
1295 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1296 setattr(module, key, add_val)
1297 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1298 setattr(module, key, add_val)
1299 elif isinstance(add_val, dict) and isinstance(curr, dict):
1300 curr.update(add_val)
1301 elif isinstance(add_val, dict) and isinstance(curr, Target):
1302 curr.__dict__.update(add_val)
1303 else:
1304 raise Error('Unimplemented type %r of additional_args: %r' %
1305 (type(add_val), key))
1306
Patrick Rohr92d74122022-10-21 15:50:52 -07001307 return blueprint
1308
1309
1310def main():
1311 parser = argparse.ArgumentParser(
1312 description='Generate Android.bp from a GN description.')
1313 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001314 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001315 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1316 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001317 )
1318 parser.add_argument(
1319 '--extras',
1320 help='Extra targets to include at the end of the Blueprint file',
1321 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1322 )
1323 parser.add_argument(
1324 '--output',
1325 help='Blueprint file to create',
1326 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1327 )
1328 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001329 '-v',
1330 '--verbose',
1331 help='Print debug logs.',
1332 action='store_true',
1333 )
1334 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001335 'targets',
1336 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001337 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1338 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001339 args = parser.parse_args()
1340
Patrick Rohr16228942022-10-26 14:00:26 -07001341 if args.verbose:
1342 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1343
Patrick Rohr3db246a2022-10-25 10:25:17 -07001344 with open(args.desc) as f:
1345 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001346
1347 gn = gn_utils.GnParser(desc)
Patrick Rohr06296362022-11-10 21:37:33 -08001348 blueprint = create_blueprint_for_targets(gn, desc, args.targets or default_targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001349 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1350 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1351
Patrick Rohr92d74122022-10-21 15:50:52 -07001352 # Add any proto groups to the blueprint.
1353 for l_name, t_names in proto_groups.items():
1354 create_proto_group_modules(blueprint, gn, l_name, t_names)
1355
1356 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001357 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001358//
1359// Licensed under the Apache License, Version 2.0 (the "License");
1360// you may not use this file except in compliance with the License.
1361// You may obtain a copy of the License at
1362//
1363// http://www.apache.org/licenses/LICENSE-2.0
1364//
1365// Unless required by applicable law or agreed to in writing, software
1366// distributed under the License is distributed on an "AS IS" BASIS,
1367// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1368// See the License for the specific language governing permissions and
1369// limitations under the License.
1370//
1371// This file is automatically generated by %s. Do not edit.
1372""" % (tool_name)
1373 ]
1374 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001375 if os.path.exists(args.extras):
1376 with open(args.extras, 'r') as r:
1377 for line in r:
1378 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001379
1380 out_files = []
1381
1382 # Generate the Android.bp file.
1383 out_files.append(args.output + '.swp')
1384 with open(out_files[-1], 'w') as f:
1385 f.write('\n'.join(output))
1386 # Text files should have a trailing EOL.
1387 f.write('\n')
1388
Patrick Rohr94693eb2022-10-25 10:09:16 -07001389 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001390
1391
1392if __name__ == '__main__':
1393 sys.exit(main())