blob: 11577374c31246777226f64e3cbd8354766467ef [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
Patrick Rohr8344c8b92022-11-08 19:25:39 -0800116def remove_local_protobuf_include(module):
117 # remove all third_party/protobuf includes as they conflict with libprotobuf
118 # in Android.
119 module.local_include_dirs = [it for it in module.local_include_dirs
120 if not it.startswith('third_party/protobuf')]
121
122
Patrick Rohr92d74122022-10-21 15:50:52 -0700123def enable_protobuf_full(module):
Patrick Rohr8344c8b92022-11-08 19:25:39 -0800124 remove_local_protobuf_include(module)
Patrick Rohr92d74122022-10-21 15:50:52 -0700125 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 Rohr8344c8b92022-11-08 19:25:39 -0800135 remove_local_protobuf_include(module)
Patrick Rohr84b16402022-11-08 19:01:01 -0800136 if module.type not in ['genrule', 'filegroup']:
137 module.shared_libs.add('libprotobuf-cpp-lite')
Patrick Rohr92d74122022-10-21 15:50:52 -0700138
139
140def enable_protoc_lib(module):
Patrick Rohr8344c8b92022-11-08 19:25:39 -0800141 remove_local_protobuf_include(module)
Patrick Rohr92d74122022-10-21 15:50:52 -0700142 if module.type == 'cc_binary_host':
143 module.static_libs.add('libprotoc')
144 else:
145 module.shared_libs.add('libprotoc')
146
147
148def enable_libunwindstack(module):
149 if module.name != 'heapprofd_standalone_client':
150 module.shared_libs.add('libunwindstack')
151 module.shared_libs.add('libprocinfo')
152 module.shared_libs.add('libbase')
153 else:
154 module.static_libs.add('libunwindstack')
155 module.static_libs.add('libprocinfo')
156 module.static_libs.add('libbase')
157 module.static_libs.add('liblzma')
158 module.static_libs.add('libdexfile_support')
159 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
160
161
162def enable_libunwind(module):
163 # libunwind is disabled on Darwin so we cannot depend on it.
164 pass
165
166
167def enable_sqlite(module):
168 if module.type == 'cc_binary_host':
169 module.static_libs.add('libsqlite')
170 module.static_libs.add('sqlite_ext_percentile')
171 elif module.host_supported:
172 # Copy what the sqlite3 command line tool does.
173 module.android.shared_libs.add('libsqlite')
174 module.android.shared_libs.add('libicu')
175 module.android.shared_libs.add('liblog')
176 module.android.shared_libs.add('libutils')
177 module.android.static_libs.add('sqlite_ext_percentile')
178 module.host.static_libs.add('libsqlite')
179 module.host.static_libs.add('sqlite_ext_percentile')
180 else:
181 module.shared_libs.add('libsqlite')
182 module.shared_libs.add('libicu')
183 module.shared_libs.add('liblog')
184 module.shared_libs.add('libutils')
185 module.static_libs.add('sqlite_ext_percentile')
186
187
188def enable_zlib(module):
189 if module.type == 'cc_binary_host':
190 module.static_libs.add('libz')
191 elif module.host_supported:
192 module.android.shared_libs.add('libz')
193 module.host.static_libs.add('libz')
194 else:
195 module.shared_libs.add('libz')
196
197
198def enable_uapi_headers(module):
199 module.include_dirs.add('bionic/libc/kernel')
200
201
202def enable_bionic_libc_platform_headers_on_android(module):
203 module.header_libs.add('bionic_libc_platform_headers')
204
205
206# Android equivalents for third-party libraries that the upstream project
207# depends on.
208builtin_deps = {
209 '//gn:default_deps':
210 lambda x: None,
211 '//gn:gtest_main':
212 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700213 '//gn:gtest_and_gmock':
214 enable_gtest_and_gmock,
215 '//gn:libunwind':
216 enable_libunwind,
Patrick Rohr92d74122022-10-21 15:50:52 -0700217 '//gn:libunwindstack':
218 enable_libunwindstack,
219 '//gn:sqlite':
220 enable_sqlite,
221 '//gn:zlib':
222 enable_zlib,
223 '//gn:bionic_kernel_uapi_headers':
224 enable_uapi_headers,
225 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
226 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900227 '//third_party/protobuf:protoc':
228 lambda x: None,
Patrick Rohr84b16402022-11-08 19:01:01 -0800229 '//third_party/protobuf:protobuf_full':
230 enable_protobuf_full,
231 '//third_party/protobuf:protobuf_lite':
232 enable_protobuf_lite,
233 '//third_party/protobuf:protoc_lib':
234 enable_protoc_lib,
Patrick Rohr92d74122022-10-21 15:50:52 -0700235}
236
237# ----------------------------------------------------------------------------
238# End of configuration.
239# ----------------------------------------------------------------------------
240
241
242class Error(Exception):
243 pass
244
245
246class ThrowingArgumentParser(argparse.ArgumentParser):
247
248 def __init__(self, context):
249 super(ThrowingArgumentParser, self).__init__()
250 self.context = context
251
252 def error(self, message):
253 raise Error('%s: %s' % (self.context, message))
254
255
256def write_blueprint_key_value(output, name, value, sort=True):
257 """Writes a Blueprint key-value pair to the output"""
258
259 if isinstance(value, bool):
260 if value:
261 output.append(' %s: true,' % name)
262 else:
263 output.append(' %s: false,' % name)
264 return
265 if not value:
266 return
267 if isinstance(value, set):
268 value = sorted(value)
269 if isinstance(value, list):
270 output.append(' %s: [' % name)
271 for item in sorted(value) if sort else value:
272 output.append(' "%s",' % item)
273 output.append(' ],')
274 return
275 if isinstance(value, Target):
276 value.to_string(output)
277 return
278 if isinstance(value, dict):
279 kv_output = []
280 for k, v in value.items():
281 write_blueprint_key_value(kv_output, k, v)
282
283 output.append(' %s: {' % name)
284 for line in kv_output:
285 output.append(' %s' % line)
286 output.append(' },')
287 return
288 output.append(' %s: "%s",' % (name, value))
289
290
291class Target(object):
292 """A target-scoped part of a module"""
293
294 def __init__(self, name):
295 self.name = name
296 self.shared_libs = set()
297 self.static_libs = set()
298 self.whole_static_libs = set()
299 self.cflags = set()
300 self.dist = dict()
301 self.strip = dict()
302 self.stl = None
303
304 def to_string(self, output):
305 nested_out = []
306 self._output_field(nested_out, 'shared_libs')
307 self._output_field(nested_out, 'static_libs')
308 self._output_field(nested_out, 'whole_static_libs')
309 self._output_field(nested_out, 'cflags')
310 self._output_field(nested_out, 'stl')
311 self._output_field(nested_out, 'dist')
312 self._output_field(nested_out, 'strip')
313
314 if nested_out:
315 output.append(' %s: {' % self.name)
316 for line in nested_out:
317 output.append(' %s' % line)
318 output.append(' },')
319
320 def _output_field(self, output, name, sort=True):
321 value = getattr(self, name)
322 return write_blueprint_key_value(output, name, value, sort)
323
324
325class Module(object):
326 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
327
328 def __init__(self, mod_type, name, gn_target):
329 self.type = mod_type
330 self.gn_target = gn_target
331 self.name = name
332 self.srcs = set()
333 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
334 self.shared_libs = set()
335 self.static_libs = set()
336 self.whole_static_libs = set()
337 self.runtime_libs = set()
338 self.tools = set()
339 self.cmd = None
340 self.host_supported = False
341 self.vendor_available = False
342 self.init_rc = set()
343 self.out = set()
344 self.export_include_dirs = set()
345 self.generated_headers = set()
346 self.export_generated_headers = set()
347 self.defaults = set()
348 self.cflags = set()
349 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900350 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700351 self.header_libs = set()
352 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700353 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700354 self.android = Target('android')
355 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700356 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700357 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700358 self.dist = dict()
359 self.strip = dict()
360 self.data = set()
361 self.apex_available = set()
362 self.min_sdk_version = None
363 self.proto = dict()
364 # The genrule_XXX below are properties that must to be propagated back
365 # on the module(s) that depend on the genrule.
366 self.genrule_headers = set()
367 self.genrule_srcs = set()
368 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700369 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700370 self.version_script = None
371 self.test_suites = set()
372 self.test_config = None
373 self.stubs = {}
374
375 def to_string(self, output):
376 if self.comment:
377 output.append('// %s' % self.comment)
378 output.append('%s {' % self.type)
379 self._output_field(output, 'name')
380 self._output_field(output, 'srcs')
381 self._output_field(output, 'shared_libs')
382 self._output_field(output, 'static_libs')
383 self._output_field(output, 'whole_static_libs')
384 self._output_field(output, 'runtime_libs')
385 self._output_field(output, 'tools')
386 self._output_field(output, 'cmd', sort=False)
387 if self.host_supported:
388 self._output_field(output, 'host_supported')
389 if self.vendor_available:
390 self._output_field(output, 'vendor_available')
391 self._output_field(output, 'init_rc')
392 self._output_field(output, 'out')
393 self._output_field(output, 'export_include_dirs')
394 self._output_field(output, 'generated_headers')
395 self._output_field(output, 'export_generated_headers')
396 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
1105 # If the module is a static library, export all the generated headers.
1106 if module.type == 'cc_library_static':
1107 module.export_generated_headers = module.generated_headers
1108
Patrick Rohr92d74122022-10-21 15:50:52 -07001109 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001110 # Currently, only one module is generated from target even target has multiple toolchains.
1111 # And module is generated based on the first visited target.
1112 # Sort deps before iteration to make result deterministic.
1113 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001114 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001115 # |builtin_deps| override GN deps with Android-specific ones. See the
1116 # config in the top of this file.
1117 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1118 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1119 continue
1120
Patrick Rohr92d74122022-10-21 15:50:52 -07001121 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1122
Motomu Utsumie246feb2022-11-01 17:25:56 +09001123 # TODO: Proper dependency check for genrule.
1124 # Currently, only propagating genrule dependencies.
1125 # Also, currently, all the dependencies are propagated upwards.
1126 # in gn, public_deps should be propagated but deps should not.
1127 # Not sure this information is available in the desc.json.
1128 # Following rule works for adding android_runtime_jni_headers to base:base.
1129 # If this doesn't work for other target, hardcoding for specific target
1130 # might be better.
1131 if module.type == "genrule" and dep_module.type == "genrule":
1132 module.genrule_headers.add(dep_module.name)
1133 module.genrule_headers.update(dep_module.genrule_headers)
1134
Patrick Rohr92d74122022-10-21 15:50:52 -07001135 # For filegroups and genrule, recurse but don't apply the deps.
1136 if not module_is_compiled:
1137 continue
1138
Patrick Rohr92d74122022-10-21 15:50:52 -07001139 if dep_module is None:
1140 continue
1141 if dep_module.type == 'cc_library_shared':
1142 module.shared_libs.add(dep_module.name)
1143 elif dep_module.type == 'cc_library_static':
1144 module.static_libs.add(dep_module.name)
1145 elif dep_module.type == 'filegroup':
1146 module.srcs.add(':' + dep_module.name)
1147 elif dep_module.type == 'genrule':
1148 module.generated_headers.update(dep_module.genrule_headers)
1149 module.srcs.update(dep_module.genrule_srcs)
1150 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001151 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001152 elif dep_module.type == 'cc_binary':
1153 continue # Ignore executables deps (used by cmdline integration tests).
1154 else:
1155 raise Error('Unknown dep %s (%s) for target %s' %
1156 (dep_module.name, dep_module.type, module.name))
1157
1158 return module
1159
Patrick Rohrb18aca22022-11-04 15:07:32 -07001160def create_java_module(blueprint, gn):
1161 bp_module_name = module_prefix + 'java'
1162 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001163 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001164 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001165
1166def create_blueprint_for_targets(gn, desc, targets):
1167 """Generate a blueprint for a list of GN targets."""
1168 blueprint = Blueprint()
1169
1170 # Default settings used by all modules.
1171 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001172 defaults.cflags = [
1173 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001174 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001175 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001176 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001177 '-Wno-sign-compare',
1178 '-Wno-sign-promo',
1179 '-Wno-unused-parameter',
1180 '-fvisibility=hidden',
1181 '-O2',
1182 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001183 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001184 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001185
Patrick Rohr92d74122022-10-21 15:50:52 -07001186 for target in targets:
1187 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001188
1189 create_java_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001190
1191 # Merge in additional hardcoded arguments.
1192 for module in blueprint.modules.values():
1193 for key, add_val in additional_args.get(module.name, []):
1194 curr = getattr(module, key)
1195 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1196 curr.update(add_val)
1197 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1198 setattr(module, key, add_val)
1199 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1200 setattr(module, key, add_val)
1201 elif isinstance(add_val, dict) and isinstance(curr, dict):
1202 curr.update(add_val)
1203 elif isinstance(add_val, dict) and isinstance(curr, Target):
1204 curr.__dict__.update(add_val)
1205 else:
1206 raise Error('Unimplemented type %r of additional_args: %r' %
1207 (type(add_val), key))
1208
Patrick Rohr92d74122022-10-21 15:50:52 -07001209 return blueprint
1210
1211
1212def main():
1213 parser = argparse.ArgumentParser(
1214 description='Generate Android.bp from a GN description.')
1215 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001216 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001217 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1218 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001219 )
1220 parser.add_argument(
1221 '--extras',
1222 help='Extra targets to include at the end of the Blueprint file',
1223 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1224 )
1225 parser.add_argument(
1226 '--output',
1227 help='Blueprint file to create',
1228 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1229 )
1230 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001231 '-v',
1232 '--verbose',
1233 help='Print debug logs.',
1234 action='store_true',
1235 )
1236 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001237 'targets',
1238 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001239 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1240 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001241 args = parser.parse_args()
1242
Patrick Rohr16228942022-10-26 14:00:26 -07001243 if args.verbose:
1244 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1245
Patrick Rohr3db246a2022-10-25 10:25:17 -07001246 with open(args.desc) as f:
1247 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001248
1249 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001250 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001251 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1252 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1253
Patrick Rohr92d74122022-10-21 15:50:52 -07001254 # Add any proto groups to the blueprint.
1255 for l_name, t_names in proto_groups.items():
1256 create_proto_group_modules(blueprint, gn, l_name, t_names)
1257
1258 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001259 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001260//
1261// Licensed under the Apache License, Version 2.0 (the "License");
1262// you may not use this file except in compliance with the License.
1263// You may obtain a copy of the License at
1264//
1265// http://www.apache.org/licenses/LICENSE-2.0
1266//
1267// Unless required by applicable law or agreed to in writing, software
1268// distributed under the License is distributed on an "AS IS" BASIS,
1269// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1270// See the License for the specific language governing permissions and
1271// limitations under the License.
1272//
1273// This file is automatically generated by %s. Do not edit.
1274""" % (tool_name)
1275 ]
1276 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001277 if os.path.exists(args.extras):
1278 with open(args.extras, 'r') as r:
1279 for line in r:
1280 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001281
1282 out_files = []
1283
1284 # Generate the Android.bp file.
1285 out_files.append(args.output + '.swp')
1286 with open(out_files[-1], 'w') as f:
1287 f.write('\n'.join(output))
1288 # Text files should have a trailing EOL.
1289 f.write('\n')
1290
Patrick Rohr94693eb2022-10-25 10:09:16 -07001291 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001292
1293
1294if __name__ == '__main__':
1295 sys.exit(main())