blob: 12f942dc87cf75056370a3a99fdb76a03a5505ac [file] [log] [blame]
dprankefe4602312015-04-08 16:20:351#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""MB - the Meta-Build wrapper around GYP and GN
7
8MB is a wrapper script for GYP and GN that can be used to generate build files
9for sets of canned configurations and analyze them.
10"""
11
12from __future__ import print_function
13
14import argparse
15import ast
dprankec3441d12015-06-23 23:01:3516import errno
dprankefe4602312015-04-08 16:20:3517import json
18import os
dpranke68d1cb182015-09-17 23:30:0019import pipes
dpranked8113582015-06-05 20:08:2520import pprint
dpranke3cec199c2015-09-22 23:29:0221import re
dprankefe4602312015-04-08 16:20:3522import shutil
23import sys
24import subprocess
dprankef61de2f2015-05-14 04:09:5625import tempfile
dprankefe4602312015-04-08 16:20:3526
dprankefe4602312015-04-08 16:20:3527def main(args):
dprankeee5b51f62015-04-09 00:03:2228 mbw = MetaBuildWrapper()
29 mbw.ParseArgs(args)
30 return mbw.args.func()
dprankefe4602312015-04-08 16:20:3531
32
33class MetaBuildWrapper(object):
34 def __init__(self):
35 p = os.path
36 d = os.path.dirname
37 self.chromium_src_dir = p.normpath(d(d(d(p.abspath(__file__)))))
38 self.default_config = p.join(self.chromium_src_dir, 'tools', 'mb',
39 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3340 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5141 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3342 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3543 self.args = argparse.Namespace()
44 self.configs = {}
45 self.masters = {}
46 self.mixins = {}
47 self.private_configs = []
48 self.common_dev_configs = []
49 self.unsupported_configs = []
50
51 def ParseArgs(self, argv):
52 def AddCommonOptions(subp):
53 subp.add_argument('-b', '--builder',
54 help='builder name to look up config from')
55 subp.add_argument('-m', '--master',
56 help='master name to look up config from')
57 subp.add_argument('-c', '--config',
58 help='configuration to analyze')
59 subp.add_argument('-f', '--config-file', metavar='PATH',
60 default=self.default_config,
61 help='path to config file '
62 '(default is //tools/mb/mb_config.pyl)')
63 subp.add_argument('-g', '--goma-dir', default=self.ExpandUser('~/goma'),
64 help='path to goma directory (default is %(default)s).')
65 subp.add_argument('-n', '--dryrun', action='store_true',
66 help='Do a dry run (i.e., do nothing, just print '
67 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4068 subp.add_argument('-v', '--verbose', action='store_true',
69 help='verbose logging')
dprankefe4602312015-04-08 16:20:3570
71 parser = argparse.ArgumentParser(prog='mb')
72 subps = parser.add_subparsers()
73
74 subp = subps.add_parser('analyze',
75 help='analyze whether changes to a set of files '
76 'will cause a set of binaries to be rebuilt.')
77 AddCommonOptions(subp)
tsergeantf061c992015-07-16 01:34:0078 subp.add_argument('--swarming-targets-file',
79 help='save runtime dependencies for targets listed '
80 'in file.')
dpranked8113582015-06-05 20:08:2581 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3582 help='path build was generated into.')
83 subp.add_argument('input_path', nargs=1,
84 help='path to a file containing the input arguments '
85 'as a JSON object.')
86 subp.add_argument('output_path', nargs=1,
87 help='path to a file containing the output arguments '
88 'as a JSON object.')
89 subp.set_defaults(func=self.CmdAnalyze)
90
91 subp = subps.add_parser('gen',
92 help='generate a new set of build files')
93 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:3994 subp.add_argument('--swarming-targets-file',
95 help='save runtime dependencies for targets listed '
96 'in file.')
dpranked8113582015-06-05 20:08:2597 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3598 help='path to generate build into')
99 subp.set_defaults(func=self.CmdGen)
100
101 subp = subps.add_parser('lookup',
102 help='look up the command for a given config or '
103 'builder')
104 AddCommonOptions(subp)
105 subp.set_defaults(func=self.CmdLookup)
106
107 subp = subps.add_parser('validate',
108 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17109 subp.add_argument('-f', '--config-file', metavar='PATH',
110 default=self.default_config,
111 help='path to config file '
112 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35113 subp.set_defaults(func=self.CmdValidate)
114
115 subp = subps.add_parser('help',
116 help='Get help on a subcommand.')
117 subp.add_argument(nargs='?', action='store', dest='subcommand',
118 help='The command to get help for.')
119 subp.set_defaults(func=self.CmdHelp)
120
121 self.args = parser.parse_args(argv)
122
123 def CmdAnalyze(self):
124 vals = self.GetConfig()
125 if vals['type'] == 'gn':
126 return self.RunGNAnalyze(vals)
127 elif vals['type'] == 'gyp':
128 return self.RunGYPAnalyze(vals)
129 else:
130 raise MBErr('Unknown meta-build type "%s"' % vals['type'])
131
132 def CmdGen(self):
133 vals = self.GetConfig()
dprankec161aa92015-09-14 20:21:13134
135 self.ClobberIfNeeded(vals)
136
dprankefe4602312015-04-08 16:20:35137 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50138 return self.RunGNGen(vals)
dpranke08d2ab12015-04-24 21:54:20139 if vals['type'] == 'gyp':
Dirk Pranke0fd41bcd2015-06-19 00:05:50140 return self.RunGYPGen(vals)
dpranke08d2ab12015-04-24 21:54:20141
142 raise MBErr('Unknown meta-build type "%s"' % vals['type'])
dprankefe4602312015-04-08 16:20:35143
144 def CmdLookup(self):
145 vals = self.GetConfig()
146 if vals['type'] == 'gn':
dpranke3cec199c2015-09-22 23:29:02147 cmd = self.GNCmd('gen', '_path_', vals['gn_args'])
148 env = None
dprankefe4602312015-04-08 16:20:35149 elif vals['type'] == 'gyp':
dprankeedc49c382015-08-14 02:32:59150 if vals['gyp_crosscompile']:
151 self.Print('GYP_CROSSCOMPILE=1')
dpranke3cec199c2015-09-22 23:29:02152 cmd, env = self.GYPCmd('_path_', vals['gyp_defines'])
dprankefe4602312015-04-08 16:20:35153 else:
154 raise MBErr('Unknown meta-build type "%s"' % vals['type'])
155
dpranke3cec199c2015-09-22 23:29:02156 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35157 return 0
158
159 def CmdHelp(self):
160 if self.args.subcommand:
161 self.ParseArgs([self.args.subcommand, '--help'])
162 else:
163 self.ParseArgs(['--help'])
164
165 def CmdValidate(self):
166 errs = []
167
168 # Read the file to make sure it parses.
169 self.ReadConfigFile()
170
171 # Figure out the whole list of configs and ensure that no config is
172 # listed in more than one category.
173 all_configs = {}
174 for config in self.common_dev_configs:
175 all_configs[config] = 'common_dev_configs'
176 for config in self.private_configs:
177 if config in all_configs:
178 errs.append('config "%s" listed in "private_configs" also '
179 'listed in "%s"' % (config, all_configs['config']))
180 else:
181 all_configs[config] = 'private_configs'
182 for config in self.unsupported_configs:
183 if config in all_configs:
184 errs.append('config "%s" listed in "unsupported_configs" also '
185 'listed in "%s"' % (config, all_configs['config']))
186 else:
187 all_configs[config] = 'unsupported_configs'
188
189 for master in self.masters:
190 for builder in self.masters[master]:
191 config = self.masters[master][builder]
192 if config in all_configs and all_configs[config] not in self.masters:
193 errs.append('Config "%s" used by a bot is also listed in "%s".' %
194 (config, all_configs[config]))
195 else:
196 all_configs[config] = master
197
198 # Check that every referenced config actually exists.
199 for config, loc in all_configs.items():
200 if not config in self.configs:
201 errs.append('Unknown config "%s" referenced from "%s".' %
202 (config, loc))
203
204 # Check that every actual config is actually referenced.
205 for config in self.configs:
206 if not config in all_configs:
207 errs.append('Unused config "%s".' % config)
208
209 # Figure out the whole list of mixins, and check that every mixin
210 # listed by a config or another mixin actually exists.
211 referenced_mixins = set()
212 for config, mixins in self.configs.items():
213 for mixin in mixins:
214 if not mixin in self.mixins:
215 errs.append('Unknown mixin "%s" referenced by config "%s".' %
216 (mixin, config))
217 referenced_mixins.add(mixin)
218
219 for mixin in self.mixins:
220 for sub_mixin in self.mixins[mixin].get('mixins', []):
221 if not sub_mixin in self.mixins:
222 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
223 (sub_mixin, mixin))
224 referenced_mixins.add(sub_mixin)
225
226 # Check that every mixin defined is actually referenced somewhere.
227 for mixin in self.mixins:
228 if not mixin in referenced_mixins:
229 errs.append('Unreferenced mixin "%s".' % mixin)
230
231 if errs:
dpranke4323c80632015-08-10 22:53:54232 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17233 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35234
dprankee0547cd2015-09-15 01:27:40235 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35236 return 0
237
238 def GetConfig(self):
239 self.ReadConfigFile()
240 config = self.ConfigFromArgs()
241 if not config in self.configs:
242 raise MBErr('Config "%s" not found in %s' %
243 (config, self.args.config_file))
244
245 return self.FlattenConfig(config)
246
247 def ReadConfigFile(self):
248 if not self.Exists(self.args.config_file):
249 raise MBErr('config file not found at %s' % self.args.config_file)
250
251 try:
252 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
253 except SyntaxError as e:
254 raise MBErr('Failed to parse config file "%s": %s' %
255 (self.args.config_file, e))
256
257 self.common_dev_configs = contents['common_dev_configs']
258 self.configs = contents['configs']
259 self.masters = contents['masters']
260 self.mixins = contents['mixins']
261 self.private_configs = contents['private_configs']
262 self.unsupported_configs = contents['unsupported_configs']
263
264 def ConfigFromArgs(self):
265 if self.args.config:
266 if self.args.master or self.args.builder:
267 raise MBErr('Can not specific both -c/--config and -m/--master or '
268 '-b/--builder')
269
270 return self.args.config
271
272 if not self.args.master or not self.args.builder:
273 raise MBErr('Must specify either -c/--config or '
274 '(-m/--master and -b/--builder)')
275
276 if not self.args.master in self.masters:
277 raise MBErr('Master name "%s" not found in "%s"' %
278 (self.args.master, self.args.config_file))
279
280 if not self.args.builder in self.masters[self.args.master]:
281 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
282 (self.args.builder, self.args.master, self.args.config_file))
283
284 return self.masters[self.args.master][self.args.builder]
285
286 def FlattenConfig(self, config):
287 mixins = self.configs[config]
288 vals = {
289 'type': None,
290 'gn_args': [],
dprankec161aa92015-09-14 20:21:13291 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59292 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35293 }
294
295 visited = []
296 self.FlattenMixins(mixins, vals, visited)
297 return vals
298
299 def FlattenMixins(self, mixins, vals, visited):
300 for m in mixins:
301 if m not in self.mixins:
302 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22303
304 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35305
306 visited.append(m)
307
308 mixin_vals = self.mixins[m]
309 if 'type' in mixin_vals:
310 vals['type'] = mixin_vals['type']
311 if 'gn_args' in mixin_vals:
312 if vals['gn_args']:
313 vals['gn_args'] += ' ' + mixin_vals['gn_args']
314 else:
315 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59316 if 'gyp_crosscompile' in mixin_vals:
317 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35318 if 'gyp_defines' in mixin_vals:
319 if vals['gyp_defines']:
320 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
321 else:
322 vals['gyp_defines'] = mixin_vals['gyp_defines']
323 if 'mixins' in mixin_vals:
324 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
325 return vals
326
dprankec161aa92015-09-14 20:21:13327 def ClobberIfNeeded(self, vals):
328 path = self.args.path[0]
329 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33330 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13331 needs_clobber = False
332 new_mb_type = vals['type']
333 if self.Exists(build_dir):
334 if self.Exists(mb_type_path):
335 old_mb_type = self.ReadFile(mb_type_path)
336 if old_mb_type != new_mb_type:
337 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
338 (old_mb_type, new_mb_type, path))
339 needs_clobber = True
340 else:
341 # There is no 'mb_type' file in the build directory, so this probably
342 # means that the prior build(s) were not done through mb, and we
343 # have no idea if this was a GYP build or a GN build. Clobber it
344 # to be safe.
345 self.Print("%s/mb_type missing, clobbering to be safe" % path)
346 needs_clobber = True
347
dpranke3cec199c2015-09-22 23:29:02348 if self.args.dryrun:
349 return
350
dprankec161aa92015-09-14 20:21:13351 if needs_clobber:
352 self.RemoveDirectory(build_dir)
353
354 self.MaybeMakeDirectory(build_dir)
355 self.WriteFile(mb_type_path, new_mb_type)
356
Dirk Pranke0fd41bcd2015-06-19 00:05:50357 def RunGNGen(self, vals):
358 path = self.args.path[0]
359
dprankeb218d912015-09-18 19:07:00360 cmd = self.GNCmd('gen', path, vals['gn_args'], extra_args=['--check'])
dpranke74559b52015-06-10 21:20:39361
362 swarming_targets = []
363 if self.args.swarming_targets_file:
364 # We need GN to generate the list of runtime dependencies for
365 # the compile targets listed (one per line) in the file so
366 # we can run them via swarming. We use ninja_to_gn.pyl to convert
367 # the compile targets to the matching GN labels.
368 contents = self.ReadFile(self.args.swarming_targets_file)
369 swarming_targets = contents.splitlines()
dpranke8c2cfd32015-09-17 20:12:33370 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47371 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39372 gn_labels = []
373 for target in swarming_targets:
dprankea55584f12015-07-22 00:52:47374 if not target in gn_isolate_map:
dpranke74559b52015-06-10 21:20:39375 raise MBErr('test target "%s" not found in %s' %
dprankea55584f12015-07-22 00:52:47376 (target, '//testing/buildbot/gn_isolate_map.pyl'))
377 gn_labels.append(gn_isolate_map[target]['label'])
dpranke74559b52015-06-10 21:20:39378
379 gn_runtime_deps_path = self.ToAbsPath(path, 'runtime_deps')
dprankec3441d12015-06-23 23:01:35380
381 # Since GN hasn't run yet, the build directory may not even exist.
382 self.MaybeMakeDirectory(self.ToAbsPath(path))
383
dpranke74559b52015-06-10 21:20:39384 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
385 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
386
dprankefe4602312015-04-08 16:20:35387 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40388 if ret:
389 # If `gn gen` failed, we should exit early rather than trying to
390 # generate isolates. Run() will have already logged any error output.
391 self.Print('GN gen failed: %d' % ret)
392 return ret
dpranke74559b52015-06-10 21:20:39393
394 for target in swarming_targets:
dprankedbdd9d82015-08-12 21:18:18395 if gn_isolate_map[target]['type'] == 'gpu_browser_test':
396 runtime_deps_target = 'browser_tests'
dpranke6abd8652015-08-28 03:21:11397 elif gn_isolate_map[target]['type'] == 'script':
398 # For script targets, the build target is usually a group,
399 # for which gn generates the runtime_deps next to the stamp file
400 # for the label, which lives under the obj/ directory.
401 label = gn_isolate_map[target]['label']
402 runtime_deps_target = 'obj/%s.stamp' % label.replace(':', '/')
dpranke34bd39d2015-06-24 02:36:52403 else:
dprankedbdd9d82015-08-12 21:18:18404 runtime_deps_target = target
dpranke8c2cfd32015-09-17 20:12:33405 if self.platform == 'win32':
dprankedbdd9d82015-08-12 21:18:18406 deps_path = self.ToAbsPath(path,
407 runtime_deps_target + '.exe.runtime_deps')
408 else:
409 deps_path = self.ToAbsPath(path,
410 runtime_deps_target + '.runtime_deps')
dpranke74559b52015-06-10 21:20:39411 if not self.Exists(deps_path):
412 raise MBErr('did not generate %s' % deps_path)
413
dprankea55584f12015-07-22 00:52:47414 command, extra_files = self.GetIsolateCommand(target, vals,
415 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30416
417 runtime_deps = self.ReadFile(deps_path).splitlines()
418
419 isolate_path = self.ToAbsPath(path, target + '.isolate')
420 self.WriteFile(isolate_path,
421 pprint.pformat({
422 'variables': {
423 'command': command,
424 'files': sorted(runtime_deps + extra_files),
dpranked5b2b9432015-06-23 16:55:30425 }
426 }) + '\n')
427
428 self.WriteJSON(
429 {
430 'args': [
431 '--isolated',
dpranke8c2cfd32015-09-17 20:12:33432 self.ToSrcRelPath('%s%s%s.isolated' % (path, self.sep, target)),
dpranked5b2b9432015-06-23 16:55:30433 '--isolate',
dpranke8c2cfd32015-09-17 20:12:33434 self.ToSrcRelPath('%s%s%s.isolate' % (path, self.sep, target)),
dpranked5b2b9432015-06-23 16:55:30435 ],
436 'dir': self.chromium_src_dir,
437 'version': 1,
438 },
439 isolate_path + 'd.gen.json',
440 )
441
dprankefe4602312015-04-08 16:20:35442 return ret
443
dprankeb218d912015-09-18 19:07:00444 def GNCmd(self, subcommand, path, gn_args='', extra_args=None):
dpranked1fba482015-04-14 20:54:51445 if self.platform == 'linux2':
dpranke8c2cfd32015-09-17 20:12:33446 subdir = 'linux64'
dpranked1fba482015-04-14 20:54:51447 elif self.platform == 'darwin':
dpranke8c2cfd32015-09-17 20:12:33448 subdir = 'mac'
dpranked1fba482015-04-14 20:54:51449 else:
dpranke8c2cfd32015-09-17 20:12:33450 subdir = 'win'
451 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, 'gn')
dpranked1fba482015-04-14 20:54:51452
453 cmd = [gn_path, subcommand, path]
dprankeee5b51f62015-04-09 00:03:22454 gn_args = gn_args.replace("$(goma_dir)", self.args.goma_dir)
dprankefe4602312015-04-08 16:20:35455 if gn_args:
456 cmd.append('--args=%s' % gn_args)
dprankeb218d912015-09-18 19:07:00457 if extra_args:
458 cmd.extend(extra_args)
dprankefe4602312015-04-08 16:20:35459 return cmd
460
Dirk Pranke0fd41bcd2015-06-19 00:05:50461 def RunGYPGen(self, vals):
462 path = self.args.path[0]
463
dpranke8c2cfd32015-09-17 20:12:33464 output_dir = self.ParseGYPConfigPath(path)
dpranke3cec199c2015-09-22 23:29:02465 cmd, env = self.GYPCmd(output_dir, vals['gyp_defines'])
dprankeedc49c382015-08-14 02:32:59466 if vals['gyp_crosscompile']:
dprankeedc49c382015-08-14 02:32:59467 env['GYP_CROSSCOMPILE'] = '1'
468 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35469 return ret
470
471 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33472 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32473 if self.args.verbose:
Dirk Pranke953b27b2015-08-11 03:59:13474 inp = self.ReadInputJSON(['files', 'targets'])
dprankecda00332015-04-11 04:18:32475 self.Print()
476 self.Print('analyze input:')
477 self.PrintJSON(inp)
478 self.Print()
479
dpranke3cec199c2015-09-22 23:29:02480 cmd, env = self.GYPCmd(output_dir, vals['gyp_defines'])
dpranke1d306312015-08-11 21:17:33481 cmd.extend(['-f', 'analyzer',
482 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35483 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02484 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32485 if not ret and self.args.verbose:
486 outp = json.loads(self.ReadFile(self.args.output_path[0]))
487 self.Print()
488 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39489 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32490 self.Print()
491
dprankefe4602312015-04-08 16:20:35492 return ret
493
dprankea55584f12015-07-22 00:52:47494 def GetIsolateCommand(self, target, vals, gn_isolate_map):
dpranked8113582015-06-05 20:08:25495 # This needs to mirror the settings in //build/config/ui.gni:
496 # use_x11 = is_linux && !use_ozone.
497 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33498 use_x11 = (self.platform == 'linux2' and
dpranked8113582015-06-05 20:08:25499 not 'target_os="android"' in vals['gn_args'] and
500 not 'use_ozone=true' in vals['gn_args'])
501
502 asan = 'is_asan=true' in vals['gn_args']
503 msan = 'is_msan=true' in vals['gn_args']
504 tsan = 'is_tsan=true' in vals['gn_args']
505
dpranke8c2cfd32015-09-17 20:12:33506 executable_suffix = '.exe' if self.platform == 'win32' else ''
dpranked8113582015-06-05 20:08:25507
dprankea55584f12015-07-22 00:52:47508 test_type = gn_isolate_map[target]['type']
509 cmdline = []
510 extra_files = []
dpranked8113582015-06-05 20:08:25511
dprankea55584f12015-07-22 00:52:47512 if use_x11 and test_type == 'windowed_test_launcher':
513 extra_files = [
514 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25515 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47516 '../../testing/xvfb.py',
517 ]
518 cmdline = [
519 '../../testing/xvfb.py',
520 '.',
521 './' + str(target),
522 '--brave-new-test-launcher',
523 '--test-launcher-bot-mode',
524 '--asan=%d' % asan,
525 '--msan=%d' % msan,
526 '--tsan=%d' % tsan,
527 ]
528 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
529 extra_files = [
530 '../../testing/test_env.py'
531 ]
532 cmdline = [
533 '../../testing/test_env.py',
dpranked8113582015-06-05 20:08:25534 './' + str(target) + executable_suffix,
535 '--brave-new-test-launcher',
536 '--test-launcher-bot-mode',
537 '--asan=%d' % asan,
538 '--msan=%d' % msan,
539 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47540 ]
dprankedbdd9d82015-08-12 21:18:18541 elif test_type == 'gpu_browser_test':
542 extra_files = [
543 '../../testing/test_env.py'
544 ]
545 gtest_filter = gn_isolate_map[target]['gtest_filter']
546 cmdline = [
547 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11548 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18549 '--test-launcher-bot-mode',
550 '--enable-gpu',
551 '--test-launcher-jobs=1',
552 '--gtest_filter=%s' % gtest_filter,
553 ]
dpranke6abd8652015-08-28 03:21:11554 elif test_type == 'script':
555 extra_files = [
556 '../../testing/test_env.py'
557 ]
558 cmdline = [
559 '../../testing/test_env.py',
560 ] + ['../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])]
dprankea55584f12015-07-22 00:52:47561 elif test_type in ('raw'):
562 extra_files = []
563 cmdline = [
564 './' + str(target) + executable_suffix,
565 ] + gn_isolate_map[target].get('args')
dpranked8113582015-06-05 20:08:25566
dprankea55584f12015-07-22 00:52:47567 else:
568 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
569 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25570
571 return cmdline, extra_files
572
dpranke74559b52015-06-10 21:20:39573 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33574 return self.PathJoin(self.chromium_src_dir,
575 self.ToSrcRelPath(build_path),
576 *comps)
dpranked8113582015-06-05 20:08:25577
dprankeee5b51f62015-04-09 00:03:22578 def ToSrcRelPath(self, path):
579 """Returns a relative path from the top of the repo."""
580 # TODO: Support normal paths in addition to source-absolute paths.
dprankefe4602312015-04-08 16:20:35581 assert(path.startswith('//'))
dpranke8c2cfd32015-09-17 20:12:33582 return path[2:].replace('/', self.sep)
dprankefe4602312015-04-08 16:20:35583
584 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:22585 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:33586 output_dir, _, _ = rpath.rpartition(self.sep)
587 return output_dir
dprankefe4602312015-04-08 16:20:35588
dpranke8c2cfd32015-09-17 20:12:33589 def GYPCmd(self, output_dir, gyp_defines):
dpranke3cec199c2015-09-22 23:29:02590 goma_dir = self.args.goma_dir
591
592 # GYP uses shlex.split() to split the gyp defines into separate arguments,
593 # so we can support backslashes and and spaces in arguments by quoting
594 # them, even on Windows, where this normally wouldn't work.
595 if '\\' in goma_dir or ' ' in goma_dir:
596 goma_dir = "'%s'" % goma_dir
597 gyp_defines = gyp_defines.replace("$(goma_dir)", goma_dir)
598
dprankefe4602312015-04-08 16:20:35599 cmd = [
dpranke8c2cfd32015-09-17 20:12:33600 self.executable,
601 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:35602 '-G',
603 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:35604 ]
dpranke3cec199c2015-09-22 23:29:02605 env = os.environ.copy()
606 env['GYP_DEFINES'] = gyp_defines
607 return cmd, env
dprankefe4602312015-04-08 16:20:35608
Dirk Pranke0fd41bcd2015-06-19 00:05:50609 def RunGNAnalyze(self, vals):
610 # analyze runs before 'gn gen' now, so we need to run gn gen
611 # in order to ensure that we have a build directory.
612 ret = self.RunGNGen(vals)
613 if ret:
614 return ret
615
dpranked8113582015-06-05 20:08:25616 inp = self.ReadInputJSON(['files', 'targets'])
dprankecda00332015-04-11 04:18:32617 if self.args.verbose:
618 self.Print()
619 self.Print('analyze input:')
620 self.PrintJSON(inp)
621 self.Print()
622
623 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35624
625 # Bail out early if a GN file was modified, since 'gn refs' won't know
626 # what to do about it.
627 if any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']):
Dirk Prankec965fa32015-04-14 23:46:29628 self.WriteJSON({'status': 'Found dependency (all)'}, output_path)
dprankefe4602312015-04-08 16:20:35629 return 0
630
dprankef61de2f2015-05-14 04:09:56631 # Bail out early if 'all' was asked for, since 'gn refs' won't recognize it.
632 if 'all' in inp['targets']:
dpranke76734662015-04-16 02:17:50633 self.WriteJSON({'status': 'Found dependency (all)'}, output_path)
634 return 0
635
dpranke7c5f614d2015-07-22 23:43:39636 # This shouldn't normally happen, but could due to unusual race conditions,
637 # like a try job that gets scheduled before a patch lands but runs after
638 # the patch has landed.
639 if not inp['files']:
640 self.Print('Warning: No files modified in patch, bailing out early.')
641 self.WriteJSON({'targets': [],
642 'build_targets': [],
643 'status': 'No dependency'}, output_path)
644 return 0
645
Dirk Pranke12ee2db2015-04-14 23:15:32646 ret = 0
dprankef61de2f2015-05-14 04:09:56647 response_file = self.TempFile()
648 response_file.write('\n'.join(inp['files']) + '\n')
649 response_file.close()
650
651 matching_targets = []
652 try:
dpranked1fba482015-04-14 20:54:51653 cmd = self.GNCmd('refs', self.args.path[0]) + [
dpranke067d0142015-05-14 22:52:45654 '@%s' % response_file.name, '--all', '--as=output']
dprankee0547cd2015-09-15 01:27:40655 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:12656 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:32657 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
658 output_path)
dpranke8c2cfd32015-09-17 20:12:33659 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:56660 for output in out.splitlines():
661 build_output = output.replace(build_dir, '')
662 if build_output in inp['targets']:
663 matching_targets.append(build_output)
dpranke067d0142015-05-14 22:52:45664
665 cmd = self.GNCmd('refs', self.args.path[0]) + [
666 '@%s' % response_file.name, '--all']
dprankee0547cd2015-09-15 01:27:40667 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:45668 if ret and not 'The input matches no targets' in out:
669 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
670 output_path)
671 for label in out.splitlines():
672 build_target = label[2:]
newt309af8f2015-08-25 22:10:20673 # We want to accept 'chrome/android:chrome_public_apk' and
674 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:45675 # getting built, but we can adjust that later if need be.
676 for input_target in inp['targets']:
677 if (input_target == build_target or
678 build_target.endswith(':' + input_target)):
679 matching_targets.append(input_target)
dprankef61de2f2015-05-14 04:09:56680 finally:
681 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:35682
dprankef61de2f2015-05-14 04:09:56683 if matching_targets:
dprankefe4602312015-04-08 16:20:35684 # TODO: it could be that a target X might depend on a target Y
685 # and both would be listed in the input, but we would only need
686 # to specify target X as a build_target (whereas both X and Y are
687 # targets). I'm not sure if that optimization is generally worth it.
dprankee0547cd2015-09-15 01:27:40688 self.WriteJSON({'targets': sorted(set(matching_targets)),
689 'build_targets': sorted(set(matching_targets)),
dprankecda00332015-04-11 04:18:32690 'status': 'Found dependency'}, output_path)
dprankefe4602312015-04-08 16:20:35691 else:
692 self.WriteJSON({'targets': [],
693 'build_targets': [],
dprankecda00332015-04-11 04:18:32694 'status': 'No dependency'}, output_path)
695
dprankee0547cd2015-09-15 01:27:40696 if self.args.verbose:
dprankecda00332015-04-11 04:18:32697 outp = json.loads(self.ReadFile(output_path))
698 self.Print()
699 self.Print('analyze output:')
700 self.PrintJSON(outp)
701 self.Print()
dprankefe4602312015-04-08 16:20:35702
703 return 0
704
dpranked8113582015-06-05 20:08:25705 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:35706 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:32707 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:35708 if not self.Exists(path):
dprankecda00332015-04-11 04:18:32709 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:35710
711 try:
712 inp = json.loads(self.ReadFile(path))
713 except Exception as e:
714 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:32715 (path, e), output_path)
dpranked8113582015-06-05 20:08:25716
717 for k in required_keys:
718 if not k in inp:
719 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
720 output_path)
dprankefe4602312015-04-08 16:20:35721
722 return inp
723
dpranked5b2b9432015-06-23 16:55:30724 def WriteFailureAndRaise(self, msg, output_path):
725 if output_path:
dprankee0547cd2015-09-15 01:27:40726 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:35727 raise MBErr(msg)
728
dprankee0547cd2015-09-15 01:27:40729 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:32730 try:
dprankee0547cd2015-09-15 01:27:40731 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
732 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:32733 except Exception as e:
734 raise MBErr('Error %s writing to the output path "%s"' %
735 (e, path))
dprankefe4602312015-04-08 16:20:35736
dpranke3cec199c2015-09-22 23:29:02737 def PrintCmd(self, cmd, env):
738 if self.platform == 'win32':
739 env_prefix = 'set '
740 env_quoter = QuoteForSet
741 shell_quoter = QuoteForCmd
742 else:
743 env_prefix = ''
744 env_quoter = pipes.quote
745 shell_quoter = pipes.quote
746
747 def print_env(var):
748 if env and var in env:
749 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
750
751 print_env('GYP_CROSSCOMPILE')
752 print_env('GYP_DEFINES')
753
dpranke8c2cfd32015-09-17 20:12:33754 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:35755 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:02756 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:35757
dprankecda00332015-04-11 04:18:32758 def PrintJSON(self, obj):
759 self.Print(json.dumps(obj, indent=2, sort_keys=True))
760
dprankefe4602312015-04-08 16:20:35761 def Print(self, *args, **kwargs):
762 # This function largely exists so it can be overridden for testing.
763 print(*args, **kwargs)
764
dprankee0547cd2015-09-15 01:27:40765 def Run(self, cmd, env=None, force_verbose=True):
dprankefe4602312015-04-08 16:20:35766 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:40767 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:02768 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:35769 if self.args.dryrun:
770 return 0, '', ''
dprankee0547cd2015-09-15 01:27:40771
dprankeedc49c382015-08-14 02:32:59772 ret, out, err = self.Call(cmd, env=env)
dprankee0547cd2015-09-15 01:27:40773 if self.args.verbose or force_verbose:
dprankefe4602312015-04-08 16:20:35774 if out:
dprankeee5b51f62015-04-09 00:03:22775 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:35776 if err:
dprankeee5b51f62015-04-09 00:03:22777 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:35778 return ret, out, err
779
dprankeedc49c382015-08-14 02:32:59780 def Call(self, cmd, env=None):
dprankefe4602312015-04-08 16:20:35781 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
dprankeedc49c382015-08-14 02:32:59782 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
783 env=env)
dprankefe4602312015-04-08 16:20:35784 out, err = p.communicate()
785 return p.returncode, out, err
786
787 def ExpandUser(self, path):
788 # This function largely exists so it can be overridden for testing.
789 return os.path.expanduser(path)
790
791 def Exists(self, path):
792 # This function largely exists so it can be overridden for testing.
793 return os.path.exists(path)
794
dprankec3441d12015-06-23 23:01:35795 def MaybeMakeDirectory(self, path):
796 try:
797 os.makedirs(path)
798 except OSError, e:
799 if e.errno != errno.EEXIST:
800 raise
801
dpranke8c2cfd32015-09-17 20:12:33802 def PathJoin(self, *comps):
803 # This function largely exists so it can be overriden for testing.
804 return os.path.join(*comps)
805
dprankefe4602312015-04-08 16:20:35806 def ReadFile(self, path):
807 # This function largely exists so it can be overriden for testing.
808 with open(path) as fp:
809 return fp.read()
810
dprankef61de2f2015-05-14 04:09:56811 def RemoveFile(self, path):
812 # This function largely exists so it can be overriden for testing.
813 os.remove(path)
814
dprankec161aa92015-09-14 20:21:13815 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:33816 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:13817 # In other places in chromium, we often have to retry this command
818 # because we're worried about other processes still holding on to
819 # file handles, but when MB is invoked, it will be early enough in the
820 # build that their should be no other processes to interfere. We
821 # can change this if need be.
822 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
823 else:
824 shutil.rmtree(abs_path, ignore_errors=True)
825
dprankef61de2f2015-05-14 04:09:56826 def TempFile(self, mode='w'):
827 # This function largely exists so it can be overriden for testing.
828 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
829
dprankee0547cd2015-09-15 01:27:40830 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:35831 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:40832 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:30833 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:35834 with open(path, 'w') as fp:
835 return fp.write(contents)
836
dprankef61de2f2015-05-14 04:09:56837
dprankefe4602312015-04-08 16:20:35838class MBErr(Exception):
839 pass
840
841
dpranke3cec199c2015-09-22 23:29:02842# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
843# details of this next section, which handles escaping command lines
844# so that they can be copied and pasted into a cmd window.
845UNSAFE_FOR_SET = set('^<>&|')
846UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
847ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
848
849
850def QuoteForSet(arg):
851 if any(a in UNSAFE_FOR_SET for a in arg):
852 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
853 return arg
854
855
856def QuoteForCmd(arg):
857 # First, escape the arg so that CommandLineToArgvW will parse it properly.
858 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
859 if arg == '' or ' ' in arg or '"' in arg:
860 quote_re = re.compile(r'(\\*)"')
861 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
862
863 # Then check to see if the arg contains any metacharacters other than
864 # double quotes; if it does, quote everything (including the double
865 # quotes) for safety.
866 if any(a in UNSAFE_FOR_CMD for a in arg):
867 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
868 return arg
869
870
dprankefe4602312015-04-08 16:20:35871if __name__ == '__main__':
872 try:
873 sys.exit(main(sys.argv[1:]))
874 except MBErr as e:
875 print(e)
876 sys.exit(1)
877 except KeyboardInterrupt:
878 print("interrupted, exiting", stream=sys.stderr)
879 sys.exit(130)