blob: 9cada7bf9ca36eec355bc5452a03013444bb3642 [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',
101 'action', 'source_set', 'proto_library')
102 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 = []
123
124 # These variables are propagated up when encountering a dependency
125 # on a source_set target.
126 self.cflags = set()
127 self.defines = set()
128 self.deps = set()
129 self.libs = set()
130 self.include_dirs = set()
131 self.ldflags = set()
132 self.source_set_deps = set() # Transitive set of source_set deps.
133 self.proto_deps = set()
134 self.transitive_proto_deps = set()
135
136 # Deps on //gn:xxx have this flag set to True. These dependencies
137 # are special because they pull third_party code from buildtools/.
138 # We don't want to keep recursing into //buildtools in generators,
139 # this flag is used to stop the recursion and create an empty
140 # placeholder target once we hit //gn:protoc or similar.
141 self.is_third_party_dep_ = False
142
143 def __lt__(self, other):
144 if isinstance(other, self.__class__):
145 return self.name < other.name
146 raise TypeError(
147 '\'<\' not supported between instances of \'%s\' and \'%s\'' %
148 (type(self).__name__, type(other).__name__))
149
150 def __repr__(self):
151 return json.dumps({
152 k: (list(sorted(v)) if isinstance(v, set) else v)
Patrick Rohr23f26192022-10-25 09:45:22 -0700153 for (k, v) in self.__dict__.items()
Patrick Rohr92d74122022-10-21 15:50:52 -0700154 },
155 indent=4,
156 sort_keys=True)
157
158 def update(self, other):
159 for key in ('cflags', 'defines', 'deps', 'include_dirs', 'ldflags',
160 'source_set_deps', 'proto_deps', 'transitive_proto_deps',
161 'libs', 'proto_paths'):
162 self.__dict__[key].update(other.__dict__.get(key, []))
163
164 def __init__(self, gn_desc):
165 self.gn_desc_ = gn_desc
166 self.all_targets = {}
167 self.linker_units = {} # Executables, shared or static libraries.
168 self.source_sets = {}
169 self.actions = {}
170 self.proto_libs = {}
171
172 def get_target(self, gn_target_name):
173 """Returns a Target object from the fully qualified GN target name.
174
175 It bubbles up variables from source_set dependencies as described in the
176 class-level comments.
177 """
178 target = self.all_targets.get(gn_target_name)
179 if target is not None:
180 return target # Target already processed.
181
182 desc = self.gn_desc_[gn_target_name]
183 target = GnParser.Target(gn_target_name, desc['type'])
184 target.testonly = desc.get('testonly', False)
185 target.toolchain = desc.get('toolchain', None)
186 self.all_targets[gn_target_name] = target
187
188 # We should never have GN targets directly depend on buidtools. They
189 # should hop via //gn:xxx, so we can give generators an opportunity to
190 # override them.
191 assert (not gn_target_name.startswith('//buildtools'))
192
193 # Don't descend further into third_party targets. Genrators are supposed
194 # to either ignore them or route to other externally-provided targets.
195 if gn_target_name.startswith('//gn'):
196 target.is_third_party_dep_ = True
197 return target
198
199 proto_target_type, proto_desc = self.get_proto_target_type(target)
200 if proto_target_type is not None:
201 self.proto_libs[target.name] = target
202 target.type = 'proto_library'
203 target.proto_plugin = proto_target_type
204 target.proto_paths.update(self.get_proto_paths(proto_desc))
205 target.proto_exports.update(self.get_proto_exports(proto_desc))
206 target.sources.update(proto_desc.get('sources', []))
207 assert (all(x.endswith('.proto') for x in target.sources))
208 elif target.type == 'source_set':
209 self.source_sets[gn_target_name] = target
210 target.sources.update(desc.get('sources', []))
211 elif target.type in LINKER_UNIT_TYPES:
212 self.linker_units[gn_target_name] = target
213 target.sources.update(desc.get('sources', []))
214 elif target.type == 'action':
215 self.actions[gn_target_name] = target
216 target.inputs.update(desc.get('inputs', []))
217 target.sources.update(desc.get('sources', []))
218 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
219 target.outputs.update(outs)
220 target.script = desc['script']
221 # Args are typically relative to the root build dir (../../xxx)
222 # because root build dir is typically out/xxx/).
223 target.args = [re.sub('^../../', '//', x) for x in desc['args']]
224
225 # Default for 'public' is //* - all headers in 'sources' are public.
226 # TODO(primiano): if a 'public' section is specified (even if empty), then
227 # the rest of 'sources' is considered inaccessible by gn. Consider
228 # emulating that, so that generated build files don't end up with overly
229 # accessible headers.
230 public_headers = [x for x in desc.get('public', []) if x != '*']
231 target.public_headers.update(public_headers)
232
233 target.cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
234 target.libs.update(desc.get('libs', []))
235 target.ldflags.update(desc.get('ldflags', []))
236 target.defines.update(desc.get('defines', []))
237 target.include_dirs.update(desc.get('include_dirs', []))
238
239 # Recurse in dependencies.
240 for dep_name in desc.get('deps', []):
241 dep = self.get_target(dep_name)
242 if dep.is_third_party_dep_:
243 target.deps.add(dep_name)
244 elif dep.type == 'proto_library':
245 target.proto_deps.add(dep_name)
246 target.transitive_proto_deps.add(dep_name)
247 target.proto_paths.update(dep.proto_paths)
248 target.transitive_proto_deps.update(dep.transitive_proto_deps)
249 elif dep.type == 'source_set':
250 target.source_set_deps.add(dep_name)
251 target.update(dep) # Bubble up source set's cflags/ldflags etc.
252 elif dep.type == 'group':
253 target.update(dep) # Bubble up groups's cflags/ldflags etc.
254 elif dep.type == 'action':
255 if proto_target_type is None:
256 target.deps.add(dep_name)
257 elif dep.type in LINKER_UNIT_TYPES:
258 target.deps.add(dep_name)
259
260 return target
261
262 def get_proto_exports(self, proto_desc):
263 # exports in metadata will be available for source_set targets.
264 metadata = proto_desc.get('metadata', {})
265 return metadata.get('exports', [])
266
267 def get_proto_paths(self, proto_desc):
268 # import_dirs in metadata will be available for source_set targets.
269 metadata = proto_desc.get('metadata', {})
270 return metadata.get('import_dirs', [])
271
272 def get_proto_target_type(self, target):
273 """ Checks if the target is a proto library and return the plugin.
274
275 Returns:
276 (None, None): if the target is not a proto library.
277 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
278 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
279 json desc of the target with the .proto sources (_gen target for
280 non-descriptor types or the target itself for descriptor type).
281 """
282 parts = target.name.split('(', 1)
283 name = parts[0]
284 toolchain = '(' + parts[1] if len(parts) > 1 else ''
285
286 # Descriptor targets don't have a _gen target; instead we look for the
287 # characteristic flag in the args of the target itself.
288 desc = self.gn_desc_.get(target.name)
289 if '--descriptor_set_out' in desc.get('args', []):
290 return 'descriptor', desc
291
292 # Source set proto targets have a non-empty proto_library_sources in the
293 # metadata of the description.
294 metadata = desc.get('metadata', {})
295 if 'proto_library_sources' in metadata:
296 return 'source_set', desc
297
298 # In all other cases, we want to look at the _gen target as that has the
299 # important information.
300 gen_desc = self.gn_desc_.get('%s_gen%s' % (name, toolchain))
301 if gen_desc is None or gen_desc['type'] != 'action':
302 return None, None
303 args = gen_desc.get('args', [])
304 if '/protoc' not in args[0]:
305 return None, None
306 plugin = 'proto'
307 for arg in (arg for arg in args if arg.startswith('--plugin=')):
308 # |arg| at this point looks like:
309 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
310 # or
311 # --plugin=protoc-gen-plugin=protozero_plugin
312 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
313 return plugin, gen_desc