blob: c14858b2c26064b02c05a583ace3ce815645e30c [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 Rohr245df582022-11-01 16:59:45 -0700806 elif target.script == '//build/android/gyp/write_build_config.py':
807 for i, val in enumerate(target.args):
808 if val == '--depfile':
809 # Depfile is not used, so no need to generate it.
810 target.args[i] = ''
811 target.args[i + 1] = ''
812 elif val in ['--deps-configs', '--bundled-srcjars']:
813 args = target.args[i + 1]
814 if args == '[]':
815 continue
816 # strip surrounding [] and split by ", "
817 args = args.strip('[]').split(', ')
818 # strip surrounding ""
819 args = [arg.strip('"') for arg in args]
820 # remove leading gen/
821 args = [re.sub('^gen/', '', arg) for arg in args]
822 # wrap filename in \"$(location filename)\"
823 args = ['\"$(location %s)\"' % arg for arg in args]
824 # join args with ", " and wrap in []
825 target.args[i + 1] = '[%s]' % ', '.join(args)
826
827 elif val == '--public-deps-configs':
828 # TODO: implement.
829 pass
830
831 elif val == '--build-config':
832 # json output of this script
833 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
834
835 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
836 '--device-jar-path', '--host-jar-path']:
837 # jar path can be within sources (../../) or output generated by
838 # another genrule (obj/)
839 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
840 filename = re.sub('^obj/', '', target.args[i + 1])
841 target.args[i + 1] = '$(location %s)' % filename
842
843 elif val == '--proguard-configs':
844 args = target.args[i + 1]
845 if args == '[]':
846 continue
847 # TODO: consider adding helpers to deal with argument lists
848 # strip surrounding [] and split by ", ", then strip surrounding ""
849 args = args.strip('[]').split(', ')
850 args = [arg.strip('"') for arg in args]
851 # remove leading ../../
852 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
853 # add dependency on proguard config file, so a $(location) wrapper can be used.
854 module.tool_files.update(args)
855 # wrap filename in \"$(location filename)\"
856 args = ['$(location %s)' % arg for arg in args]
857 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900858 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
859 for i, val in enumerate(target.args):
860 if val == '--output':
861 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900862 elif target.script == "//tools/grit/stamp_grit_sources.py":
863 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
864 # Directory that contains grit scripts
865 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
866 # Path to the stamp file
867 target.args[1] = '$(out)'
868 # Script tries to create args[2] file but this is not in the output.
869 # Specifying file under $(genDir) so that parent directory exists.
870 # If this file is used by other module, we may need to add this file to the outputs.
871 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000872 elif target.script == "//tools/grit/grit.py":
873 for i, val in enumerate(target.args):
874 if val == '-i':
875 # Delete leading ../..
876 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
877 target.args[i + 1] = '$(location %s)' % filename
878 elif val == '-o':
879 filename = re.sub('^gen/', '', target.args[i + 1])
880 if filename == "net":
881 # This is a directory not a file
882 target.args[i + 1] = '$(genDir)/net'
883 else:
884 # This is an output fil
885 target.args[i + 1] = '$(location %s)' % filename
886 elif val == '--depfile':
887 # The depfile is replaced by adding /tools/**/*.py to the tools_files
888 # This is basically just globbing all the needed sources by hardcoding.
889 module.tool_files.update([
890 "tools/grit/**/*.py",
891 "third_party/six/src/six.py" # This is not picked up by default. Must be added
892 ])
893
894 # Delete the depfile argument
895 target.args[i] = ' '
896 target.args[i + 1] = ' '
897 elif val == '--input':
898 # Delete leading ../..
899 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
900 # This is an output file so use $(location %s)
901 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohr245df582022-11-01 16:59:45 -0700902
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700903 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700904 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700905
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700906 # Handle passing parameters via response file by piping them into the script
907 # and reading them from /dev/stdin.
908 response_file = '{{response_file_name}}'
909 use_response_file = response_file in target.args
910 if use_response_file:
911 # Replace {{response_file_contents}} with /dev/stdin
912 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
913
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700914 # escape " and \$ in target.args.
915 # once all actions are properly implemented, this may not be necessary anymore.
916 # TODO: is this the right place to do this?
917 target.args = [arg.replace('"', r'\"') for arg in target.args]
918 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
919
Patrick Rohr9b99a982022-10-28 11:00:57 -0700920 # put all args on a new line for better diffs.
921 NEWLINE = ' " +\n "'
922 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700923 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700924
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700925 if use_response_file:
926 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700927 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700928
Patrick Rohr67f4d432022-10-26 16:04:15 -0700929 if all(os.path.splitext(it)[1] == '.h' for it in target.outputs):
930 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700931
Patrick Rohr0db9f852022-10-27 13:49:57 -0700932 # gn treats inputs and sources for actions equally.
933 # soong only supports source files inside srcs, non-source files are added as
934 # tool_files dependency.
935 for it in target.sources or target.inputs:
936 if is_supported_source_file(it):
937 module.srcs.add(gn_utils.label_to_path(it))
938 else:
939 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700940
Patrick Rohr15a2c302022-10-26 15:08:57 -0700941 # Actions using template "action_with_pydeps" also put script inside inputs.
942 # TODO: it might make sense to filter inputs inside GnParser.
943 if script in module.srcs:
944 module.srcs.remove(script)
945
Patrick Rohre1a853e2022-10-26 12:31:39 -0700946 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900947
948 if target.name == "//build/android:build_config_gen":
949 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900950 elif target.script == "//tools/grit/stamp_grit_sources.py":
951 # stamp_grit_sources.py is not executable
952 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000953 elif target.script == "//base/android/jni_generator/jni_generator.py":
954 # android_jar.classes should be part of the tools as it list implicit classes
955 # for the script to generate JNI headers.
956 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumia6c33152022-11-02 18:21:55 +0900957
Patrick Rohre1a853e2022-10-26 12:31:39 -0700958 blueprint.add_module(module)
959 return module
960
961
Patrick Rohr92d74122022-10-21 15:50:52 -0700962
963def _get_cflags(target):
964 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900965 # Consider proper allowlist or denylist if needed
966 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700967 return cflags
968
969
970def create_modules_from_target(blueprint, gn, gn_target_name):
971 """Generate module(s) for a given GN target.
972
973 Given a GN target name, generate one or more corresponding modules into a
974 blueprint. The only case when this generates >1 module is proto libraries.
975
976 Args:
977 blueprint: Blueprint instance which is being generated.
978 gn: gn_utils.GnParser object.
979 gn_target_name: GN target for module generation.
980 """
981 bp_module_name = label_to_module_name(gn_target_name)
982 if bp_module_name in blueprint.modules:
983 return blueprint.modules[bp_module_name]
984 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -0700985 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -0700986
987 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
988 if target.type == 'executable':
989 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
990 module_type = 'cc_binary_host'
991 elif target.testonly:
992 module_type = 'cc_test'
993 else:
994 module_type = 'cc_binary'
995 module = Module(module_type, bp_module_name, gn_target_name)
996 elif target.type == 'static_library':
997 module = Module('cc_library_static', bp_module_name, gn_target_name)
998 elif target.type == 'shared_library':
999 module = Module('cc_library_shared', bp_module_name, gn_target_name)
1000 elif target.type == 'source_set':
1001 module = Module('filegroup', bp_module_name, gn_target_name)
1002 elif target.type == 'group':
1003 # "group" targets are resolved recursively by gn_utils.get_target().
1004 # There's nothing we need to do at this level for them.
1005 return None
1006 elif target.type == 'proto_library':
1007 module = create_proto_modules(blueprint, gn, target)
1008 if module is None:
1009 return None
1010 elif target.type == 'action':
1011 if 'gen_amalgamated_sql_metrics' in target.name:
1012 module = create_amalgamated_sql_metrics_module(blueprint, target)
1013 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1014 module = create_cc_proto_descriptor_module(blueprint, target)
1015 elif target.type == 'action' and \
1016 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1017 module = create_gen_version_module(blueprint, target, bp_module_name)
1018 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001019 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001020 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001021 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001022 elif target.type == 'copy':
1023 # TODO: careful now! copy targets are not supported yet, but this will stop
1024 # traversing the dependency tree. For //base:base, this is not a big
1025 # problem as libicu contains the only copy target which happens to be a
1026 # leaf node.
1027 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001028 else:
1029 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1030
1031 blueprint.add_module(module)
1032 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001033 module.init_rc = target_initrc.get(target.name, [])
1034 module.srcs.update(
1035 gn_utils.label_to_path(src)
1036 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001037 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001038
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001039 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001040 if target.type in gn_utils.LINKER_UNIT_TYPES:
1041 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001042 # TODO: implement proper cflag parsing.
1043 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001044 if '-std=' in flag:
1045 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001046 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001047 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001048
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001049 # Adding local_include_dirs is necessary due to source_sets / filegroups
1050 # which do not properly propagate include directories.
1051 # Filter any directory inside //out as a) this directory does not exist for
1052 # aosp / soong builds and b) the include directory should already be
1053 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001054 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001055 for d in target.include_dirs
1056 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001057 module.local_include_dirs = sorted(list(local_include_dirs_set))
1058
1059 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1060 # in //base:base needs to have sysroot include after icu/source/common
1061 # include. So adding sysroot include at the end.
1062 for flag in target.cflags:
1063 if '--sysroot' in flag:
1064 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001065
1066 module_is_compiled = module.type not in ('genrule', 'filegroup')
1067 if module_is_compiled:
1068 # Don't try to inject library/source dependencies into genrules or
1069 # filegroups because they are not compiled in the traditional sense.
1070 module.defaults = [defaults_module]
1071 for lib in target.libs:
1072 # Generally library names should be mangled as 'libXXX', unless they
1073 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1074 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1075 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1076 else 'lib' + lib
1077 if lib in shared_library_allowlist:
1078 module.add_android_shared_lib(android_lib)
1079 if lib in static_library_allowlist:
1080 module.add_android_static_lib(android_lib)
1081
1082 # If the module is a static library, export all the generated headers.
1083 if module.type == 'cc_library_static':
1084 module.export_generated_headers = module.generated_headers
1085
Patrick Rohr92d74122022-10-21 15:50:52 -07001086 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001087 # Currently, only one module is generated from target even target has multiple toolchains.
1088 # And module is generated based on the first visited target.
1089 # Sort deps before iteration to make result deterministic.
1090 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001091 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001092 # |builtin_deps| override GN deps with Android-specific ones. See the
1093 # config in the top of this file.
1094 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1095 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1096 continue
1097
Patrick Rohr92d74122022-10-21 15:50:52 -07001098 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1099
Motomu Utsumie246feb2022-11-01 17:25:56 +09001100 # TODO: Proper dependency check for genrule.
1101 # Currently, only propagating genrule dependencies.
1102 # Also, currently, all the dependencies are propagated upwards.
1103 # in gn, public_deps should be propagated but deps should not.
1104 # Not sure this information is available in the desc.json.
1105 # Following rule works for adding android_runtime_jni_headers to base:base.
1106 # If this doesn't work for other target, hardcoding for specific target
1107 # might be better.
1108 if module.type == "genrule" and dep_module.type == "genrule":
1109 module.genrule_headers.add(dep_module.name)
1110 module.genrule_headers.update(dep_module.genrule_headers)
1111
Patrick Rohr92d74122022-10-21 15:50:52 -07001112 # For filegroups and genrule, recurse but don't apply the deps.
1113 if not module_is_compiled:
1114 continue
1115
Patrick Rohr92d74122022-10-21 15:50:52 -07001116 if dep_module is None:
1117 continue
1118 if dep_module.type == 'cc_library_shared':
1119 module.shared_libs.add(dep_module.name)
1120 elif dep_module.type == 'cc_library_static':
1121 module.static_libs.add(dep_module.name)
1122 elif dep_module.type == 'filegroup':
1123 module.srcs.add(':' + dep_module.name)
1124 elif dep_module.type == 'genrule':
1125 module.generated_headers.update(dep_module.genrule_headers)
1126 module.srcs.update(dep_module.genrule_srcs)
1127 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001128 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001129 elif dep_module.type == 'cc_binary':
1130 continue # Ignore executables deps (used by cmdline integration tests).
1131 else:
1132 raise Error('Unknown dep %s (%s) for target %s' %
1133 (dep_module.name, dep_module.type, module.name))
1134
1135 return module
1136
Patrick Rohrb18aca22022-11-04 15:07:32 -07001137def create_java_module(blueprint, gn):
1138 bp_module_name = module_prefix + 'java'
1139 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001140 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001141 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001142
1143def create_blueprint_for_targets(gn, desc, targets):
1144 """Generate a blueprint for a list of GN targets."""
1145 blueprint = Blueprint()
1146
1147 # Default settings used by all modules.
1148 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001149 defaults.cflags = [
1150 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001151 '-Wno-non-virtual-dtor',
Patrick Rohr5c700022022-11-08 19:33:07 -08001152 '-Wno-macro-redefined',
Patrick Rohr98065152022-10-31 14:49:58 -07001153 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001154 '-Wno-sign-compare',
1155 '-Wno-sign-promo',
1156 '-Wno-unused-parameter',
1157 '-fvisibility=hidden',
1158 '-O2',
1159 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001160 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001161 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001162
Patrick Rohr92d74122022-10-21 15:50:52 -07001163 for target in targets:
1164 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001165
1166 create_java_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001167
1168 # Merge in additional hardcoded arguments.
1169 for module in blueprint.modules.values():
1170 for key, add_val in additional_args.get(module.name, []):
1171 curr = getattr(module, key)
1172 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1173 curr.update(add_val)
1174 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1175 setattr(module, key, add_val)
1176 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1177 setattr(module, key, add_val)
1178 elif isinstance(add_val, dict) and isinstance(curr, dict):
1179 curr.update(add_val)
1180 elif isinstance(add_val, dict) and isinstance(curr, Target):
1181 curr.__dict__.update(add_val)
1182 else:
1183 raise Error('Unimplemented type %r of additional_args: %r' %
1184 (type(add_val), key))
1185
Patrick Rohr92d74122022-10-21 15:50:52 -07001186 return blueprint
1187
1188
1189def main():
1190 parser = argparse.ArgumentParser(
1191 description='Generate Android.bp from a GN description.')
1192 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001193 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001194 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1195 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001196 )
1197 parser.add_argument(
1198 '--extras',
1199 help='Extra targets to include at the end of the Blueprint file',
1200 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1201 )
1202 parser.add_argument(
1203 '--output',
1204 help='Blueprint file to create',
1205 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1206 )
1207 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001208 '-v',
1209 '--verbose',
1210 help='Print debug logs.',
1211 action='store_true',
1212 )
1213 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001214 'targets',
1215 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001216 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1217 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001218 args = parser.parse_args()
1219
Patrick Rohr16228942022-10-26 14:00:26 -07001220 if args.verbose:
1221 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1222
Patrick Rohr3db246a2022-10-25 10:25:17 -07001223 with open(args.desc) as f:
1224 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001225
1226 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001227 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001228 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1229 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1230
Patrick Rohr92d74122022-10-21 15:50:52 -07001231 # Add any proto groups to the blueprint.
1232 for l_name, t_names in proto_groups.items():
1233 create_proto_group_modules(blueprint, gn, l_name, t_names)
1234
1235 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001236 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001237//
1238// Licensed under the Apache License, Version 2.0 (the "License");
1239// you may not use this file except in compliance with the License.
1240// You may obtain a copy of the License at
1241//
1242// http://www.apache.org/licenses/LICENSE-2.0
1243//
1244// Unless required by applicable law or agreed to in writing, software
1245// distributed under the License is distributed on an "AS IS" BASIS,
1246// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1247// See the License for the specific language governing permissions and
1248// limitations under the License.
1249//
1250// This file is automatically generated by %s. Do not edit.
1251""" % (tool_name)
1252 ]
1253 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001254 if os.path.exists(args.extras):
1255 with open(args.extras, 'r') as r:
1256 for line in r:
1257 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001258
1259 out_files = []
1260
1261 # Generate the Android.bp file.
1262 out_files.append(args.output + '.swp')
1263 with open(out_files[-1], 'w') as f:
1264 f.write('\n'.join(output))
1265 # Text files should have a trailing EOL.
1266 f.write('\n')
1267
Patrick Rohr94693eb2022-10-25 10:09:16 -07001268 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001269
1270
1271if __name__ == '__main__':
1272 sys.exit(main())