blob: fd8bc755ba2d2de777a5fb0f645a5efdff1c68f4 [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'
32TARGET_TOOLCHAIN = '//gn/standalone/toolchain:gcc_like_host'
33HOST_TOOLCHAIN = '//gn/standalone/toolchain:gcc_like_host'
34LINKER_UNIT_TYPES = ('executable', 'shared_library', 'static_library')
35
36# TODO(primiano): investigate these, they require further componentization.
37ODR_VIOLATION_IGNORE_TARGETS = {
38 '//test/cts:perfetto_cts_deps',
39 '//:perfetto_integrationtests',
40}
41
42
Patrick Rohr92d74122022-10-21 15:50:52 -070043def repo_root():
44 """Returns an absolute path to the repository root."""
45 return os.path.join(
46 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
47
48
Patrick Rohr92d74122022-10-21 15:50:52 -070049def label_to_path(label):
50 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
51 assert label.startswith('//')
Patrick Rohrc6331c82022-10-25 11:34:20 -070052 return label[2:] or "./"
Patrick Rohr92d74122022-10-21 15:50:52 -070053
54
55def label_without_toolchain(label):
56 """Strips the toolchain from a GN label.
57
58 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
59 gcc_like_host) without the parenthesised toolchain part.
60 """
61 return label.split('(')[0]
62
63
64def label_to_target_name_with_path(label):
65 """
66 Turn a GN label into a target name involving the full path.
67 e.g., //src/perfetto:tests -> src_perfetto_tests
68 """
69 name = re.sub(r'^//:?', '', label)
70 name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
71 return name
72
73
Patrick Rohr92d74122022-10-21 15:50:52 -070074class GnParser(object):
75 """A parser with some cleverness for GN json desc files
76
77 The main goals of this parser are:
78 1) Deal with the fact that other build systems don't have an equivalent
79 notion to GN's source_set. Conversely to Bazel's and Soong's filegroups,
80 GN source_sets expect that dependencies, cflags and other source_set
81 properties propagate up to the linker unit (static_library, executable or
82 shared_library). This parser simulates the same behavior: when a
83 source_set is encountered, some of its variables (cflags and such) are
84 copied up to the dependent targets. This is to allow gen_xxx to create
85 one filegroup for each source_set and then squash all the other flags
86 onto the linker unit.
87 2) Detect and special-case protobuf targets, figuring out the protoc-plugin
88 being used.
89 """
90
91 class Target(object):
92 """Reperesents A GN target.
93
94 Maked properties are propagated up the dependency chain when a
95 source_set dependency is encountered.
96 """
97
98 def __init__(self, name, type):
99 self.name = name # e.g. //src/ipc:ipc
100
101 VALID_TYPES = ('static_library', 'shared_library', 'executable', 'group',
Patrick Rohrda778a02022-10-25 16:17:31 -0700102 'action', 'source_set', 'proto_library', 'copy', 'action_foreach')
Patrick Rohr92d74122022-10-21 15:50:52 -0700103 assert (type in VALID_TYPES)
104 self.type = type
105 self.testonly = False
106 self.toolchain = None
107
108 # These are valid only for type == proto_library.
109 # This is typically: 'proto', 'protozero', 'ipc'.
110 self.proto_plugin = None
111 self.proto_paths = set()
112 self.proto_exports = set()
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900113 self.proto_in_dir = ""
Patrick Rohr92d74122022-10-21 15:50:52 -0700114
115 self.sources = set()
116 # TODO(primiano): consider whether the public section should be part of
117 # bubbled-up sources.
118 self.public_headers = set() # 'public'
119
120 # These are valid only for type == 'action'
121 self.inputs = set()
122 self.outputs = set()
123 self.script = None
124 self.args = []
Patrick Rohr09716f52022-10-27 13:02:36 -0700125 self.response_file_contents = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700126
127 # These variables are propagated up when encountering a dependency
128 # on a source_set target.
129 self.cflags = set()
130 self.defines = set()
131 self.deps = set()
132 self.libs = set()
133 self.include_dirs = set()
134 self.ldflags = set()
135 self.source_set_deps = set() # Transitive set of source_set deps.
136 self.proto_deps = set()
137 self.transitive_proto_deps = set()
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800138 self.transitive_static_libs_deps = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700139
140 # Deps on //gn:xxx have this flag set to True. These dependencies
141 # are special because they pull third_party code from buildtools/.
142 # We don't want to keep recursing into //buildtools in generators,
143 # this flag is used to stop the recursion and create an empty
144 # placeholder target once we hit //gn:protoc or similar.
145 self.is_third_party_dep_ = False
146
147 def __lt__(self, other):
148 if isinstance(other, self.__class__):
149 return self.name < other.name
150 raise TypeError(
151 '\'<\' not supported between instances of \'%s\' and \'%s\'' %
152 (type(self).__name__, type(other).__name__))
153
154 def __repr__(self):
155 return json.dumps({
156 k: (list(sorted(v)) if isinstance(v, set) else v)
Patrick Rohr23f26192022-10-25 09:45:22 -0700157 for (k, v) in self.__dict__.items()
Patrick Rohr92d74122022-10-21 15:50:52 -0700158 },
159 indent=4,
160 sort_keys=True)
161
162 def update(self, other):
163 for key in ('cflags', 'defines', 'deps', 'include_dirs', 'ldflags',
164 'source_set_deps', 'proto_deps', 'transitive_proto_deps',
165 'libs', 'proto_paths'):
166 self.__dict__[key].update(other.__dict__.get(key, []))
167
Patrick Rohr564d6be2022-11-15 12:57:57 -0800168 def __init__(self):
Patrick Rohr92d74122022-10-21 15:50:52 -0700169 self.all_targets = {}
170 self.linker_units = {} # Executables, shared or static libraries.
171 self.source_sets = {}
172 self.actions = {}
173 self.proto_libs = {}
Patrick Rohrb27587e2022-11-04 14:57:24 -0700174 self.java_sources = set()
Patrick Rohr92d74122022-10-21 15:50:52 -0700175
Patrick Rohr09716f52022-10-27 13:02:36 -0700176 def _get_response_file_contents(self, action_desc):
Patrick Rohrc20887d2022-10-28 12:59:20 -0700177 # response_file_contents are formatted as:
178 # ['--flags', '--flag=true && false'] and need to be formatted as:
179 # '--flags --flag=\"true && false\"'
180 flags = action_desc.get('response_file_contents', [])
181 formatted_flags = []
182 for flag in flags:
183 if '=' in flag:
184 key, val = flag.split('=')
185 formatted_flags.append('%s=\\"%s\\"' % (key, val))
186 else:
187 formatted_flags.append(flag)
188
189 return ' '.join(formatted_flags)
Patrick Rohr09716f52022-10-27 13:02:36 -0700190
Patrick Rohraf92fa62022-11-04 14:27:04 -0700191 def _is_java_target(self, target):
192 # Per https://chromium.googlesource.com/chromium/src/build/+/HEAD/android/docs/java_toolchain.md
193 # java target names must end in "_java".
194 # TODO: There are some other possible variations we might need to support.
Patrick Rohr67f53122022-11-09 10:57:40 -0800195 return target.type == 'group' and re.match('.*_java$', target.name)
Patrick Rohraf92fa62022-11-04 14:27:04 -0700196
Patrick Rohr92d74122022-10-21 15:50:52 -0700197 def get_target(self, gn_target_name):
198 """Returns a Target object from the fully qualified GN target name.
199
Patrick Rohrd0077b72022-11-15 12:43:26 -0800200 get_target() requires that parse_gn_desc() has already been called.
201 """
202 return self.all_targets[gn_target_name]
203
Patrick Rohr564d6be2022-11-15 12:57:57 -0800204 def parse_gn_desc(self, gn_desc, gn_target_name):
Patrick Rohrd0077b72022-11-15 12:43:26 -0800205 """Parses a gn desc tree and resolves all target dependencies.
206
Patrick Rohr92d74122022-10-21 15:50:52 -0700207 It bubbles up variables from source_set dependencies as described in the
208 class-level comments.
209 """
210 target = self.all_targets.get(gn_target_name)
211 if target is not None:
212 return target # Target already processed.
213
Patrick Rohr564d6be2022-11-15 12:57:57 -0800214 desc = gn_desc[gn_target_name]
Patrick Rohr92d74122022-10-21 15:50:52 -0700215 target = GnParser.Target(gn_target_name, desc['type'])
216 target.testonly = desc.get('testonly', False)
217 target.toolchain = desc.get('toolchain', None)
218 self.all_targets[gn_target_name] = target
219
Patrick Rohr0d40da32022-11-15 13:08:12 -0800220 proto_target_type, proto_desc = self.get_proto_target_type(gn_desc, gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700221 if proto_target_type is not None:
222 self.proto_libs[target.name] = target
223 target.type = 'proto_library'
224 target.proto_plugin = proto_target_type
225 target.proto_paths.update(self.get_proto_paths(proto_desc))
226 target.proto_exports.update(self.get_proto_exports(proto_desc))
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900227 target.proto_in_dir = self.get_proto_in_dir(proto_desc)
Patrick Rohr92d74122022-10-21 15:50:52 -0700228 target.sources.update(proto_desc.get('sources', []))
229 assert (all(x.endswith('.proto') for x in target.sources))
230 elif target.type == 'source_set':
231 self.source_sets[gn_target_name] = target
232 target.sources.update(desc.get('sources', []))
233 elif target.type in LINKER_UNIT_TYPES:
234 self.linker_units[gn_target_name] = target
235 target.sources.update(desc.get('sources', []))
Patrick Rohrda778a02022-10-25 16:17:31 -0700236 elif target.type in ['action', 'action_foreach']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700237 self.actions[gn_target_name] = target
238 target.inputs.update(desc.get('inputs', []))
239 target.sources.update(desc.get('sources', []))
240 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
241 target.outputs.update(outs)
242 target.script = desc['script']
Patrick Rohr7aa98f92022-10-28 11:16:36 -0700243 target.args = desc['args']
Patrick Rohr09716f52022-10-27 13:02:36 -0700244 target.response_file_contents = self._get_response_file_contents(desc)
Patrick Rohrda778a02022-10-25 16:17:31 -0700245 elif target.type == 'copy':
246 # TODO: copy rules are not currently implemented.
247 self.actions[gn_target_name] = target
Patrick Rohr67f53122022-11-09 10:57:40 -0800248 elif self._is_java_target(target):
Patrick Rohraf92fa62022-11-04 14:27:04 -0700249 # java_group identifies the group target generated by the android_library
250 # or java_library template. A java_group must not be added as a dependency, but sources are collected
251 log.debug('Found java target %s', target.name)
252 target.type = 'java_group'
Patrick Rohr92d74122022-10-21 15:50:52 -0700253
254 # Default for 'public' is //* - all headers in 'sources' are public.
255 # TODO(primiano): if a 'public' section is specified (even if empty), then
256 # the rest of 'sources' is considered inaccessible by gn. Consider
257 # emulating that, so that generated build files don't end up with overly
258 # accessible headers.
259 public_headers = [x for x in desc.get('public', []) if x != '*']
260 target.public_headers.update(public_headers)
261
262 target.cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
263 target.libs.update(desc.get('libs', []))
264 target.ldflags.update(desc.get('ldflags', []))
265 target.defines.update(desc.get('defines', []))
266 target.include_dirs.update(desc.get('include_dirs', []))
267
268 # Recurse in dependencies.
269 for dep_name in desc.get('deps', []):
Patrick Rohr564d6be2022-11-15 12:57:57 -0800270 dep = self.parse_gn_desc(gn_desc, dep_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700271 if dep.is_third_party_dep_:
272 target.deps.add(dep_name)
273 elif dep.type == 'proto_library':
274 target.proto_deps.add(dep_name)
275 target.transitive_proto_deps.add(dep_name)
276 target.proto_paths.update(dep.proto_paths)
277 target.transitive_proto_deps.update(dep.transitive_proto_deps)
278 elif dep.type == 'source_set':
279 target.source_set_deps.add(dep_name)
280 target.update(dep) # Bubble up source set's cflags/ldflags etc.
281 elif dep.type == 'group':
282 target.update(dep) # Bubble up groups's cflags/ldflags etc.
Patrick Rohrda778a02022-10-25 16:17:31 -0700283 elif dep.type in ['action', 'action_foreach', 'copy']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700284 if proto_target_type is None:
285 target.deps.add(dep_name)
286 elif dep.type in LINKER_UNIT_TYPES:
287 target.deps.add(dep_name)
Patrick Rohr3624f952022-11-04 14:30:18 -0700288 elif dep.type == 'java_group':
289 # Explicitly break dependency chain when a java_group is added.
290 # Java sources are collected and eventually compiled as one large
291 # java_library.
292 pass
Patrick Rohr92d74122022-10-21 15:50:52 -0700293
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800294 if dep.type == 'static_library':
295 # Bubble up static_libs. Necessary, since soong does not propagate
296 # static_libs up the build tree.
Patrick Rohra9c1dda2022-11-14 19:02:40 -0800297 # Protobuf dependencies are handled separately.
298 if '//third_party/protobuf' not in dep_name:
299 target.transitive_static_libs_deps.add(dep_name)
300
301 target.transitive_static_libs_deps.update(dep.transitive_static_libs_deps)
302 target.deps.update(target.transitive_static_libs_deps)
Patrick Rohr5de9f2e2022-11-11 15:33:20 -0800303
Patrick Rohrb27587e2022-11-04 14:57:24 -0700304 # Collect java sources. Java sources are kept inside the __compile_java target.
305 # This target can be used for both host and target compilation; only add
306 # the sources if they are destined for the target (i.e. they are a
307 # dependency of the __dex target)
308 # Note: this skips prebuilt java dependencies. These will have to be
309 # added manually when building the jar.
310 if re.match('.*__dex$', target.name):
311 if re.match('.*__compile_java$', dep.name):
312 log.debug('Adding java sources for %s', dep.name)
313 java_srcs = [src for src in dep.inputs if os.path.splitext(src)[1] == '.java']
314 self.java_sources.update(java_srcs)
315
Patrick Rohr92d74122022-10-21 15:50:52 -0700316 return target
317
318 def get_proto_exports(self, proto_desc):
319 # exports in metadata will be available for source_set targets.
320 metadata = proto_desc.get('metadata', {})
321 return metadata.get('exports', [])
322
323 def get_proto_paths(self, proto_desc):
324 # import_dirs in metadata will be available for source_set targets.
325 metadata = proto_desc.get('metadata', {})
326 return metadata.get('import_dirs', [])
327
Motomu Utsumid7e0e422022-11-08 17:49:52 +0900328
329 def get_proto_in_dir(self, proto_desc):
330 args = proto_desc.get('args')
331 return re.sub('^\.\./\.\./', '', args[args.index('--proto-in-dir') + 1])
332
Patrick Rohr0d40da32022-11-15 13:08:12 -0800333 def get_proto_target_type(self, gn_desc, gn_target_name):
Patrick Rohr92d74122022-10-21 15:50:52 -0700334 """ Checks if the target is a proto library and return the plugin.
335
336 Returns:
337 (None, None): if the target is not a proto library.
338 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
339 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
340 json desc of the target with the .proto sources (_gen target for
341 non-descriptor types or the target itself for descriptor type).
342 """
Patrick Rohr0d40da32022-11-15 13:08:12 -0800343 parts = gn_target_name.split('(', 1)
Patrick Rohr92d74122022-10-21 15:50:52 -0700344 name = parts[0]
345 toolchain = '(' + parts[1] if len(parts) > 1 else ''
346
347 # Descriptor targets don't have a _gen target; instead we look for the
348 # characteristic flag in the args of the target itself.
Patrick Rohr0d40da32022-11-15 13:08:12 -0800349 desc = gn_desc.get(gn_target_name)
Patrick Rohr92d74122022-10-21 15:50:52 -0700350 if '--descriptor_set_out' in desc.get('args', []):
351 return 'descriptor', desc
352
353 # Source set proto targets have a non-empty proto_library_sources in the
354 # metadata of the description.
355 metadata = desc.get('metadata', {})
356 if 'proto_library_sources' in metadata:
357 return 'source_set', desc
358
359 # In all other cases, we want to look at the _gen target as that has the
360 # important information.
Patrick Rohr564d6be2022-11-15 12:57:57 -0800361 gen_desc = gn_desc.get('%s_gen%s' % (name, toolchain))
Patrick Rohr92d74122022-10-21 15:50:52 -0700362 if gen_desc is None or gen_desc['type'] != 'action':
363 return None, None
Patrick Rohrc5980782022-11-07 16:34:03 -0800364 if gen_desc['script'] != '//tools/protoc_wrapper/protoc_wrapper.py':
Patrick Rohr92d74122022-10-21 15:50:52 -0700365 return None, None
366 plugin = 'proto'
Patrick Rohrc5980782022-11-07 16:34:03 -0800367 args = gen_desc.get('args', [])
Patrick Rohr92d74122022-10-21 15:50:52 -0700368 for arg in (arg for arg in args if arg.startswith('--plugin=')):
369 # |arg| at this point looks like:
370 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
371 # or
372 # --plugin=protoc-gen-plugin=protozero_plugin
373 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
374 return plugin, gen_desc