blob: 7e6752b0df89f78f420d1f3cacd48e37d8e0feff [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):
Patrick Rohrc20887d2022-10-28 12:59:20 -0700174 # response_file_contents are formatted as:
175 # ['--flags', '--flag=true && false'] and need to be formatted as:
176 # '--flags --flag=\"true && false\"'
177 flags = action_desc.get('response_file_contents', [])
178 formatted_flags = []
179 for flag in flags:
180 if '=' in flag:
181 key, val = flag.split('=')
182 formatted_flags.append('%s=\\"%s\\"' % (key, val))
183 else:
184 formatted_flags.append(flag)
185
186 return ' '.join(formatted_flags)
Patrick Rohr09716f52022-10-27 13:02:36 -0700187
Patrick Rohr92d74122022-10-21 15:50:52 -0700188 def get_target(self, gn_target_name):
189 """Returns a Target object from the fully qualified GN target name.
190
191 It bubbles up variables from source_set dependencies as described in the
192 class-level comments.
193 """
194 target = self.all_targets.get(gn_target_name)
195 if target is not None:
196 return target # Target already processed.
197
198 desc = self.gn_desc_[gn_target_name]
199 target = GnParser.Target(gn_target_name, desc['type'])
200 target.testonly = desc.get('testonly', False)
201 target.toolchain = desc.get('toolchain', None)
202 self.all_targets[gn_target_name] = target
203
Patrick Rohr26af1e72022-10-25 12:11:05 -0700204 # TODO: determine if below comment should apply for cronet builds in Android.
Patrick Rohr92d74122022-10-21 15:50:52 -0700205 # We should never have GN targets directly depend on buidtools. They
206 # should hop via //gn:xxx, so we can give generators an opportunity to
207 # override them.
Patrick Rohr26af1e72022-10-25 12:11:05 -0700208 # Specifically allow targets to depend on libc++ and libunwind.
209 if not any(match in gn_target_name for match in ['libc++', 'libunwind']):
210 assert (not gn_target_name.startswith('//buildtools'))
211
Patrick Rohr92d74122022-10-21 15:50:52 -0700212
213 # Don't descend further into third_party targets. Genrators are supposed
214 # to either ignore them or route to other externally-provided targets.
215 if gn_target_name.startswith('//gn'):
216 target.is_third_party_dep_ = True
217 return target
218
219 proto_target_type, proto_desc = self.get_proto_target_type(target)
220 if proto_target_type is not None:
221 self.proto_libs[target.name] = target
222 target.type = 'proto_library'
223 target.proto_plugin = proto_target_type
224 target.proto_paths.update(self.get_proto_paths(proto_desc))
225 target.proto_exports.update(self.get_proto_exports(proto_desc))
226 target.sources.update(proto_desc.get('sources', []))
227 assert (all(x.endswith('.proto') for x in target.sources))
228 elif target.type == 'source_set':
229 self.source_sets[gn_target_name] = target
230 target.sources.update(desc.get('sources', []))
231 elif target.type in LINKER_UNIT_TYPES:
232 self.linker_units[gn_target_name] = target
233 target.sources.update(desc.get('sources', []))
Patrick Rohrda778a02022-10-25 16:17:31 -0700234 elif target.type in ['action', 'action_foreach']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700235 self.actions[gn_target_name] = target
236 target.inputs.update(desc.get('inputs', []))
237 target.sources.update(desc.get('sources', []))
238 outs = [re.sub('^//out/.+?/gen/', '', x) for x in desc['outputs']]
239 target.outputs.update(outs)
240 target.script = desc['script']
241 # Args are typically relative to the root build dir (../../xxx)
242 # because root build dir is typically out/xxx/).
243 target.args = [re.sub('^../../', '//', x) for x in desc['args']]
Patrick Rohr7aa98f92022-10-28 11:16:36 -0700244 target.args = desc['args']
Patrick Rohr09716f52022-10-27 13:02:36 -0700245 target.response_file_contents = self._get_response_file_contents(desc)
Patrick Rohrda778a02022-10-25 16:17:31 -0700246 elif target.type == 'copy':
247 # TODO: copy rules are not currently implemented.
248 self.actions[gn_target_name] = target
Patrick Rohr92d74122022-10-21 15:50:52 -0700249
250 # Default for 'public' is //* - all headers in 'sources' are public.
251 # TODO(primiano): if a 'public' section is specified (even if empty), then
252 # the rest of 'sources' is considered inaccessible by gn. Consider
253 # emulating that, so that generated build files don't end up with overly
254 # accessible headers.
255 public_headers = [x for x in desc.get('public', []) if x != '*']
256 target.public_headers.update(public_headers)
257
258 target.cflags.update(desc.get('cflags', []) + desc.get('cflags_cc', []))
259 target.libs.update(desc.get('libs', []))
260 target.ldflags.update(desc.get('ldflags', []))
261 target.defines.update(desc.get('defines', []))
262 target.include_dirs.update(desc.get('include_dirs', []))
263
264 # Recurse in dependencies.
265 for dep_name in desc.get('deps', []):
266 dep = self.get_target(dep_name)
267 if dep.is_third_party_dep_:
268 target.deps.add(dep_name)
269 elif dep.type == 'proto_library':
270 target.proto_deps.add(dep_name)
271 target.transitive_proto_deps.add(dep_name)
272 target.proto_paths.update(dep.proto_paths)
273 target.transitive_proto_deps.update(dep.transitive_proto_deps)
274 elif dep.type == 'source_set':
275 target.source_set_deps.add(dep_name)
276 target.update(dep) # Bubble up source set's cflags/ldflags etc.
277 elif dep.type == 'group':
278 target.update(dep) # Bubble up groups's cflags/ldflags etc.
Patrick Rohrda778a02022-10-25 16:17:31 -0700279 elif dep.type in ['action', 'action_foreach', 'copy']:
Patrick Rohr92d74122022-10-21 15:50:52 -0700280 if proto_target_type is None:
281 target.deps.add(dep_name)
282 elif dep.type in LINKER_UNIT_TYPES:
283 target.deps.add(dep_name)
284
285 return target
286
287 def get_proto_exports(self, proto_desc):
288 # exports in metadata will be available for source_set targets.
289 metadata = proto_desc.get('metadata', {})
290 return metadata.get('exports', [])
291
292 def get_proto_paths(self, proto_desc):
293 # import_dirs in metadata will be available for source_set targets.
294 metadata = proto_desc.get('metadata', {})
295 return metadata.get('import_dirs', [])
296
297 def get_proto_target_type(self, target):
298 """ Checks if the target is a proto library and return the plugin.
299
300 Returns:
301 (None, None): if the target is not a proto library.
302 (plugin, proto_desc) where |plugin| is 'proto' in the default (lite)
303 case or 'protozero' or 'ipc' or 'descriptor'; |proto_desc| is the GN
304 json desc of the target with the .proto sources (_gen target for
305 non-descriptor types or the target itself for descriptor type).
306 """
307 parts = target.name.split('(', 1)
308 name = parts[0]
309 toolchain = '(' + parts[1] if len(parts) > 1 else ''
310
311 # Descriptor targets don't have a _gen target; instead we look for the
312 # characteristic flag in the args of the target itself.
313 desc = self.gn_desc_.get(target.name)
314 if '--descriptor_set_out' in desc.get('args', []):
315 return 'descriptor', desc
316
317 # Source set proto targets have a non-empty proto_library_sources in the
318 # metadata of the description.
319 metadata = desc.get('metadata', {})
320 if 'proto_library_sources' in metadata:
321 return 'source_set', desc
322
323 # In all other cases, we want to look at the _gen target as that has the
324 # important information.
325 gen_desc = self.gn_desc_.get('%s_gen%s' % (name, toolchain))
326 if gen_desc is None or gen_desc['type'] != 'action':
327 return None, None
328 args = gen_desc.get('args', [])
329 if '/protoc' not in args[0]:
330 return None, None
331 plugin = 'proto'
332 for arg in (arg for arg in args if arg.startswith('--plugin=')):
333 # |arg| at this point looks like:
334 # --plugin=protoc-gen-plugin=gcc_like_host/protozero_plugin
335 # or
336 # --plugin=protoc-gen-plugin=protozero_plugin
337 plugin = arg.split('=')[-1].split('/')[-1].replace('_plugin', '')
338 return plugin, gen_desc