blob: 8237cdf4ef8afb48a45d68a83a18cbf1c9da26c6 [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': [
112 ('export_static_lib_headers', {'cronet_aml_net_third_party_quiche_quiche'}),
113 ]
Patrick Rohr92d74122022-10-21 15:50:52 -0700114}
115
116
117def enable_gtest_and_gmock(module):
118 module.static_libs.add('libgmock')
119 module.static_libs.add('libgtest')
120 if module.name != 'perfetto_gtest_logcat_printer':
121 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
122
123
124def enable_protobuf_full(module):
125 if module.type == 'cc_binary_host':
126 module.static_libs.add('libprotobuf-cpp-full')
127 elif module.host_supported:
128 module.host.static_libs.add('libprotobuf-cpp-full')
129 module.android.shared_libs.add('libprotobuf-cpp-full')
Patrick Rohr84b16402022-11-08 19:01:01 -0800130 elif module.type not in ['genrule', 'filegroup']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700131 module.shared_libs.add('libprotobuf-cpp-full')
132
133
134def enable_protobuf_lite(module):
Patrick Rohr84b16402022-11-08 19:01:01 -0800135 if module.type not in ['genrule', 'filegroup']:
136 module.shared_libs.add('libprotobuf-cpp-lite')
Patrick Rohr92d74122022-10-21 15:50:52 -0700137
138
139def enable_protoc_lib(module):
140 if module.type == 'cc_binary_host':
141 module.static_libs.add('libprotoc')
142 else:
143 module.shared_libs.add('libprotoc')
144
145
146def enable_libunwindstack(module):
147 if module.name != 'heapprofd_standalone_client':
148 module.shared_libs.add('libunwindstack')
149 module.shared_libs.add('libprocinfo')
150 module.shared_libs.add('libbase')
151 else:
152 module.static_libs.add('libunwindstack')
153 module.static_libs.add('libprocinfo')
154 module.static_libs.add('libbase')
155 module.static_libs.add('liblzma')
156 module.static_libs.add('libdexfile_support')
157 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
158
159
160def enable_libunwind(module):
161 # libunwind is disabled on Darwin so we cannot depend on it.
162 pass
163
164
165def enable_sqlite(module):
166 if module.type == 'cc_binary_host':
167 module.static_libs.add('libsqlite')
168 module.static_libs.add('sqlite_ext_percentile')
169 elif module.host_supported:
170 # Copy what the sqlite3 command line tool does.
171 module.android.shared_libs.add('libsqlite')
172 module.android.shared_libs.add('libicu')
173 module.android.shared_libs.add('liblog')
174 module.android.shared_libs.add('libutils')
175 module.android.static_libs.add('sqlite_ext_percentile')
176 module.host.static_libs.add('libsqlite')
177 module.host.static_libs.add('sqlite_ext_percentile')
178 else:
179 module.shared_libs.add('libsqlite')
180 module.shared_libs.add('libicu')
181 module.shared_libs.add('liblog')
182 module.shared_libs.add('libutils')
183 module.static_libs.add('sqlite_ext_percentile')
184
185
186def enable_zlib(module):
187 if module.type == 'cc_binary_host':
188 module.static_libs.add('libz')
189 elif module.host_supported:
190 module.android.shared_libs.add('libz')
191 module.host.static_libs.add('libz')
192 else:
193 module.shared_libs.add('libz')
194
195
196def enable_uapi_headers(module):
197 module.include_dirs.add('bionic/libc/kernel')
198
199
200def enable_bionic_libc_platform_headers_on_android(module):
201 module.header_libs.add('bionic_libc_platform_headers')
202
203
204# Android equivalents for third-party libraries that the upstream project
205# depends on.
206builtin_deps = {
207 '//gn:default_deps':
208 lambda x: None,
209 '//gn:gtest_main':
210 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700211 '//gn:gtest_and_gmock':
212 enable_gtest_and_gmock,
213 '//gn:libunwind':
214 enable_libunwind,
Patrick Rohr92d74122022-10-21 15:50:52 -0700215 '//gn:libunwindstack':
216 enable_libunwindstack,
217 '//gn:sqlite':
218 enable_sqlite,
219 '//gn:zlib':
220 enable_zlib,
221 '//gn:bionic_kernel_uapi_headers':
222 enable_uapi_headers,
223 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
224 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900225 '//third_party/protobuf:protoc':
226 lambda x: None,
Patrick Rohr84b16402022-11-08 19:01:01 -0800227 '//third_party/protobuf:protobuf_full':
228 enable_protobuf_full,
229 '//third_party/protobuf:protobuf_lite':
230 enable_protobuf_lite,
231 '//third_party/protobuf:protoc_lib':
232 enable_protoc_lib,
Patrick Rohr92d74122022-10-21 15:50:52 -0700233}
234
235# ----------------------------------------------------------------------------
236# End of configuration.
237# ----------------------------------------------------------------------------
238
239
240class Error(Exception):
241 pass
242
243
244class ThrowingArgumentParser(argparse.ArgumentParser):
245
246 def __init__(self, context):
247 super(ThrowingArgumentParser, self).__init__()
248 self.context = context
249
250 def error(self, message):
251 raise Error('%s: %s' % (self.context, message))
252
253
254def write_blueprint_key_value(output, name, value, sort=True):
255 """Writes a Blueprint key-value pair to the output"""
256
257 if isinstance(value, bool):
258 if value:
259 output.append(' %s: true,' % name)
260 else:
261 output.append(' %s: false,' % name)
262 return
263 if not value:
264 return
265 if isinstance(value, set):
266 value = sorted(value)
267 if isinstance(value, list):
268 output.append(' %s: [' % name)
269 for item in sorted(value) if sort else value:
270 output.append(' "%s",' % item)
271 output.append(' ],')
272 return
273 if isinstance(value, Target):
274 value.to_string(output)
275 return
276 if isinstance(value, dict):
277 kv_output = []
278 for k, v in value.items():
279 write_blueprint_key_value(kv_output, k, v)
280
281 output.append(' %s: {' % name)
282 for line in kv_output:
283 output.append(' %s' % line)
284 output.append(' },')
285 return
286 output.append(' %s: "%s",' % (name, value))
287
288
289class Target(object):
290 """A target-scoped part of a module"""
291
292 def __init__(self, name):
293 self.name = name
294 self.shared_libs = set()
295 self.static_libs = set()
296 self.whole_static_libs = set()
297 self.cflags = set()
298 self.dist = dict()
299 self.strip = dict()
300 self.stl = None
301
302 def to_string(self, output):
303 nested_out = []
304 self._output_field(nested_out, 'shared_libs')
305 self._output_field(nested_out, 'static_libs')
306 self._output_field(nested_out, 'whole_static_libs')
307 self._output_field(nested_out, 'cflags')
308 self._output_field(nested_out, 'stl')
309 self._output_field(nested_out, 'dist')
310 self._output_field(nested_out, 'strip')
311
312 if nested_out:
313 output.append(' %s: {' % self.name)
314 for line in nested_out:
315 output.append(' %s' % line)
316 output.append(' },')
317
318 def _output_field(self, output, name, sort=True):
319 value = getattr(self, name)
320 return write_blueprint_key_value(output, name, value, sort)
321
322
323class Module(object):
324 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
325
326 def __init__(self, mod_type, name, gn_target):
327 self.type = mod_type
328 self.gn_target = gn_target
329 self.name = name
330 self.srcs = set()
331 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
332 self.shared_libs = set()
333 self.static_libs = set()
334 self.whole_static_libs = set()
335 self.runtime_libs = set()
336 self.tools = set()
337 self.cmd = None
338 self.host_supported = False
339 self.vendor_available = False
340 self.init_rc = set()
341 self.out = set()
342 self.export_include_dirs = set()
343 self.generated_headers = set()
344 self.export_generated_headers = set()
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800345 self.export_static_lib_headers = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700346 self.defaults = set()
347 self.cflags = set()
348 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900349 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700350 self.header_libs = set()
351 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700352 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700353 self.android = Target('android')
354 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700355 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700356 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700357 self.dist = dict()
358 self.strip = dict()
359 self.data = set()
360 self.apex_available = set()
361 self.min_sdk_version = None
362 self.proto = dict()
363 # The genrule_XXX below are properties that must to be propagated back
364 # on the module(s) that depend on the genrule.
365 self.genrule_headers = set()
366 self.genrule_srcs = set()
367 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700368 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700369 self.version_script = None
370 self.test_suites = set()
371 self.test_config = None
372 self.stubs = {}
373
374 def to_string(self, output):
375 if self.comment:
376 output.append('// %s' % self.comment)
377 output.append('%s {' % self.type)
378 self._output_field(output, 'name')
379 self._output_field(output, 'srcs')
380 self._output_field(output, 'shared_libs')
381 self._output_field(output, 'static_libs')
382 self._output_field(output, 'whole_static_libs')
383 self._output_field(output, 'runtime_libs')
384 self._output_field(output, 'tools')
385 self._output_field(output, 'cmd', sort=False)
386 if self.host_supported:
387 self._output_field(output, 'host_supported')
388 if self.vendor_available:
389 self._output_field(output, 'vendor_available')
390 self._output_field(output, 'init_rc')
391 self._output_field(output, 'out')
392 self._output_field(output, 'export_include_dirs')
393 self._output_field(output, 'generated_headers')
394 self._output_field(output, 'export_generated_headers')
Patrick Rohrbb0956e2022-11-09 15:37:16 -0800395 self._output_field(output, 'export_static_lib_headers')
Patrick Rohr92d74122022-10-21 15:50:52 -0700396 self._output_field(output, 'defaults')
397 self._output_field(output, 'cflags')
398 self._output_field(output, 'include_dirs')
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900399 self._output_field(output, 'local_include_dirs', sort=False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700400 self._output_field(output, 'header_libs')
401 self._output_field(output, 'required')
402 self._output_field(output, 'dist')
403 self._output_field(output, 'strip')
404 self._output_field(output, 'tool_files')
405 self._output_field(output, 'data')
406 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700407 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700408 self._output_field(output, 'apex_available')
409 self._output_field(output, 'min_sdk_version')
410 self._output_field(output, 'version_script')
411 self._output_field(output, 'test_suites')
412 self._output_field(output, 'test_config')
413 self._output_field(output, 'stubs')
414 self._output_field(output, 'proto')
415
416 target_out = []
417 self._output_field(target_out, 'android')
418 self._output_field(target_out, 'host')
419 if target_out:
420 output.append(' target: {')
421 for line in target_out:
422 output.append(' %s' % line)
423 output.append(' },')
424
Patrick Rohr92d74122022-10-21 15:50:52 -0700425 output.append('}')
426 output.append('')
427
428 def add_android_static_lib(self, lib):
429 if self.type == 'cc_binary_host':
430 raise Exception('Adding Android static lib for host tool is unsupported')
431 elif self.host_supported:
432 self.android.static_libs.add(lib)
433 else:
434 self.static_libs.add(lib)
435
436 def add_android_shared_lib(self, lib):
437 if self.type == 'cc_binary_host':
438 raise Exception('Adding Android shared lib for host tool is unsupported')
439 elif self.host_supported:
440 self.android.shared_libs.add(lib)
441 else:
442 self.shared_libs.add(lib)
443
444 def _output_field(self, output, name, sort=True):
445 value = getattr(self, name)
446 return write_blueprint_key_value(output, name, value, sort)
447
448
449class Blueprint(object):
450 """In-memory representation of an Android.bp file."""
451
452 def __init__(self):
453 self.modules = {}
454
455 def add_module(self, module):
456 """Adds a new module to the blueprint, replacing any existing module
457 with the same name.
458
459 Args:
460 module: Module instance.
461 """
462 self.modules[module.name] = module
463
464 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700465 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700466 m.to_string(output)
467
468
469def label_to_module_name(label):
470 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
471 # If the label is explicibly listed in the default target list, don't prefix
472 # its name and return just the target name. This is so tools like
473 # "traceconv" stay as such in the Android tree.
474 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700475 module = re.sub(r'^//:?', '', label_without_toolchain)
476 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
477 if not module.startswith(module_prefix):
478 return module_prefix + module
479 return module
480
481
482def is_supported_source_file(name):
483 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrd604f9f2022-10-27 13:56:42 -0700484 return os.path.splitext(name)[1] in ['.c', '.cc', '.java', '.proto']
Patrick Rohr92d74122022-10-21 15:50:52 -0700485
486
487def create_proto_modules(blueprint, gn, target):
488 """Generate genrules for a proto GN target.
489
490 GN actions are used to dynamically generate files during the build. The
491 Soong equivalent is a genrule. This function turns a specific kind of
492 genrule which turns .proto files into source and header files into a pair
493 equivalent genrules.
494
495 Args:
496 blueprint: Blueprint instance which is being generated.
497 target: gn_utils.Target object.
498
499 Returns:
500 The source_genrule module.
501 """
502 assert (target.type == 'proto_library')
503
504 tools = {'aprotoc'}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900505 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700506 target_module_name = label_to_module_name(target.name)
507
508 # In GN builds the proto path is always relative to the output directory
509 # (out/tmp.xxx).
Motomu Utsumie8457452022-11-08 18:47:51 +0900510 cmd = ['$(location aprotoc)']
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900511 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700512
513 if buildtools_protobuf_src in target.proto_paths:
514 cmd += ['--proto_path=%s' % android_protobuf_src]
515
516 # We don't generate any targets for source_set proto modules because
517 # they will be inlined into other modules if required.
518 if target.proto_plugin == 'source_set':
519 return None
520
521 # Descriptor targets only generate a single target.
522 if target.proto_plugin == 'descriptor':
523 out = '{}.bin'.format(target_module_name)
524
525 cmd += ['--descriptor_set_out=$(out)']
526 cmd += ['$(in)']
527
528 descriptor_module = Module('genrule', target_module_name, target.name)
529 descriptor_module.cmd = ' '.join(cmd)
530 descriptor_module.out = [out]
531 descriptor_module.tools = tools
532 blueprint.add_module(descriptor_module)
533
534 # Recursively extract the .proto files of all the dependencies and
535 # add them to srcs.
536 descriptor_module.srcs.update(
537 gn_utils.label_to_path(src) for src in target.sources)
538 for dep in target.transitive_proto_deps:
539 current_target = gn.get_target(dep)
540 descriptor_module.srcs.update(
541 gn_utils.label_to_path(src) for src in current_target.sources)
542
543 return descriptor_module
544
545 # We create two genrules for each proto target: one for the headers and
546 # another for the sources. This is because the module that depends on the
547 # generated files needs to declare two different types of dependencies --
548 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
549 # valid to generate .h files from a source dependency and vice versa.
550 source_module_name = target_module_name + '_gen'
551 source_module = Module('genrule', source_module_name, target.name)
552 blueprint.add_module(source_module)
553 source_module.srcs.update(
554 gn_utils.label_to_path(src) for src in target.sources)
555
556 header_module = Module('genrule', source_module_name + '_headers',
557 target.name)
558 blueprint.add_module(header_module)
559 header_module.srcs = set(source_module.srcs)
560
561 # TODO(primiano): at some point we should remove this. This was introduced
562 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
563 # avoid doing multi-repo changes and allow old clients in the android tree
564 # to still do the old #include "perfetto/..." rather than
565 # #include "protos/perfetto/...".
566 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800567 # Since the .cc file and .h get created by a different gerule target, they
568 # are not put in the same intermediate path, so local includes do not work
569 # without explictily exporting the include dir.
570 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700571
572 source_module.genrule_srcs.add(':' + source_module.name)
573 source_module.genrule_headers.add(header_module.name)
574
575 if target.proto_plugin == 'proto':
576 suffixes = ['pb']
577 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
578 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
579 elif target.proto_plugin == 'protozero':
580 suffixes = ['pbzero']
581 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
582 tools.add(plugin.name)
583 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
584 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
585 elif target.proto_plugin == 'cppgen':
586 suffixes = ['gen']
587 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
588 tools.add(plugin.name)
589 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
590 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
591 elif target.proto_plugin == 'ipc':
592 suffixes = ['ipc']
593 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
594 tools.add(plugin.name)
595 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
596 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
597 else:
598 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
599
600 cmd += ['$(in)']
601 source_module.cmd = ' '.join(cmd)
602 header_module.cmd = source_module.cmd
603 source_module.tools = tools
604 header_module.tools = tools
605
606 for sfx in suffixes:
607 source_module.out.update('%s/%s' %
608 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
609 for src in source_module.srcs)
610 header_module.out.update('%s/%s' %
611 (tree_path, src.replace('.proto', '.%s.h' % sfx))
612 for src in header_module.srcs)
613 return source_module
614
615
616def create_amalgamated_sql_metrics_module(blueprint, target):
617 bp_module_name = label_to_module_name(target.name)
618 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700619 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700620 module.cmd = ' '.join([
621 '$(location tools/gen_amalgamated_sql_metrics.py)',
622 '--cpp_out=$(out)',
623 '$(in)',
624 ])
625 module.genrule_headers.add(module.name)
626 module.out.update(target.outputs)
627 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
628 blueprint.add_module(module)
629 return module
630
631
632def create_cc_proto_descriptor_module(blueprint, target):
633 bp_module_name = label_to_module_name(target.name)
634 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700635 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700636 module.cmd = ' '.join([
637 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
638 '--cpp_out=$(out)', '$(in)'
639 ])
640 module.genrule_headers.add(module.name)
641 module.srcs.update(
642 ':' + label_to_module_name(dep) for dep in target.proto_deps)
643 module.srcs.update(
644 gn_utils.label_to_path(src)
645 for src in target.inputs
646 if "tmp.gn_utils" not in src)
647 module.out.update(target.outputs)
648 blueprint.add_module(module)
649 return module
650
651
652def create_gen_version_module(blueprint, target, bp_module_name):
653 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
654 script_path = gn_utils.label_to_path(target.script)
655 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700656 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700657 module.out.update(target.outputs)
658 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
659 module.cmd = ' '.join([
660 'python3 $(location %s)' % script_path, '--no_git',
661 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
662 ])
663 blueprint.add_module(module)
664 return module
665
666
667def create_proto_group_modules(blueprint, gn, module_name, target_names):
668 # TODO(lalitm): today, we're only adding a Java lite module because that's
669 # the only one used in practice. In the future, if we need other target types
670 # (e.g. C++, Java full etc.) add them here.
671 bp_module_name = label_to_module_name(module_name) + '_java_protos'
672 module = Module('java_library', bp_module_name, bp_module_name)
673 module.comment = f'''GN: [{', '.join(target_names)}]'''
674 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
675
676 for name in target_names:
677 target = gn.get_target(name)
678 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
679 for dep_label in target.transitive_proto_deps:
680 dep = gn.get_target(dep_label)
681 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
682
683 blueprint.add_module(module)
684
Motomu Utsumia6c33152022-11-02 18:21:55 +0900685# HACK: Need to support build_cofig_gen flexibly instead of hardcoding
686# build_config_gen generates srcjar by executing gcc via gcc_preprocess.py but gcc is not
687# available in genrule sandbox. Also gcc path is not configurable.
688# Under the //net:net, gcc_preprocess.py is only used for build_config_gen.
689# So, for now, hardcoding BuildConfig.java and generates srcjar by soong_zip.
690def override_build_config_gen(module):
691 module.tool_files.clear()
692 module.tools.add("soong_zip")
693 cmd = [
694 "echo",
695 "\\\"package org.chromium.build;\\n",
696 "public class BuildConfig {\\n",
697 "public static boolean IS_MULTIDEX_ENABLED ;\\n",
698 "public static boolean ENABLE_ASSERTS = true;\\n",
699 "public static boolean IS_UBSAN ;\\n",
700 "public static boolean IS_CHROME_BRANDED ;\\n",
701 "public static int R_STRING_PRODUCT_VERSION ;\\n",
702 "public static int MIN_SDK_VERSION = 1;\\n",
703 "public static boolean BUNDLES_SUPPORTED ;\\n",
704 "public static boolean IS_INCREMENTAL_INSTALL ;\\n",
705 "public static boolean ISOLATED_SPLITS_ENABLED ;\\n",
706 "public static boolean IS_FOR_TEST ;\\n",
707 "}\\n\\\"",
708 "> $(genDir)/BuildConfig.java &&",
709 "$(location soong_zip) -o $(out) -srcjar -f $(genDir)/BuildConfig.java"
710 ]
711 NEWLINE = ' " +\n "'
712 module.cmd = NEWLINE.join(cmd)
713 return module
714
Mohannad Farragbab6c892022-11-02 14:09:46 +0000715def create_action_foreach_modules(blueprint, target):
716 """ The following assumes that rebase_path exists in the args.
717 The args of an action_foreach contains hints about which output files are generated
718 by which source files.
719 This is copied directly from the args
720 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
721 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
722 """
723 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900724 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000725 # don't add script arg for the first source -- create_action_module
726 # already does this.
727 if i != 0:
728 new_args.append('&& python3 $(location %s)' %
729 gn_utils.label_to_path(target.script))
730 for arg in target.args:
731 if '{{source}}' in arg:
732 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
733 elif '{{source_name_part}}' in arg:
734 source_name_part = src.split("/")[-1] # Get the file name only
735 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
736 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
737 # file_name represent the output file name. But we need the whole path
738 # This can be found from target.outputs.
739 for out in target.outputs:
740 if out.endswith(file_name):
741 new_args.append('$(location %s)' % out)
742 else:
743 new_args.append(arg)
744
745 target.args = new_args
746 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900747
Patrick Rohr7be99032022-10-31 11:54:19 -0700748def create_action_module(blueprint, target):
749 bp_module_name = label_to_module_name(target.name)
750 module = Module('genrule', bp_module_name, target.name)
751
Patrick Rohr9b99a982022-10-28 11:00:57 -0700752 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
753 # TODO: we may want to only do this for python scripts arguments. If argparse
754 # is used, this transformation is safe.
755 target.args = [str for it in target.args for str in it.split('=')]
756
Motomu Utsumibf569d42022-10-28 16:47:34 +0900757 if target.script == "//build/write_buildflag_header.py":
758 # write_buildflag_header.py writes result to args.genDir/args.output
759 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700760 for i, val in enumerate(target.args):
761 if val == '--gen-dir':
762 target.args[i + 1] = '.'
Patrick Rohrfa972402022-11-01 11:54:35 -0700763 elif val == '--output':
764 target.args[i + 1] = '$(out)'
765
766 elif target.script == '//build/write_build_date_header.py':
767 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700768
Patrick Rohr8acccca2022-10-28 10:39:06 -0700769 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohrc5cc21a2022-10-31 11:57:49 -0700770 # chromium builds against a prebuilt ndk that contains the jni_headers, so
771 # a dependency is never explicitly created.
772 module.genrule_header_libs.add('jni_headers')
Patrick Rohr131ba282022-10-31 16:36:20 -0700773 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700774 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900775 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700776 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
777 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700778 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700779 # --input_file supports both .class specifiers or source files as arguments.
780 # Only source files need to be wrapped inside a $(location <label>) tag.
781 if re.match('.*\.class$', target.args[i + 1]):
782 continue
783 # replace --input_file ../../... with --input_file $(location ...)
784 # TODO: put inside function
785 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
786 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700787 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700788 # delete all leading ../
789 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700790 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700791 # this is not needed for aosp builds.
792 target.args[i] = ''
793 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700794 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700795 # delete leading ../../ and add path to javap
796 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
797 target.args[i + 1] = '$(location %s)' % filename
798 needs_javap = True
799
800 if needs_javap:
801 target.args.append('--javap')
802 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700803 # fix target.output directory to match #include statements.
804 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700805
Patrick Rohrf6d2b612022-11-09 12:30:26 -0800806 elif target.script == '//base/android/jni_generator/jni_registration_generator.py':
807 # jni_registration_generator.py pulls in some config dependencies that we
808 # do not handle. Remove them.
809 # TODO: find a better way to do this.
810 target.deps.clear()
811
Patrick Rohr245df582022-11-01 16:59:45 -0700812 elif target.script == '//build/android/gyp/write_build_config.py':
813 for i, val in enumerate(target.args):
814 if val == '--depfile':
815 # Depfile is not used, so no need to generate it.
816 target.args[i] = ''
817 target.args[i + 1] = ''
818 elif val in ['--deps-configs', '--bundled-srcjars']:
819 args = target.args[i + 1]
820 if args == '[]':
821 continue
822 # strip surrounding [] and split by ", "
823 args = args.strip('[]').split(', ')
824 # strip surrounding ""
825 args = [arg.strip('"') for arg in args]
826 # remove leading gen/
827 args = [re.sub('^gen/', '', arg) for arg in args]
828 # wrap filename in \"$(location filename)\"
829 args = ['\"$(location %s)\"' % arg for arg in args]
830 # join args with ", " and wrap in []
831 target.args[i + 1] = '[%s]' % ', '.join(args)
832
833 elif val == '--public-deps-configs':
834 # TODO: implement.
835 pass
836
837 elif val == '--build-config':
838 # json output of this script
839 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
840
841 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
842 '--device-jar-path', '--host-jar-path']:
843 # jar path can be within sources (../../) or output generated by
844 # another genrule (obj/)
845 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
846 filename = re.sub('^obj/', '', target.args[i + 1])
847 target.args[i + 1] = '$(location %s)' % filename
848
849 elif val == '--proguard-configs':
850 args = target.args[i + 1]
851 if args == '[]':
852 continue
853 # TODO: consider adding helpers to deal with argument lists
854 # strip surrounding [] and split by ", ", then strip surrounding ""
855 args = args.strip('[]').split(', ')
856 args = [arg.strip('"') for arg in args]
857 # remove leading ../../
858 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
859 # add dependency on proguard config file, so a $(location) wrapper can be used.
860 module.tool_files.update(args)
861 # wrap filename in \"$(location filename)\"
862 args = ['$(location %s)' % arg for arg in args]
863 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900864 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
865 for i, val in enumerate(target.args):
866 if val == '--output':
867 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900868 elif target.script == "//tools/grit/stamp_grit_sources.py":
869 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
870 # Directory that contains grit scripts
871 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
872 # Path to the stamp file
873 target.args[1] = '$(out)'
874 # Script tries to create args[2] file but this is not in the output.
875 # Specifying file under $(genDir) so that parent directory exists.
876 # If this file is used by other module, we may need to add this file to the outputs.
877 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000878 elif target.script == "//tools/grit/grit.py":
879 for i, val in enumerate(target.args):
880 if val == '-i':
881 # Delete leading ../..
882 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
883 target.args[i + 1] = '$(location %s)' % filename
884 elif val == '-o':
885 filename = re.sub('^gen/', '', target.args[i + 1])
886 if filename == "net":
887 # This is a directory not a file
888 target.args[i + 1] = '$(genDir)/net'
889 else:
890 # This is an output fil
891 target.args[i + 1] = '$(location %s)' % filename
892 elif val == '--depfile':
893 # The depfile is replaced by adding /tools/**/*.py to the tools_files
894 # This is basically just globbing all the needed sources by hardcoding.
895 module.tool_files.update([
896 "tools/grit/**/*.py",
897 "third_party/six/src/six.py" # This is not picked up by default. Must be added
898 ])
899
900 # Delete the depfile argument
901 target.args[i] = ' '
902 target.args[i + 1] = ' '
903 elif val == '--input':
904 # Delete leading ../..
905 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
906 # This is an output file so use $(location %s)
907 target.args[i + 1] = '$(location %s)' % filename
Motomu Utsumia0cc6662022-11-09 15:22:27 +0900908 elif target.script == "//net/tools/dafsa/make_dafsa.py":
909 # This script generates .cc files but source (registry_controlled_domain.cc) in the target that
910 # depends on this target includes .cc file this script generates.
911 module.genrule_headers.add(module.name)
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900912 elif target.script == "//build/util/version.py":
Motomu Utsumib0a49e42022-11-09 18:12:27 +0900913 # android_chrome_version.py is not specified in anywhere but version.py imports this file
914 module.tool_files.add('build/util/android_chrome_version.py')
Motomu Utsumi847a6d32022-11-09 17:32:06 +0900915 for i, val in enumerate(target.args):
916 if val.startswith('../../'):
917 filename = re.sub('^\.\./\.\./', '', val)
918 target.args[i] = '$(location %s)' % filename
Motomu Utsumiee279c52022-11-09 17:46:27 +0900919 elif val == '-e':
920 # arg for -e EVAL option should be passed in -e PATCH_HI=int(PATCH)//256 format.
921 target.args[i + 1] = '%s=\'%s\'' % (target.args[i + 1], target.args[i + 2])
922 target.args[i + 2] = ''
Motomu Utsumi438f2c22022-11-09 18:16:40 +0900923 elif val == '-o':
924 target.args[i + 1] = '$(out)'
Patrick Rohr245df582022-11-01 16:59:45 -0700925
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700926 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700927 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700928
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700929 # Handle passing parameters via response file by piping them into the script
930 # and reading them from /dev/stdin.
931 response_file = '{{response_file_name}}'
932 use_response_file = response_file in target.args
933 if use_response_file:
934 # Replace {{response_file_contents}} with /dev/stdin
935 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
936
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700937 # escape " and \$ in target.args.
938 # once all actions are properly implemented, this may not be necessary anymore.
939 # TODO: is this the right place to do this?
940 target.args = [arg.replace('"', r'\"') for arg in target.args]
941 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
942
Patrick Rohr9b99a982022-10-28 11:00:57 -0700943 # put all args on a new line for better diffs.
944 NEWLINE = ' " +\n "'
945 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700946 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700947
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700948 if use_response_file:
949 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700950 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700951
Patrick Rohr67f4d432022-10-26 16:04:15 -0700952 if all(os.path.splitext(it)[1] == '.h' for it in target.outputs):
953 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700954
Patrick Rohr0db9f852022-10-27 13:49:57 -0700955 # gn treats inputs and sources for actions equally.
956 # soong only supports source files inside srcs, non-source files are added as
957 # tool_files dependency.
958 for it in target.sources or target.inputs:
959 if is_supported_source_file(it):
960 module.srcs.add(gn_utils.label_to_path(it))
961 else:
962 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700963
Patrick Rohr15a2c302022-10-26 15:08:57 -0700964 # Actions using template "action_with_pydeps" also put script inside inputs.
965 # TODO: it might make sense to filter inputs inside GnParser.
966 if script in module.srcs:
967 module.srcs.remove(script)
968
Patrick Rohre1a853e2022-10-26 12:31:39 -0700969 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900970
971 if target.name == "//build/android:build_config_gen":
972 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900973 elif target.script == "//tools/grit/stamp_grit_sources.py":
974 # stamp_grit_sources.py is not executable
975 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000976 elif target.script == "//base/android/jni_generator/jni_generator.py":
977 # android_jar.classes should be part of the tools as it list implicit classes
978 # for the script to generate JNI headers.
979 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumia6c33152022-11-02 18:21:55 +0900980
Patrick Rohre1a853e2022-10-26 12:31:39 -0700981 blueprint.add_module(module)
982 return module
983
984
Patrick Rohr92d74122022-10-21 15:50:52 -0700985
986def _get_cflags(target):
987 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900988 # Consider proper allowlist or denylist if needed
989 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700990 return cflags
991
992
993def create_modules_from_target(blueprint, gn, gn_target_name):
994 """Generate module(s) for a given GN target.
995
996 Given a GN target name, generate one or more corresponding modules into a
997 blueprint. The only case when this generates >1 module is proto libraries.
998
999 Args:
1000 blueprint: Blueprint instance which is being generated.
1001 gn: gn_utils.GnParser object.
1002 gn_target_name: GN target for module generation.
1003 """
1004 bp_module_name = label_to_module_name(gn_target_name)
1005 if bp_module_name in blueprint.modules:
1006 return blueprint.modules[bp_module_name]
1007 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -07001008 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -07001009
1010 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
1011 if target.type == 'executable':
1012 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
1013 module_type = 'cc_binary_host'
1014 elif target.testonly:
1015 module_type = 'cc_test'
1016 else:
1017 module_type = 'cc_binary'
1018 module = Module(module_type, bp_module_name, gn_target_name)
1019 elif target.type == 'static_library':
1020 module = Module('cc_library_static', bp_module_name, gn_target_name)
1021 elif target.type == 'shared_library':
1022 module = Module('cc_library_shared', bp_module_name, gn_target_name)
1023 elif target.type == 'source_set':
1024 module = Module('filegroup', bp_module_name, gn_target_name)
1025 elif target.type == 'group':
1026 # "group" targets are resolved recursively by gn_utils.get_target().
1027 # There's nothing we need to do at this level for them.
1028 return None
1029 elif target.type == 'proto_library':
1030 module = create_proto_modules(blueprint, gn, target)
1031 if module is None:
1032 return None
1033 elif target.type == 'action':
1034 if 'gen_amalgamated_sql_metrics' in target.name:
1035 module = create_amalgamated_sql_metrics_module(blueprint, target)
1036 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1037 module = create_cc_proto_descriptor_module(blueprint, target)
1038 elif target.type == 'action' and \
1039 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1040 module = create_gen_version_module(blueprint, target, bp_module_name)
1041 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001042 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001043 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001044 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001045 elif target.type == 'copy':
1046 # TODO: careful now! copy targets are not supported yet, but this will stop
1047 # traversing the dependency tree. For //base:base, this is not a big
1048 # problem as libicu contains the only copy target which happens to be a
1049 # leaf node.
1050 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001051 else:
1052 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1053
1054 blueprint.add_module(module)
1055 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001056 module.init_rc = target_initrc.get(target.name, [])
1057 module.srcs.update(
1058 gn_utils.label_to_path(src)
1059 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001060 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001061
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001062 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001063 if target.type in gn_utils.LINKER_UNIT_TYPES:
1064 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001065 # TODO: implement proper cflag parsing.
1066 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001067 if '-std=' in flag:
1068 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001069 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001070 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001071
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001072 # Adding local_include_dirs is necessary due to source_sets / filegroups
1073 # which do not properly propagate include directories.
1074 # Filter any directory inside //out as a) this directory does not exist for
1075 # aosp / soong builds and b) the include directory should already be
1076 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001077 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001078 for d in target.include_dirs
1079 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001080 module.local_include_dirs = sorted(list(local_include_dirs_set))
1081
1082 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1083 # in //base:base needs to have sysroot include after icu/source/common
1084 # include. So adding sysroot include at the end.
1085 for flag in target.cflags:
1086 if '--sysroot' in flag:
1087 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001088
1089 module_is_compiled = module.type not in ('genrule', 'filegroup')
1090 if module_is_compiled:
1091 # Don't try to inject library/source dependencies into genrules or
1092 # filegroups because they are not compiled in the traditional sense.
1093 module.defaults = [defaults_module]
1094 for lib in target.libs:
1095 # Generally library names should be mangled as 'libXXX', unless they
1096 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1097 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1098 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1099 else 'lib' + lib
1100 if lib in shared_library_allowlist:
1101 module.add_android_shared_lib(android_lib)
1102 if lib in static_library_allowlist:
1103 module.add_android_static_lib(android_lib)
1104
Patrick Rohrd9dd3b92022-11-09 16:15:30 -08001105 # Remove prohibited include directories
1106 module.local_include_dirs = [d for d in module.local_include_dirs
1107 if d not in local_include_dirs_denylist]
1108
1109
Patrick Rohr92d74122022-10-21 15:50:52 -07001110 # If the module is a static library, export all the generated headers.
1111 if module.type == 'cc_library_static':
1112 module.export_generated_headers = module.generated_headers
1113
Patrick Rohr92d74122022-10-21 15:50:52 -07001114 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001115 # Currently, only one module is generated from target even target has multiple toolchains.
1116 # And module is generated based on the first visited target.
1117 # Sort deps before iteration to make result deterministic.
1118 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001119 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001120 # |builtin_deps| override GN deps with Android-specific ones. See the
1121 # config in the top of this file.
1122 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1123 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1124 continue
1125
Patrick Rohr92d74122022-10-21 15:50:52 -07001126 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1127
Motomu Utsumie246feb2022-11-01 17:25:56 +09001128 # TODO: Proper dependency check for genrule.
1129 # Currently, only propagating genrule dependencies.
1130 # Also, currently, all the dependencies are propagated upwards.
1131 # in gn, public_deps should be propagated but deps should not.
1132 # Not sure this information is available in the desc.json.
1133 # Following rule works for adding android_runtime_jni_headers to base:base.
1134 # If this doesn't work for other target, hardcoding for specific target
1135 # might be better.
1136 if module.type == "genrule" and dep_module.type == "genrule":
1137 module.genrule_headers.add(dep_module.name)
1138 module.genrule_headers.update(dep_module.genrule_headers)
1139
Patrick Rohr92d74122022-10-21 15:50:52 -07001140 # For filegroups and genrule, recurse but don't apply the deps.
1141 if not module_is_compiled:
1142 continue
1143
Patrick Rohr92d74122022-10-21 15:50:52 -07001144 if dep_module is None:
1145 continue
1146 if dep_module.type == 'cc_library_shared':
1147 module.shared_libs.add(dep_module.name)
1148 elif dep_module.type == 'cc_library_static':
1149 module.static_libs.add(dep_module.name)
1150 elif dep_module.type == 'filegroup':
1151 module.srcs.add(':' + dep_module.name)
1152 elif dep_module.type == 'genrule':
1153 module.generated_headers.update(dep_module.genrule_headers)
1154 module.srcs.update(dep_module.genrule_srcs)
1155 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001156 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001157 elif dep_module.type == 'cc_binary':
1158 continue # Ignore executables deps (used by cmdline integration tests).
1159 else:
1160 raise Error('Unknown dep %s (%s) for target %s' %
1161 (dep_module.name, dep_module.type, module.name))
1162
1163 return module
1164
Patrick Rohrb18aca22022-11-04 15:07:32 -07001165def create_java_module(blueprint, gn):
1166 bp_module_name = module_prefix + 'java'
1167 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001168 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001169 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001170
1171def create_blueprint_for_targets(gn, desc, targets):
1172 """Generate a blueprint for a list of GN targets."""
1173 blueprint = Blueprint()
1174
1175 # Default settings used by all modules.
1176 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001177 defaults.cflags = [
1178 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001179 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001180 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001181 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001182 '-Wno-sign-compare',
1183 '-Wno-sign-promo',
1184 '-Wno-unused-parameter',
1185 '-fvisibility=hidden',
1186 '-O2',
1187 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001188 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001189 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001190
Patrick Rohr92d74122022-10-21 15:50:52 -07001191 for target in targets:
1192 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001193
1194 create_java_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001195
1196 # Merge in additional hardcoded arguments.
1197 for module in blueprint.modules.values():
1198 for key, add_val in additional_args.get(module.name, []):
1199 curr = getattr(module, key)
1200 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1201 curr.update(add_val)
1202 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1203 setattr(module, key, add_val)
1204 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1205 setattr(module, key, add_val)
1206 elif isinstance(add_val, dict) and isinstance(curr, dict):
1207 curr.update(add_val)
1208 elif isinstance(add_val, dict) and isinstance(curr, Target):
1209 curr.__dict__.update(add_val)
1210 else:
1211 raise Error('Unimplemented type %r of additional_args: %r' %
1212 (type(add_val), key))
1213
Patrick Rohr92d74122022-10-21 15:50:52 -07001214 return blueprint
1215
1216
1217def main():
1218 parser = argparse.ArgumentParser(
1219 description='Generate Android.bp from a GN description.')
1220 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001221 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001222 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1223 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001224 )
1225 parser.add_argument(
1226 '--extras',
1227 help='Extra targets to include at the end of the Blueprint file',
1228 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1229 )
1230 parser.add_argument(
1231 '--output',
1232 help='Blueprint file to create',
1233 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1234 )
1235 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001236 '-v',
1237 '--verbose',
1238 help='Print debug logs.',
1239 action='store_true',
1240 )
1241 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001242 'targets',
1243 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001244 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1245 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001246 args = parser.parse_args()
1247
Patrick Rohr16228942022-10-26 14:00:26 -07001248 if args.verbose:
1249 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1250
Patrick Rohr3db246a2022-10-25 10:25:17 -07001251 with open(args.desc) as f:
1252 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001253
1254 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001255 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001256 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1257 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1258
Patrick Rohr92d74122022-10-21 15:50:52 -07001259 # Add any proto groups to the blueprint.
1260 for l_name, t_names in proto_groups.items():
1261 create_proto_group_modules(blueprint, gn, l_name, t_names)
1262
1263 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001264 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001265//
1266// Licensed under the Apache License, Version 2.0 (the "License");
1267// you may not use this file except in compliance with the License.
1268// You may obtain a copy of the License at
1269//
1270// http://www.apache.org/licenses/LICENSE-2.0
1271//
1272// Unless required by applicable law or agreed to in writing, software
1273// distributed under the License is distributed on an "AS IS" BASIS,
1274// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1275// See the License for the specific language governing permissions and
1276// limitations under the License.
1277//
1278// This file is automatically generated by %s. Do not edit.
1279""" % (tool_name)
1280 ]
1281 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001282 if os.path.exists(args.extras):
1283 with open(args.extras, 'r') as r:
1284 for line in r:
1285 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001286
1287 out_files = []
1288
1289 # Generate the Android.bp file.
1290 out_files.append(args.output + '.swp')
1291 with open(out_files[-1], 'w') as f:
1292 f.write('\n'.join(output))
1293 # Text files should have a trailing EOL.
1294 f.write('\n')
1295
Patrick Rohr94693eb2022-10-25 10:09:16 -07001296 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001297
1298
1299if __name__ == '__main__':
1300 sys.exit(main())