blob: 130f8ff715e862210024b31d4ac88e94b367245c [file] [log] [blame]
Patrick Rohr92d74122022-10-21 15:50:52 -07001# Copyright (C) 2022 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# A collection of utilities for extracting build rule information from GN
16# projects.
17
18from __future__ import print_function
19import collections
20import errno
21import filecmp
22import json
Patrick Rohraf92fa62022-11-04 14:27:04 -070023import logging as log
Patrick Rohr92d74122022-10-21 15:50:52 -070024import os
25import re
26import shutil
27import subprocess
28import sys
Patrick Rohr92d74122022-10-21 15:50:52 -070029
30BUILDFLAGS_TARGET = '//gn:gen_buildflags'
31GEN_VERSION_TARGET = '//src/base:version_gen_h'
Mohannad Farrag7f29d832022-11-23 19:52:41 +000032LINKER_UNIT_TYPES = ('executable', 'shared_library', 'static_library', 'source_set')
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +000033JAVA_BANNED_SCRIPTS = [
34 "//build/android/gyp/turbine.py",
35 "//build/android/gyp/compile_java.py",
36 "//build/android/gyp/filter_zip.py",
37 "//build/android/gyp/dex.py",
38 "//build/android/gyp/write_build_config.py",
39 "//build/android/gyp/create_r_java.py",
40 "//build/android/gyp/ijar.py",
41 "//build/android/gyp/create_r_java.py",
42 "//build/android/gyp/bytecode_processor.py",
43 "//build/android/gyp/prepare_resources.py",
44 "//build/android/gyp/aar.py",
45 "//build/android/gyp/zip.py",
46]
Patrick Rohr92d74122022-10-21 15:50:52 -070047# TODO(primiano): investigate these, they require further componentization.
48ODR_VIOLATION_IGNORE_TARGETS = {
49 '//test/cts:perfetto_cts_deps',
50 '//:perfetto_integrationtests',
51}
Mohannad Farrag4bea14a2022-11-22 15:38:30 +000052ARCH_REGEX = r'(android_x86_64|android_x86|android_arm|android_arm64|host)'
53DEX_REGEX = '.*__dex__%s$' % ARCH_REGEX
54COMPILE_JAVA_REGEX = '.*__compile_java__%s$' % ARCH_REGEX
Mohannad Farraga0e37c12022-12-02 14:46:08 +000055RESPONSE_FILE = '{{response_file_name}}'
56
Patrick Rohr92d74122022-10-21 15:50:52 -070057def repo_root():
58 """Returns an absolute path to the repository root."""
59 return os.path.join(
60 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
61
62
Patrick Rohr92d74122022-10-21 15:50:52 -070063def label_to_path(label):
64 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
65 assert label.startswith('//')
Patrick Rohrc6331c82022-10-25 11:34:20 -070066 return label[2:] or "./"
Patrick Rohr92d74122022-10-21 15:50:52 -070067
68
69def label_without_toolchain(label):
70 """Strips the toolchain from a GN label.
71
72 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
73 gcc_like_host) without the parenthesised toolchain part.
74 """
75 return label.split('(')[0]
76
77
78def label_to_target_name_with_path(label):
79 """
80 Turn a GN label into a target name involving the full path.
81 e.g., //src/perfetto:tests -> src_perfetto_tests
82 """
83 name = re.sub(r'^//:?', '', label)
84 name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
85 return name
86
Mohannad Farraga0db68b2022-11-24 12:28:09 +000087def _is_java_source(src):
88 return os.path.splitext(src)[1] == '.java' and not src.startswith("//out/test/gen/")
Patrick Rohr92d74122022-10-21 15:50:52 -070089
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +000090def is_java_action(script, outputs):
91 return (script != "" and script not in JAVA_BANNED_SCRIPTS) and any(
92 [file.endswith(".srcjar") or file.endswith(".java")
93 for file in outputs])
94
Patrick Rohr92d74122022-10-21 15:50:52 -070095class GnParser(object):
96 """A parser with some cleverness for GN json desc files
97
98 The main goals of this parser are:
99 1) Deal with the fact that other build systems don't have an equivalent
100 notion to GN's source_set. Conversely to Bazel's and Soong's filegroups,
101 GN source_sets expect that dependencies, cflags and other source_set
102 properties propagate up to the linker unit (static_library, executable or
103 shared_library). This parser simulates the same behavior: when a
104 source_set is encountered, some of its variables (cflags and such) are
105 copied up to the dependent targets. This is to allow gen_xxx to create
106 one filegroup for each source_set and then squash all the other flags
107 onto the linker unit.
108 2) Detect and special-case protobuf targets, figuring out the protoc-plugin
109 being used.
110 """
111
112 class Target(object):
113 """Reperesents A GN target.
114
115 Maked properties are propagated up the dependency chain when a
116 source_set dependency is encountered.
117 """
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800118 class Arch():
119 """Architecture-dependent properties
120 """
121 def __init__(self):
122 self.sources = set()
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900123 self.cflags = set()
Motomu Utsumi80e04472022-11-17 21:54:06 +0900124 self.defines = set()
Motomu Utsumi778f8302022-11-17 22:12:17 +0900125 self.include_dirs = set()
Patrick Rohr297f9792022-11-16 23:40:40 -0800126 self.deps = set()
127 self.transitive_static_libs_deps = set()
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000128 self.source_set_deps = set()
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800129
Patrick Rohr92d74122022-10-21 15:50:52 -0700130
131 def __init__(self, name, type):
132 self.name = name # e.g. //src/ipc:ipc
133
134 VALID_TYPES = ('static_library', 'shared_library', 'executable', 'group',
Patrick Rohrda778a02022-10-25 16:17:31 -0700135 'action', 'source_set', 'proto_library', 'copy', 'action_foreach')
Patrick Rohr92d74122022-10-21 15:50:52 -0700136 assert (type in VALID_TYPES)
137 self.type = type
138 self.testonly = False
139 self.toolchain = None
140
141 # These are valid only for type == proto_library.
142 # This is typically: 'proto', 'protozero', 'ipc'.
143 self.proto_plugin = None
144 self.proto_paths = set()
145 self.proto_exports = set()
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900146 self.proto_in_dir = ""
Patrick Rohr92d74122022-10-21 15:50:52 -0700147
148 self.sources = set()
149 # TODO(primiano): consider whether the public section should be part of
150 # bubbled-up sources.
151 self.public_headers = set() # 'public'
152
153 # These are valid only for type == 'action'
154 self.inputs = set()
155 self.outputs = set()
156 self.script = None
157 self.args = []
Patrick Rohr09716f52022-10-27 13:02:36 -0700158 self.response_file_contents = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700159
160 # These variables are propagated up when encountering a dependency
161 # on a source_set target.
162 self.cflags = set()
163 self.defines = set()
164 self.deps = set()
165 self.libs = set()
166 self.include_dirs = set()
167 self.ldflags = set()
168 self.source_set_deps = set() # Transitive set of source_set deps.
169 self.proto_deps = set()
170 self.transitive_proto_deps = set()
Mohannad Farragbaf0d572022-11-22 11:53:54 +0000171 self.rtti = False
Patrick Rohr92d74122022-10-21 15:50:52 -0700172
Patrick Rohr70913562022-11-15 21:49:28 -0800173 # TODO: come up with a better way to only run this once.
174 # is_finalized tracks whether finalize() was called on this target.
175 self.is_finalized = False
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800176 self.arch = dict()
177
Motomu Utsumiee47af62022-11-30 16:41:15 +0900178 # This is used to get the name/version of libcronet
179 self.output_name = None
180
Patrick Rohrc8f41cd2022-11-15 22:46:10 -0800181 def host_supported(self):
182 return 'host' in self.arch
183
184 def device_supported(self):
185 return any([name.startswith('android') for name in self.arch.keys()])
186
Patrick Rohr92d74122022-10-21 15:50:52 -0700187 def __lt__(self, other):
188 if isinstance(other, self.__class__):
189 return self.name < other.name
190 raise TypeError(
191 '\'<\' not supported between instances of \'%s\' and \'%s\'' %
192 (type(self).__name__, type(other).__name__))
193
194 def __repr__(self):
195 return json.dumps({
196 k: (list(sorted(v)) if isinstance(v, set) else v)
Patrick Rohr23f26192022-10-25 09:45:22 -0700197 for (k, v) in self.__dict__.items()
Patrick Rohr92d74122022-10-21 15:50:52 -0700198 },
199 indent=4,
200 sort_keys=True)
201
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900202 def update(self, other, arch):
Patrick Rohr92d74122022-10-21 15:50:52 -0700203 for key in ('cflags', 'defines', 'deps', 'include_dirs', 'ldflags',
204 'source_set_deps', 'proto_deps', 'transitive_proto_deps',
205 'libs', 'proto_paths'):
206 self.__dict__[key].update(other.__dict__.get(key, []))
207
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000208 for key_in_arch in ('cflags', 'defines', 'include_dirs', 'source_set_deps'):
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900209 self.arch[arch].__dict__[key_in_arch].update(
210 other.arch[arch].__dict__.get(key_in_arch, []))
211
Patrick Rohr70913562022-11-15 21:49:28 -0800212 def finalize(self):
213 """Move common properties out of arch-dependent subobjects to Target object.
214
215 TODO: find a better name for this function.
216 """
217 if self.is_finalized:
218 return
219 self.is_finalized = True
220
Patrick Rohr70913562022-11-15 21:49:28 -0800221 # Target contains the intersection of arch-dependent properties
222 self.sources = set.intersection(*[arch.sources for arch in self.arch.values()])
Motomu Utsumif0f47682022-11-17 22:34:39 +0900223 self.cflags = set.intersection(*[arch.cflags for arch in self.arch.values()])
224 self.defines = set.intersection(*[arch.defines for arch in self.arch.values()])
225 self.include_dirs = set.intersection(*[arch.include_dirs for arch in self.arch.values()])
Patrick Rohr297f9792022-11-16 23:40:40 -0800226 self.deps.update(set.intersection(*[arch.deps for arch in self.arch.values()]))
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000227 self.source_set_deps.update(set.intersection(*[arch.source_set_deps for arch in self.arch.values()]))
Patrick Rohr70913562022-11-15 21:49:28 -0800228
229 # Deduplicate arch-dependent properties
230 for arch in self.arch.keys():
231 self.arch[arch].sources -= self.sources
Motomu Utsumif0f47682022-11-17 22:34:39 +0900232 self.arch[arch].cflags -= self.cflags
233 self.arch[arch].defines -= self.defines
234 self.arch[arch].include_dirs -= self.include_dirs
Patrick Rohr297f9792022-11-16 23:40:40 -0800235 self.arch[arch].deps -= self.deps
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000236 self.arch[arch].source_set_deps -= self.source_set_deps
Patrick Rohr297f9792022-11-16 23:40:40 -0800237
Patrick Rohr70913562022-11-15 21:49:28 -0800238
Patrick Rohr564d6be2022-11-15 12:57:57 -0800239 def __init__(self):
Patrick Rohr92d74122022-10-21 15:50:52 -0700240 self.all_targets = {}
241 self.linker_units = {} # Executables, shared or static libraries.
242 self.source_sets = {}
243 self.actions = {}
244 self.proto_libs = {}
Patrick Rohrb27587e2022-11-04 14:57:24 -0700245 self.java_sources = set()
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000246 self.java_actions = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700247
Patrick Rohr09716f52022-10-27 13:02:36 -0700248 def _get_response_file_contents(self, action_desc):
Patrick Rohrc20887d2022-10-28 12:59:20 -0700249 # response_file_contents are formatted as:
250 # ['--flags', '--flag=true && false'] and need to be formatted as:
251 # '--flags --flag=\"true && false\"'
252 flags = action_desc.get('response_file_contents', [])
253 formatted_flags = []
254 for flag in flags:
255 if '=' in flag:
256 key, val = flag.split('=')
257 formatted_flags.append('%s=\\"%s\\"' % (key, val))
258 else:
259 formatted_flags.append(flag)
260
261 return ' '.join(formatted_flags)
Patrick Rohr09716f52022-10-27 13:02:36 -0700262
Patrick Rohraf92fa62022-11-04 14:27:04 -0700263 def _is_java_target(self, target):
264 # Per https://chromium.googlesource.com/chromium/src/build/+/HEAD/android/docs/java_toolchain.md
265 # java target names must end in "_java".
266 # TODO: There are some other possible variations we might need to support.
Patrick Rohr67f53122022-11-09 10:57:40 -0800267 return target.type == 'group' and re.match('.*_java$', target.name)
Patrick Rohraf92fa62022-11-04 14:27:04 -0700268
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800269 def _get_arch(self, toolchain):
Patrick Rohrd938d532022-11-15 22:17:08 -0800270 if toolchain == '//build/toolchain/android:android_clang_x86':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800271 return 'android_x86'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800272 elif toolchain == '//build/toolchain/android:android_clang_x64':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800273 return 'android_x86_64'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800274 elif toolchain == '//build/toolchain/android:android_clang_arm':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800275 return 'android_arm'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800276 elif toolchain == '//build/toolchain/android:android_clang_arm64':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800277 return 'android_arm64'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800278 else:
279 return 'host'
280
Patrick Rohr92d74122022-10-21 15:50:52 -0700281 def get_target(self, gn_target_name):
282 """Returns a Target object from the fully qualified GN target name.
283
Patrick Rohrd0077b72022-11-15 12:43:26 -0800284 get_target() requires that parse_gn_desc() has already been called.
285 """
Patrick Rohr70913562022-11-15 21:49:28 -0800286 # Run this every time as parse_gn_desc can be called at any time.
287 for target in self.all_targets.values():
288 target.finalize()
289
Patrick Rohr7705bdb2022-11-15 13:26:30 -0800290 return self.all_targets[label_without_toolchain(gn_target_name)]
Patrick Rohrd0077b72022-11-15 12:43:26 -0800291
Patrick Rohr564d6be2022-11-15 12:57:57 -0800292 def parse_gn_desc(self, gn_desc, gn_target_name):
Patrick Rohrd0077b72022-11-15 12:43:26 -0800293 """Parses a gn desc tree and resolves all target dependencies.
294
Patrick Rohr92d74122022-10-21 15:50:52 -0700295 It bubbles up variables from source_set dependencies as described in the
296 class-level comments.
297 """
Patrick Rohr7705bdb2022-11-15 13:26:30 -0800298 # Use name without toolchain for targets to support targets built for
299 # multiple archs.
300 target_name = label_without_toolchain(gn_target_name)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800301 desc = gn_desc[gn_target_name]
Patrick Rohr98600682022-11-18 18:29:15 -0800302 type_ = desc['type']
Patrick Rohrd938d532022-11-15 22:17:08 -0800303 arch = self._get_arch(desc['toolchain'])
Patrick Rohr98600682022-11-18 18:29:15 -0800304
305 # Action modules can differ depending on the target architecture, yet
306 # genrule's do not allow to overload cmd per target OS / arch. Create a
307 # separate action for every architecture.
Mohannad Farragd7efd7b92022-11-21 16:15:16 +0000308 # Cover both action and action_foreach
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000309 if type_.startswith('action') and \
310 not is_java_action(desc.get("script", ""), desc.get("outputs", [])):
311 # Don't meddle with the java actions name
Patrick Rohr98600682022-11-18 18:29:15 -0800312 target_name += '__' + arch
313
314 target = self.all_targets.get(target_name)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800315 if target is None:
Patrick Rohr98600682022-11-18 18:29:15 -0800316 target = GnParser.Target(target_name, type_)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800317 self.all_targets[target_name] = target
318
319 if arch not in target.arch:
320 target.arch[arch] = GnParser.Target.Arch()
321 else:
Patrick Rohr92d74122022-10-21 15:50:52 -0700322 return target # Target already processed.
323
Patrick Rohr92d74122022-10-21 15:50:52 -0700324 target.testonly = desc.get('testonly', False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700325
Patrick Rohr0d40da32022-11-15 13:08:12 -0800326 proto_target_type, proto_desc = self.get_proto_target_type(gn_desc, gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700327 if proto_target_type is not None:
328 self.proto_libs[target.name] = target
329 target.type = 'proto_library'
330 target.proto_plugin = proto_target_type
331 target.proto_paths.update(self.get_proto_paths(proto_desc))
332 target.proto_exports.update(self.get_proto_exports(proto_desc))
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900333 target.proto_in_dir = self.get_proto_in_dir(proto_desc)
Patrick Rohrad7a29c2022-11-16 21:48:09 -0800334 for gn_proto_deps_name in proto_desc.get('deps', []):
335 dep = self.parse_gn_desc(gn_desc, gn_proto_deps_name)
336 target.deps.add(dep.name)
Patrick Rohr53dcd102022-11-15 21:53:02 -0800337 target.arch[arch].sources.update(proto_desc.get('sources', []))
338 assert (all(x.endswith('.proto') for x in target.arch[arch].sources))
Patrick Rohr92d74122022-10-21 15:50:52 -0700339 elif target.type == 'source_set':
340 self.source_sets[gn_target_name] = target
Patrick Rohr53dcd102022-11-15 21:53:02 -0800341 target.arch[arch].sources.update(desc.get('sources', []))
Patrick Rohr92d74122022-10-21 15:50:52 -0700342 elif target.type in LINKER_UNIT_TYPES:
343 self.linker_units[gn_target_name] = target
Patrick Rohr53dcd102022-11-15 21:53:02 -0800344 target.arch[arch].sources.update(desc.get('sources', []))
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000345 elif desc.get("script", "") in JAVA_BANNED_SCRIPTS or self._is_java_target(target):
346 # java_group identifies the group target generated by the android_library
347 # or java_library template. A java_group must not be added as a dependency, but sources are collected
348 log.debug('Found java target %s', target.name)
349 if target.type == "action":
350 # Convert java actions into java_group and keep the inputs for collection.
351 target.inputs.update(desc.get('inputs', []))
352 target.type = 'java_group'
Patrick Rohrda778a02022-10-25 16:17:31 -0700353 elif target.type in ['action', 'action_foreach']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700354 self.actions[gn_target_name] = target
355 target.inputs.update(desc.get('inputs', []))
Patrick Rohr53dcd102022-11-15 21:53:02 -0800356 target.arch[arch].sources.update(desc.get('sources', []))
Patrick Rohr92d74122022-10-21 15:50:52 -0700357 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
358 target.outputs.update(outs)
359 target.script = desc['script']
Patrick Rohr7aa98f92022-10-28 11:16:36 -0700360 target.args = desc['args']
Patrick Rohr09716f52022-10-27 13:02:36 -0700361 target.response_file_contents = self._get_response_file_contents(desc)
Patrick Rohrda778a02022-10-25 16:17:31 -0700362 elif target.type == 'copy':
363 # TODO: copy rules are not currently implemented.
364 self.actions[gn_target_name] = target
Patrick Rohr92d74122022-10-21 15:50:52 -0700365
366 # Default for 'public' is //* - all headers in 'sources' are public.
367 # TODO(primiano): if a 'public' section is specified (even if empty), then
368 # the rest of 'sources' is considered inaccessible by gn. Consider
369 # emulating that, so that generated build files don't end up with overly
370 # accessible headers.
371 public_headers = [x for x in desc.get('public', []) if x != '*']
372 target.public_headers.update(public_headers)
373
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900374 target.arch[arch].cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
Patrick Rohr92d74122022-10-21 15:50:52 -0700375 target.libs.update(desc.get('libs', []))
376 target.ldflags.update(desc.get('ldflags', []))
Motomu Utsumi80e04472022-11-17 21:54:06 +0900377 target.arch[arch].defines.update(desc.get('defines', []))
Motomu Utsumi778f8302022-11-17 22:12:17 +0900378 target.arch[arch].include_dirs.update(desc.get('include_dirs', []))
Motomu Utsumiee47af62022-11-30 16:41:15 +0900379 target.output_name = desc.get('output_name', None)
Mohannad Farragbaf0d572022-11-22 11:53:54 +0000380 if "-frtti" in target.arch[arch].cflags:
381 target.rtti = True
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000382
Patrick Rohr92d74122022-10-21 15:50:52 -0700383 # Recurse in dependencies.
Patrick Rohr7f4631e2022-11-15 14:35:03 -0800384 for gn_dep_name in desc.get('deps', []):
385 dep = self.parse_gn_desc(gn_desc, gn_dep_name)
Patrick Rohrf1004372022-11-16 23:04:05 -0800386 if dep.type == 'proto_library':
Patrick Rohr9006b362022-11-16 21:49:53 -0800387 target.proto_deps.add(dep.name)
388 target.transitive_proto_deps.add(dep.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700389 target.proto_paths.update(dep.proto_paths)
390 target.transitive_proto_deps.update(dep.transitive_proto_deps)
391 elif dep.type == 'source_set':
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000392 target.arch[arch].source_set_deps.add(dep.name)
393 target.arch[arch].source_set_deps.update(dep.arch[arch].source_set_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -0700394 elif dep.type == 'group':
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900395 target.update(dep, arch) # Bubble up groups's cflags/ldflags etc.
Patrick Rohrda778a02022-10-25 16:17:31 -0700396 elif dep.type in ['action', 'action_foreach', 'copy']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700397 if proto_target_type is None:
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000398 target.arch[arch].deps.add(dep.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700399 elif dep.type in LINKER_UNIT_TYPES:
Patrick Rohr297f9792022-11-16 23:40:40 -0800400 target.arch[arch].deps.add(dep.name)
Patrick Rohr3624f952022-11-04 14:30:18 -0700401 elif dep.type == 'java_group':
402 # Explicitly break dependency chain when a java_group is added.
403 # Java sources are collected and eventually compiled as one large
404 # java_library.
405 pass
Patrick Rohr92d74122022-10-21 15:50:52 -0700406
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000407 # Source set bubble up transitive source sets but can't be combined with this
408 # if they are combined then source sets will bubble up static libraries
409 # while we only want to have source sets bubble up only source sets.
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800410 if dep.type == 'static_library':
411 # Bubble up static_libs. Necessary, since soong does not propagate
412 # static_libs up the build tree.
Patrick Rohr297f9792022-11-16 23:40:40 -0800413 target.arch[arch].transitive_static_libs_deps.add(dep.name)
Patrick Rohra9c1dda2022-11-14 19:02:40 -0800414
Patrick Rohr297f9792022-11-16 23:40:40 -0800415 if arch in dep.arch:
416 target.arch[arch].transitive_static_libs_deps.update(
417 dep.arch[arch].transitive_static_libs_deps)
418 target.arch[arch].deps.update(target.arch[arch].transitive_static_libs_deps)
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800419
Patrick Rohrb27587e2022-11-04 14:57:24 -0700420 # Collect java sources. Java sources are kept inside the __compile_java target.
421 # This target can be used for both host and target compilation; only add
422 # the sources if they are destined for the target (i.e. they are a
423 # dependency of the __dex target)
424 # Note: this skips prebuilt java dependencies. These will have to be
425 # added manually when building the jar.
Mohannad Farrag4bea14a2022-11-22 15:38:30 +0000426 if re.match(DEX_REGEX, target.name):
427 if re.match(COMPILE_JAVA_REGEX, dep.name):
Patrick Rohrb27587e2022-11-04 14:57:24 -0700428 log.debug('Adding java sources for %s', dep.name)
Mohannad Farraga0db68b2022-11-24 12:28:09 +0000429 java_srcs = [src for src in dep.inputs if _is_java_source(src)]
Patrick Rohrb27587e2022-11-04 14:57:24 -0700430 self.java_sources.update(java_srcs)
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000431 if dep.type in ["action"] and target.type == "java_group":
Motomu Utsumi6e514122022-12-05 17:51:40 +0900432 # //base:base_java_aidl generates srcjar from .aidl files. But java_library in soong can
433 # directly have .aidl files in srcs. So adding .aidl files to the java_sources.
434 # TODO: Find a better way/place to do this.
435 if dep.name == '//base:base_java_aidl':
436 self.java_sources.update(dep.arch[arch].sources)
437 else:
438 self.java_actions.add(dep.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700439 return target
440
441 def get_proto_exports(self, proto_desc):
442 # exports in metadata will be available for source_set targets.
443 metadata = proto_desc.get('metadata', {})
444 return metadata.get('exports', [])
445
446 def get_proto_paths(self, proto_desc):
447 # import_dirs in metadata will be available for source_set targets.
448 metadata = proto_desc.get('metadata', {})
449 return metadata.get('import_dirs', [])
450
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900451
452 def get_proto_in_dir(self, proto_desc):
453 args = proto_desc.get('args')
454 return re.sub('^\.\./\.\./', '', args[args.index('--proto-in-dir') + 1])
455
Patrick Rohr0d40da32022-11-15 13:08:12 -0800456 def get_proto_target_type(self, gn_desc, gn_target_name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700457 """ Checks if the target is a proto library and return the plugin.
458
459 Returns:
460 (None, None): if the target is not a proto library.
461 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
462 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
463 json desc of the target with the .proto sources (_gen target for
464 non-descriptor types or the target itself for descriptor type).
465 """
Patrick Rohr0d40da32022-11-15 13:08:12 -0800466 parts = gn_target_name.split('(', 1)
Patrick Rohr92d74122022-10-21 15:50:52 -0700467 name = parts[0]
468 toolchain = '(' + parts[1] if len(parts) > 1 else ''
469
470 # Descriptor targets don't have a _gen target; instead we look for the
471 # characteristic flag in the args of the target itself.
Patrick Rohr0d40da32022-11-15 13:08:12 -0800472 desc = gn_desc.get(gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700473 if '--descriptor_set_out' in desc.get('args', []):
474 return 'descriptor', desc
475
476 # Source set proto targets have a non-empty proto_library_sources in the
477 # metadata of the description.
478 metadata = desc.get('metadata', {})
479 if 'proto_library_sources' in metadata:
480 return 'source_set', desc
481
482 # In all other cases, we want to look at the _gen target as that has the
483 # important information.
Patrick Rohr564d6be2022-11-15 12:57:57 -0800484 gen_desc = gn_desc.get('%s_gen%s' % (name, toolchain))
Patrick Rohr92d74122022-10-21 15:50:52 -0700485 if gen_desc is None or gen_desc['type'] != 'action':
486 return None, None
Patrick Rohrc5980782022-11-07 16:34:03 -0800487 if gen_desc['script'] != '//tools/protoc_wrapper/protoc_wrapper.py':
Patrick Rohr92d74122022-10-21 15:50:52 -0700488 return None, None
489 plugin = 'proto'
Patrick Rohrc5980782022-11-07 16:34:03 -0800490 args = gen_desc.get('args', [])
Patrick Rohr92d74122022-10-21 15:50:52 -0700491 for arg in (arg for arg in args if arg.startswith('--plugin=')):
492 # |arg| at this point looks like:
493 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
494 # or
495 # --plugin=protoc-gen-plugin=protozero_plugin
496 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
497 return plugin, gen_desc