blob: 576df25976c06b3950d5b61ade2a587eda15818d [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
Motomu Utsumi5fde8e12022-12-16 16:59:46 +090018import copy
Patrick Rohr92d74122022-10-21 15:50:52 -070019import json
Patrick Rohraf92fa62022-11-04 14:27:04 -070020import logging as log
Patrick Rohr92d74122022-10-21 15:50:52 -070021import os
22import re
Patrick Rohr92d74122022-10-21 15:50:52 -070023
24BUILDFLAGS_TARGET = '//gn:gen_buildflags'
25GEN_VERSION_TARGET = '//src/base:version_gen_h'
Mohannad Farrag7f29d832022-11-23 19:52:41 +000026LINKER_UNIT_TYPES = ('executable', 'shared_library', 'static_library', 'source_set')
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +000027JAVA_BANNED_SCRIPTS = [
28 "//build/android/gyp/turbine.py",
29 "//build/android/gyp/compile_java.py",
30 "//build/android/gyp/filter_zip.py",
31 "//build/android/gyp/dex.py",
32 "//build/android/gyp/write_build_config.py",
33 "//build/android/gyp/create_r_java.py",
34 "//build/android/gyp/ijar.py",
35 "//build/android/gyp/create_r_java.py",
36 "//build/android/gyp/bytecode_processor.py",
37 "//build/android/gyp/prepare_resources.py",
38 "//build/android/gyp/aar.py",
39 "//build/android/gyp/zip.py",
40]
Patrick Rohr92d74122022-10-21 15:50:52 -070041# TODO(primiano): investigate these, they require further componentization.
42ODR_VIOLATION_IGNORE_TARGETS = {
43 '//test/cts:perfetto_cts_deps',
44 '//:perfetto_integrationtests',
45}
Mohannad Farrag4bea14a2022-11-22 15:38:30 +000046ARCH_REGEX = r'(android_x86_64|android_x86|android_arm|android_arm64|host)'
Mohannad Farraga0e37c12022-12-02 14:46:08 +000047RESPONSE_FILE = '{{response_file_name}}'
48
Patrick Rohr92d74122022-10-21 15:50:52 -070049def repo_root():
50 """Returns an absolute path to the repository root."""
51 return os.path.join(
52 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
53
54
Patrick Rohr92d74122022-10-21 15:50:52 -070055def label_to_path(label):
56 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
57 assert label.startswith('//')
Patrick Rohrc6331c82022-10-25 11:34:20 -070058 return label[2:] or "./"
Patrick Rohr92d74122022-10-21 15:50:52 -070059
60
61def label_without_toolchain(label):
62 """Strips the toolchain from a GN label.
63
64 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
65 gcc_like_host) without the parenthesised toolchain part.
66 """
67 return label.split('(')[0]
68
69
70def label_to_target_name_with_path(label):
71 """
72 Turn a GN label into a target name involving the full path.
73 e.g., //src/perfetto:tests -> src_perfetto_tests
74 """
75 name = re.sub(r'^//:?', '', label)
76 name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
77 return name
78
Mohannad Farraga0db68b2022-11-24 12:28:09 +000079def _is_java_source(src):
80 return os.path.splitext(src)[1] == '.java' and not src.startswith("//out/test/gen/")
Patrick Rohr92d74122022-10-21 15:50:52 -070081
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +000082def is_java_action(script, outputs):
83 return (script != "" and script not in JAVA_BANNED_SCRIPTS) and any(
84 [file.endswith(".srcjar") or file.endswith(".java")
85 for file in outputs])
86
Patrick Rohr92d74122022-10-21 15:50:52 -070087class GnParser(object):
88 """A parser with some cleverness for GN json desc files
89
90 The main goals of this parser are:
91 1) Deal with the fact that other build systems don't have an equivalent
92 notion to GN's source_set. Conversely to Bazel's and Soong's filegroups,
93 GN source_sets expect that dependencies, cflags and other source_set
94 properties propagate up to the linker unit (static_library, executable or
95 shared_library). This parser simulates the same behavior: when a
96 source_set is encountered, some of its variables (cflags and such) are
97 copied up to the dependent targets. This is to allow gen_xxx to create
98 one filegroup for each source_set and then squash all the other flags
99 onto the linker unit.
100 2) Detect and special-case protobuf targets, figuring out the protoc-plugin
101 being used.
102 """
103
104 class Target(object):
105 """Reperesents A GN target.
106
107 Maked properties are propagated up the dependency chain when a
108 source_set dependency is encountered.
109 """
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800110 class Arch():
111 """Architecture-dependent properties
112 """
113 def __init__(self):
114 self.sources = set()
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900115 self.cflags = set()
Motomu Utsumi80e04472022-11-17 21:54:06 +0900116 self.defines = set()
Motomu Utsumi778f8302022-11-17 22:12:17 +0900117 self.include_dirs = set()
Patrick Rohr297f9792022-11-16 23:40:40 -0800118 self.deps = set()
119 self.transitive_static_libs_deps = set()
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000120 self.source_set_deps = set()
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800121
Patrick Rohr92d74122022-10-21 15:50:52 -0700122
123 def __init__(self, name, type):
124 self.name = name # e.g. //src/ipc:ipc
125
126 VALID_TYPES = ('static_library', 'shared_library', 'executable', 'group',
Patrick Rohrda778a02022-10-25 16:17:31 -0700127 'action', 'source_set', 'proto_library', 'copy', 'action_foreach')
Patrick Rohr92d74122022-10-21 15:50:52 -0700128 assert (type in VALID_TYPES)
129 self.type = type
130 self.testonly = False
131 self.toolchain = None
132
133 # These are valid only for type == proto_library.
134 # This is typically: 'proto', 'protozero', 'ipc'.
135 self.proto_plugin = None
136 self.proto_paths = set()
137 self.proto_exports = set()
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900138 self.proto_in_dir = ""
Patrick Rohr92d74122022-10-21 15:50:52 -0700139
140 self.sources = set()
141 # TODO(primiano): consider whether the public section should be part of
142 # bubbled-up sources.
143 self.public_headers = set() # 'public'
144
145 # These are valid only for type == 'action'
146 self.inputs = set()
147 self.outputs = set()
Motomu Utsumi27bf5962022-12-16 16:54:58 +0900148 self.script = ''
Patrick Rohr92d74122022-10-21 15:50:52 -0700149 self.args = []
Motomu Utsumi27bf5962022-12-16 16:54:58 +0900150 self.response_file_contents = ''
Patrick Rohr92d74122022-10-21 15:50:52 -0700151
152 # These variables are propagated up when encountering a dependency
153 # on a source_set target.
154 self.cflags = set()
155 self.defines = set()
156 self.deps = set()
157 self.libs = set()
158 self.include_dirs = set()
159 self.ldflags = set()
160 self.source_set_deps = set() # Transitive set of source_set deps.
161 self.proto_deps = set()
162 self.transitive_proto_deps = set()
Mohannad Farragbaf0d572022-11-22 11:53:54 +0000163 self.rtti = False
Patrick Rohr92d74122022-10-21 15:50:52 -0700164
Patrick Rohr70913562022-11-15 21:49:28 -0800165 # TODO: come up with a better way to only run this once.
166 # is_finalized tracks whether finalize() was called on this target.
167 self.is_finalized = False
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800168 self.arch = dict()
169
Motomu Utsumiee47af62022-11-30 16:41:15 +0900170 # This is used to get the name/version of libcronet
171 self.output_name = None
172
Patrick Rohrc8f41cd2022-11-15 22:46:10 -0800173 def host_supported(self):
174 return 'host' in self.arch
175
176 def device_supported(self):
177 return any([name.startswith('android') for name in self.arch.keys()])
178
Patrick Rohr94c24902022-12-14 19:44:44 -0800179 def is_linker_unit_type(self):
180 return self.type in LINKER_UNIT_TYPES
181
Patrick Rohr92d74122022-10-21 15:50:52 -0700182 def __lt__(self, other):
183 if isinstance(other, self.__class__):
184 return self.name < other.name
185 raise TypeError(
186 '\'<\' not supported between instances of \'%s\' and \'%s\'' %
187 (type(self).__name__, type(other).__name__))
188
189 def __repr__(self):
190 return json.dumps({
191 k: (list(sorted(v)) if isinstance(v, set) else v)
Patrick Rohr23f26192022-10-25 09:45:22 -0700192 for (k, v) in self.__dict__.items()
Patrick Rohr92d74122022-10-21 15:50:52 -0700193 },
194 indent=4,
195 sort_keys=True)
196
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900197 def update(self, other, arch):
Patrick Rohr92d74122022-10-21 15:50:52 -0700198 for key in ('cflags', 'defines', 'deps', 'include_dirs', 'ldflags',
199 'source_set_deps', 'proto_deps', 'transitive_proto_deps',
200 'libs', 'proto_paths'):
201 self.__dict__[key].update(other.__dict__.get(key, []))
202
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000203 for key_in_arch in ('cflags', 'defines', 'include_dirs', 'source_set_deps'):
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900204 self.arch[arch].__dict__[key_in_arch].update(
205 other.arch[arch].__dict__.get(key_in_arch, []))
206
Motomu Utsumi2648df02022-12-16 15:05:25 +0900207 def _finalize_set_attribute(self, key):
208 # Target contains the intersection of arch-dependent properties
209 getattr(self, key)\
210 .update(set.intersection(*[getattr(arch, key) for arch in self.arch.values()]))
211
212 # Deduplicate arch-dependent properties
213 for arch in self.arch.values():
214 getattr(arch, key).difference_update(getattr(self, key))
215
Motomu Utsumi5fde8e12022-12-16 16:59:46 +0900216 def _finalize_non_set_attribute(self, key):
217 # Only when all the arch has the same non empty value, move the value to the target common
218 val = getattr(list(self.arch.values())[0], key)
219 if val and all([val == getattr(arch, key) for arch in self.arch.values()]):
220 setattr(self, key, copy.deepcopy(val))
221 for arch in self.arch.values():
222 getattr(arch, key, None)
223
Motomu Utsumi2648df02022-12-16 15:05:25 +0900224 def _finalize_attribute(self, key):
225 val = getattr(self, key)
226 if isinstance(val, set):
227 self._finalize_set_attribute(key)
Motomu Utsumi5fde8e12022-12-16 16:59:46 +0900228 elif isinstance(val, (list, str)):
229 self._finalize_non_set_attribute(key)
Motomu Utsumi2648df02022-12-16 15:05:25 +0900230 else:
231 raise TypeError(f'Unsupported type: {type(val)}')
232
Patrick Rohr70913562022-11-15 21:49:28 -0800233 def finalize(self):
234 """Move common properties out of arch-dependent subobjects to Target object.
235
236 TODO: find a better name for this function.
237 """
238 if self.is_finalized:
239 return
240 self.is_finalized = True
241
Motomu Utsumi5fde8e12022-12-16 16:59:46 +0900242 if len(self.arch) == 0:
243 return
244
Motomu Utsumi2648df02022-12-16 15:05:25 +0900245 for key in ('sources', 'cflags', 'defines', 'include_dirs', 'deps', 'source_set_deps'):
246 self._finalize_attribute(key)
Patrick Rohr297f9792022-11-16 23:40:40 -0800247
Patrick Rohr70913562022-11-15 21:49:28 -0800248
Patrick Rohr0913f0b2022-12-13 09:13:20 -0800249 def __init__(self, builtin_deps):
250 self.builtin_deps = builtin_deps
Patrick Rohr92d74122022-10-21 15:50:52 -0700251 self.all_targets = {}
252 self.linker_units = {} # Executables, shared or static libraries.
253 self.source_sets = {}
254 self.actions = {}
255 self.proto_libs = {}
Patrick Rohrb27587e2022-11-04 14:57:24 -0700256 self.java_sources = set()
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000257 self.java_actions = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700258
Patrick Rohr09716f52022-10-27 13:02:36 -0700259 def _get_response_file_contents(self, action_desc):
Patrick Rohrc20887d2022-10-28 12:59:20 -0700260 # response_file_contents are formatted as:
261 # ['--flags', '--flag=true && false'] and need to be formatted as:
262 # '--flags --flag=\"true && false\"'
263 flags = action_desc.get('response_file_contents', [])
264 formatted_flags = []
265 for flag in flags:
266 if '=' in flag:
267 key, val = flag.split('=')
268 formatted_flags.append('%s=\\"%s\\"' % (key, val))
269 else:
270 formatted_flags.append(flag)
271
272 return ' '.join(formatted_flags)
Patrick Rohr09716f52022-10-27 13:02:36 -0700273
Patrick Rohrdf3c20c2022-12-12 20:19:26 -0800274 def _is_java_group(self, type_, target_name):
Patrick Rohraf92fa62022-11-04 14:27:04 -0700275 # Per https://chromium.googlesource.com/chromium/src/build/+/HEAD/android/docs/java_toolchain.md
276 # java target names must end in "_java".
277 # TODO: There are some other possible variations we might need to support.
Patrick Rohr689a9c02022-12-13 14:55:27 -0800278 return type_ == 'group' and target_name.endswith('_java')
Patrick Rohraf92fa62022-11-04 14:27:04 -0700279
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800280 def _get_arch(self, toolchain):
Patrick Rohrd938d532022-11-15 22:17:08 -0800281 if toolchain == '//build/toolchain/android:android_clang_x86':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800282 return 'android_x86'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800283 elif toolchain == '//build/toolchain/android:android_clang_x64':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800284 return 'android_x86_64'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800285 elif toolchain == '//build/toolchain/android:android_clang_arm':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800286 return 'android_arm'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800287 elif toolchain == '//build/toolchain/android:android_clang_arm64':
Patrick Rohr4eff2102022-11-15 22:21:52 -0800288 return 'android_arm64'
Patrick Rohr81a4ac32022-11-15 14:38:21 -0800289 else:
290 return 'host'
291
Patrick Rohr92d74122022-10-21 15:50:52 -0700292 def get_target(self, gn_target_name):
293 """Returns a Target object from the fully qualified GN target name.
294
Patrick Rohrd0077b72022-11-15 12:43:26 -0800295 get_target() requires that parse_gn_desc() has already been called.
296 """
Patrick Rohr70913562022-11-15 21:49:28 -0800297 # Run this every time as parse_gn_desc can be called at any time.
298 for target in self.all_targets.values():
299 target.finalize()
300
Patrick Rohr7705bdb2022-11-15 13:26:30 -0800301 return self.all_targets[label_without_toolchain(gn_target_name)]
Patrick Rohrd0077b72022-11-15 12:43:26 -0800302
Patrick Rohr0c7ef522022-12-12 20:29:19 -0800303 def parse_gn_desc(self, gn_desc, gn_target_name, is_java_target = False):
Patrick Rohrd0077b72022-11-15 12:43:26 -0800304 """Parses a gn desc tree and resolves all target dependencies.
305
Patrick Rohr92d74122022-10-21 15:50:52 -0700306 It bubbles up variables from source_set dependencies as described in the
307 class-level comments.
308 """
Patrick Rohr7705bdb2022-11-15 13:26:30 -0800309 # Use name without toolchain for targets to support targets built for
310 # multiple archs.
311 target_name = label_without_toolchain(gn_target_name)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800312 desc = gn_desc[gn_target_name]
Patrick Rohr98600682022-11-18 18:29:15 -0800313 type_ = desc['type']
Patrick Rohrd938d532022-11-15 22:17:08 -0800314 arch = self._get_arch(desc['toolchain'])
Patrick Rohr98600682022-11-18 18:29:15 -0800315
Patrick Rohr689a9c02022-12-13 14:55:27 -0800316 is_java_target |= self._is_java_group(type_, target_name)
Patrick Rohr0c7ef522022-12-12 20:29:19 -0800317
Patrick Rohr98600682022-11-18 18:29:15 -0800318 # Action modules can differ depending on the target architecture, yet
319 # genrule's do not allow to overload cmd per target OS / arch. Create a
320 # separate action for every architecture.
Mohannad Farragd7efd7b92022-11-21 16:15:16 +0000321 # Cover both action and action_foreach
Patrick Rohr0c7ef522022-12-12 20:29:19 -0800322 if type_.startswith('action') and not is_java_target:
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000323 # Don't meddle with the java actions name
Patrick Rohr98600682022-11-18 18:29:15 -0800324 target_name += '__' + arch
325
326 target = self.all_targets.get(target_name)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800327 if target is None:
Patrick Rohr98600682022-11-18 18:29:15 -0800328 target = GnParser.Target(target_name, type_)
Patrick Rohr02ad51f2022-11-15 13:54:07 -0800329 self.all_targets[target_name] = target
330
331 if arch not in target.arch:
332 target.arch[arch] = GnParser.Target.Arch()
333 else:
Patrick Rohr92d74122022-10-21 15:50:52 -0700334 return target # Target already processed.
335
Patrick Rohr0913f0b2022-12-13 09:13:20 -0800336 if target.name in self.builtin_deps:
Patrick Rohr6cd0f252022-12-15 10:37:55 -0800337 # return early, no need to parse any further as the module is a builtin.
338 return target
Patrick Rohr0913f0b2022-12-13 09:13:20 -0800339
Patrick Rohr92d74122022-10-21 15:50:52 -0700340 target.testonly = desc.get('testonly', False)
Patrick Rohr92d74122022-10-21 15:50:52 -0700341
Patrick Rohr0d40da32022-11-15 13:08:12 -0800342 proto_target_type, proto_desc = self.get_proto_target_type(gn_desc, gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700343 if proto_target_type is not None:
344 self.proto_libs[target.name] = target
345 target.type = 'proto_library'
346 target.proto_plugin = proto_target_type
347 target.proto_paths.update(self.get_proto_paths(proto_desc))
348 target.proto_exports.update(self.get_proto_exports(proto_desc))
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900349 target.proto_in_dir = self.get_proto_in_dir(proto_desc)
Patrick Rohrad7a29c2022-11-16 21:48:09 -0800350 for gn_proto_deps_name in proto_desc.get('deps', []):
351 dep = self.parse_gn_desc(gn_desc, gn_proto_deps_name)
352 target.deps.add(dep.name)
Patrick Rohr53dcd102022-11-15 21:53:02 -0800353 target.arch[arch].sources.update(proto_desc.get('sources', []))
354 assert (all(x.endswith('.proto') for x in target.arch[arch].sources))
Patrick Rohr92d74122022-10-21 15:50:52 -0700355 elif target.type == 'source_set':
356 self.source_sets[gn_target_name] = target
Patrick Rohr53dcd102022-11-15 21:53:02 -0800357 target.arch[arch].sources.update(desc.get('sources', []))
Patrick Rohr94c24902022-12-14 19:44:44 -0800358 elif target.is_linker_unit_type():
Patrick Rohr92d74122022-10-21 15:50:52 -0700359 self.linker_units[gn_target_name] = target
Patrick Rohr53dcd102022-11-15 21:53:02 -0800360 target.arch[arch].sources.update(desc.get('sources', []))
Patrick Rohrdf3c20c2022-12-12 20:19:26 -0800361 elif (desc.get("script", "") in JAVA_BANNED_SCRIPTS
362 or self._is_java_group(target.type, target.name)):
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000363 # java_group identifies the group target generated by the android_library
Patrick Rohre71a0612022-12-13 14:58:14 -0800364 # or java_library template. A java_group must not be added as a
365 # dependency, but sources are collected.
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000366 log.debug('Found java target %s', target.name)
367 if target.type == "action":
368 # Convert java actions into java_group and keep the inputs for collection.
369 target.inputs.update(desc.get('inputs', []))
370 target.type = 'java_group'
Patrick Rohrda778a02022-10-25 16:17:31 -0700371 elif target.type in ['action', 'action_foreach']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700372 self.actions[gn_target_name] = target
373 target.inputs.update(desc.get('inputs', []))
Patrick Rohr53dcd102022-11-15 21:53:02 -0800374 target.arch[arch].sources.update(desc.get('sources', []))
Patrick Rohr92d74122022-10-21 15:50:52 -0700375 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
376 target.outputs.update(outs)
377 target.script = desc['script']
Patrick Rohr7aa98f92022-10-28 11:16:36 -0700378 target.args = desc['args']
Patrick Rohr09716f52022-10-27 13:02:36 -0700379 target.response_file_contents = self._get_response_file_contents(desc)
Patrick Rohrda778a02022-10-25 16:17:31 -0700380 elif target.type == 'copy':
381 # TODO: copy rules are not currently implemented.
382 self.actions[gn_target_name] = target
Patrick Rohr92d74122022-10-21 15:50:52 -0700383
384 # Default for 'public' is //* - all headers in 'sources' are public.
385 # TODO(primiano): if a 'public' section is specified (even if empty), then
386 # the rest of 'sources' is considered inaccessible by gn. Consider
387 # emulating that, so that generated build files don't end up with overly
388 # accessible headers.
389 public_headers = [x for x in desc.get('public', []) if x != '*']
390 target.public_headers.update(public_headers)
391
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900392 target.arch[arch].cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
Patrick Rohr92d74122022-10-21 15:50:52 -0700393 target.libs.update(desc.get('libs', []))
394 target.ldflags.update(desc.get('ldflags', []))
Motomu Utsumi80e04472022-11-17 21:54:06 +0900395 target.arch[arch].defines.update(desc.get('defines', []))
Motomu Utsumi778f8302022-11-17 22:12:17 +0900396 target.arch[arch].include_dirs.update(desc.get('include_dirs', []))
Motomu Utsumiee47af62022-11-30 16:41:15 +0900397 target.output_name = desc.get('output_name', None)
Mohannad Farragbaf0d572022-11-22 11:53:54 +0000398 if "-frtti" in target.arch[arch].cflags:
399 target.rtti = True
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000400
Patrick Rohr92d74122022-10-21 15:50:52 -0700401 # Recurse in dependencies.
Patrick Rohr7f4631e2022-11-15 14:35:03 -0800402 for gn_dep_name in desc.get('deps', []):
Patrick Rohr0c7ef522022-12-12 20:29:19 -0800403 dep = self.parse_gn_desc(gn_desc, gn_dep_name, is_java_target)
Patrick Rohr6cd0f252022-12-15 10:37:55 -0800404 if dep.type == 'proto_library':
Patrick Rohr9006b362022-11-16 21:49:53 -0800405 target.proto_deps.add(dep.name)
406 target.transitive_proto_deps.add(dep.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700407 target.proto_paths.update(dep.proto_paths)
408 target.transitive_proto_deps.update(dep.transitive_proto_deps)
409 elif dep.type == 'source_set':
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000410 target.arch[arch].source_set_deps.add(dep.name)
411 target.arch[arch].source_set_deps.update(dep.arch[arch].source_set_deps)
Patrick Rohr70695562022-12-14 19:45:34 -0800412 # flatten source_set deps
413 if target.is_linker_unit_type():
414 target.arch[arch].deps.update(target.arch[arch].source_set_deps)
Patrick Rohr92d74122022-10-21 15:50:52 -0700415 elif dep.type == 'group':
Motomu Utsumi1c64e442022-11-17 21:51:37 +0900416 target.update(dep, arch) # Bubble up groups's cflags/ldflags etc.
Patrick Rohrda778a02022-10-25 16:17:31 -0700417 elif dep.type in ['action', 'action_foreach', 'copy']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700418 if proto_target_type is None:
Mohannad Farrag1de6cb12022-11-28 12:27:26 +0000419 target.arch[arch].deps.add(dep.name)
Patrick Rohr94c24902022-12-14 19:44:44 -0800420 elif dep.is_linker_unit_type():
Patrick Rohr297f9792022-11-16 23:40:40 -0800421 target.arch[arch].deps.add(dep.name)
Patrick Rohr3624f952022-11-04 14:30:18 -0700422 elif dep.type == 'java_group':
423 # Explicitly break dependency chain when a java_group is added.
424 # Java sources are collected and eventually compiled as one large
425 # java_library.
426 pass
Patrick Rohr92d74122022-10-21 15:50:52 -0700427
Mohannad Farrag7f29d832022-11-23 19:52:41 +0000428 # Source set bubble up transitive source sets but can't be combined with this
429 # if they are combined then source sets will bubble up static libraries
430 # while we only want to have source sets bubble up only source sets.
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800431 if dep.type == 'static_library':
432 # Bubble up static_libs. Necessary, since soong does not propagate
433 # static_libs up the build tree.
Patrick Rohr297f9792022-11-16 23:40:40 -0800434 target.arch[arch].transitive_static_libs_deps.add(dep.name)
Patrick Rohra9c1dda2022-11-14 19:02:40 -0800435
Patrick Rohr297f9792022-11-16 23:40:40 -0800436 if arch in dep.arch:
437 target.arch[arch].transitive_static_libs_deps.update(
438 dep.arch[arch].transitive_static_libs_deps)
439 target.arch[arch].deps.update(target.arch[arch].transitive_static_libs_deps)
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800440
Patrick Rohrb27587e2022-11-04 14:57:24 -0700441 # Collect java sources. Java sources are kept inside the __compile_java target.
442 # This target can be used for both host and target compilation; only add
443 # the sources if they are destined for the target (i.e. they are a
444 # dependency of the __dex target)
445 # Note: this skips prebuilt java dependencies. These will have to be
446 # added manually when building the jar.
Patrick Rohr0c7ef522022-12-12 20:29:19 -0800447 if target.name.endswith('__dex'):
448 if dep.name.endswith('__compile_java'):
Patrick Rohrb27587e2022-11-04 14:57:24 -0700449 log.debug('Adding java sources for %s', dep.name)
Mohannad Farraga0db68b2022-11-24 12:28:09 +0000450 java_srcs = [src for src in dep.inputs if _is_java_source(src)]
Patrick Rohrb27587e2022-11-04 14:57:24 -0700451 self.java_sources.update(java_srcs)
Mohannad Farrag6a2d88a2022-11-28 19:33:48 +0000452 if dep.type in ["action"] and target.type == "java_group":
Motomu Utsumi6e514122022-12-05 17:51:40 +0900453 # //base:base_java_aidl generates srcjar from .aidl files. But java_library in soong can
454 # directly have .aidl files in srcs. So adding .aidl files to the java_sources.
455 # TODO: Find a better way/place to do this.
456 if dep.name == '//base:base_java_aidl':
457 self.java_sources.update(dep.arch[arch].sources)
458 else:
459 self.java_actions.add(dep.name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700460 return target
461
462 def get_proto_exports(self, proto_desc):
463 # exports in metadata will be available for source_set targets.
464 metadata = proto_desc.get('metadata', {})
465 return metadata.get('exports', [])
466
467 def get_proto_paths(self, proto_desc):
468 # import_dirs in metadata will be available for source_set targets.
469 metadata = proto_desc.get('metadata', {})
470 return metadata.get('import_dirs', [])
471
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900472
473 def get_proto_in_dir(self, proto_desc):
474 args = proto_desc.get('args')
475 return re.sub('^\.\./\.\./', '', args[args.index('--proto-in-dir') + 1])
476
Patrick Rohr0d40da32022-11-15 13:08:12 -0800477 def get_proto_target_type(self, gn_desc, gn_target_name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700478 """ Checks if the target is a proto library and return the plugin.
479
480 Returns:
481 (None, None): if the target is not a proto library.
482 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
483 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
484 json desc of the target with the .proto sources (_gen target for
485 non-descriptor types or the target itself for descriptor type).
486 """
Patrick Rohr0d40da32022-11-15 13:08:12 -0800487 parts = gn_target_name.split('(', 1)
Patrick Rohr92d74122022-10-21 15:50:52 -0700488 name = parts[0]
489 toolchain = '(' + parts[1] if len(parts) > 1 else ''
490
491 # Descriptor targets don't have a _gen target; instead we look for the
492 # characteristic flag in the args of the target itself.
Patrick Rohr0d40da32022-11-15 13:08:12 -0800493 desc = gn_desc.get(gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700494 if '--descriptor_set_out' in desc.get('args', []):
495 return 'descriptor', desc
496
497 # Source set proto targets have a non-empty proto_library_sources in the
498 # metadata of the description.
499 metadata = desc.get('metadata', {})
500 if 'proto_library_sources' in metadata:
501 return 'source_set', desc
502
503 # In all other cases, we want to look at the _gen target as that has the
504 # important information.
Patrick Rohr564d6be2022-11-15 12:57:57 -0800505 gen_desc = gn_desc.get('%s_gen%s' % (name, toolchain))
Patrick Rohr92d74122022-10-21 15:50:52 -0700506 if gen_desc is None or gen_desc['type'] != 'action':
507 return None, None
Patrick Rohrc5980782022-11-07 16:34:03 -0800508 if gen_desc['script'] != '//tools/protoc_wrapper/protoc_wrapper.py':
Patrick Rohr92d74122022-10-21 15:50:52 -0700509 return None, None
510 plugin = 'proto'
Patrick Rohrc5980782022-11-07 16:34:03 -0800511 args = gen_desc.get('args', [])
Patrick Rohr92d74122022-10-21 15:50:52 -0700512 for arg in (arg for arg in args if arg.startswith('--plugin=')):
513 # |arg| at this point looks like:
514 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
515 # or
516 # --plugin=protoc-gen-plugin=protozero_plugin
517 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
518 return plugin, gen_desc