blob: 539817bb0ea7ff47aa7f2449727ddd92f0151665 [file] [log] [blame]
Patrick Rohr92d74122022-10-21 15:50:52 -07001#!/usr/bin/env python3
2# Copyright (C) 2022 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16# This tool translates a collection of BUILD.gn files into a mostly equivalent
17# Android.bp file for the Android Soong build system. The input to the tool is a
18# JSON description of the GN build definition generated with the following
19# command:
20#
21# gn desc out --format=json --all-toolchains "//*" > desc.json
22#
23# The tool is then given a list of GN labels for which to generate Android.bp
24# build rules. The dependencies for the GN labels are squashed to the generated
25# Android.bp target, except for actions which get their own genrule. Some
26# libraries are also mapped to their Android equivalents -- see |builtin_deps|.
27
28import argparse
29import collections
30import json
Patrick Rohr16228942022-10-26 14:00:26 -070031import logging as log
Patrick Rohr92d74122022-10-21 15:50:52 -070032import os
33import re
34import sys
Motomu Utsumic6277d92022-11-07 15:15:17 +090035import copy
Patrick Rohr92d74122022-10-21 15:50:52 -070036
37import gn_utils
38
Patrick Rohr92d74122022-10-21 15:50:52 -070039ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
40
Patrick Rohr92d74122022-10-21 15:50:52 -070041# Defines a custom init_rc argument to be applied to the corresponding output
42# blueprint target.
43target_initrc = {
Patrick Rohrc36ef422022-10-25 10:38:05 -070044 # TODO: this can probably be removed.
Patrick Rohr92d74122022-10-21 15:50:52 -070045}
46
47target_host_supported = [
Patrick Rohrdc383942022-10-25 10:45:29 -070048 # TODO: remove if this is not useful for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070049]
50
Patrick Rohr92d74122022-10-21 15:50:52 -070051# Proto target groups which will be made public.
52proto_groups = {
Patrick Rohr95212a22022-10-25 09:53:13 -070053 # TODO: remove if this is not used for the cronet build.
Patrick Rohr92d74122022-10-21 15:50:52 -070054}
55
56# All module names are prefixed with this string to avoid collisions.
Patrick Rohr61b2bad2022-10-25 10:49:20 -070057module_prefix = 'cronet_aml_'
Patrick Rohr92d74122022-10-21 15:50:52 -070058
59# Shared libraries which are directly translated to Android system equivalents.
60shared_library_allowlist = [
61 'android',
62 'android.hardware.atrace@1.0',
63 'android.hardware.health@2.0',
64 'android.hardware.health-V1-ndk',
65 'android.hardware.power.stats@1.0',
66 "android.hardware.power.stats-V1-cpp",
67 'base',
68 'binder',
69 'binder_ndk',
70 'cutils',
71 'hidlbase',
72 'hidltransport',
73 'hwbinder',
74 'incident',
75 'log',
76 'services',
77 'statssocket',
78 "tracingproxy",
79 'utils',
80]
81
82# Static libraries which are directly translated to Android system equivalents.
83static_library_allowlist = [
84 'statslog_perfetto',
85]
86
87# Name of the module which settings such as compiler flags for all other
88# modules.
89defaults_module = module_prefix + 'defaults'
90
91# Location of the project in the Android source tree.
Patrick Rohr76ceeb52022-11-07 14:18:58 -080092tree_path = 'external/chromium_org'
Patrick Rohr92d74122022-10-21 15:50:52 -070093
94# Path for the protobuf sources in the standalone build.
95buildtools_protobuf_src = '//buildtools/protobuf/src'
96
97# Location of the protobuf src dir in the Android source tree.
98android_protobuf_src = 'external/protobuf/src'
99
100# Compiler flags which are passed through to the blueprint.
101cflag_allowlist = r'^-DPERFETTO.*$'
102
Patrick Rohr92d74122022-10-21 15:50:52 -0700103# Additional arguments to apply to Android.bp rules.
104additional_args = {
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800105 # TODO: remove if not needed.
Patrick Rohr92d74122022-10-21 15:50:52 -0700106}
107
108
109def enable_gtest_and_gmock(module):
110 module.static_libs.add('libgmock')
111 module.static_libs.add('libgtest')
112 if module.name != 'perfetto_gtest_logcat_printer':
113 module.whole_static_libs.add('perfetto_gtest_logcat_printer')
114
115
116def enable_protobuf_full(module):
117 if module.type == 'cc_binary_host':
118 module.static_libs.add('libprotobuf-cpp-full')
119 elif module.host_supported:
120 module.host.static_libs.add('libprotobuf-cpp-full')
121 module.android.shared_libs.add('libprotobuf-cpp-full')
Patrick Rohr84b16402022-11-08 19:01:01 -0800122 elif module.type not in ['genrule', 'filegroup']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700123 module.shared_libs.add('libprotobuf-cpp-full')
124
125
126def enable_protobuf_lite(module):
Patrick Rohr84b16402022-11-08 19:01:01 -0800127 if module.type not in ['genrule', 'filegroup']:
128 module.shared_libs.add('libprotobuf-cpp-lite')
Patrick Rohr92d74122022-10-21 15:50:52 -0700129
130
131def enable_protoc_lib(module):
132 if module.type == 'cc_binary_host':
133 module.static_libs.add('libprotoc')
134 else:
135 module.shared_libs.add('libprotoc')
136
137
138def enable_libunwindstack(module):
139 if module.name != 'heapprofd_standalone_client':
140 module.shared_libs.add('libunwindstack')
141 module.shared_libs.add('libprocinfo')
142 module.shared_libs.add('libbase')
143 else:
144 module.static_libs.add('libunwindstack')
145 module.static_libs.add('libprocinfo')
146 module.static_libs.add('libbase')
147 module.static_libs.add('liblzma')
148 module.static_libs.add('libdexfile_support')
149 module.runtime_libs.add('libdexfile') # libdexfile_support dependency
150
151
152def enable_libunwind(module):
153 # libunwind is disabled on Darwin so we cannot depend on it.
154 pass
155
156
157def enable_sqlite(module):
158 if module.type == 'cc_binary_host':
159 module.static_libs.add('libsqlite')
160 module.static_libs.add('sqlite_ext_percentile')
161 elif module.host_supported:
162 # Copy what the sqlite3 command line tool does.
163 module.android.shared_libs.add('libsqlite')
164 module.android.shared_libs.add('libicu')
165 module.android.shared_libs.add('liblog')
166 module.android.shared_libs.add('libutils')
167 module.android.static_libs.add('sqlite_ext_percentile')
168 module.host.static_libs.add('libsqlite')
169 module.host.static_libs.add('sqlite_ext_percentile')
170 else:
171 module.shared_libs.add('libsqlite')
172 module.shared_libs.add('libicu')
173 module.shared_libs.add('liblog')
174 module.shared_libs.add('libutils')
175 module.static_libs.add('sqlite_ext_percentile')
176
177
178def enable_zlib(module):
179 if module.type == 'cc_binary_host':
180 module.static_libs.add('libz')
181 elif module.host_supported:
182 module.android.shared_libs.add('libz')
183 module.host.static_libs.add('libz')
184 else:
185 module.shared_libs.add('libz')
186
187
188def enable_uapi_headers(module):
189 module.include_dirs.add('bionic/libc/kernel')
190
191
192def enable_bionic_libc_platform_headers_on_android(module):
193 module.header_libs.add('bionic_libc_platform_headers')
194
195
196# Android equivalents for third-party libraries that the upstream project
197# depends on.
198builtin_deps = {
199 '//gn:default_deps':
200 lambda x: None,
201 '//gn:gtest_main':
202 lambda x: None,
Patrick Rohr92d74122022-10-21 15:50:52 -0700203 '//gn:gtest_and_gmock':
204 enable_gtest_and_gmock,
205 '//gn:libunwind':
206 enable_libunwind,
Patrick Rohr92d74122022-10-21 15:50:52 -0700207 '//gn:libunwindstack':
208 enable_libunwindstack,
209 '//gn:sqlite':
210 enable_sqlite,
211 '//gn:zlib':
212 enable_zlib,
213 '//gn:bionic_kernel_uapi_headers':
214 enable_uapi_headers,
215 '//src/profiling/memory:bionic_libc_platform_headers_on_android':
216 enable_bionic_libc_platform_headers_on_android,
Motomu Utsumidfc8e6a2022-11-04 18:25:33 +0900217 '//third_party/protobuf:protoc':
218 lambda x: None,
Patrick Rohr84b16402022-11-08 19:01:01 -0800219 '//third_party/protobuf:protobuf_full':
220 enable_protobuf_full,
221 '//third_party/protobuf:protobuf_lite':
222 enable_protobuf_lite,
223 '//third_party/protobuf:protoc_lib':
224 enable_protoc_lib,
Patrick Rohr92d74122022-10-21 15:50:52 -0700225}
226
227# ----------------------------------------------------------------------------
228# End of configuration.
229# ----------------------------------------------------------------------------
230
231
232class Error(Exception):
233 pass
234
235
236class ThrowingArgumentParser(argparse.ArgumentParser):
237
238 def __init__(self, context):
239 super(ThrowingArgumentParser, self).__init__()
240 self.context = context
241
242 def error(self, message):
243 raise Error('%s: %s' % (self.context, message))
244
245
246def write_blueprint_key_value(output, name, value, sort=True):
247 """Writes a Blueprint key-value pair to the output"""
248
249 if isinstance(value, bool):
250 if value:
251 output.append(' %s: true,' % name)
252 else:
253 output.append(' %s: false,' % name)
254 return
255 if not value:
256 return
257 if isinstance(value, set):
258 value = sorted(value)
259 if isinstance(value, list):
260 output.append(' %s: [' % name)
261 for item in sorted(value) if sort else value:
262 output.append(' "%s",' % item)
263 output.append(' ],')
264 return
265 if isinstance(value, Target):
266 value.to_string(output)
267 return
268 if isinstance(value, dict):
269 kv_output = []
270 for k, v in value.items():
271 write_blueprint_key_value(kv_output, k, v)
272
273 output.append(' %s: {' % name)
274 for line in kv_output:
275 output.append(' %s' % line)
276 output.append(' },')
277 return
278 output.append(' %s: "%s",' % (name, value))
279
280
281class Target(object):
282 """A target-scoped part of a module"""
283
284 def __init__(self, name):
285 self.name = name
286 self.shared_libs = set()
287 self.static_libs = set()
288 self.whole_static_libs = set()
289 self.cflags = set()
290 self.dist = dict()
291 self.strip = dict()
292 self.stl = None
293
294 def to_string(self, output):
295 nested_out = []
296 self._output_field(nested_out, 'shared_libs')
297 self._output_field(nested_out, 'static_libs')
298 self._output_field(nested_out, 'whole_static_libs')
299 self._output_field(nested_out, 'cflags')
300 self._output_field(nested_out, 'stl')
301 self._output_field(nested_out, 'dist')
302 self._output_field(nested_out, 'strip')
303
304 if nested_out:
305 output.append(' %s: {' % self.name)
306 for line in nested_out:
307 output.append(' %s' % line)
308 output.append(' },')
309
310 def _output_field(self, output, name, sort=True):
311 value = getattr(self, name)
312 return write_blueprint_key_value(output, name, value, sort)
313
314
315class Module(object):
316 """A single module (e.g., cc_binary, cc_test) in a blueprint."""
317
318 def __init__(self, mod_type, name, gn_target):
319 self.type = mod_type
320 self.gn_target = gn_target
321 self.name = name
322 self.srcs = set()
323 self.comment = 'GN: ' + gn_utils.label_without_toolchain(gn_target)
324 self.shared_libs = set()
325 self.static_libs = set()
326 self.whole_static_libs = set()
327 self.runtime_libs = set()
328 self.tools = set()
329 self.cmd = None
330 self.host_supported = False
331 self.vendor_available = False
332 self.init_rc = set()
333 self.out = set()
334 self.export_include_dirs = set()
335 self.generated_headers = set()
336 self.export_generated_headers = set()
337 self.defaults = set()
338 self.cflags = set()
339 self.include_dirs = set()
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900340 self.local_include_dirs = []
Patrick Rohr92d74122022-10-21 15:50:52 -0700341 self.header_libs = set()
342 self.required = set()
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700343 self.tool_files = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700344 self.android = Target('android')
345 self.host = Target('host')
Patrick Rohr92d74122022-10-21 15:50:52 -0700346 self.stl = None
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700347 self.cpp_std = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700348 self.dist = dict()
349 self.strip = dict()
350 self.data = set()
351 self.apex_available = set()
352 self.min_sdk_version = None
353 self.proto = dict()
354 # The genrule_XXX below are properties that must to be propagated back
355 # on the module(s) that depend on the genrule.
356 self.genrule_headers = set()
357 self.genrule_srcs = set()
358 self.genrule_shared_libs = set()
Patrick Rohra1a27872022-10-31 11:57:14 -0700359 self.genrule_header_libs = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700360 self.version_script = None
361 self.test_suites = set()
362 self.test_config = None
363 self.stubs = {}
364
365 def to_string(self, output):
366 if self.comment:
367 output.append('// %s' % self.comment)
368 output.append('%s {' % self.type)
369 self._output_field(output, 'name')
370 self._output_field(output, 'srcs')
371 self._output_field(output, 'shared_libs')
372 self._output_field(output, 'static_libs')
373 self._output_field(output, 'whole_static_libs')
374 self._output_field(output, 'runtime_libs')
375 self._output_field(output, 'tools')
376 self._output_field(output, 'cmd', sort=False)
377 if self.host_supported:
378 self._output_field(output, 'host_supported')
379 if self.vendor_available:
380 self._output_field(output, 'vendor_available')
381 self._output_field(output, 'init_rc')
382 self._output_field(output, 'out')
383 self._output_field(output, 'export_include_dirs')
384 self._output_field(output, 'generated_headers')
385 self._output_field(output, 'export_generated_headers')
386 self._output_field(output, 'defaults')
387 self._output_field(output, 'cflags')
388 self._output_field(output, 'include_dirs')
Motomu Utsumi97fb1812022-11-01 13:08:10 +0900389 self._output_field(output, 'local_include_dirs', sort=False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700390 self._output_field(output, 'header_libs')
391 self._output_field(output, 'required')
392 self._output_field(output, 'dist')
393 self._output_field(output, 'strip')
394 self._output_field(output, 'tool_files')
395 self._output_field(output, 'data')
396 self._output_field(output, 'stl')
Patrick Rohrb8f830a2022-10-31 11:18:57 -0700397 self._output_field(output, 'cpp_std')
Patrick Rohr92d74122022-10-21 15:50:52 -0700398 self._output_field(output, 'apex_available')
399 self._output_field(output, 'min_sdk_version')
400 self._output_field(output, 'version_script')
401 self._output_field(output, 'test_suites')
402 self._output_field(output, 'test_config')
403 self._output_field(output, 'stubs')
404 self._output_field(output, 'proto')
405
406 target_out = []
407 self._output_field(target_out, 'android')
408 self._output_field(target_out, 'host')
409 if target_out:
410 output.append(' target: {')
411 for line in target_out:
412 output.append(' %s' % line)
413 output.append(' },')
414
Patrick Rohr92d74122022-10-21 15:50:52 -0700415 output.append('}')
416 output.append('')
417
418 def add_android_static_lib(self, lib):
419 if self.type == 'cc_binary_host':
420 raise Exception('Adding Android static lib for host tool is unsupported')
421 elif self.host_supported:
422 self.android.static_libs.add(lib)
423 else:
424 self.static_libs.add(lib)
425
426 def add_android_shared_lib(self, lib):
427 if self.type == 'cc_binary_host':
428 raise Exception('Adding Android shared lib for host tool is unsupported')
429 elif self.host_supported:
430 self.android.shared_libs.add(lib)
431 else:
432 self.shared_libs.add(lib)
433
434 def _output_field(self, output, name, sort=True):
435 value = getattr(self, name)
436 return write_blueprint_key_value(output, name, value, sort)
437
438
439class Blueprint(object):
440 """In-memory representation of an Android.bp file."""
441
442 def __init__(self):
443 self.modules = {}
444
445 def add_module(self, module):
446 """Adds a new module to the blueprint, replacing any existing module
447 with the same name.
448
449 Args:
450 module: Module instance.
451 """
452 self.modules[module.name] = module
453
454 def to_string(self, output):
Patrick Rohr23f26192022-10-25 09:45:22 -0700455 for m in sorted(self.modules.values(), key=lambda m: m.name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700456 m.to_string(output)
457
458
459def label_to_module_name(label):
460 """Turn a GN label (e.g., //:perfetto_tests) into a module name."""
461 # If the label is explicibly listed in the default target list, don't prefix
462 # its name and return just the target name. This is so tools like
463 # "traceconv" stay as such in the Android tree.
464 label_without_toolchain = gn_utils.label_without_toolchain(label)
Patrick Rohr92d74122022-10-21 15:50:52 -0700465 module = re.sub(r'^//:?', '', label_without_toolchain)
466 module = re.sub(r'[^a-zA-Z0-9_]', '_', module)
467 if not module.startswith(module_prefix):
468 return module_prefix + module
469 return module
470
471
472def is_supported_source_file(name):
473 """Returns True if |name| can appear in a 'srcs' list."""
Patrick Rohrd604f9f2022-10-27 13:56:42 -0700474 return os.path.splitext(name)[1] in ['.c', '.cc', '.java', '.proto']
Patrick Rohr92d74122022-10-21 15:50:52 -0700475
476
477def create_proto_modules(blueprint, gn, target):
478 """Generate genrules for a proto GN target.
479
480 GN actions are used to dynamically generate files during the build. The
481 Soong equivalent is a genrule. This function turns a specific kind of
482 genrule which turns .proto files into source and header files into a pair
483 equivalent genrules.
484
485 Args:
486 blueprint: Blueprint instance which is being generated.
487 target: gn_utils.Target object.
488
489 Returns:
490 The source_genrule module.
491 """
492 assert (target.type == 'proto_library')
493
494 tools = {'aprotoc'}
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900495 cpp_out_dir = '$(genDir)/%s/%s/' % (tree_path, target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700496 target_module_name = label_to_module_name(target.name)
497
498 # In GN builds the proto path is always relative to the output directory
499 # (out/tmp.xxx).
Motomu Utsumie8457452022-11-08 18:47:51 +0900500 cmd = ['$(location aprotoc)']
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900501 cmd += ['--proto_path=%s/%s' % (tree_path, target.proto_in_dir)]
Patrick Rohr92d74122022-10-21 15:50:52 -0700502
503 if buildtools_protobuf_src in target.proto_paths:
504 cmd += ['--proto_path=%s' % android_protobuf_src]
505
506 # We don't generate any targets for source_set proto modules because
507 # they will be inlined into other modules if required.
508 if target.proto_plugin == 'source_set':
509 return None
510
511 # Descriptor targets only generate a single target.
512 if target.proto_plugin == 'descriptor':
513 out = '{}.bin'.format(target_module_name)
514
515 cmd += ['--descriptor_set_out=$(out)']
516 cmd += ['$(in)']
517
518 descriptor_module = Module('genrule', target_module_name, target.name)
519 descriptor_module.cmd = ' '.join(cmd)
520 descriptor_module.out = [out]
521 descriptor_module.tools = tools
522 blueprint.add_module(descriptor_module)
523
524 # Recursively extract the .proto files of all the dependencies and
525 # add them to srcs.
526 descriptor_module.srcs.update(
527 gn_utils.label_to_path(src) for src in target.sources)
528 for dep in target.transitive_proto_deps:
529 current_target = gn.get_target(dep)
530 descriptor_module.srcs.update(
531 gn_utils.label_to_path(src) for src in current_target.sources)
532
533 return descriptor_module
534
535 # We create two genrules for each proto target: one for the headers and
536 # another for the sources. This is because the module that depends on the
537 # generated files needs to declare two different types of dependencies --
538 # source files in 'srcs' and headers in 'generated_headers' -- and it's not
539 # valid to generate .h files from a source dependency and vice versa.
540 source_module_name = target_module_name + '_gen'
541 source_module = Module('genrule', source_module_name, target.name)
542 blueprint.add_module(source_module)
543 source_module.srcs.update(
544 gn_utils.label_to_path(src) for src in target.sources)
545
546 header_module = Module('genrule', source_module_name + '_headers',
547 target.name)
548 blueprint.add_module(header_module)
549 header_module.srcs = set(source_module.srcs)
550
551 # TODO(primiano): at some point we should remove this. This was introduced
552 # by aosp/1108421 when adding "protos/" to .proto include paths, in order to
553 # avoid doing multi-repo changes and allow old clients in the android tree
554 # to still do the old #include "perfetto/..." rather than
555 # #include "protos/perfetto/...".
556 header_module.export_include_dirs = {'.', 'protos'}
Patrick Rohr2267a0a2022-11-08 18:59:34 -0800557 # Since the .cc file and .h get created by a different gerule target, they
558 # are not put in the same intermediate path, so local includes do not work
559 # without explictily exporting the include dir.
560 header_module.export_include_dirs.add(target.proto_in_dir)
Patrick Rohr92d74122022-10-21 15:50:52 -0700561
562 source_module.genrule_srcs.add(':' + source_module.name)
563 source_module.genrule_headers.add(header_module.name)
564
565 if target.proto_plugin == 'proto':
566 suffixes = ['pb']
567 source_module.genrule_shared_libs.add('libprotobuf-cpp-lite')
568 cmd += ['--cpp_out=lite=true:' + cpp_out_dir]
569 elif target.proto_plugin == 'protozero':
570 suffixes = ['pbzero']
571 plugin = create_modules_from_target(blueprint, gn, protozero_plugin)
572 tools.add(plugin.name)
573 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
574 cmd += ['--plugin_out=wrapper_namespace=pbzero:' + cpp_out_dir]
575 elif target.proto_plugin == 'cppgen':
576 suffixes = ['gen']
577 plugin = create_modules_from_target(blueprint, gn, cppgen_plugin)
578 tools.add(plugin.name)
579 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
580 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
581 elif target.proto_plugin == 'ipc':
582 suffixes = ['ipc']
583 plugin = create_modules_from_target(blueprint, gn, ipc_plugin)
584 tools.add(plugin.name)
585 cmd += ['--plugin=protoc-gen-plugin=$(location %s)' % plugin.name]
586 cmd += ['--plugin_out=wrapper_namespace=gen:' + cpp_out_dir]
587 else:
588 raise Error('Unsupported proto plugin: %s' % target.proto_plugin)
589
590 cmd += ['$(in)']
591 source_module.cmd = ' '.join(cmd)
592 header_module.cmd = source_module.cmd
593 source_module.tools = tools
594 header_module.tools = tools
595
596 for sfx in suffixes:
597 source_module.out.update('%s/%s' %
598 (tree_path, src.replace('.proto', '.%s.cc' % sfx))
599 for src in source_module.srcs)
600 header_module.out.update('%s/%s' %
601 (tree_path, src.replace('.proto', '.%s.h' % sfx))
602 for src in header_module.srcs)
603 return source_module
604
605
606def create_amalgamated_sql_metrics_module(blueprint, target):
607 bp_module_name = label_to_module_name(target.name)
608 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700609 module.tool_files.add('tools/gen_amalgamated_sql_metrics.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700610 module.cmd = ' '.join([
611 '$(location tools/gen_amalgamated_sql_metrics.py)',
612 '--cpp_out=$(out)',
613 '$(in)',
614 ])
615 module.genrule_headers.add(module.name)
616 module.out.update(target.outputs)
617 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
618 blueprint.add_module(module)
619 return module
620
621
622def create_cc_proto_descriptor_module(blueprint, target):
623 bp_module_name = label_to_module_name(target.name)
624 module = Module('genrule', bp_module_name, target.name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700625 module.tool_files.add('tools/gen_cc_proto_descriptor.py')
Patrick Rohr92d74122022-10-21 15:50:52 -0700626 module.cmd = ' '.join([
627 '$(location tools/gen_cc_proto_descriptor.py)', '--gen_dir=$(genDir)',
628 '--cpp_out=$(out)', '$(in)'
629 ])
630 module.genrule_headers.add(module.name)
631 module.srcs.update(
632 ':' + label_to_module_name(dep) for dep in target.proto_deps)
633 module.srcs.update(
634 gn_utils.label_to_path(src)
635 for src in target.inputs
636 if "tmp.gn_utils" not in src)
637 module.out.update(target.outputs)
638 blueprint.add_module(module)
639 return module
640
641
642def create_gen_version_module(blueprint, target, bp_module_name):
643 module = Module('genrule', bp_module_name, gn_utils.GEN_VERSION_TARGET)
644 script_path = gn_utils.label_to_path(target.script)
645 module.genrule_headers.add(bp_module_name)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700646 module.tool_files.add(script_path)
Patrick Rohr92d74122022-10-21 15:50:52 -0700647 module.out.update(target.outputs)
648 module.srcs.update(gn_utils.label_to_path(src) for src in target.inputs)
649 module.cmd = ' '.join([
650 'python3 $(location %s)' % script_path, '--no_git',
651 '--changelog=$(location CHANGELOG)', '--cpp_out=$(out)'
652 ])
653 blueprint.add_module(module)
654 return module
655
656
657def create_proto_group_modules(blueprint, gn, module_name, target_names):
658 # TODO(lalitm): today, we're only adding a Java lite module because that's
659 # the only one used in practice. In the future, if we need other target types
660 # (e.g. C++, Java full etc.) add them here.
661 bp_module_name = label_to_module_name(module_name) + '_java_protos'
662 module = Module('java_library', bp_module_name, bp_module_name)
663 module.comment = f'''GN: [{', '.join(target_names)}]'''
664 module.proto = {'type': 'lite', 'canonical_path_from_root': False}
665
666 for name in target_names:
667 target = gn.get_target(name)
668 module.srcs.update(gn_utils.label_to_path(src) for src in target.sources)
669 for dep_label in target.transitive_proto_deps:
670 dep = gn.get_target(dep_label)
671 module.srcs.update(gn_utils.label_to_path(src) for src in dep.sources)
672
673 blueprint.add_module(module)
674
Motomu Utsumia6c33152022-11-02 18:21:55 +0900675# HACK: Need to support build_cofig_gen flexibly instead of hardcoding
676# build_config_gen generates srcjar by executing gcc via gcc_preprocess.py but gcc is not
677# available in genrule sandbox. Also gcc path is not configurable.
678# Under the //net:net, gcc_preprocess.py is only used for build_config_gen.
679# So, for now, hardcoding BuildConfig.java and generates srcjar by soong_zip.
680def override_build_config_gen(module):
681 module.tool_files.clear()
682 module.tools.add("soong_zip")
683 cmd = [
684 "echo",
685 "\\\"package org.chromium.build;\\n",
686 "public class BuildConfig {\\n",
687 "public static boolean IS_MULTIDEX_ENABLED ;\\n",
688 "public static boolean ENABLE_ASSERTS = true;\\n",
689 "public static boolean IS_UBSAN ;\\n",
690 "public static boolean IS_CHROME_BRANDED ;\\n",
691 "public static int R_STRING_PRODUCT_VERSION ;\\n",
692 "public static int MIN_SDK_VERSION = 1;\\n",
693 "public static boolean BUNDLES_SUPPORTED ;\\n",
694 "public static boolean IS_INCREMENTAL_INSTALL ;\\n",
695 "public static boolean ISOLATED_SPLITS_ENABLED ;\\n",
696 "public static boolean IS_FOR_TEST ;\\n",
697 "}\\n\\\"",
698 "> $(genDir)/BuildConfig.java &&",
699 "$(location soong_zip) -o $(out) -srcjar -f $(genDir)/BuildConfig.java"
700 ]
701 NEWLINE = ' " +\n "'
702 module.cmd = NEWLINE.join(cmd)
703 return module
704
Mohannad Farragbab6c892022-11-02 14:09:46 +0000705def create_action_foreach_modules(blueprint, target):
706 """ The following assumes that rebase_path exists in the args.
707 The args of an action_foreach contains hints about which output files are generated
708 by which source files.
709 This is copied directly from the args
710 "gen/net/base/registry_controlled_domains/{{source_name_part}}-reversed-inc.cc"
711 So each source file will generate an output whose name is the {source_name-reversed-inc.cc}
712 """
713 new_args = []
Motomu Utsumi56afcac2022-11-04 12:58:30 +0900714 for i, src in enumerate(sorted(target.sources)):
Mohannad Farragbab6c892022-11-02 14:09:46 +0000715 # don't add script arg for the first source -- create_action_module
716 # already does this.
717 if i != 0:
718 new_args.append('&& python3 $(location %s)' %
719 gn_utils.label_to_path(target.script))
720 for arg in target.args:
721 if '{{source}}' in arg:
722 new_args.append('$(location %s)' % (gn_utils.label_to_path(src)))
723 elif '{{source_name_part}}' in arg:
724 source_name_part = src.split("/")[-1] # Get the file name only
725 source_name_part = source_name_part.split(".")[0] # Remove the extension (Ex: .cc)
726 file_name = arg.replace('{{source_name_part}}', source_name_part).split("/")[-1]
727 # file_name represent the output file name. But we need the whole path
728 # This can be found from target.outputs.
729 for out in target.outputs:
730 if out.endswith(file_name):
731 new_args.append('$(location %s)' % out)
732 else:
733 new_args.append(arg)
734
735 target.args = new_args
736 return create_action_module(blueprint, target)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900737
Patrick Rohr7be99032022-10-31 11:54:19 -0700738def create_action_module(blueprint, target):
739 bp_module_name = label_to_module_name(target.name)
740 module = Module('genrule', bp_module_name, target.name)
741
Patrick Rohr9b99a982022-10-28 11:00:57 -0700742 # Convert ['--param=value'] to ['--param', 'value'] for consistency.
743 # TODO: we may want to only do this for python scripts arguments. If argparse
744 # is used, this transformation is safe.
745 target.args = [str for it in target.args for str in it.split('=')]
746
Motomu Utsumibf569d42022-10-28 16:47:34 +0900747 if target.script == "//build/write_buildflag_header.py":
748 # write_buildflag_header.py writes result to args.genDir/args.output
749 # So, override args.genDir by '.' so that args.output=$(out) works
Patrick Rohrde568a22022-10-28 09:22:35 -0700750 for i, val in enumerate(target.args):
751 if val == '--gen-dir':
752 target.args[i + 1] = '.'
Patrick Rohrfa972402022-11-01 11:54:35 -0700753 elif val == '--output':
754 target.args[i + 1] = '$(out)'
755
756 elif target.script == '//build/write_build_date_header.py':
757 target.args[0] = '$(out)'
Patrick Rohr0db9f852022-10-27 13:49:57 -0700758
Patrick Rohr8acccca2022-10-28 10:39:06 -0700759 elif target.script == '//base/android/jni_generator/jni_generator.py':
Patrick Rohrc5cc21a2022-10-31 11:57:49 -0700760 # chromium builds against a prebuilt ndk that contains the jni_headers, so
761 # a dependency is never explicitly created.
762 module.genrule_header_libs.add('jni_headers')
Patrick Rohr131ba282022-10-31 16:36:20 -0700763 needs_javap = False
Patrick Rohr8acccca2022-10-28 10:39:06 -0700764 for i, val in enumerate(target.args):
Motomu Utsumi6f9139d2022-10-31 12:15:19 +0900765 if val == '--output_dir':
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700766 # replace --output_dir gen/jni_headers/... with --output_dir $(genDir)/...
767 target.args[i + 1] = re.sub('^gen/jni_headers', '$(genDir)', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700768 elif val == '--input_file':
Patrick Rohr8acccca2022-10-28 10:39:06 -0700769 # --input_file supports both .class specifiers or source files as arguments.
770 # Only source files need to be wrapped inside a $(location <label>) tag.
771 if re.match('.*\.class$', target.args[i + 1]):
772 continue
773 # replace --input_file ../../... with --input_file $(location ...)
774 # TODO: put inside function
775 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
776 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700777 elif val == '--includes' and 'jni_generator_helper' in target.args[i + 1]:
Patrick Rohrd89e8bf2022-10-31 14:51:05 -0700778 # delete all leading ../
779 target.args[i + 1] = re.sub('^(\.\./)+', '', target.args[i + 1])
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700780 elif val == '--prev_output_dir':
Patrick Rohr131ba282022-10-31 16:36:20 -0700781 # this is not needed for aosp builds.
782 target.args[i] = ''
783 target.args[i + 1] = ''
Patrick Rohrbec0c8c2022-11-01 11:56:38 -0700784 elif val == '--jar_file':
Patrick Rohr131ba282022-10-31 16:36:20 -0700785 # delete leading ../../ and add path to javap
786 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
787 target.args[i + 1] = '$(location %s)' % filename
788 needs_javap = True
789
790 if needs_javap:
791 target.args.append('--javap')
792 target.args.append('$$(find out/.path -name javap)')
Patrick Rohrf1d08f82022-10-31 14:43:59 -0700793 # fix target.output directory to match #include statements.
794 target.outputs = [re.sub('^jni_headers/', '', out) for out in target.outputs]
Patrick Rohr8acccca2022-10-28 10:39:06 -0700795
Patrick Rohr245df582022-11-01 16:59:45 -0700796 elif target.script == '//build/android/gyp/write_build_config.py':
797 for i, val in enumerate(target.args):
798 if val == '--depfile':
799 # Depfile is not used, so no need to generate it.
800 target.args[i] = ''
801 target.args[i + 1] = ''
802 elif val in ['--deps-configs', '--bundled-srcjars']:
803 args = target.args[i + 1]
804 if args == '[]':
805 continue
806 # strip surrounding [] and split by ", "
807 args = args.strip('[]').split(', ')
808 # strip surrounding ""
809 args = [arg.strip('"') for arg in args]
810 # remove leading gen/
811 args = [re.sub('^gen/', '', arg) for arg in args]
812 # wrap filename in \"$(location filename)\"
813 args = ['\"$(location %s)\"' % arg for arg in args]
814 # join args with ", " and wrap in []
815 target.args[i + 1] = '[%s]' % ', '.join(args)
816
817 elif val == '--public-deps-configs':
818 # TODO: implement.
819 pass
820
821 elif val == '--build-config':
822 # json output of this script
823 target.args[i + 1] = re.sub('^gen', '$(genDir)', target.args[i + 1])
824
825 elif val in ['--unprocessed-jar-path', '--interface-jar-path',
826 '--device-jar-path', '--host-jar-path']:
827 # jar path can be within sources (../../) or output generated by
828 # another genrule (obj/)
829 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
830 filename = re.sub('^obj/', '', target.args[i + 1])
831 target.args[i + 1] = '$(location %s)' % filename
832
833 elif val == '--proguard-configs':
834 args = target.args[i + 1]
835 if args == '[]':
836 continue
837 # TODO: consider adding helpers to deal with argument lists
838 # strip surrounding [] and split by ", ", then strip surrounding ""
839 args = args.strip('[]').split(', ')
840 args = [arg.strip('"') for arg in args]
841 # remove leading ../../
842 args = [re.sub('^\.\./\.\./', '', arg) for arg in args]
843 # add dependency on proguard config file, so a $(location) wrapper can be used.
844 module.tool_files.update(args)
845 # wrap filename in \"$(location filename)\"
846 args = ['$(location %s)' % arg for arg in args]
847 target.args[i + 1] = '[%s]' % ', '.join(args)
Motomu Utsumi1caa39b2022-11-02 18:38:13 +0900848 elif target.script == "//build/android/gyp/write_native_libraries_java.py":
849 for i, val in enumerate(target.args):
850 if val == '--output':
851 target.args[i + 1] = '$(out)'
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900852 elif target.script == "//tools/grit/stamp_grit_sources.py":
853 target.outputs = [re.sub('^\/\/', '', out) for out in target.outputs]
854 # Directory that contains grit scripts
855 target.args[0] = '`dirname $(location tools/grit/grit.py)`'
856 # Path to the stamp file
857 target.args[1] = '$(out)'
858 # Script tries to create args[2] file but this is not in the output.
859 # Specifying file under $(genDir) so that parent directory exists.
860 # If this file is used by other module, we may need to add this file to the outputs.
861 target.args[2] = '$(genDir)/' + target.args[2].split('/')[-1]
Mohannad Farrag033c9d62022-11-07 14:55:49 +0000862 elif target.script == "//tools/grit/grit.py":
863 for i, val in enumerate(target.args):
864 if val == '-i':
865 # Delete leading ../..
866 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
867 target.args[i + 1] = '$(location %s)' % filename
868 elif val == '-o':
869 filename = re.sub('^gen/', '', target.args[i + 1])
870 if filename == "net":
871 # This is a directory not a file
872 target.args[i + 1] = '$(genDir)/net'
873 else:
874 # This is an output fil
875 target.args[i + 1] = '$(location %s)' % filename
876 elif val == '--depfile':
877 # The depfile is replaced by adding /tools/**/*.py to the tools_files
878 # This is basically just globbing all the needed sources by hardcoding.
879 module.tool_files.update([
880 "tools/grit/**/*.py",
881 "third_party/six/src/six.py" # This is not picked up by default. Must be added
882 ])
883
884 # Delete the depfile argument
885 target.args[i] = ' '
886 target.args[i + 1] = ' '
887 elif val == '--input':
888 # Delete leading ../..
889 filename = re.sub('^\.\./\.\./', '', target.args[i + 1])
890 # This is an output file so use $(location %s)
891 target.args[i + 1] = '$(location %s)' % filename
Patrick Rohr245df582022-11-01 16:59:45 -0700892
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700893 script = gn_utils.label_to_path(target.script)
Patrick Rohr3d8c7282022-10-27 13:36:31 -0700894 module.tool_files.add(script)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700895
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700896 # Handle passing parameters via response file by piping them into the script
897 # and reading them from /dev/stdin.
898 response_file = '{{response_file_name}}'
899 use_response_file = response_file in target.args
900 if use_response_file:
901 # Replace {{response_file_contents}} with /dev/stdin
902 target.args = ['/dev/stdin' if it == response_file else it for it in target.args]
903
Patrick Rohr4b0952d2022-11-01 12:42:31 -0700904 # escape " and \$ in target.args.
905 # once all actions are properly implemented, this may not be necessary anymore.
906 # TODO: is this the right place to do this?
907 target.args = [arg.replace('"', r'\"') for arg in target.args]
908 target.args = [arg.replace(r'\$', r'\\$') for arg in target.args]
909
Patrick Rohr9b99a982022-10-28 11:00:57 -0700910 # put all args on a new line for better diffs.
911 NEWLINE = ' " +\n "'
912 arg_string = NEWLINE.join(target.args)
Patrick Rohr2041d5b2022-10-26 15:07:53 -0700913 module.cmd = '$(location %s) %s' % (script, arg_string)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700914
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700915 if use_response_file:
916 # Pipe response file contents into script
Patrick Rohr9b99a982022-10-28 11:00:57 -0700917 module.cmd = 'echo \'%s\' |%s%s' % (target.response_file_contents, NEWLINE, module.cmd)
Patrick Rohr8a4e2bd2022-10-27 13:06:16 -0700918
Patrick Rohr67f4d432022-10-26 16:04:15 -0700919 if all(os.path.splitext(it)[1] == '.h' for it in target.outputs):
920 module.genrule_headers.add(bp_module_name)
Patrick Rohre1a853e2022-10-26 12:31:39 -0700921
Patrick Rohr0db9f852022-10-27 13:49:57 -0700922 # gn treats inputs and sources for actions equally.
923 # soong only supports source files inside srcs, non-source files are added as
924 # tool_files dependency.
925 for it in target.sources or target.inputs:
926 if is_supported_source_file(it):
927 module.srcs.add(gn_utils.label_to_path(it))
928 else:
929 module.tool_files.add(gn_utils.label_to_path(it))
Patrick Rohre1a853e2022-10-26 12:31:39 -0700930
Patrick Rohr15a2c302022-10-26 15:08:57 -0700931 # Actions using template "action_with_pydeps" also put script inside inputs.
932 # TODO: it might make sense to filter inputs inside GnParser.
933 if script in module.srcs:
934 module.srcs.remove(script)
935
Patrick Rohre1a853e2022-10-26 12:31:39 -0700936 module.out.update(target.outputs)
Motomu Utsumia6c33152022-11-02 18:21:55 +0900937
938 if target.name == "//build/android:build_config_gen":
939 module = override_build_config_gen(module)
Motomu Utsumi26211dc2022-11-02 19:38:47 +0900940 elif target.script == "//tools/grit/stamp_grit_sources.py":
941 # stamp_grit_sources.py is not executable
942 module.cmd = "python " + module.cmd
Mohannad Farrag18d7b512022-11-07 13:26:30 +0000943 elif target.script == "//base/android/jni_generator/jni_generator.py":
944 # android_jar.classes should be part of the tools as it list implicit classes
945 # for the script to generate JNI headers.
946 module.tool_files.add("base/android/jni_generator/android_jar.classes")
Motomu Utsumia6c33152022-11-02 18:21:55 +0900947
Patrick Rohre1a853e2022-10-26 12:31:39 -0700948 blueprint.add_module(module)
949 return module
950
951
Patrick Rohr92d74122022-10-21 15:50:52 -0700952
953def _get_cflags(target):
954 cflags = {flag for flag in target.cflags if re.match(cflag_allowlist, flag)}
Motomu Utsumifa7e9262022-10-26 19:43:02 +0900955 # Consider proper allowlist or denylist if needed
956 cflags |= set("-D%s" % define.replace("\"", "\\\"") for define in target.defines)
Patrick Rohr92d74122022-10-21 15:50:52 -0700957 return cflags
958
959
960def create_modules_from_target(blueprint, gn, gn_target_name):
961 """Generate module(s) for a given GN target.
962
963 Given a GN target name, generate one or more corresponding modules into a
964 blueprint. The only case when this generates >1 module is proto libraries.
965
966 Args:
967 blueprint: Blueprint instance which is being generated.
968 gn: gn_utils.GnParser object.
969 gn_target_name: GN target for module generation.
970 """
971 bp_module_name = label_to_module_name(gn_target_name)
972 if bp_module_name in blueprint.modules:
973 return blueprint.modules[bp_module_name]
974 target = gn.get_target(gn_target_name)
Patrick Rohr16228942022-10-26 14:00:26 -0700975 log.info('create modules for %s (%s)', target.name, target.type)
Patrick Rohr92d74122022-10-21 15:50:52 -0700976
977 name_without_toolchain = gn_utils.label_without_toolchain(target.name)
978 if target.type == 'executable':
979 if target.toolchain == gn_utils.HOST_TOOLCHAIN:
980 module_type = 'cc_binary_host'
981 elif target.testonly:
982 module_type = 'cc_test'
983 else:
984 module_type = 'cc_binary'
985 module = Module(module_type, bp_module_name, gn_target_name)
986 elif target.type == 'static_library':
987 module = Module('cc_library_static', bp_module_name, gn_target_name)
988 elif target.type == 'shared_library':
989 module = Module('cc_library_shared', bp_module_name, gn_target_name)
990 elif target.type == 'source_set':
991 module = Module('filegroup', bp_module_name, gn_target_name)
992 elif target.type == 'group':
993 # "group" targets are resolved recursively by gn_utils.get_target().
994 # There's nothing we need to do at this level for them.
995 return None
996 elif target.type == 'proto_library':
997 module = create_proto_modules(blueprint, gn, target)
998 if module is None:
999 return None
1000 elif target.type == 'action':
1001 if 'gen_amalgamated_sql_metrics' in target.name:
1002 module = create_amalgamated_sql_metrics_module(blueprint, target)
1003 elif re.match('.*gen_cc_.*_descriptor$', name_without_toolchain):
1004 module = create_cc_proto_descriptor_module(blueprint, target)
1005 elif target.type == 'action' and \
1006 name_without_toolchain == gn_utils.GEN_VERSION_TARGET:
1007 module = create_gen_version_module(blueprint, target, bp_module_name)
1008 else:
Patrick Rohre1a853e2022-10-26 12:31:39 -07001009 module = create_action_module(blueprint, target)
Mohannad Farragf076f3e2022-10-31 17:45:28 +00001010 elif target.type == 'action_foreach':
Mohannad Farragbab6c892022-11-02 14:09:46 +00001011 module = create_action_foreach_modules(blueprint, target)
Patrick Rohr59a76652022-10-26 12:36:56 -07001012 elif target.type == 'copy':
1013 # TODO: careful now! copy targets are not supported yet, but this will stop
1014 # traversing the dependency tree. For //base:base, this is not a big
1015 # problem as libicu contains the only copy target which happens to be a
1016 # leaf node.
1017 return None
Patrick Rohr92d74122022-10-21 15:50:52 -07001018 else:
1019 raise Error('Unknown target %s (%s)' % (target.name, target.type))
1020
1021 blueprint.add_module(module)
1022 module.host_supported = (name_without_toolchain in target_host_supported)
Patrick Rohr92d74122022-10-21 15:50:52 -07001023 module.init_rc = target_initrc.get(target.name, [])
1024 module.srcs.update(
1025 gn_utils.label_to_path(src)
1026 for src in target.sources
Motomu Utsumif951e502022-11-07 19:31:15 +09001027 if is_supported_source_file(src) and not src.startswith("//out/test"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001028
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001029 local_include_dirs_set = set()
Patrick Rohr92d74122022-10-21 15:50:52 -07001030 if target.type in gn_utils.LINKER_UNIT_TYPES:
1031 module.cflags.update(_get_cflags(target))
Patrick Rohrf22e9d02022-10-28 14:20:46 -07001032 # TODO: implement proper cflag parsing.
1033 for flag in target.cflags:
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001034 if '-std=' in flag:
1035 module.cpp_std = flag[len('-std='):]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001036 if '-isystem' in flag:
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001037 local_include_dirs_set.add(flag[len('-isystem../../'):])
Patrick Rohrb8f830a2022-10-31 11:18:57 -07001038
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001039 # Adding local_include_dirs is necessary due to source_sets / filegroups
1040 # which do not properly propagate include directories.
1041 # Filter any directory inside //out as a) this directory does not exist for
1042 # aosp / soong builds and b) the include directory should already be
1043 # configured via library dependency.
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001044 local_include_dirs_set.update([gn_utils.label_to_path(d)
Patrick Rohrd0abc2a2022-10-31 13:29:16 -07001045 for d in target.include_dirs
1046 if not re.match('^//out/.*', d)])
Motomu Utsumi97fb1812022-11-01 13:08:10 +09001047 module.local_include_dirs = sorted(list(local_include_dirs_set))
1048
1049 # Order matters for some targets. For example, base/time/time_exploded_icu.cc
1050 # in //base:base needs to have sysroot include after icu/source/common
1051 # include. So adding sysroot include at the end.
1052 for flag in target.cflags:
1053 if '--sysroot' in flag:
1054 module.local_include_dirs.append(flag[len('--sysroot=../../'):] + "/usr/include")
Patrick Rohr92d74122022-10-21 15:50:52 -07001055
1056 module_is_compiled = module.type not in ('genrule', 'filegroup')
1057 if module_is_compiled:
1058 # Don't try to inject library/source dependencies into genrules or
1059 # filegroups because they are not compiled in the traditional sense.
1060 module.defaults = [defaults_module]
1061 for lib in target.libs:
1062 # Generally library names should be mangled as 'libXXX', unless they
1063 # are HAL libraries (e.g., android.hardware.health@2.0) or AIDL c++ / NDK
1064 # libraries (e.g. "android.hardware.power.stats-V1-cpp")
1065 android_lib = lib if '@' in lib or "-cpp" in lib or "-ndk" in lib \
1066 else 'lib' + lib
1067 if lib in shared_library_allowlist:
1068 module.add_android_shared_lib(android_lib)
1069 if lib in static_library_allowlist:
1070 module.add_android_static_lib(android_lib)
1071
1072 # If the module is a static library, export all the generated headers.
1073 if module.type == 'cc_library_static':
1074 module.export_generated_headers = module.generated_headers
1075
Patrick Rohr92d74122022-10-21 15:50:52 -07001076 # dep_name is an unmangled GN target name (e.g. //foo:bar(toolchain)).
Motomu Utsumif1daa232022-11-08 13:28:37 +09001077 # Currently, only one module is generated from target even target has multiple toolchains.
1078 # And module is generated based on the first visited target.
1079 # Sort deps before iteration to make result deterministic.
1080 all_deps = sorted(target.deps | target.source_set_deps | target.transitive_proto_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -07001081 for dep_name in all_deps:
Patrick Rohr5cc46e02022-10-26 14:32:45 -07001082 # |builtin_deps| override GN deps with Android-specific ones. See the
1083 # config in the top of this file.
1084 if gn_utils.label_without_toolchain(dep_name) in builtin_deps:
1085 builtin_deps[gn_utils.label_without_toolchain(dep_name)](module)
1086 continue
1087
Patrick Rohr92d74122022-10-21 15:50:52 -07001088 dep_module = create_modules_from_target(blueprint, gn, dep_name)
1089
Motomu Utsumie246feb2022-11-01 17:25:56 +09001090 # TODO: Proper dependency check for genrule.
1091 # Currently, only propagating genrule dependencies.
1092 # Also, currently, all the dependencies are propagated upwards.
1093 # in gn, public_deps should be propagated but deps should not.
1094 # Not sure this information is available in the desc.json.
1095 # Following rule works for adding android_runtime_jni_headers to base:base.
1096 # If this doesn't work for other target, hardcoding for specific target
1097 # might be better.
1098 if module.type == "genrule" and dep_module.type == "genrule":
1099 module.genrule_headers.add(dep_module.name)
1100 module.genrule_headers.update(dep_module.genrule_headers)
1101
Patrick Rohr92d74122022-10-21 15:50:52 -07001102 # For filegroups and genrule, recurse but don't apply the deps.
1103 if not module_is_compiled:
1104 continue
1105
Patrick Rohr92d74122022-10-21 15:50:52 -07001106 if dep_module is None:
1107 continue
1108 if dep_module.type == 'cc_library_shared':
1109 module.shared_libs.add(dep_module.name)
1110 elif dep_module.type == 'cc_library_static':
1111 module.static_libs.add(dep_module.name)
1112 elif dep_module.type == 'filegroup':
1113 module.srcs.add(':' + dep_module.name)
1114 elif dep_module.type == 'genrule':
1115 module.generated_headers.update(dep_module.genrule_headers)
1116 module.srcs.update(dep_module.genrule_srcs)
1117 module.shared_libs.update(dep_module.genrule_shared_libs)
Patrick Rohra1a27872022-10-31 11:57:14 -07001118 module.header_libs.update(dep_module.genrule_header_libs)
Patrick Rohr92d74122022-10-21 15:50:52 -07001119 elif dep_module.type == 'cc_binary':
1120 continue # Ignore executables deps (used by cmdline integration tests).
1121 else:
1122 raise Error('Unknown dep %s (%s) for target %s' %
1123 (dep_module.name, dep_module.type, module.name))
1124
1125 return module
1126
Patrick Rohrb18aca22022-11-04 15:07:32 -07001127def create_java_module(blueprint, gn):
1128 bp_module_name = module_prefix + 'java'
1129 module = Module('java_library', bp_module_name, '//gn:java')
Mohannad Farrag21562d62022-11-07 13:09:31 +00001130 module.srcs.update([gn_utils.label_to_path(source) for source in gn.java_sources])
Patrick Rohrb18aca22022-11-04 15:07:32 -07001131 blueprint.add_module(module)
Patrick Rohr92d74122022-10-21 15:50:52 -07001132
1133def create_blueprint_for_targets(gn, desc, targets):
1134 """Generate a blueprint for a list of GN targets."""
1135 blueprint = Blueprint()
1136
1137 # Default settings used by all modules.
1138 defaults = Module('cc_defaults', defaults_module, '//gn:default_deps')
Patrick Rohr92d74122022-10-21 15:50:52 -07001139 defaults.cflags = [
1140 '-Wno-error=return-type',
Patrick Rohr3a1ec1d2022-10-31 13:30:17 -07001141 '-Wno-non-virtual-dtor',
Patrick Rohr98065152022-10-31 14:49:58 -07001142 '-Wno-missing-field-initializers',
Patrick Rohr92d74122022-10-21 15:50:52 -07001143 '-Wno-sign-compare',
1144 '-Wno-sign-promo',
1145 '-Wno-unused-parameter',
1146 '-fvisibility=hidden',
1147 '-O2',
1148 ]
Patrick Rohr61f2acb2022-10-31 14:08:18 -07001149 defaults.stl = 'none'
Patrick Rohr92d74122022-10-21 15:50:52 -07001150 blueprint.add_module(defaults)
Patrick Rohr344b2472022-10-25 11:32:15 -07001151
Patrick Rohr92d74122022-10-21 15:50:52 -07001152 for target in targets:
1153 create_modules_from_target(blueprint, gn, target)
Patrick Rohrb18aca22022-11-04 15:07:32 -07001154
1155 create_java_module(blueprint, gn)
Patrick Rohra7d029d2022-11-08 12:23:11 -08001156
1157 # Merge in additional hardcoded arguments.
1158 for module in blueprint.modules.values():
1159 for key, add_val in additional_args.get(module.name, []):
1160 curr = getattr(module, key)
1161 if add_val and isinstance(add_val, set) and isinstance(curr, set):
1162 curr.update(add_val)
1163 elif isinstance(add_val, str) and (not curr or isinstance(curr, str)):
1164 setattr(module, key, add_val)
1165 elif isinstance(add_val, bool) and (not curr or isinstance(curr, bool)):
1166 setattr(module, key, add_val)
1167 elif isinstance(add_val, dict) and isinstance(curr, dict):
1168 curr.update(add_val)
1169 elif isinstance(add_val, dict) and isinstance(curr, Target):
1170 curr.__dict__.update(add_val)
1171 else:
1172 raise Error('Unimplemented type %r of additional_args: %r' %
1173 (type(add_val), key))
1174
Patrick Rohr92d74122022-10-21 15:50:52 -07001175 return blueprint
1176
1177
1178def main():
1179 parser = argparse.ArgumentParser(
1180 description='Generate Android.bp from a GN description.')
1181 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001182 '--desc',
Patrick Rohr3db246a2022-10-25 10:25:17 -07001183 help='GN description (e.g., gn desc out --format=json --all-toolchains "//*"',
1184 required=True
Patrick Rohr92d74122022-10-21 15:50:52 -07001185 )
1186 parser.add_argument(
1187 '--extras',
1188 help='Extra targets to include at the end of the Blueprint file',
1189 default=os.path.join(gn_utils.repo_root(), 'Android.bp.extras'),
1190 )
1191 parser.add_argument(
1192 '--output',
1193 help='Blueprint file to create',
1194 default=os.path.join(gn_utils.repo_root(), 'Android.bp'),
1195 )
1196 parser.add_argument(
Patrick Rohr16228942022-10-26 14:00:26 -07001197 '-v',
1198 '--verbose',
1199 help='Print debug logs.',
1200 action='store_true',
1201 )
1202 parser.add_argument(
Patrick Rohr92d74122022-10-21 15:50:52 -07001203 'targets',
1204 nargs=argparse.REMAINDER,
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001205 help='Targets to include in the blueprint (e.g., "//:perfetto_tests")'
1206 )
Patrick Rohr92d74122022-10-21 15:50:52 -07001207 args = parser.parse_args()
1208
Patrick Rohr16228942022-10-26 14:00:26 -07001209 if args.verbose:
1210 log.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level=log.DEBUG)
1211
Patrick Rohr3db246a2022-10-25 10:25:17 -07001212 with open(args.desc) as f:
1213 desc = json.load(f)
Patrick Rohr92d74122022-10-21 15:50:52 -07001214
1215 gn = gn_utils.GnParser(desc)
Patrick Rohr1aa504a2022-10-25 10:30:42 -07001216 blueprint = create_blueprint_for_targets(gn, desc, args.targets)
Patrick Rohr92d74122022-10-21 15:50:52 -07001217 project_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
1218 tool_name = os.path.relpath(os.path.abspath(__file__), project_root)
1219
Patrick Rohr92d74122022-10-21 15:50:52 -07001220 # Add any proto groups to the blueprint.
1221 for l_name, t_names in proto_groups.items():
1222 create_proto_group_modules(blueprint, gn, l_name, t_names)
1223
1224 output = [
Patrick Rohr5478b392022-10-25 09:58:50 -07001225 """// Copyright (C) 2022 The Android Open Source Project
Patrick Rohr92d74122022-10-21 15:50:52 -07001226//
1227// Licensed under the Apache License, Version 2.0 (the "License");
1228// you may not use this file except in compliance with the License.
1229// You may obtain a copy of the License at
1230//
1231// http://www.apache.org/licenses/LICENSE-2.0
1232//
1233// Unless required by applicable law or agreed to in writing, software
1234// distributed under the License is distributed on an "AS IS" BASIS,
1235// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1236// See the License for the specific language governing permissions and
1237// limitations under the License.
1238//
1239// This file is automatically generated by %s. Do not edit.
1240""" % (tool_name)
1241 ]
1242 blueprint.to_string(output)
Patrick Rohrcb98e9b2022-10-25 09:57:02 -07001243 if os.path.exists(args.extras):
1244 with open(args.extras, 'r') as r:
1245 for line in r:
1246 output.append(line.rstrip("\n\r"))
Patrick Rohr92d74122022-10-21 15:50:52 -07001247
1248 out_files = []
1249
1250 # Generate the Android.bp file.
1251 out_files.append(args.output + '.swp')
1252 with open(out_files[-1], 'w') as f:
1253 f.write('\n'.join(output))
1254 # Text files should have a trailing EOL.
1255 f.write('\n')
1256
Patrick Rohr94693eb2022-10-25 10:09:16 -07001257 return 0
Patrick Rohr92d74122022-10-21 15:50:52 -07001258
1259
1260if __name__ == '__main__':
1261 sys.exit(main())