blob: ef3bf55901ed3a51e7bb48f6eccd5021f32105d7 [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
23import os
24import re
25import shutil
26import subprocess
27import sys
Patrick Rohr92d74122022-10-21 15:50:52 -070028
29BUILDFLAGS_TARGET = '//gn:gen_buildflags'
30GEN_VERSION_TARGET = '//src/base:version_gen_h'
31TARGET_TOOLCHAIN = '//gn/standalone/toolchain:gcc_like_host'
32HOST_TOOLCHAIN = '//gn/standalone/toolchain:gcc_like_host'
33LINKER_UNIT_TYPES = ('executable', 'shared_library', 'static_library')
34
35# TODO(primiano): investigate these, they require further componentization.
36ODR_VIOLATION_IGNORE_TARGETS = {
37 '//test/cts:perfetto_cts_deps',
38 '//:perfetto_integrationtests',
39}
40
41
Patrick Rohr92d74122022-10-21 15:50:52 -070042def repo_root():
43 """Returns an absolute path to the repository root."""
44 return os.path.join(
45 os.path.realpath(os.path.dirname(__file__)), os.path.pardir)
46
47
Patrick Rohr92d74122022-10-21 15:50:52 -070048def label_to_path(label):
49 """Turn a GN output label (e.g., //some_dir/file.cc) into a path."""
50 assert label.startswith('//')
Patrick Rohrc6331c82022-10-25 11:34:20 -070051 return label[2:] or "./"
Patrick Rohr92d74122022-10-21 15:50:52 -070052
53
54def label_without_toolchain(label):
55 """Strips the toolchain from a GN label.
56
57 Return a GN label (e.g //buildtools:protobuf(//gn/standalone/toolchain:
58 gcc_like_host) without the parenthesised toolchain part.
59 """
60 return label.split('(')[0]
61
62
63def label_to_target_name_with_path(label):
64 """
65 Turn a GN label into a target name involving the full path.
66 e.g., //src/perfetto:tests -> src_perfetto_tests
67 """
68 name = re.sub(r'^//:?', '', label)
69 name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
70 return name
71
72
Patrick Rohr92d74122022-10-21 15:50:52 -070073class GnParser(object):
74 """A parser with some cleverness for GN json desc files
75
76 The main goals of this parser are:
77 1) Deal with the fact that other build systems don't have an equivalent
78 notion to GN's source_set. Conversely to Bazel's and Soong's filegroups,
79 GN source_sets expect that dependencies, cflags and other source_set
80 properties propagate up to the linker unit (static_library, executable or
81 shared_library). This parser simulates the same behavior: when a
82 source_set is encountered, some of its variables (cflags and such) are
83 copied up to the dependent targets. This is to allow gen_xxx to create
84 one filegroup for each source_set and then squash all the other flags
85 onto the linker unit.
86 2) Detect and special-case protobuf targets, figuring out the protoc-plugin
87 being used.
88 """
89
90 class Target(object):
91 """Reperesents A GN target.
92
93 Maked properties are propagated up the dependency chain when a
94 source_set dependency is encountered.
95 """
96
97 def __init__(self, name, type):
98 self.name = name # e.g. //src/ipc:ipc
99
100 VALID_TYPES = ('static_library', 'shared_library', 'executable', 'group',
Patrick Rohrda778a02022-10-25 16:17:31 -0700101 'action', 'source_set', 'proto_library', 'copy', 'action_foreach')
Patrick Rohr92d74122022-10-21 15:50:52 -0700102 assert (type in VALID_TYPES)
103 self.type = type
104 self.testonly = False
105 self.toolchain = None
106
107 # These are valid only for type == proto_library.
108 # This is typically: 'proto', 'protozero', 'ipc'.
109 self.proto_plugin = None
110 self.proto_paths = set()
111 self.proto_exports = set()
112
113 self.sources = set()
114 # TODO(primiano): consider whether the public section should be part of
115 # bubbled-up sources.
116 self.public_headers = set() # 'public'
117
118 # These are valid only for type == 'action'
119 self.inputs = set()
120 self.outputs = set()
121 self.script = None
122 self.args = []
Patrick Rohr09716f52022-10-27 13:02:36 -0700123 self.response_file_contents = None
Patrick Rohr92d74122022-10-21 15:50:52 -0700124
125 # These variables are propagated up when encountering a dependency
126 # on a source_set target.
127 self.cflags = set()
128 self.defines = set()
129 self.deps = set()
130 self.libs = set()
131 self.include_dirs = set()
132 self.ldflags = set()
133 self.source_set_deps = set() # Transitive set of source_set deps.
134 self.proto_deps = set()
135 self.transitive_proto_deps = set()
136
137 # Deps on //gn:xxx have this flag set to True. These dependencies
138 # are special because they pull third_party code from buildtools/.
139 # We don't want to keep recursing into //buildtools in generators,
140 # this flag is used to stop the recursion and create an empty
141 # placeholder target once we hit //gn:protoc or similar.
142 self.is_third_party_dep_ = False
143
144 def __lt__(self, other):
145 if isinstance(other, self.__class__):
146 return self.name < other.name
147 raise TypeError(
148 '\'<\' not supported between instances of \'%s\' and \'%s\'' %
149 (type(self).__name__, type(other).__name__))
150
151 def __repr__(self):
152 return json.dumps({
153 k: (list(sorted(v)) if isinstance(v, set) else v)
Patrick Rohr23f26192022-10-25 09:45:22 -0700154 for (k, v) in self.__dict__.items()
Patrick Rohr92d74122022-10-21 15:50:52 -0700155 },
156 indent=4,
157 sort_keys=True)
158
159 def update(self, other):
160 for key in ('cflags', 'defines', 'deps', 'include_dirs', 'ldflags',
161 'source_set_deps', 'proto_deps', 'transitive_proto_deps',
162 'libs', 'proto_paths'):
163 self.__dict__[key].update(other.__dict__.get(key, []))
164
165 def __init__(self, gn_desc):
166 self.gn_desc_ = gn_desc
167 self.all_targets = {}
168 self.linker_units = {} # Executables, shared or static libraries.
169 self.source_sets = {}
170 self.actions = {}
171 self.proto_libs = {}
172
Patrick Rohr09716f52022-10-27 13:02:36 -0700173 def _get_response_file_contents(self, action_desc):
174 contents = ' '.join(action_desc.get('response_file_contents', []))
175 # escape both single and double quotes.
176 contents.replace('"', '\"')
177 contents.replace("'", '\'')
178 return contents
179
Patrick Rohr92d74122022-10-21 15:50:52 -0700180 def get_target(self, gn_target_name):
181 """Returns a Target object from the fully qualified GN target name.
182
183 It bubbles up variables from source_set dependencies as described in the
184 class-level comments.
185 """
186 target = self.all_targets.get(gn_target_name)
187 if target is not None:
188 return target # Target already processed.
189
190 desc = self.gn_desc_[gn_target_name]
191 target = GnParser.Target(gn_target_name, desc['type'])
192 target.testonly = desc.get('testonly', False)
193 target.toolchain = desc.get('toolchain', None)
194 self.all_targets[gn_target_name] = target
195
Patrick Rohr26af1e72022-10-25 12:11:05 -0700196 # TODO: determine if below comment should apply for cronet builds in Android.
Patrick Rohr92d74122022-10-21 15:50:52 -0700197 # We should never have GN targets directly depend on buidtools. They
198 # should hop via //gn:xxx, so we can give generators an opportunity to
199 # override them.
Patrick Rohr26af1e72022-10-25 12:11:05 -0700200 # Specifically allow targets to depend on libc++ and libunwind.
201 if not any(match in gn_target_name for match in ['libc++', 'libunwind']):
202 assert (not gn_target_name.startswith('//buildtools'))
203
Patrick Rohr92d74122022-10-21 15:50:52 -0700204
205 # Don't descend further into third_party targets. Genrators are supposed
206 # to either ignore them or route to other externally-provided targets.
207 if gn_target_name.startswith('//gn'):
208 target.is_third_party_dep_ = True
209 return target
210
211 proto_target_type, proto_desc = self.get_proto_target_type(target)
212 if proto_target_type is not None:
213 self.proto_libs[target.name] = target
214 target.type = 'proto_library'
215 target.proto_plugin = proto_target_type
216 target.proto_paths.update(self.get_proto_paths(proto_desc))
217 target.proto_exports.update(self.get_proto_exports(proto_desc))
218 target.sources.update(proto_desc.get('sources', []))
219 assert (all(x.endswith('.proto') for x in target.sources))
220 elif target.type == 'source_set':
221 self.source_sets[gn_target_name] = target
222 target.sources.update(desc.get('sources', []))
223 elif target.type in LINKER_UNIT_TYPES:
224 self.linker_units[gn_target_name] = target
225 target.sources.update(desc.get('sources', []))
Patrick Rohrda778a02022-10-25 16:17:31 -0700226 elif target.type in ['action', 'action_foreach']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700227 self.actions[gn_target_name] = target
228 target.inputs.update(desc.get('inputs', []))
229 target.sources.update(desc.get('sources', []))
230 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
231 target.outputs.update(outs)
232 target.script = desc['script']
233 # Args are typically relative to the root build dir (../../xxx)
234 # because root build dir is typically out/xxx/).
235 target.args = [re.sub('^../../', '//', x) for x in desc['args']]
Patrick Rohr09716f52022-10-27 13:02:36 -0700236 target.response_file_contents = self._get_response_file_contents(desc)
Patrick Rohrda778a02022-10-25 16:17:31 -0700237 elif target.type == 'copy':
238 # TODO: copy rules are not currently implemented.
239 self.actions[gn_target_name] = target
Patrick Rohr92d74122022-10-21 15:50:52 -0700240
241 # Default for 'public' is //* - all headers in 'sources' are public.
242 # TODO(primiano): if a 'public' section is specified (even if empty), then
243 # the rest of 'sources' is considered inaccessible by gn. Consider
244 # emulating that, so that generated build files don't end up with overly
245 # accessible headers.
246 public_headers = [x for x in desc.get('public', []) if x != '*']
247 target.public_headers.update(public_headers)
248
249 target.cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
250 target.libs.update(desc.get('libs', []))
251 target.ldflags.update(desc.get('ldflags', []))
252 target.defines.update(desc.get('defines', []))
253 target.include_dirs.update(desc.get('include_dirs', []))
254
255 # Recurse in dependencies.
256 for dep_name in desc.get('deps', []):
257 dep = self.get_target(dep_name)
258 if dep.is_third_party_dep_:
259 target.deps.add(dep_name)
260 elif dep.type == 'proto_library':
261 target.proto_deps.add(dep_name)
262 target.transitive_proto_deps.add(dep_name)
263 target.proto_paths.update(dep.proto_paths)
264 target.transitive_proto_deps.update(dep.transitive_proto_deps)
265 elif dep.type == 'source_set':
266 target.source_set_deps.add(dep_name)
267 target.update(dep) # Bubble up source set's cflags/ldflags etc.
268 elif dep.type == 'group':
269 target.update(dep) # Bubble up groups's cflags/ldflags etc.
Patrick Rohrda778a02022-10-25 16:17:31 -0700270 elif dep.type in ['action', 'action_foreach', 'copy']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700271 if proto_target_type is None:
272 target.deps.add(dep_name)
273 elif dep.type in LINKER_UNIT_TYPES:
274 target.deps.add(dep_name)
275
276 return target
277
278 def get_proto_exports(self, proto_desc):
279 # exports in metadata will be available for source_set targets.
280 metadata = proto_desc.get('metadata', {})
281 return metadata.get('exports', [])
282
283 def get_proto_paths(self, proto_desc):
284 # import_dirs in metadata will be available for source_set targets.
285 metadata = proto_desc.get('metadata', {})
286 return metadata.get('import_dirs', [])
287
288 def get_proto_target_type(self, target):
289 """ Checks if the target is a proto library and return the plugin.
290
291 Returns:
292 (None, None): if the target is not a proto library.
293 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
294 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
295 json desc of the target with the .proto sources (_gen target for
296 non-descriptor types or the target itself for descriptor type).
297 """
298 parts = target.name.split('(', 1)
299 name = parts[0]
300 toolchain = '(' + parts[1] if len(parts) > 1 else ''
301
302 # Descriptor targets don't have a _gen target; instead we look for the
303 # characteristic flag in the args of the target itself.
304 desc = self.gn_desc_.get(target.name)
305 if '--descriptor_set_out' in desc.get('args', []):
306 return 'descriptor', desc
307
308 # Source set proto targets have a non-empty proto_library_sources in the
309 # metadata of the description.
310 metadata = desc.get('metadata', {})
311 if 'proto_library_sources' in metadata:
312 return 'source_set', desc
313
314 # In all other cases, we want to look at the _gen target as that has the
315 # important information.
316 gen_desc = self.gn_desc_.get('%s_gen%s' % (name, toolchain))
317 if gen_desc is None or gen_desc['type'] != 'action':
318 return None, None
319 args = gen_desc.get('args', [])
320 if '/protoc' not in args[0]:
321 return None, None
322 plugin = 'proto'
323 for arg in (arg for arg in args if arg.startswith('--plugin=')):
324 # |arg| at this point looks like:
325 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
326 # or
327 # --plugin=protoc-gen-plugin=protozero_plugin
328 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
329 return plugin, gen_desc