blob: 2caf80597ece8812f75228193142a8a5b761e6e3 [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 Rohr92d74122022-10-21 15:50:52 -070041# Defines a custom init_rc argument to be applied to the corresponding output
42# blueprint target.
43target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070044 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070045}
46
47target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070048 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070049]
50
Patrick Rohr92d74122022-10-21 15:50:52 -070051# Proto target groups which will be made public.
52proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070053 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070054}
55
56# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070057module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070058
59# Shared libraries which are directly translated to Android system equivalents.
60shared_library_allowlist = [
61 'android',
62 'android.hardware.atrace@1.0',
63 'android.hardware.health@2.0',
64 'android.hardware.health-V1-ndk',
65 'android.hardware.power.stats@1.0',
66 "android.hardware.power.stats-V1-cpp",
67 'base',
68 'binder',
69 'binder_ndk',
70 'cutils',
71 'hidlbase',
72 'hidltransport',
73 'hwbinder',
74 'incident',
75 'log',
76 'services',
77 'statssocket',
78 "tracingproxy",
79 'utils',
80]
81
82# Static libraries which are directly translated to Android system equivalents.
83static_library_allowlist = [
84 'statslog_perfetto',
85]
86
Patrick Rohrd9dd3b92022-11-09 16:15:30 -080087# Include directories that will be removed from all targets.
88local_include_dirs_denylist = [
89 'third_party/protobuf/src/',
90]
91
Patrick Rohr92d74122022-10-21 15:50:52 -070092# Name of the module which settings such as compiler flags for all other
93# modules.
94defaults_module = module_prefix + 'defaults'
95
96# Location of the project in the Android source tree.
Patrick Rohr76ceeb52022-11-07 14:18:58 -080097tree_path = 'external/chromium_org'
Patrick Rohr92d74122022-10-21 15:50:52 -070098
99# Path for the protobuf sources in the standalone build.
100buildtools_protobuf_src = '//buildtools/protobuf/src'
101
102# Location of the protobuf src dir in the Android source tree.
103android_protobuf_src = 'external/protobuf/src'
104
105# Compiler flags which are passed through to the blueprint.
106cflag_allowlist = r'^-DPERFETTO.*$'
107
Patrick Rohr92d74122022-10-21 15:50:52 -0700108# Additional arguments to apply to Android.bp rules.
109additional_args = {
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800110 # TODO: remove if not needed.
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800111 'cronet_aml_net_net': [
Patrick Rohr9f4d3e32022-11-09 16:37:31 -0800112 ('export_static_lib_headers', {
113 'cronet_aml_net_third_party_quiche_quiche',
114 'cronet_aml_crypto_crypto',
115 }),
Mohannad Farrage7d29312022-11-10 17:39:16 +0000116 ('whole_static_libs', {
117 'cronet_aml_net_third_party_quiche_quiche',
118 'cronet_aml_base_base',
119 "cronet_aml_crypto_crypto",
120 "cronet_aml_third_party_boringssl_boringssl",
121 }),
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800122 ]
Patrick Rohr92d74122022-10-21 15:50:52 -0700123}
124
125
126def enable_gtest_and_gmock(module):
127 module.static_libs.add('libgmock')
128 module.static_libs.add('libgtest')
129 if module.name != 'perfetto_gtest_logcat_printer':
130 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
131
132
133def enable_protobuf_full(module):
134 if module.type == 'cc_binary_host':
135 module.static_libs.add('libprotobuf-cpp-full')
136 elif module.host_supported:
137 module.host.static_libs.add('libprotobuf-cpp-full')
138 module.android.shared_libs.add('libprotobuf-cpp-full')
Patrick Rohr84b16402022-11-08 19:01:01 -0800139 elif module.type not in ['genrule', 'filegroup']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700140 module.shared_libs.add('libprotobuf-cpp-full')
141
142
143def enable_protobuf_lite(module):
Patrick Rohr84b16402022-11-08 19:01:01 -0800144 if module.type not in ['genrule', 'filegroup']:
145 module.shared_libs.add('libprotobuf-cpp-lite')
Patrick Rohr92d74122022-10-21 15:50:52 -0700146
147
148def enable_protoc_lib(module):
149 if module.type == 'cc_binary_host':
150 module.static_libs.add('libprotoc')
151 else:
152 module.shared_libs.add('libprotoc')
153
154
155def enable_libunwindstack(module):
156 if module.name != 'heapprofd_standalone_client':
157 module.shared_libs.add('libunwindstack')
158 module.shared_libs.add('libprocinfo')
159 module.shared_libs.add('libbase')
160 else:
161 module.static_libs.add('libunwindstack')
162 module.static_libs.add('libprocinfo')
163 module.static_libs.add('libbase')
164 module.static_libs.add('liblzma')
165 module.static_libs.add('libdexfile_support')
166 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
167
168
169def enable_libunwind(module):
170 # libunwind is disabled on Darwin so we cannot depend on it.
171 pass
172
173
174def enable_sqlite(module):
175 if module.type == 'cc_binary_host':
176 module.static_libs.add('libsqlite')
177 module.static_libs.add('sqlite_ext_percentile')
178 elif module.host_supported:
179 # Copy what the sqlite3 command line tool does.
180 module.android.shared_libs.add('libsqlite')
181 module.android.shared_libs.add('libicu')
182 module.android.shared_libs.add('liblog')
183 module.android.shared_libs.add('libutils')
184 module.android.static_libs.add('sqlite_ext_percentile')
185 module.host.static_libs.add('libsqlite')
186 module.host.static_libs.add('sqlite_ext_percentile')
187 else:
188 module.shared_libs.add('libsqlite')
189 module.shared_libs.add('libicu')
190 module.shared_libs.add('liblog')
191 module.shared_libs.add('libutils')
192 module.static_libs.add('sqlite_ext_percentile')
193
194
195def enable_zlib(module):
196 if module.type == 'cc_binary_host':
197 module.static_libs.add('libz')
198 elif module.host_supported:
199 module.android.shared_libs.add('libz')
200 module.host.static_libs.add('libz')
201 else:
202 module.shared_libs.add('libz')
203
204
205def enable_uapi_headers(module):
206 module.include_dirs.add('bionic/libc/kernel')
207
208
209def enable_bionic_libc_platform_headers_on_android(module):
210 module.header_libs.add('bionic_libc_platform_headers')
211
212
213# Android equivalents for third-party libraries that the upstream project
214# depends on.
215builtin_deps = {
216 '//gn:default_deps':
217 lambda x: None,
218 '//gn:gtest_main':
219 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700220 '//gn:gtest_and_gmock':
221 enable_gtest_and_gmock,
222 '//gn:libunwind':
223 enable_libunwind,
Patrick Rohr92d74122022-10-21 15:50:52 -0700224 '//gn:libunwindstack':
225 enable_libunwindstack,
226 '//gn:sqlite':
227 enable_sqlite,
228 '//gn:zlib':
229 enable_zlib,
230 '//gn:bionic_kernel_uapi_headers':
231 enable_uapi_headers,
232 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
233 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900234 '//third_party/protobuf:protoc':
235 lambda x: None,
Patrick Rohr84b16402022-11-08 19:01:01 -0800236 '//third_party/protobuf:protobuf_full':
237 enable_protobuf_full,
238 '//third_party/protobuf:protobuf_lite':
239 enable_protobuf_lite,
240 '//third_party/protobuf:protoc_lib':
241 enable_protoc_lib,
Patrick Rohr92d74122022-10-21 15:50:52 -0700242}
243
244# ----------------------------------------------------------------------------
245# End of configuration.
246# ----------------------------------------------------------------------------
247
248
249class Error(Exception):
250 pass
251
252
253class ThrowingArgumentParser(argparse.ArgumentParser):
254
255 def __init__(self, context):
256 super(ThrowingArgumentParser, self).__init__()
257 self.context = context
258
259 def error(self, message):
260 raise Error('%s: %s' % (self.context, message))
261
262
263def write_blueprint_key_value(output, name, value, sort=True):
264 """Writes a Blueprint key-value pair to the output"""
265
266 if isinstance(value, bool):
267 if value:
268 output.append(' %s: true,' % name)
269 else:
270 output.append(' %s: false,' % name)
271 return
272 if not value:
273 return
274 if isinstance(value, set):
275 value = sorted(value)
276 if isinstance(value, list):
277 output.append(' %s: [' % name)
278 for item in sorted(value) if sort else value:
279 output.append(' "%s",' % item)
280 output.append(' ],')
281 return
282 if isinstance(value, Target):
283 value.to_string(output)
284 return
285 if isinstance(value, dict):
286 kv_output = []
287 for k, v in value.items():
288 write_blueprint_key_value(kv_output, k, v)
289
290 output.append(' %s: {' % name)
291 for line in kv_output:
292 output.append(' %s' % line)
293 output.append(' },')
294 return
295 output.append(' %s: "%s",' % (name, value))
296
297
298class Target(object):
299 """A target-scoped part of a module"""
300
301 def __init__(self, name):
302 self.name = name
303 self.shared_libs = set()
304 self.static_libs = set()
305 self.whole_static_libs = set()
306 self.cflags = set()
307 self.dist = dict()
308 self.strip = dict()
309 self.stl = None
310
311 def to_string(self, output):
312 nested_out = []
313 self._output_field(nested_out, 'shared_libs')
314 self._output_field(nested_out, 'static_libs')
315 self._output_field(nested_out, 'whole_static_libs')
316 self._output_field(nested_out, 'cflags')
317 self._output_field(nested_out, 'stl')
318 self._output_field(nested_out, 'dist')
319 self._output_field(nested_out, 'strip')
320
321 if nested_out:
322 output.append(' %s: {' % self.name)
323 for line in nested_out:
324 output.append(' %s' % line)
325 output.append(' },')
326
327 def _output_field(self, output, name, sort=True):
328 value = getattr(self, name)
329 return write_blueprint_key_value(output, name, value, sort)
330
331
332class Module(object):
333 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
334
335 def __init__(self, mod_type, name, gn_target):
336 self.type = mod_type
337 self.gn_target = gn_target
338 self.name = name
339 self.srcs = set()
340 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
341 self.shared_libs = set()
342 self.static_libs = set()
343 self.whole_static_libs = set()
344 self.runtime_libs = set()
345 self.tools = set()
346 self.cmd = None
347 self.host_supported = False
348 self.vendor_available = False
349 self.init_rc = set()
350 self.out = set()
351 self.export_include_dirs = set()
352 self.generated_headers = set()
353 self.export_generated_headers = set()
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800354 self.export_static_lib_headers = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700355 self.defaults = set()
356 self.cflags = set()
357 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900358 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700359 self.header_libs = set()
360 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700361 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700362 self.android = Target('android')
363 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700364 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700365 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700366 self.dist = dict()
367 self.strip = dict()
368 self.data = set()
369 self.apex_available = set()
370 self.min_sdk_version = None
371 self.proto = dict()
372 # The genrule_XXX below are properties that must to be propagated back
373 # on the module(s) that depend on the genrule.
374 self.genrule_headers = set()
375 self.genrule_srcs = set()
376 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700377 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700378 self.version_script = None
379 self.test_suites = set()
380 self.test_config = None
381 self.stubs = {}
382
383 def to_string(self, output):
384 if self.comment:
385 output.append('// %s' % self.comment)
386 output.append('%s {' % self.type)
387 self._output_field(output, 'name')
388 self._output_field(output, 'srcs')
389 self._output_field(output, 'shared_libs')
390 self._output_field(output, 'static_libs')
391 self._output_field(output, 'whole_static_libs')
392 self._output_field(output, 'runtime_libs')
393 self._output_field(output, 'tools')
394 self._output_field(output, 'cmd', sort=False)
395 if self.host_supported:
396 self._output_field(output, 'host_supported')
397 if self.vendor_available:
398 self._output_field(output, 'vendor_available')
399 self._output_field(output, 'init_rc')
400 self._output_field(output, 'out')
401 self._output_field(output, 'export_include_dirs')
402 self._output_field(output, 'generated_headers')
403 self._output_field(output, 'export_generated_headers')
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800404 self._output_field(output, 'export_static_lib_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -0700405 self._output_field(output, 'defaults')
406 self._output_field(output, 'cflags')
407 self._output_field(output, 'include_dirs')
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900408 self._output_field(output, 'local_include_dirs', sort=False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700409 self._output_field(output, 'header_libs')
410 self._output_field(output, 'required')
411 self._output_field(output, 'dist')
412 self._output_field(output, 'strip')
413 self._output_field(output, 'tool_files')
414 self._output_field(output, 'data')
415 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700416 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700417 self._output_field(output, 'apex_available')
418 self._output_field(output, 'min_sdk_version')
419 self._output_field(output, 'version_script')
420 self._output_field(output, 'test_suites')
421 self._output_field(output, 'test_config')
422 self._output_field(output, 'stubs')
423 self._output_field(output, 'proto')
424
425 target_out = []
426 self._output_field(target_out, 'android')
427 self._output_field(target_out, 'host')
428 if target_out:
429 output.append(' target: {')
430 for line in target_out:
431 output.append(' %s' % line)
432 output.append(' },')
433
Patrick Rohr92d74122022-10-21 15:50:52 -0700434 output.append('}')
435 output.append('')
436
437 def add_android_static_lib(self, lib):
438 if self.type == 'cc_binary_host':
439 raise Exception('Adding Android static lib for host tool is unsupported')
440 elif self.host_supported:
441 self.android.static_libs.add(lib)
442 else:
443 self.static_libs.add(lib)
444
445 def add_android_shared_lib(self, lib):
446 if self.type == 'cc_binary_host':
447 raise Exception('Adding Android shared lib for host tool is unsupported')
448 elif self.host_supported:
449 self.android.shared_libs.add(lib)
450 else:
451 self.shared_libs.add(lib)
452
453 def _output_field(self, output, name, sort=True):
454 value = getattr(self, name)
455 return write_blueprint_key_value(output, name, value, sort)
456
457
458class Blueprint(object):
459 """In-memory representation of an Android.bp file."""
460
461 def __init__(self):
462 self.modules = {}
463
464 def add_module(self, module):
465 """Adds a new module to the blueprint, replacing any existing module
466 with the same name.
467
468 Args:
469 module: Module instance.
470 """
471 self.modules[module.name] = module
472
473 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700474 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700475 m.to_string(output)
476
477
478def label_to_module_name(label):
479 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
480 # If the label is explicibly listed in the default target list, don't prefix
481 # its name and return just the target name. This is so tools like
482 # "traceconv" stay as such in the Android tree.
483 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700484 module = re.sub(r'^//:?', '', label_without_toolchain)
485 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
486 if not module.startswith(module_prefix):
487 return module_prefix + module
488 return module
489
490
491def is_supported_source_file(name):
492 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrd604f9f2022-10-27 13:56:42 -0700493 return os.path.splitext(name)[1] in ['.c', '.cc', '.java', '.proto']
Patrick Rohr92d74122022-10-21 15:50:52 -0700494
495
496def create_proto_modules(blueprint, gn, target):
497 """Generate genrules for a proto GN target.
498
499 GN actions are used to dynamically generate files during the build. The
500 Soong equivalent is a genrule. This function turns a specific kind of
501 genrule which turns .proto files into source and header files into a pair
502 equivalent genrules.
503
504 Args:
505 blueprint: Blueprint instance which is being generated.
506 target: gn_utils.Target object.
507
508 Returns:
509 The source_genrule module.
510 """
511 assert (target.type == 'proto_library')
512
513 tools = {'aprotoc'}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900514 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700515 target_module_name = label_to_module_name(target.name)
516
517 # In GN builds the proto path is always relative to the output directory
518 # (out/tmp.xxx).
Motomu Utsumie8457452022-11-08 18:47:51 +0900519 cmd = ['$(location aprotoc)']
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900520 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700521
522 if buildtools_protobuf_src in target.proto_paths:
523 cmd += ['--proto_path=%s' % android_protobuf_src]
524
525 # We don't generate any targets for source_set proto modules because
526 # they will be inlined into other modules if required.
527 if target.proto_plugin == 'source_set':
528 return None
529
530 # Descriptor targets only generate a single target.
531 if target.proto_plugin == 'descriptor':
532 out = '{}.bin'.format(target_module_name)
533
534 cmd += ['--descriptor_set_out=$(out)']
535 cmd += ['$(in)']
536
537 descriptor_module = Module('genrule', target_module_name, target.name)
538 descriptor_module.cmd = ' '.join(cmd)
539 descriptor_module.out = [out]
540 descriptor_module.tools = tools
541 blueprint.add_module(descriptor_module)
542
543 # Recursively extract the .proto files of all the dependencies and
544 # add them to srcs.
545 descriptor_module.srcs.update(
546 gn_utils.label_to_path(src) for src in target.sources)
547 for dep in target.transitive_proto_deps:
548 current_target = gn.get_target(dep)
549 descriptor_module.srcs.update(
550 gn_utils.label_to_path(src) for src in current_target.sources)
551
552 return descriptor_module
553
554 # We create two genrules for each proto target: one for the headers and
555 # another for the sources. This is because the module that depends on the
556 # generated files needs to declare two different types of dependencies --
557 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
558 # valid to generate .h files from a source dependency and vice versa.
559 source_module_name = target_module_name + '_gen'
560 source_module = Module('genrule', source_module_name, target.name)
561 blueprint.add_module(source_module)
562 source_module.srcs.update(
563 gn_utils.label_to_path(src) for src in target.sources)
564
565 header_module = Module('genrule', source_module_name + '_headers',
566 target.name)
567 blueprint.add_module(header_module)
568 header_module.srcs = set(source_module.srcs)
569
570 # TODO(primiano): at some point we should remove this. This was introduced
571 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
572 # avoid doing multi-repo changes and allow old clients in the android tree
573 # to still do the old #include "perfetto/..." rather than
574 # #include "protos/perfetto/...".
575 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800576 # Since the .cc file and .h get created by a different gerule target, they
577 # are not put in the same intermediate path, so local includes do not work
578 # without explictily exporting the include dir.
579 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700580
581 source_module.genrule_srcs.add(':' + source_module.name)
582 source_module.genrule_headers.add(header_module.name)
583
584 if target.proto_plugin == 'proto':
585 suffixes = ['pb']
586 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
587 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
588 elif target.proto_plugin == 'protozero':
589 suffixes = ['pbzero']
590 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
591 tools.add(plugin.name)
592 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
593 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
594 elif target.proto_plugin == 'cppgen':
595 suffixes = ['gen']
596 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
597 tools.add(plugin.name)
598 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
599 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
600 elif target.proto_plugin == 'ipc':
601 suffixes = ['ipc']
602 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
603 tools.add(plugin.name)
604 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
605 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
606 else:
607 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
608
609 cmd += ['$(in)']
610 source_module.cmd = ' '.join(cmd)
611 header_module.cmd = source_module.cmd
612 source_module.tools = tools
613 header_module.tools = tools
614
615 for sfx in suffixes:
616 source_module.out.update('%s/%s' %
617 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
618 for src in source_module.srcs)
619 header_module.out.update('%s/%s' %
620 (tree_path, src.replace('.proto', '.%s.h' % sfx))
621 for src in header_module.srcs)
622 return source_module
623
624
625def create_amalgamated_sql_metrics_module(blueprint, target):
626 bp_module_name = label_to_module_name(target.name)
627 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700628 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700629 module.cmd = ' '.join([
630 '$(location tools/gen_amalgamated_sql_metrics.py)',
631 '--cpp_out=$(out)',
632 '$(in)',
633 ])
634 module.genrule_headers.add(module.name)
635 module.out.update(target.outputs)
636 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
637 blueprint.add_module(module)
638 return module
639
640
641def create_cc_proto_descriptor_module(blueprint, target):
642 bp_module_name = label_to_module_name(target.name)
643 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700644 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700645 module.cmd = ' '.join([
646 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
647 '--cpp_out=$(out)', '$(in)'
648 ])
649 module.genrule_headers.add(module.name)
650 module.srcs.update(
651 ':' + label_to_module_name(dep) for dep in target.proto_deps)
652 module.srcs.update(
653 gn_utils.label_to_path(src)
654 for src in target.inputs
655 if "tmp.gn_utils" not in src)
656 module.out.update(target.outputs)
657 blueprint.add_module(module)
658 return module
659
660
661def create_gen_version_module(blueprint, target, bp_module_name):
662 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
663 script_path = gn_utils.label_to_path(target.script)
664 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700665 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700666 module.out.update(target.outputs)
667 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
668 module.cmd = ' '.join([
669 'python3 $(location %s)' % script_path, '--no_git',
670 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
671 ])
672 blueprint.add_module(module)
673 return module
674
675
676def create_proto_group_modules(blueprint, gn, module_name, target_names):
677 # TODO(lalitm): today, we're only adding a Java lite module because that's
678 # the only one used in practice. In the future, if we need other target types
679 # (e.g. C++, Java full etc.) add them here.
680 bp_module_name = label_to_module_name(module_name) + '_java_protos'
681 module = Module('java_library', bp_module_name, bp_module_name)
682 module.comment = f'''GN: [{', '.join(target_names)}]'''
683 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
684
685 for name in target_names:
686 target = gn.get_target(name)
687 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
688 for dep_label in target.transitive_proto_deps:
689 dep = gn.get_target(dep_label)
690 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
691
692 blueprint.add_module(module)
693
Motomu Utsumia6c33152022-11-02 18:21:55 +0900694# HACK: Need to support build_cofig_gen flexibly instead of hardcoding
695# build_config_gen generates srcjar by executing gcc via gcc_preprocess.py but gcc is not
696# available in genrule sandbox. Also gcc path is not configurable.
697# Under the //net:net, gcc_preprocess.py is only used for build_config_gen.
698# So, for now, hardcoding BuildConfig.java and generates srcjar by soong_zip.
699def override_build_config_gen(module):
700 module.tool_files.clear()
701 module.tools.add("soong_zip")
702 cmd = [
703 "echo",
704 "\\\"package org.chromium.build;\\n",
705 "public class BuildConfig {\\n",
706 "public static boolean IS_MULTIDEX_ENABLED ;\\n",
707 "public static boolean ENABLE_ASSERTS = true;\\n",
708 "public static boolean IS_UBSAN ;\\n",
709 "public static boolean IS_CHROME_BRANDED ;\\n",
710 "public static int R_STRING_PRODUCT_VERSION ;\\n",
711 "public static int MIN_SDK_VERSION = 1;\\n",
712 "public static boolean BUNDLES_SUPPORTED ;\\n",
713 "public static boolean IS_INCREMENTAL_INSTALL ;\\n",
714 "public static boolean ISOLATED_SPLITS_ENABLED ;\\n",
715 "public static boolean IS_FOR_TEST ;\\n",
716 "}\\n\\\"",
717 "> $(genDir)/BuildConfig.java &&",
718 "$(location soong_zip) -o $(out) -srcjar -f $(genDir)/BuildConfig.java"
719 ]
720 NEWLINE = ' " +\n "'
721 module.cmd = NEWLINE.join(cmd)
722 return module
723
Mohannad Farragbab6c892022-11-02 14:09:46 +0000724def create_action_foreach_modules(blueprint, target):
725 """ The following assumes that rebase_path exists in the args.
726 The args of an action_foreach contains hints about which output files are generated
727 by which source files.
728 This is copied directly from the args
729 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
730 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
731 """
732 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900733 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000734 # don't add script arg for the first source -- create_action_module
735 # already does this.
736 if i != 0:
737 new_args.append('&& python3 $(location %s)' %
738 gn_utils.label_to_path(target.script))
739 for arg in target.args:
740 if '{{source}}' in arg:
741 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
742 elif '{{source_name_part}}' in arg:
743 source_name_part = src.split("/")[-1] # Get the file name only
744 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
745 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
746 # file_name represent the output file name. But we need the whole path
747 # This can be found from target.outputs.
748 for out in target.outputs:
749 if out.endswith(file_name):
750 new_args.append('$(location %s)' % out)
751 else:
752 new_args.append(arg)
753
754 target.args = new_args
755 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900756
Patrick Rohr7be99032022-10-31 11:54:19 -0700757def create_action_module(blueprint, target):
758 bp_module_name = label_to_module_name(target.name)
759 module = Module('genrule', bp_module_name, target.name)
760
Patrick Rohr9b99a982022-10-28 11:00:57 -0700761 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
762 # TODO: we may want to only do this for python scripts arguments. If argparse
763 # is used, this transformation is safe.
764 target.args = [str for it in target.args for str in it.split('=')]
765
Motomu Utsumibf569d42022-10-28 16:47:34 +0900766 if target.script == "//build/write_buildflag_header.py":
767 # write_buildflag_header.py writes result to args.genDir/args.output
768 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700769 for i, val in enumerate(target.args):
770 if val == '--gen-dir':
771 target.args[i + 1] = '.'
Patrick Rohrfa972402022-11-01 11:54:35 -0700772 elif val == '--output':
773 target.args[i + 1] = '$(out)'
774
775 elif target.script == '//build/write_build_date_header.py':
776 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700777
Patrick Rohr8acccca2022-10-28 10:39:06 -0700778 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohrc5cc21a2022-10-31 11:57:49 -0700779 # chromium builds against a prebuilt ndk that contains the jni_headers, so
780 # a dependency is never explicitly created.
781 module.genrule_header_libs.add('jni_headers')
Patrick Rohr131ba282022-10-31 16:36:20 -0700782 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700783 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900784 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700785 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
786 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700787 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700788 # --input_file supports both .class specifiers or source files as arguments.
789 # Only source files need to be wrapped inside a $(location <label>) tag.
790 if re.match('.*\.class$', target.args[i + 1]):
791 continue
792 # replace --input_file ../../... with --input_file $(location ...)
793 # TODO: put inside function
794 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
795 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700796 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700797 # delete all leading ../
798 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700799 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700800 # this is not needed for aosp builds.
801 target.args[i] = ''
802 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700803 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700804 # delete leading ../../ and add path to javap
805 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
806 target.args[i + 1] = '$(location %s)' % filename
807 needs_javap = True
808
809 if needs_javap:
810 target.args.append('--javap')
811 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700812 # fix target.output directory to match #include statements.
813 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700814
Patrick Rohrf6d2b612022-11-09 12:30:26 -0800815 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
816 # jni_registration_generator.py pulls in some config dependencies that we
817 # do not handle. Remove them.
818 # TODO: find a better way to do this.
819 target.deps.clear()
820
Motomu Utsumied009082022-11-10 16:26:44 +0900821 target.inputs = [file for file in target.inputs if not file.startswith('//out/')]
Motomu Utsumi6b4acaa2022-11-10 16:13:24 +0900822 for i, val in enumerate(target.args):
823 if val in ['--depfile', '--srcjar-path', '--header-path']:
824 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +0900825 if val == '--sources-files':
826 target.args[i + 1] = '$(genDir)/java.sources'
Motomu Utsumi47d122f2022-11-10 17:32:23 +0900827 elif val == '--sources-exclusions':
828 # update_jni_registration_module removes them from the srcs of the module
829 # It might be better to remove sources by '--sources-exclusions'
830 target.args[i] = ''
831 target.args[i + 1] = ''
Motomu Utsumi6b4acaa2022-11-10 16:13:24 +0900832
Patrick Rohr245df582022-11-01 16:59:45 -0700833 elif target.script == '//build/android/gyp/write_build_config.py':
834 for i, val in enumerate(target.args):
835 if val == '--depfile':
836 # Depfile is not used, so no need to generate it.
837 target.args[i] = ''
838 target.args[i + 1] = ''
839 elif val in ['--deps-configs', '--bundled-srcjars']:
840 args = target.args[i + 1]
841 if args == '[]':
842 continue
843 # strip surrounding [] and split by ", "
844 args = args.strip('[]').split(', ')
845 # strip surrounding ""
846 args = [arg.strip('"') for arg in args]
847 # remove leading gen/
848 args = [re.sub('^gen/', '', arg) for arg in args]
849 # wrap filename in \"$(location filename)\"
850 args = ['\"$(location %s)\"' % arg for arg in args]
851 # join args with ", " and wrap in []
852 target.args[i + 1] = '[%s]' % ', '.join(args)
853
854 elif val == '--public-deps-configs':
855 # TODO: implement.
856 pass
857
858 elif val == '--build-config':
859 # json output of this script
860 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
861
862 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
863 '--device-jar-path', '--host-jar-path']:
864 # jar path can be within sources (../../) or output generated by
865 # another genrule (obj/)
866 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
867 filename = re.sub('^obj/', '', target.args[i + 1])
868 target.args[i + 1] = '$(location %s)' % filename
869
870 elif val == '--proguard-configs':
871 args = target.args[i + 1]
872 if args == '[]':
873 continue
874 # TODO: consider adding helpers to deal with argument lists
875 # strip surrounding [] and split by ", ", then strip surrounding ""
876 args = args.strip('[]').split(', ')
877 args = [arg.strip('"') for arg in args]
878 # remove leading ../../
879 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
880 # add dependency on proguard config file, so a $(location) wrapper can be used.
881 module.tool_files.update(args)
882 # wrap filename in \"$(location filename)\"
883 args = ['$(location %s)' % arg for arg in args]
884 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900885 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
886 for i, val in enumerate(target.args):
887 if val == '--output':
888 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900889 elif target.script == "//tools/grit/stamp_grit_sources.py":
890 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
891 # Directory that contains grit scripts
892 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
893 # Path to the stamp file
894 target.args[1] = '$(out)'
895 # Script tries to create args[2] file but this is not in the output.
896 # Specifying file under $(genDir) so that parent directory exists.
897 # If this file is used by other module, we may need to add this file to the outputs.
898 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000899 elif target.script == "//tools/grit/grit.py":
900 for i, val in enumerate(target.args):
901 if val == '-i':
902 # Delete leading ../..
903 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
904 target.args[i + 1] = '$(location %s)' % filename
905 elif val == '-o':
906 filename = re.sub('^gen/', '', target.args[i + 1])
907 if filename == "net":
908 # This is a directory not a file
909 target.args[i + 1] = '$(genDir)/net'
910 else:
911 # This is an output fil
912 target.args[i + 1] = '$(location %s)' % filename
913 elif val == '--depfile':
914 # The depfile is replaced by adding /tools/**/*.py to the tools_files
915 # This is basically just globbing all the needed sources by hardcoding.
916 module.tool_files.update([
917 "tools/grit/**/*.py",
918 "third_party/six/src/six.py" # This is not picked up by default. Must be added
919 ])
920
921 # Delete the depfile argument
922 target.args[i] = ' '
923 target.args[i + 1] = ' '
924 elif val == '--input':
925 # Delete leading ../..
926 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
927 # This is an output file so use $(location %s)
928 target.args[i + 1] = '$(location %s)' % filename
Motomu Utsumia0cc6662022-11-09 15:22:27 +0900929 elif target.script == "//net/tools/dafsa/make_dafsa.py":
930 # This script generates .cc files but source (registry_controlled_domain.cc) in the target that
931 # depends on this target includes .cc file this script generates.
932 module.genrule_headers.add(module.name)
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900933 elif target.script == "//build/util/version.py":
Motomu Utsumib0a49e42022-11-09 18:12:27 +0900934 # android_chrome_version.py is not specified in anywhere but version.py imports this file
935 module.tool_files.add('build/util/android_chrome_version.py')
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900936 for i, val in enumerate(target.args):
937 if val.startswith('../../'):
938 filename = re.sub('^\.\./\.\./', '', val)
939 target.args[i] = '$(location %s)' % filename
Motomu Utsumiee279c52022-11-09 17:46:27 +0900940 elif val == '-e':
941 # arg for -e EVAL option should be passed in -e PATCH_HI=int(PATCH)//256 format.
942 target.args[i + 1] = '%s=\'%s\'' % (target.args[i + 1], target.args[i + 2])
943 target.args[i + 2] = ''
Motomu Utsumi438f2c22022-11-09 18:16:40 +0900944 elif val == '-o':
945 target.args[i + 1] = '$(out)'
Patrick Rohr245df582022-11-01 16:59:45 -0700946
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700947 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700948 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700949
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700950 # Handle passing parameters via response file by piping them into the script
951 # and reading them from /dev/stdin.
952 response_file = '{{response_file_name}}'
953 use_response_file = response_file in target.args
954 if use_response_file:
955 # Replace {{response_file_contents}} with /dev/stdin
956 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
957
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700958 # escape " and \$ in target.args.
959 # once all actions are properly implemented, this may not be necessary anymore.
960 # TODO: is this the right place to do this?
961 target.args = [arg.replace('"', r'\"') for arg in target.args]
962 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
963
Patrick Rohr9b99a982022-10-28 11:00:57 -0700964 # put all args on a new line for better diffs.
965 NEWLINE = ' " +\n "'
966 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700967 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700968
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700969 if use_response_file:
970 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700971 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700972
Motomu Utsumi7e983832022-11-10 16:04:46 +0900973 if any(os.path.splitext(it)[1] == '.h' for it in target.outputs):
Patrick Rohr67f4d432022-10-26 16:04:15 -0700974 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700975
Patrick Rohr0db9f852022-10-27 13:49:57 -0700976 # gn treats inputs and sources for actions equally.
977 # soong only supports source files inside srcs, non-source files are added as
978 # tool_files dependency.
979 for it in target.sources or target.inputs:
980 if is_supported_source_file(it):
981 module.srcs.add(gn_utils.label_to_path(it))
982 else:
983 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700984
Patrick Rohr15a2c302022-10-26 15:08:57 -0700985 # Actions using template "action_with_pydeps" also put script inside inputs.
986 # TODO: it might make sense to filter inputs inside GnParser.
987 if script in module.srcs:
988 module.srcs.remove(script)
989
Patrick Rohre1a853e2022-10-26 12:31:39 -0700990 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900991
992 if target.name == "//build/android:build_config_gen":
993 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900994 elif target.script == "//tools/grit/stamp_grit_sources.py":
995 # stamp_grit_sources.py is not executable
996 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000997 elif target.script == "//base/android/jni_generator/jni_generator.py":
998 # android_jar.classes should be part of the tools as it list implicit classes
999 # for the script to generate JNI headers.
1000 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001001 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
Motomu Utsumi9ca466b2022-11-10 17:12:29 +09001002 # jni_registration_generator.py doesn't work with python2
1003 module.cmd = "python3 " + module.cmd
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001004 # Path in the original sources file does not work in genrule.
1005 # So creating sources file in cmd based on the srcs of this target.
1006 # Adding ../$(current_dir)/ to the head because jni_registration_generator.py uses the files
1007 # whose path startswith(..)
1008 commands = ["current_dir=`basename \\\`pwd\\\``;",
1009 "for f in $(in);",
1010 "do",
1011 "echo \\\"../$$current_dir/$$f\\\" >> $(genDir)/java.sources;",
1012 "done;",
1013 module.cmd]
Motomu Utsumi2a892d22022-11-10 18:03:20 +09001014
1015 # .h file jni_registration_generator.py generates has #define with directory name.
1016 # With the genrule env that contains "." which is invalid. So replace that at the end of cmd.
Mohannad Farrag7c0f0982022-11-10 14:39:49 +00001017 commands.append(";sed -i -e 's/OUT_SOONG_.TEMP_SBOX_.*_OUT/GEN/g' ")
Motomu Utsumi2a892d22022-11-10 18:03:20 +09001018 commands.append("$(genDir)/components/cronet/android/cronet_jni_registration.h")
Motomu Utsumi7bc2fcc2022-11-10 17:09:54 +09001019 module.cmd = NEWLINE.join(commands)
Motomu Utsumia6c33152022-11-02 18:21:55 +09001020
Patrick Rohre1a853e2022-10-26 12:31:39 -07001021 blueprint.add_module(module)
1022 return module
1023
1024
Patrick Rohr92d74122022-10-21 15:50:52 -07001025
1026def _get_cflags(target):
1027 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +09001028 # Consider proper allowlist or denylist if needed
1029 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -07001030 return cflags
1031
1032
1033def create_modules_from_target(blueprint, gn, gn_target_name):
1034 """Generate module(s) for a given GN target.
1035
1036 Given a GN target name, generate one or more corresponding modules into a
1037 blueprint. The only case when this generates >1 module is proto libraries.
1038
1039 Args:
1040 blueprint: Blueprint instance which is being generated.
1041 gn: gn_utils.GnParser object.
1042 gn_target_name: GN target for module generation.
1043 """
1044 bp_module_name = label_to_module_name(gn_target_name)
1045 if bp_module_name in blueprint.modules:
1046 return blueprint.modules[bp_module_name]
1047 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -07001048 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -07001049
1050 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
1051 if target.type == 'executable':
1052 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
1053 module_type = 'cc_binary_host'
1054 elif target.testonly:
1055 module_type = 'cc_test'
1056 else:
1057 module_type = 'cc_binary'
1058 module = Module(module_type, bp_module_name, gn_target_name)
1059 elif target.type == 'static_library':
1060 module = Module('cc_library_static', bp_module_name, gn_target_name)
1061 elif target.type == 'shared_library':
1062 module = Module('cc_library_shared', bp_module_name, gn_target_name)
1063 elif target.type == 'source_set':
1064 module = Module('filegroup', bp_module_name, gn_target_name)
1065 elif target.type == 'group':
1066 # "group" targets are resolved recursively by gn_utils.get_target().
1067 # There's nothing we need to do at this level for them.
1068 return None
1069 elif target.type == 'proto_library':
1070 module = create_proto_modules(blueprint, gn, target)
1071 if module is None:
1072 return None
1073 elif target.type == 'action':
1074 if 'gen_amalgamated_sql_metrics' in target.name:
1075 module = create_amalgamated_sql_metrics_module(blueprint, target)
1076 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1077 module = create_cc_proto_descriptor_module(blueprint, target)
1078 elif target.type == 'action' and \
1079 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1080 module = create_gen_version_module(blueprint, target, bp_module_name)
1081 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001082 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001083 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001084 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001085 elif target.type == 'copy':
1086 # TODO: careful now! copy targets are not supported yet, but this will stop
1087 # traversing the dependency tree. For //base:base, this is not a big
1088 # problem as libicu contains the only copy target which happens to be a
1089 # leaf node.
1090 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001091 else:
1092 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1093
1094 blueprint.add_module(module)
1095 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001096 module.init_rc = target_initrc.get(target.name, [])
1097 module.srcs.update(
1098 gn_utils.label_to_path(src)
1099 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001100 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001101
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001102 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001103 if target.type in gn_utils.LINKER_UNIT_TYPES:
1104 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001105 # TODO: implement proper cflag parsing.
1106 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001107 if '-std=' in flag:
1108 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001109 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001110 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001111
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001112 # Adding local_include_dirs is necessary due to source_sets / filegroups
1113 # which do not properly propagate include directories.
1114 # Filter any directory inside //out as a) this directory does not exist for
1115 # aosp / soong builds and b) the include directory should already be
1116 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001117 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001118 for d in target.include_dirs
1119 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001120 module.local_include_dirs = sorted(list(local_include_dirs_set))
1121
1122 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1123 # in //base:base needs to have sysroot include after icu/source/common
1124 # include. So adding sysroot include at the end.
1125 for flag in target.cflags:
1126 if '--sysroot' in flag:
1127 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001128
1129 module_is_compiled = module.type not in ('genrule', 'filegroup')
1130 if module_is_compiled:
1131 # Don't try to inject library/source dependencies into genrules or
1132 # filegroups because they are not compiled in the traditional sense.
1133 module.defaults = [defaults_module]
1134 for lib in target.libs:
1135 # Generally library names should be mangled as 'libXXX', unless they
1136 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1137 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1138 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1139 else 'lib' + lib
1140 if lib in shared_library_allowlist:
1141 module.add_android_shared_lib(android_lib)
1142 if lib in static_library_allowlist:
1143 module.add_android_static_lib(android_lib)
1144
Patrick Rohrd9dd3b92022-11-09 16:15:30 -08001145 # Remove prohibited include directories
1146 module.local_include_dirs = [d for d in module.local_include_dirs
1147 if d not in local_include_dirs_denylist]
1148
1149
Patrick Rohr92d74122022-10-21 15:50:52 -07001150 # If the module is a static library, export all the generated headers.
1151 if module.type == 'cc_library_static':
1152 module.export_generated_headers = module.generated_headers
1153
Patrick Rohr92d74122022-10-21 15:50:52 -07001154 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001155 # Currently, only one module is generated from target even target has multiple toolchains.
1156 # And module is generated based on the first visited target.
1157 # Sort deps before iteration to make result deterministic.
1158 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001159 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001160 # |builtin_deps| override GN deps with Android-specific ones. See the
1161 # config in the top of this file.
1162 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1163 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1164 continue
1165
Patrick Rohr92d74122022-10-21 15:50:52 -07001166 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1167
Motomu Utsumie246feb2022-11-01 17:25:56 +09001168 # TODO: Proper dependency check for genrule.
1169 # Currently, only propagating genrule dependencies.
1170 # Also, currently, all the dependencies are propagated upwards.
1171 # in gn, public_deps should be propagated but deps should not.
1172 # Not sure this information is available in the desc.json.
1173 # Following rule works for adding android_runtime_jni_headers to base:base.
1174 # If this doesn't work for other target, hardcoding for specific target
1175 # might be better.
1176 if module.type == "genrule" and dep_module.type == "genrule":
1177 module.genrule_headers.add(dep_module.name)
1178 module.genrule_headers.update(dep_module.genrule_headers)
1179
Patrick Rohr92d74122022-10-21 15:50:52 -07001180 # For filegroups and genrule, recurse but don't apply the deps.
1181 if not module_is_compiled:
1182 continue
1183
Patrick Rohr92d74122022-10-21 15:50:52 -07001184 if dep_module is None:
1185 continue
1186 if dep_module.type == 'cc_library_shared':
1187 module.shared_libs.add(dep_module.name)
1188 elif dep_module.type == 'cc_library_static':
1189 module.static_libs.add(dep_module.name)
1190 elif dep_module.type == 'filegroup':
1191 module.srcs.add(':' + dep_module.name)
1192 elif dep_module.type == 'genrule':
1193 module.generated_headers.update(dep_module.genrule_headers)
1194 module.srcs.update(dep_module.genrule_srcs)
1195 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001196 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001197 elif dep_module.type == 'cc_binary':
1198 continue # Ignore executables deps (used by cmdline integration tests).
1199 else:
1200 raise Error('Unknown dep %s (%s) for target %s' %
1201 (dep_module.name, dep_module.type, module.name))
1202
1203 return module
1204
Patrick Rohrb18aca22022-11-04 15:07:32 -07001205def create_java_module(blueprint, gn):
1206 bp_module_name = module_prefix + 'java'
1207 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001208 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001209 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001210
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001211def update_jni_registration_module(blueprint, gn):
1212 bp_module_name = label_to_module_name('//components/cronet/android:cronet_jni_registration')
1213 module = blueprint.modules[bp_module_name]
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001214
1215 # TODO: deny list is in the arg of jni_registration_generator.py. Should not be hardcoded
1216 deny_list = [
1217 '//base/android/java/src/org/chromium/base/library_loader/LibraryLoader.java',
1218 '//base/android/java/src/org/chromium/base/library_loader/LibraryPrefetcher.java',
1219 '//base/android/java/src/org/chromium/base/process_launcher/ChildProcessService.java',
1220 '//base/android/java/src/org/chromium/base/SysUtils.java']
1221
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001222 # TODO: java_sources might not contain all the required java files
Motomu Utsumi47d122f2022-11-10 17:32:23 +09001223 module.srcs.update([gn_utils.label_to_path(source)
1224 for source in gn.java_sources if source not in deny_list])
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001225
Motomu Utsumi79bd0c82022-11-10 17:52:24 +09001226 # TODO: Remove hardcoded file addition to srcs
1227 # jni_registration_generator.py generates empty .h file if native methods are not found in the
1228 # java files. But android:cronet depends on `RegisterNonMainDexNatives` which is in the template
1229 # of .h file. To make script generate non empty .h file, adding java file which contains native
1230 # method. Once all the required java files are added to the srcs, this can be removed.
1231 module.srcs.update([
1232 "components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequest.java"])
1233
Patrick Rohr92d74122022-10-21 15:50:52 -07001234def create_blueprint_for_targets(gn, desc, targets):
1235 """Generate a blueprint for a list of GN targets."""
1236 blueprint = Blueprint()
1237
1238 # Default settings used by all modules.
1239 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001240 defaults.cflags = [
1241 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001242 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001243 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001244 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001245 '-Wno-sign-compare',
1246 '-Wno-sign-promo',
1247 '-Wno-unused-parameter',
Mohannad Farragd98a96d2022-11-10 14:56:19 +00001248 '-Wno-deprecated-non-prototype', # needed for zlib
Patrick Rohr92d74122022-10-21 15:50:52 -07001249 '-fvisibility=hidden',
1250 '-O2',
1251 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001252 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001253 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001254
Patrick Rohr92d74122022-10-21 15:50:52 -07001255 for target in targets:
1256 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001257
1258 create_java_module(blueprint, gn)
Motomu Utsumie3ce7702022-11-10 16:22:11 +09001259 update_jni_registration_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001260
1261 # Merge in additional hardcoded arguments.
1262 for module in blueprint.modules.values():
1263 for key, add_val in additional_args.get(module.name, []):
1264 curr = getattr(module, key)
1265 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1266 curr.update(add_val)
1267 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1268 setattr(module, key, add_val)
1269 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1270 setattr(module, key, add_val)
1271 elif isinstance(add_val, dict) and isinstance(curr, dict):
1272 curr.update(add_val)
1273 elif isinstance(add_val, dict) and isinstance(curr, Target):
1274 curr.__dict__.update(add_val)
1275 else:
1276 raise Error('Unimplemented type %r of additional_args: %r' %
1277 (type(add_val), key))
1278
Patrick Rohr92d74122022-10-21 15:50:52 -07001279 return blueprint
1280
1281
1282def main():
1283 parser = argparse.ArgumentParser(
1284 description='Generate Android.bp from a GN description.')
1285 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001286 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001287 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1288 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001289 )
1290 parser.add_argument(
1291 '--extras',
1292 help='Extra targets to include at the end of the Blueprint file',
1293 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1294 )
1295 parser.add_argument(
1296 '--output',
1297 help='Blueprint file to create',
1298 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1299 )
1300 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001301 '-v',
1302 '--verbose',
1303 help='Print debug logs.',
1304 action='store_true',
1305 )
1306 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001307 'targets',
1308 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001309 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1310 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001311 args = parser.parse_args()
1312
Patrick Rohr16228942022-10-26 14:00:26 -07001313 if args.verbose:
1314 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1315
Patrick Rohr3db246a2022-10-25 10:25:17 -07001316 with open(args.desc) as f:
1317 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001318
1319 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001320 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001321 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1322 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1323
Patrick Rohr92d74122022-10-21 15:50:52 -07001324 # Add any proto groups to the blueprint.
1325 for l_name, t_names in proto_groups.items():
1326 create_proto_group_modules(blueprint, gn, l_name, t_names)
1327
1328 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001329 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001330//
1331// Licensed under the Apache License, Version 2.0 (the "License");
1332// you may not use this file except in compliance with the License.
1333// You may obtain a copy of the License at
1334//
1335// http://www.apache.org/licenses/LICENSE-2.0
1336//
1337// Unless required by applicable law or agreed to in writing, software
1338// distributed under the License is distributed on an "AS IS" BASIS,
1339// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1340// See the License for the specific language governing permissions and
1341// limitations under the License.
1342//
1343// This file is automatically generated by %s. Do not edit.
1344""" % (tool_name)
1345 ]
1346 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001347 if os.path.exists(args.extras):
1348 with open(args.extras, 'r') as r:
1349 for line in r:
1350 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001351
1352 out_files = []
1353
1354 # Generate the Android.bp file.
1355 out_files.append(args.output + '.swp')
1356 with open(out_files[-1], 'w') as f:
1357 f.write('\n'.join(output))
1358 # Text files should have a trailing EOL.
1359 f.write('\n')
1360
Patrick Rohr94693eb2022-10-25 10:09:16 -07001361 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001362
1363
1364if __name__ == '__main__':
1365 sys.exit(main())