blob: db2691d12b18b7f09a456044de8b34d1fbd436c4 [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
87# Name of the module which settings such as compiler flags for all other
88# modules.
89defaults_module = module_prefix + 'defaults'
90
91# Location of the project in the Android source tree.
Patrick Rohr76ceeb52022-11-07 14:18:58 -080092tree_path = 'external/chromium_org'
Patrick Rohr92d74122022-10-21 15:50:52 -070093
94# Path for the protobuf sources in the standalone build.
95buildtools_protobuf_src = '//buildtools/protobuf/src'
96
97# Location of the protobuf src dir in the Android source tree.
98android_protobuf_src = 'external/protobuf/src'
99
100# Compiler flags which are passed through to the blueprint.
101cflag_allowlist = r'^-DPERFETTO.*$'
102
Patrick Rohr92d74122022-10-21 15:50:52 -0700103# Additional arguments to apply to Android.bp rules.
104additional_args = {
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800105 # TODO: remove if not needed.
Patrick Rohr92d74122022-10-21 15:50:52 -0700106}
107
108
109def enable_gtest_and_gmock(module):
110 module.static_libs.add('libgmock')
111 module.static_libs.add('libgtest')
112 if module.name != 'perfetto_gtest_logcat_printer':
113 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
114
115
116def enable_protobuf_full(module):
117 if module.type == 'cc_binary_host':
118 module.static_libs.add('libprotobuf-cpp-full')
119 elif module.host_supported:
120 module.host.static_libs.add('libprotobuf-cpp-full')
121 module.android.shared_libs.add('libprotobuf-cpp-full')
122 else:
123 module.shared_libs.add('libprotobuf-cpp-full')
124
125
126def enable_protobuf_lite(module):
127 module.shared_libs.add('libprotobuf-cpp-lite')
128
129
130def enable_protoc_lib(module):
131 if module.type == 'cc_binary_host':
132 module.static_libs.add('libprotoc')
133 else:
134 module.shared_libs.add('libprotoc')
135
136
137def enable_libunwindstack(module):
138 if module.name != 'heapprofd_standalone_client':
139 module.shared_libs.add('libunwindstack')
140 module.shared_libs.add('libprocinfo')
141 module.shared_libs.add('libbase')
142 else:
143 module.static_libs.add('libunwindstack')
144 module.static_libs.add('libprocinfo')
145 module.static_libs.add('libbase')
146 module.static_libs.add('liblzma')
147 module.static_libs.add('libdexfile_support')
148 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
149
150
151def enable_libunwind(module):
152 # libunwind is disabled on Darwin so we cannot depend on it.
153 pass
154
155
156def enable_sqlite(module):
157 if module.type == 'cc_binary_host':
158 module.static_libs.add('libsqlite')
159 module.static_libs.add('sqlite_ext_percentile')
160 elif module.host_supported:
161 # Copy what the sqlite3 command line tool does.
162 module.android.shared_libs.add('libsqlite')
163 module.android.shared_libs.add('libicu')
164 module.android.shared_libs.add('liblog')
165 module.android.shared_libs.add('libutils')
166 module.android.static_libs.add('sqlite_ext_percentile')
167 module.host.static_libs.add('libsqlite')
168 module.host.static_libs.add('sqlite_ext_percentile')
169 else:
170 module.shared_libs.add('libsqlite')
171 module.shared_libs.add('libicu')
172 module.shared_libs.add('liblog')
173 module.shared_libs.add('libutils')
174 module.static_libs.add('sqlite_ext_percentile')
175
176
177def enable_zlib(module):
178 if module.type == 'cc_binary_host':
179 module.static_libs.add('libz')
180 elif module.host_supported:
181 module.android.shared_libs.add('libz')
182 module.host.static_libs.add('libz')
183 else:
184 module.shared_libs.add('libz')
185
186
187def enable_uapi_headers(module):
188 module.include_dirs.add('bionic/libc/kernel')
189
190
191def enable_bionic_libc_platform_headers_on_android(module):
192 module.header_libs.add('bionic_libc_platform_headers')
193
194
195# Android equivalents for third-party libraries that the upstream project
196# depends on.
197builtin_deps = {
198 '//gn:default_deps':
199 lambda x: None,
200 '//gn:gtest_main':
201 lambda x: None,
202 '//gn:protoc':
203 lambda x: None,
204 '//gn:gtest_and_gmock':
205 enable_gtest_and_gmock,
206 '//gn:libunwind':
207 enable_libunwind,
208 '//gn:protobuf_full':
209 enable_protobuf_full,
210 '//gn:protobuf_lite':
211 enable_protobuf_lite,
212 '//gn:protoc_lib':
213 enable_protoc_lib,
214 '//gn:libunwindstack':
215 enable_libunwindstack,
216 '//gn:sqlite':
217 enable_sqlite,
218 '//gn:zlib':
219 enable_zlib,
220 '//gn:bionic_kernel_uapi_headers':
221 enable_uapi_headers,
222 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
223 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900224 '//third_party/protobuf:protoc':
225 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700226}
227
228# ----------------------------------------------------------------------------
229# End of configuration.
230# ----------------------------------------------------------------------------
231
232
233class Error(Exception):
234 pass
235
236
237class ThrowingArgumentParser(argparse.ArgumentParser):
238
239 def __init__(self, context):
240 super(ThrowingArgumentParser, self).__init__()
241 self.context = context
242
243 def error(self, message):
244 raise Error('%s: %s' % (self.context, message))
245
246
247def write_blueprint_key_value(output, name, value, sort=True):
248 """Writes a Blueprint key-value pair to the output"""
249
250 if isinstance(value, bool):
251 if value:
252 output.append(' %s: true,' % name)
253 else:
254 output.append(' %s: false,' % name)
255 return
256 if not value:
257 return
258 if isinstance(value, set):
259 value = sorted(value)
260 if isinstance(value, list):
261 output.append(' %s: [' % name)
262 for item in sorted(value) if sort else value:
263 output.append(' "%s",' % item)
264 output.append(' ],')
265 return
266 if isinstance(value, Target):
267 value.to_string(output)
268 return
269 if isinstance(value, dict):
270 kv_output = []
271 for k, v in value.items():
272 write_blueprint_key_value(kv_output, k, v)
273
274 output.append(' %s: {' % name)
275 for line in kv_output:
276 output.append(' %s' % line)
277 output.append(' },')
278 return
279 output.append(' %s: "%s",' % (name, value))
280
281
282class Target(object):
283 """A target-scoped part of a module"""
284
285 def __init__(self, name):
286 self.name = name
287 self.shared_libs = set()
288 self.static_libs = set()
289 self.whole_static_libs = set()
290 self.cflags = set()
291 self.dist = dict()
292 self.strip = dict()
293 self.stl = None
294
295 def to_string(self, output):
296 nested_out = []
297 self._output_field(nested_out, 'shared_libs')
298 self._output_field(nested_out, 'static_libs')
299 self._output_field(nested_out, 'whole_static_libs')
300 self._output_field(nested_out, 'cflags')
301 self._output_field(nested_out, 'stl')
302 self._output_field(nested_out, 'dist')
303 self._output_field(nested_out, 'strip')
304
305 if nested_out:
306 output.append(' %s: {' % self.name)
307 for line in nested_out:
308 output.append(' %s' % line)
309 output.append(' },')
310
311 def _output_field(self, output, name, sort=True):
312 value = getattr(self, name)
313 return write_blueprint_key_value(output, name, value, sort)
314
315
316class Module(object):
317 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
318
319 def __init__(self, mod_type, name, gn_target):
320 self.type = mod_type
321 self.gn_target = gn_target
322 self.name = name
323 self.srcs = set()
324 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
325 self.shared_libs = set()
326 self.static_libs = set()
327 self.whole_static_libs = set()
328 self.runtime_libs = set()
329 self.tools = set()
330 self.cmd = None
331 self.host_supported = False
332 self.vendor_available = False
333 self.init_rc = set()
334 self.out = set()
335 self.export_include_dirs = set()
336 self.generated_headers = set()
337 self.export_generated_headers = set()
338 self.defaults = set()
339 self.cflags = set()
340 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900341 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700342 self.header_libs = set()
343 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700344 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700345 self.android = Target('android')
346 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700347 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700348 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700349 self.dist = dict()
350 self.strip = dict()
351 self.data = set()
352 self.apex_available = set()
353 self.min_sdk_version = None
354 self.proto = dict()
355 # The genrule_XXX below are properties that must to be propagated back
356 # on the module(s) that depend on the genrule.
357 self.genrule_headers = set()
358 self.genrule_srcs = set()
359 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700360 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700361 self.version_script = None
362 self.test_suites = set()
363 self.test_config = None
364 self.stubs = {}
365
366 def to_string(self, output):
367 if self.comment:
368 output.append('// %s' % self.comment)
369 output.append('%s {' % self.type)
370 self._output_field(output, 'name')
371 self._output_field(output, 'srcs')
372 self._output_field(output, 'shared_libs')
373 self._output_field(output, 'static_libs')
374 self._output_field(output, 'whole_static_libs')
375 self._output_field(output, 'runtime_libs')
376 self._output_field(output, 'tools')
377 self._output_field(output, 'cmd', sort=False)
378 if self.host_supported:
379 self._output_field(output, 'host_supported')
380 if self.vendor_available:
381 self._output_field(output, 'vendor_available')
382 self._output_field(output, 'init_rc')
383 self._output_field(output, 'out')
384 self._output_field(output, 'export_include_dirs')
385 self._output_field(output, 'generated_headers')
386 self._output_field(output, 'export_generated_headers')
387 self._output_field(output, 'defaults')
388 self._output_field(output, 'cflags')
389 self._output_field(output, 'include_dirs')
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900390 self._output_field(output, 'local_include_dirs', sort=False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700391 self._output_field(output, 'header_libs')
392 self._output_field(output, 'required')
393 self._output_field(output, 'dist')
394 self._output_field(output, 'strip')
395 self._output_field(output, 'tool_files')
396 self._output_field(output, 'data')
397 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700398 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700399 self._output_field(output, 'apex_available')
400 self._output_field(output, 'min_sdk_version')
401 self._output_field(output, 'version_script')
402 self._output_field(output, 'test_suites')
403 self._output_field(output, 'test_config')
404 self._output_field(output, 'stubs')
405 self._output_field(output, 'proto')
406
407 target_out = []
408 self._output_field(target_out, 'android')
409 self._output_field(target_out, 'host')
410 if target_out:
411 output.append(' target: {')
412 for line in target_out:
413 output.append(' %s' % line)
414 output.append(' },')
415
Patrick Rohr92d74122022-10-21 15:50:52 -0700416 output.append('}')
417 output.append('')
418
419 def add_android_static_lib(self, lib):
420 if self.type == 'cc_binary_host':
421 raise Exception('Adding Android static lib for host tool is unsupported')
422 elif self.host_supported:
423 self.android.static_libs.add(lib)
424 else:
425 self.static_libs.add(lib)
426
427 def add_android_shared_lib(self, lib):
428 if self.type == 'cc_binary_host':
429 raise Exception('Adding Android shared lib for host tool is unsupported')
430 elif self.host_supported:
431 self.android.shared_libs.add(lib)
432 else:
433 self.shared_libs.add(lib)
434
435 def _output_field(self, output, name, sort=True):
436 value = getattr(self, name)
437 return write_blueprint_key_value(output, name, value, sort)
438
439
440class Blueprint(object):
441 """In-memory representation of an Android.bp file."""
442
443 def __init__(self):
444 self.modules = {}
445
446 def add_module(self, module):
447 """Adds a new module to the blueprint, replacing any existing module
448 with the same name.
449
450 Args:
451 module: Module instance.
452 """
453 self.modules[module.name] = module
454
455 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700456 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700457 m.to_string(output)
458
459
460def label_to_module_name(label):
461 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
462 # If the label is explicibly listed in the default target list, don't prefix
463 # its name and return just the target name. This is so tools like
464 # "traceconv" stay as such in the Android tree.
465 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700466 module = re.sub(r'^//:?', '', label_without_toolchain)
467 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
468 if not module.startswith(module_prefix):
469 return module_prefix + module
470 return module
471
472
473def is_supported_source_file(name):
474 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrd604f9f2022-10-27 13:56:42 -0700475 return os.path.splitext(name)[1] in ['.c', '.cc', '.java', '.proto']
Patrick Rohr92d74122022-10-21 15:50:52 -0700476
477
478def create_proto_modules(blueprint, gn, target):
479 """Generate genrules for a proto GN target.
480
481 GN actions are used to dynamically generate files during the build. The
482 Soong equivalent is a genrule. This function turns a specific kind of
483 genrule which turns .proto files into source and header files into a pair
484 equivalent genrules.
485
486 Args:
487 blueprint: Blueprint instance which is being generated.
488 target: gn_utils.Target object.
489
490 Returns:
491 The source_genrule module.
492 """
493 assert (target.type == 'proto_library')
494
495 tools = {'aprotoc'}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900496 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700497 target_module_name = label_to_module_name(target.name)
498
499 # In GN builds the proto path is always relative to the output directory
500 # (out/tmp.xxx).
Motomu Utsumie8457452022-11-08 18:47:51 +0900501 cmd = ['$(location aprotoc)']
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900502 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700503
504 if buildtools_protobuf_src in target.proto_paths:
505 cmd += ['--proto_path=%s' % android_protobuf_src]
506
507 # We don't generate any targets for source_set proto modules because
508 # they will be inlined into other modules if required.
509 if target.proto_plugin == 'source_set':
510 return None
511
512 # Descriptor targets only generate a single target.
513 if target.proto_plugin == 'descriptor':
514 out = '{}.bin'.format(target_module_name)
515
516 cmd += ['--descriptor_set_out=$(out)']
517 cmd += ['$(in)']
518
519 descriptor_module = Module('genrule', target_module_name, target.name)
520 descriptor_module.cmd = ' '.join(cmd)
521 descriptor_module.out = [out]
522 descriptor_module.tools = tools
523 blueprint.add_module(descriptor_module)
524
525 # Recursively extract the .proto files of all the dependencies and
526 # add them to srcs.
527 descriptor_module.srcs.update(
528 gn_utils.label_to_path(src) for src in target.sources)
529 for dep in target.transitive_proto_deps:
530 current_target = gn.get_target(dep)
531 descriptor_module.srcs.update(
532 gn_utils.label_to_path(src) for src in current_target.sources)
533
534 return descriptor_module
535
536 # We create two genrules for each proto target: one for the headers and
537 # another for the sources. This is because the module that depends on the
538 # generated files needs to declare two different types of dependencies --
539 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
540 # valid to generate .h files from a source dependency and vice versa.
541 source_module_name = target_module_name + '_gen'
542 source_module = Module('genrule', source_module_name, target.name)
543 blueprint.add_module(source_module)
544 source_module.srcs.update(
545 gn_utils.label_to_path(src) for src in target.sources)
546
547 header_module = Module('genrule', source_module_name + '_headers',
548 target.name)
549 blueprint.add_module(header_module)
550 header_module.srcs = set(source_module.srcs)
551
552 # TODO(primiano): at some point we should remove this. This was introduced
553 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
554 # avoid doing multi-repo changes and allow old clients in the android tree
555 # to still do the old #include "perfetto/..." rather than
556 # #include "protos/perfetto/...".
557 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800558 # Since the .cc file and .h get created by a different gerule target, they
559 # are not put in the same intermediate path, so local includes do not work
560 # without explictily exporting the include dir.
561 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700562
563 source_module.genrule_srcs.add(':' + source_module.name)
564 source_module.genrule_headers.add(header_module.name)
565
566 if target.proto_plugin == 'proto':
567 suffixes = ['pb']
568 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
569 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
570 elif target.proto_plugin == 'protozero':
571 suffixes = ['pbzero']
572 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
573 tools.add(plugin.name)
574 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
575 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
576 elif target.proto_plugin == 'cppgen':
577 suffixes = ['gen']
578 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
579 tools.add(plugin.name)
580 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
581 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
582 elif target.proto_plugin == 'ipc':
583 suffixes = ['ipc']
584 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
585 tools.add(plugin.name)
586 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
587 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
588 else:
589 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
590
591 cmd += ['$(in)']
592 source_module.cmd = ' '.join(cmd)
593 header_module.cmd = source_module.cmd
594 source_module.tools = tools
595 header_module.tools = tools
596
597 for sfx in suffixes:
598 source_module.out.update('%s/%s' %
599 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
600 for src in source_module.srcs)
601 header_module.out.update('%s/%s' %
602 (tree_path, src.replace('.proto', '.%s.h' % sfx))
603 for src in header_module.srcs)
604 return source_module
605
606
607def create_amalgamated_sql_metrics_module(blueprint, target):
608 bp_module_name = label_to_module_name(target.name)
609 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700610 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700611 module.cmd = ' '.join([
612 '$(location tools/gen_amalgamated_sql_metrics.py)',
613 '--cpp_out=$(out)',
614 '$(in)',
615 ])
616 module.genrule_headers.add(module.name)
617 module.out.update(target.outputs)
618 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
619 blueprint.add_module(module)
620 return module
621
622
623def create_cc_proto_descriptor_module(blueprint, target):
624 bp_module_name = label_to_module_name(target.name)
625 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700626 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700627 module.cmd = ' '.join([
628 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
629 '--cpp_out=$(out)', '$(in)'
630 ])
631 module.genrule_headers.add(module.name)
632 module.srcs.update(
633 ':' + label_to_module_name(dep) for dep in target.proto_deps)
634 module.srcs.update(
635 gn_utils.label_to_path(src)
636 for src in target.inputs
637 if "tmp.gn_utils" not in src)
638 module.out.update(target.outputs)
639 blueprint.add_module(module)
640 return module
641
642
643def create_gen_version_module(blueprint, target, bp_module_name):
644 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
645 script_path = gn_utils.label_to_path(target.script)
646 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700647 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700648 module.out.update(target.outputs)
649 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
650 module.cmd = ' '.join([
651 'python3 $(location %s)' % script_path, '--no_git',
652 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
653 ])
654 blueprint.add_module(module)
655 return module
656
657
658def create_proto_group_modules(blueprint, gn, module_name, target_names):
659 # TODO(lalitm): today, we're only adding a Java lite module because that's
660 # the only one used in practice. In the future, if we need other target types
661 # (e.g. C++, Java full etc.) add them here.
662 bp_module_name = label_to_module_name(module_name) + '_java_protos'
663 module = Module('java_library', bp_module_name, bp_module_name)
664 module.comment = f'''GN: [{', '.join(target_names)}]'''
665 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
666
667 for name in target_names:
668 target = gn.get_target(name)
669 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
670 for dep_label in target.transitive_proto_deps:
671 dep = gn.get_target(dep_label)
672 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
673
674 blueprint.add_module(module)
675
Motomu Utsumia6c33152022-11-02 18:21:55 +0900676# HACK: Need to support build_cofig_gen flexibly instead of hardcoding
677# build_config_gen generates srcjar by executing gcc via gcc_preprocess.py but gcc is not
678# available in genrule sandbox. Also gcc path is not configurable.
679# Under the //net:net, gcc_preprocess.py is only used for build_config_gen.
680# So, for now, hardcoding BuildConfig.java and generates srcjar by soong_zip.
681def override_build_config_gen(module):
682 module.tool_files.clear()
683 module.tools.add("soong_zip")
684 cmd = [
685 "echo",
686 "\\\"package org.chromium.build;\\n",
687 "public class BuildConfig {\\n",
688 "public static boolean IS_MULTIDEX_ENABLED ;\\n",
689 "public static boolean ENABLE_ASSERTS = true;\\n",
690 "public static boolean IS_UBSAN ;\\n",
691 "public static boolean IS_CHROME_BRANDED ;\\n",
692 "public static int R_STRING_PRODUCT_VERSION ;\\n",
693 "public static int MIN_SDK_VERSION = 1;\\n",
694 "public static boolean BUNDLES_SUPPORTED ;\\n",
695 "public static boolean IS_INCREMENTAL_INSTALL ;\\n",
696 "public static boolean ISOLATED_SPLITS_ENABLED ;\\n",
697 "public static boolean IS_FOR_TEST ;\\n",
698 "}\\n\\\"",
699 "> $(genDir)/BuildConfig.java &&",
700 "$(location soong_zip) -o $(out) -srcjar -f $(genDir)/BuildConfig.java"
701 ]
702 NEWLINE = ' " +\n "'
703 module.cmd = NEWLINE.join(cmd)
704 return module
705
Mohannad Farragbab6c892022-11-02 14:09:46 +0000706def create_action_foreach_modules(blueprint, target):
707 """ The following assumes that rebase_path exists in the args.
708 The args of an action_foreach contains hints about which output files are generated
709 by which source files.
710 This is copied directly from the args
711 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
712 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
713 """
714 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900715 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000716 # don't add script arg for the first source -- create_action_module
717 # already does this.
718 if i != 0:
719 new_args.append('&& python3 $(location %s)' %
720 gn_utils.label_to_path(target.script))
721 for arg in target.args:
722 if '{{source}}' in arg:
723 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
724 elif '{{source_name_part}}' in arg:
725 source_name_part = src.split("/")[-1] # Get the file name only
726 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
727 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
728 # file_name represent the output file name. But we need the whole path
729 # This can be found from target.outputs.
730 for out in target.outputs:
731 if out.endswith(file_name):
732 new_args.append('$(location %s)' % out)
733 else:
734 new_args.append(arg)
735
736 target.args = new_args
737 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900738
Patrick Rohr7be99032022-10-31 11:54:19 -0700739def create_action_module(blueprint, target):
740 bp_module_name = label_to_module_name(target.name)
741 module = Module('genrule', bp_module_name, target.name)
742
Patrick Rohr9b99a982022-10-28 11:00:57 -0700743 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
744 # TODO: we may want to only do this for python scripts arguments. If argparse
745 # is used, this transformation is safe.
746 target.args = [str for it in target.args for str in it.split('=')]
747
Motomu Utsumibf569d42022-10-28 16:47:34 +0900748 if target.script == "//build/write_buildflag_header.py":
749 # write_buildflag_header.py writes result to args.genDir/args.output
750 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700751 for i, val in enumerate(target.args):
752 if val == '--gen-dir':
753 target.args[i + 1] = '.'
Patrick Rohrfa972402022-11-01 11:54:35 -0700754 elif val == '--output':
755 target.args[i + 1] = '$(out)'
756
757 elif target.script == '//build/write_build_date_header.py':
758 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700759
Patrick Rohr8acccca2022-10-28 10:39:06 -0700760 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohrc5cc21a2022-10-31 11:57:49 -0700761 # chromium builds against a prebuilt ndk that contains the jni_headers, so
762 # a dependency is never explicitly created.
763 module.genrule_header_libs.add('jni_headers')
Patrick Rohr131ba282022-10-31 16:36:20 -0700764 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700765 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900766 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700767 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
768 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700769 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700770 # --input_file supports both .class specifiers or source files as arguments.
771 # Only source files need to be wrapped inside a $(location <label>) tag.
772 if re.match('.*\.class$', target.args[i + 1]):
773 continue
774 # replace --input_file ../../... with --input_file $(location ...)
775 # TODO: put inside function
776 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
777 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700778 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700779 # delete all leading ../
780 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700781 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700782 # this is not needed for aosp builds.
783 target.args[i] = ''
784 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700785 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700786 # delete leading ../../ and add path to javap
787 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
788 target.args[i + 1] = '$(location %s)' % filename
789 needs_javap = True
790
791 if needs_javap:
792 target.args.append('--javap')
793 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700794 # fix target.output directory to match #include statements.
795 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700796
Patrick Rohr245df582022-11-01 16:59:45 -0700797 elif target.script == '//build/android/gyp/write_build_config.py':
798 for i, val in enumerate(target.args):
799 if val == '--depfile':
800 # Depfile is not used, so no need to generate it.
801 target.args[i] = ''
802 target.args[i + 1] = ''
803 elif val in ['--deps-configs', '--bundled-srcjars']:
804 args = target.args[i + 1]
805 if args == '[]':
806 continue
807 # strip surrounding [] and split by ", "
808 args = args.strip('[]').split(', ')
809 # strip surrounding ""
810 args = [arg.strip('"') for arg in args]
811 # remove leading gen/
812 args = [re.sub('^gen/', '', arg) for arg in args]
813 # wrap filename in \"$(location filename)\"
814 args = ['\"$(location %s)\"' % arg for arg in args]
815 # join args with ", " and wrap in []
816 target.args[i + 1] = '[%s]' % ', '.join(args)
817
818 elif val == '--public-deps-configs':
819 # TODO: implement.
820 pass
821
822 elif val == '--build-config':
823 # json output of this script
824 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
825
826 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
827 '--device-jar-path', '--host-jar-path']:
828 # jar path can be within sources (../../) or output generated by
829 # another genrule (obj/)
830 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
831 filename = re.sub('^obj/', '', target.args[i + 1])
832 target.args[i + 1] = '$(location %s)' % filename
833
834 elif val == '--proguard-configs':
835 args = target.args[i + 1]
836 if args == '[]':
837 continue
838 # TODO: consider adding helpers to deal with argument lists
839 # strip surrounding [] and split by ", ", then strip surrounding ""
840 args = args.strip('[]').split(', ')
841 args = [arg.strip('"') for arg in args]
842 # remove leading ../../
843 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
844 # add dependency on proguard config file, so a $(location) wrapper can be used.
845 module.tool_files.update(args)
846 # wrap filename in \"$(location filename)\"
847 args = ['$(location %s)' % arg for arg in args]
848 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900849 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
850 for i, val in enumerate(target.args):
851 if val == '--output':
852 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900853 elif target.script == "//tools/grit/stamp_grit_sources.py":
854 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
855 # Directory that contains grit scripts
856 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
857 # Path to the stamp file
858 target.args[1] = '$(out)'
859 # Script tries to create args[2] file but this is not in the output.
860 # Specifying file under $(genDir) so that parent directory exists.
861 # If this file is used by other module, we may need to add this file to the outputs.
862 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000863 elif target.script == "//tools/grit/grit.py":
864 for i, val in enumerate(target.args):
865 if val == '-i':
866 # Delete leading ../..
867 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
868 target.args[i + 1] = '$(location %s)' % filename
869 elif val == '-o':
870 filename = re.sub('^gen/', '', target.args[i + 1])
871 if filename == "net":
872 # This is a directory not a file
873 target.args[i + 1] = '$(genDir)/net'
874 else:
875 # This is an output fil
876 target.args[i + 1] = '$(location %s)' % filename
877 elif val == '--depfile':
878 # The depfile is replaced by adding /tools/**/*.py to the tools_files
879 # This is basically just globbing all the needed sources by hardcoding.
880 module.tool_files.update([
881 "tools/grit/**/*.py",
882 "third_party/six/src/six.py" # This is not picked up by default. Must be added
883 ])
884
885 # Delete the depfile argument
886 target.args[i] = ' '
887 target.args[i + 1] = ' '
888 elif val == '--input':
889 # Delete leading ../..
890 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
891 # This is an output file so use $(location %s)
892 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohr245df582022-11-01 16:59:45 -0700893
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700894 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700895 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700896
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700897 # Handle passing parameters via response file by piping them into the script
898 # and reading them from /dev/stdin.
899 response_file = '{{response_file_name}}'
900 use_response_file = response_file in target.args
901 if use_response_file:
902 # Replace {{response_file_contents}} with /dev/stdin
903 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
904
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700905 # escape " and \$ in target.args.
906 # once all actions are properly implemented, this may not be necessary anymore.
907 # TODO: is this the right place to do this?
908 target.args = [arg.replace('"', r'\"') for arg in target.args]
909 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
910
Patrick Rohr9b99a982022-10-28 11:00:57 -0700911 # put all args on a new line for better diffs.
912 NEWLINE = ' " +\n "'
913 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700914 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700915
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700916 if use_response_file:
917 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700918 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700919
Patrick Rohr67f4d432022-10-26 16:04:15 -0700920 if all(os.path.splitext(it)[1] == '.h' for it in target.outputs):
921 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700922
Patrick Rohr0db9f852022-10-27 13:49:57 -0700923 # gn treats inputs and sources for actions equally.
924 # soong only supports source files inside srcs, non-source files are added as
925 # tool_files dependency.
926 for it in target.sources or target.inputs:
927 if is_supported_source_file(it):
928 module.srcs.add(gn_utils.label_to_path(it))
929 else:
930 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700931
Patrick Rohr15a2c302022-10-26 15:08:57 -0700932 # Actions using template "action_with_pydeps" also put script inside inputs.
933 # TODO: it might make sense to filter inputs inside GnParser.
934 if script in module.srcs:
935 module.srcs.remove(script)
936
Patrick Rohre1a853e2022-10-26 12:31:39 -0700937 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900938
939 if target.name == "//build/android:build_config_gen":
940 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900941 elif target.script == "//tools/grit/stamp_grit_sources.py":
942 # stamp_grit_sources.py is not executable
943 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000944 elif target.script == "//base/android/jni_generator/jni_generator.py":
945 # android_jar.classes should be part of the tools as it list implicit classes
946 # for the script to generate JNI headers.
947 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumia6c33152022-11-02 18:21:55 +0900948
Patrick Rohre1a853e2022-10-26 12:31:39 -0700949 blueprint.add_module(module)
950 return module
951
952
Patrick Rohr92d74122022-10-21 15:50:52 -0700953
954def _get_cflags(target):
955 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900956 # Consider proper allowlist or denylist if needed
957 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700958 return cflags
959
960
961def create_modules_from_target(blueprint, gn, gn_target_name):
962 """Generate module(s) for a given GN target.
963
964 Given a GN target name, generate one or more corresponding modules into a
965 blueprint. The only case when this generates >1 module is proto libraries.
966
967 Args:
968 blueprint: Blueprint instance which is being generated.
969 gn: gn_utils.GnParser object.
970 gn_target_name: GN target for module generation.
971 """
972 bp_module_name = label_to_module_name(gn_target_name)
973 if bp_module_name in blueprint.modules:
974 return blueprint.modules[bp_module_name]
975 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -0700976 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -0700977
978 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
979 if target.type == 'executable':
980 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
981 module_type = 'cc_binary_host'
982 elif target.testonly:
983 module_type = 'cc_test'
984 else:
985 module_type = 'cc_binary'
986 module = Module(module_type, bp_module_name, gn_target_name)
987 elif target.type == 'static_library':
988 module = Module('cc_library_static', bp_module_name, gn_target_name)
989 elif target.type == 'shared_library':
990 module = Module('cc_library_shared', bp_module_name, gn_target_name)
991 elif target.type == 'source_set':
992 module = Module('filegroup', bp_module_name, gn_target_name)
993 elif target.type == 'group':
994 # "group" targets are resolved recursively by gn_utils.get_target().
995 # There's nothing we need to do at this level for them.
996 return None
997 elif target.type == 'proto_library':
998 module = create_proto_modules(blueprint, gn, target)
999 if module is None:
1000 return None
1001 elif target.type == 'action':
1002 if 'gen_amalgamated_sql_metrics' in target.name:
1003 module = create_amalgamated_sql_metrics_module(blueprint, target)
1004 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1005 module = create_cc_proto_descriptor_module(blueprint, target)
1006 elif target.type == 'action' and \
1007 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1008 module = create_gen_version_module(blueprint, target, bp_module_name)
1009 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001010 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001011 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001012 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001013 elif target.type == 'copy':
1014 # TODO: careful now! copy targets are not supported yet, but this will stop
1015 # traversing the dependency tree. For //base:base, this is not a big
1016 # problem as libicu contains the only copy target which happens to be a
1017 # leaf node.
1018 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001019 else:
1020 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1021
1022 blueprint.add_module(module)
1023 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001024 module.init_rc = target_initrc.get(target.name, [])
1025 module.srcs.update(
1026 gn_utils.label_to_path(src)
1027 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001028 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001029
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001030 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001031 if target.type in gn_utils.LINKER_UNIT_TYPES:
1032 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001033 # TODO: implement proper cflag parsing.
1034 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001035 if '-std=' in flag:
1036 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001037 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001038 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001039
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001040 # Adding local_include_dirs is necessary due to source_sets / filegroups
1041 # which do not properly propagate include directories.
1042 # Filter any directory inside //out as a) this directory does not exist for
1043 # aosp / soong builds and b) the include directory should already be
1044 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001045 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001046 for d in target.include_dirs
1047 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001048 module.local_include_dirs = sorted(list(local_include_dirs_set))
1049
1050 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1051 # in //base:base needs to have sysroot include after icu/source/common
1052 # include. So adding sysroot include at the end.
1053 for flag in target.cflags:
1054 if '--sysroot' in flag:
1055 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001056
1057 module_is_compiled = module.type not in ('genrule', 'filegroup')
1058 if module_is_compiled:
1059 # Don't try to inject library/source dependencies into genrules or
1060 # filegroups because they are not compiled in the traditional sense.
1061 module.defaults = [defaults_module]
1062 for lib in target.libs:
1063 # Generally library names should be mangled as 'libXXX', unless they
1064 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1065 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1066 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1067 else 'lib' + lib
1068 if lib in shared_library_allowlist:
1069 module.add_android_shared_lib(android_lib)
1070 if lib in static_library_allowlist:
1071 module.add_android_static_lib(android_lib)
1072
1073 # If the module is a static library, export all the generated headers.
1074 if module.type == 'cc_library_static':
1075 module.export_generated_headers = module.generated_headers
1076
Patrick Rohr92d74122022-10-21 15:50:52 -07001077 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001078 # Currently, only one module is generated from target even target has multiple toolchains.
1079 # And module is generated based on the first visited target.
1080 # Sort deps before iteration to make result deterministic.
1081 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001082 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001083 # |builtin_deps| override GN deps with Android-specific ones. See the
1084 # config in the top of this file.
1085 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1086 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1087 continue
1088
Patrick Rohr92d74122022-10-21 15:50:52 -07001089 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1090
Motomu Utsumie246feb2022-11-01 17:25:56 +09001091 # TODO: Proper dependency check for genrule.
1092 # Currently, only propagating genrule dependencies.
1093 # Also, currently, all the dependencies are propagated upwards.
1094 # in gn, public_deps should be propagated but deps should not.
1095 # Not sure this information is available in the desc.json.
1096 # Following rule works for adding android_runtime_jni_headers to base:base.
1097 # If this doesn't work for other target, hardcoding for specific target
1098 # might be better.
1099 if module.type == "genrule" and dep_module.type == "genrule":
1100 module.genrule_headers.add(dep_module.name)
1101 module.genrule_headers.update(dep_module.genrule_headers)
1102
Patrick Rohr92d74122022-10-21 15:50:52 -07001103 # For filegroups and genrule, recurse but don't apply the deps.
1104 if not module_is_compiled:
1105 continue
1106
Patrick Rohr92d74122022-10-21 15:50:52 -07001107 if dep_module is None:
1108 continue
1109 if dep_module.type == 'cc_library_shared':
1110 module.shared_libs.add(dep_module.name)
1111 elif dep_module.type == 'cc_library_static':
1112 module.static_libs.add(dep_module.name)
1113 elif dep_module.type == 'filegroup':
1114 module.srcs.add(':' + dep_module.name)
1115 elif dep_module.type == 'genrule':
1116 module.generated_headers.update(dep_module.genrule_headers)
1117 module.srcs.update(dep_module.genrule_srcs)
1118 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001119 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001120 elif dep_module.type == 'cc_binary':
1121 continue # Ignore executables deps (used by cmdline integration tests).
1122 else:
1123 raise Error('Unknown dep %s (%s) for target %s' %
1124 (dep_module.name, dep_module.type, module.name))
1125
1126 return module
1127
Patrick Rohrb18aca22022-11-04 15:07:32 -07001128def create_java_module(blueprint, gn):
1129 bp_module_name = module_prefix + 'java'
1130 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001131 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001132 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001133
1134def create_blueprint_for_targets(gn, desc, targets):
1135 """Generate a blueprint for a list of GN targets."""
1136 blueprint = Blueprint()
1137
1138 # Default settings used by all modules.
1139 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001140 defaults.cflags = [
1141 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001142 '-Wno-non-virtual-dtor',
Patrick Rohr98065152022-10-31 14:49:58 -07001143 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001144 '-Wno-sign-compare',
1145 '-Wno-sign-promo',
1146 '-Wno-unused-parameter',
1147 '-fvisibility=hidden',
1148 '-O2',
1149 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001150 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001151 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001152
Patrick Rohr92d74122022-10-21 15:50:52 -07001153 for target in targets:
1154 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001155
1156 create_java_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001157
1158 # Merge in additional hardcoded arguments.
1159 for module in blueprint.modules.values():
1160 for key, add_val in additional_args.get(module.name, []):
1161 curr = getattr(module, key)
1162 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1163 curr.update(add_val)
1164 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1165 setattr(module, key, add_val)
1166 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1167 setattr(module, key, add_val)
1168 elif isinstance(add_val, dict) and isinstance(curr, dict):
1169 curr.update(add_val)
1170 elif isinstance(add_val, dict) and isinstance(curr, Target):
1171 curr.__dict__.update(add_val)
1172 else:
1173 raise Error('Unimplemented type %r of additional_args: %r' %
1174 (type(add_val), key))
1175
Patrick Rohr92d74122022-10-21 15:50:52 -07001176 return blueprint
1177
1178
1179def main():
1180 parser = argparse.ArgumentParser(
1181 description='Generate Android.bp from a GN description.')
1182 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001183 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001184 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1185 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001186 )
1187 parser.add_argument(
1188 '--extras',
1189 help='Extra targets to include at the end of the Blueprint file',
1190 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1191 )
1192 parser.add_argument(
1193 '--output',
1194 help='Blueprint file to create',
1195 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1196 )
1197 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001198 '-v',
1199 '--verbose',
1200 help='Print debug logs.',
1201 action='store_true',
1202 )
1203 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001204 'targets',
1205 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001206 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1207 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001208 args = parser.parse_args()
1209
Patrick Rohr16228942022-10-26 14:00:26 -07001210 if args.verbose:
1211 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1212
Patrick Rohr3db246a2022-10-25 10:25:17 -07001213 with open(args.desc) as f:
1214 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001215
1216 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001217 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001218 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1219 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1220
Patrick Rohr92d74122022-10-21 15:50:52 -07001221 # Add any proto groups to the blueprint.
1222 for l_name, t_names in proto_groups.items():
1223 create_proto_group_modules(blueprint, gn, l_name, t_names)
1224
1225 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001226 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001227//
1228// Licensed under the Apache License, Version 2.0 (the "License");
1229// you may not use this file except in compliance with the License.
1230// You may obtain a copy of the License at
1231//
1232// http://www.apache.org/licenses/LICENSE-2.0
1233//
1234// Unless required by applicable law or agreed to in writing, software
1235// distributed under the License is distributed on an "AS IS" BASIS,
1236// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1237// See the License for the specific language governing permissions and
1238// limitations under the License.
1239//
1240// This file is automatically generated by %s. Do not edit.
1241""" % (tool_name)
1242 ]
1243 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001244 if os.path.exists(args.extras):
1245 with open(args.extras, 'r') as r:
1246 for line in r:
1247 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001248
1249 out_files = []
1250
1251 # Generate the Android.bp file.
1252 out_files.append(args.output + '.swp')
1253 with open(out_files[-1], 'w') as f:
1254 f.write('\n'.join(output))
1255 # Text files should have a trailing EOL.
1256 f.write('\n')
1257
Patrick Rohr94693eb2022-10-25 10:09:16 -07001258 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001259
1260
1261if __name__ == '__main__':
1262 sys.exit(main())