Compute if a layer is clipped outside CalcDrawProps
[chromium-blink-merge.git] / tools / auto_bisect / builder.py
blob9a93089608729fde6ccef3dd600999ad84ff5d5f
1 # Copyright 2014 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Classes and functions for building Chrome.
7 This includes functions for running commands to build, as well as
8 specific rules about which targets to build.
9 """
11 import os
12 import subprocess
13 import sys
15 import bisect_utils
17 ORIGINAL_ENV = {}
20 class Builder(object):
21 """Subclasses of the Builder class are used by the bisect script to build
22 relevant targets.
23 """
24 def __init__(self, opts):
25 """Performs setup for building with target build system.
27 Args:
28 opts: Options parsed from command line.
30 Raises:
31 RuntimeError: Some condition necessary for building was not met.
32 """
33 if bisect_utils.IsWindowsHost():
34 if not opts.build_preference:
35 opts.build_preference = 'msvs'
37 if opts.build_preference == 'msvs':
38 if not os.getenv('VS100COMNTOOLS'):
39 raise RuntimeError(
40 'Path to visual studio could not be determined.')
41 else:
42 # Need to re-escape goma dir, see crbug.com/394990.
43 if opts.goma_dir:
44 opts.goma_dir = opts.goma_dir.encode('string_escape')
45 SetBuildSystemDefault(opts.build_preference, opts.use_goma,
46 opts.goma_dir, opts.target_arch)
47 else:
48 if not opts.build_preference:
49 if 'ninja' in os.getenv('GYP_GENERATORS', default=''):
50 opts.build_preference = 'ninja'
51 else:
52 opts.build_preference = 'make'
54 SetBuildSystemDefault(opts.build_preference, opts.use_goma, opts.goma_dir)
56 if not SetupPlatformBuildEnvironment(opts):
57 raise RuntimeError('Failed to set platform environment.')
59 @staticmethod
60 def FromOpts(opts):
61 """Constructs and returns a Builder object.
63 Args:
64 opts: Options parsed from the command-line.
65 """
66 builder = None
67 if opts.target_platform == 'android':
68 builder = AndroidBuilder(opts)
69 elif opts.target_platform == 'android-chrome':
70 builder = AndroidChromeBuilder(opts)
71 else:
72 builder = DesktopBuilder(opts)
73 return builder
75 def Build(self, depot, opts):
76 """Runs a command to build Chrome."""
77 raise NotImplementedError()
80 def GetBuildOutputDirectory(opts, src_dir=None):
81 """Returns the path to the build directory, relative to the checkout root.
83 Assumes that the current working directory is the checkout root.
85 Args:
86 opts: Command-line options.
87 src_dir: Path to chromium/src directory.
89 Returns:
90 A path to the directory to use as build output directory.
92 Raises:
93 NotImplementedError: The platform according to sys.platform is unexpected.
94 """
95 src_dir = src_dir or 'src'
96 if opts.build_preference == 'ninja' or bisect_utils.IsLinuxHost():
97 return os.path.join(src_dir, 'out')
98 if bisect_utils.IsMacHost():
99 return os.path.join(src_dir, 'xcodebuild')
100 if bisect_utils.IsWindowsHost():
101 return os.path.join(src_dir, 'build')
102 raise NotImplementedError('Unexpected platform %s' % sys.platform)
105 class DesktopBuilder(Builder):
106 """DesktopBuilder is used to build Chromium on Linux, Mac, or Windows."""
108 def __init__(self, opts):
109 super(DesktopBuilder, self).__init__(opts)
111 def Build(self, depot, opts):
112 """Builds chromium_builder_perf target using options passed into the script.
114 Args:
115 depot: Name of current depot being bisected.
116 opts: The options parsed from the command line.
118 Returns:
119 True if build was successful.
121 targets = ['chromium_builder_perf']
123 threads = None
124 if opts.use_goma:
125 threads = opts.goma_threads
127 build_success = False
128 if opts.build_preference == 'make':
129 build_success = BuildWithMake(threads, targets, opts.target_build_type)
130 elif opts.build_preference == 'ninja':
131 build_success = BuildWithNinja(threads, targets, opts.target_build_type)
132 elif opts.build_preference == 'msvs':
133 assert bisect_utils.IsWindowsHost(), 'msvs is only supported on Windows.'
134 build_success = BuildWithVisualStudio(targets, opts.target_build_type)
135 else:
136 assert False, 'No build system defined.'
137 return build_success
140 class AndroidBuilder(Builder):
141 """AndroidBuilder is used to build on android."""
143 def __init__(self, opts):
144 super(AndroidBuilder, self).__init__(opts)
146 # TODO(qyearsley): Make this a class method and verify that it works with
147 # a unit test.
148 # pylint: disable=R0201
149 def _GetTargets(self):
150 """Returns a list of build targets."""
151 return ['chrome_shell_apk', 'cc_perftests_apk', 'android_tools']
153 def Build(self, depot, opts):
154 """Builds the android content shell and other necessary tools.
156 Args:
157 depot: Current depot being bisected.
158 opts: The options parsed from the command line.
160 Returns:
161 True if build was successful.
163 threads = None
164 if opts.use_goma:
165 threads = opts.goma_threads
167 build_success = False
168 if opts.build_preference == 'ninja':
169 build_success = BuildWithNinja(
170 threads, self._GetTargets(), opts.target_build_type)
171 else:
172 assert False, 'No build system defined.'
174 return build_success
177 class AndroidChromeBuilder(AndroidBuilder):
178 """AndroidChromeBuilder is used to build "android-chrome".
180 This is slightly different from AndroidBuilder.
183 def __init__(self, opts):
184 super(AndroidChromeBuilder, self).__init__(opts)
186 # TODO(qyearsley): Make this a class method and verify that it works with
187 # a unit test.
188 # pylint: disable=R0201
189 def _GetTargets(self):
190 """Returns a list of build targets."""
191 return AndroidBuilder._GetTargets(self) + ['chrome_apk']
194 def SetBuildSystemDefault(build_system, use_goma, goma_dir, target_arch='ia32'):
195 """Sets up any environment variables needed to build with the specified build
196 system.
198 Args:
199 build_system: A string specifying build system. Currently only 'ninja' or
200 'make' are supported.
201 use_goma: Determines whether to GOMA for compile.
202 goma_dir: GOMA directory path.
203 target_arch: The target build architecture, ia32 or x64. Default is ia32.
205 if build_system == 'ninja':
206 gyp_var = os.getenv('GYP_GENERATORS', default='')
208 if not gyp_var or not 'ninja' in gyp_var:
209 if gyp_var:
210 os.environ['GYP_GENERATORS'] = gyp_var + ',ninja'
211 else:
212 os.environ['GYP_GENERATORS'] = 'ninja'
214 if bisect_utils.IsWindowsHost():
215 os.environ['GYP_DEFINES'] = 'component=shared_library '\
216 'incremental_chrome_dll=1 disable_nacl=1 fastbuild=1 '\
217 'chromium_win_pch=0'
219 elif build_system == 'make':
220 os.environ['GYP_GENERATORS'] = 'make'
221 else:
222 raise RuntimeError('%s build not supported.' % build_system)
224 if use_goma:
225 os.environ['GYP_DEFINES'] = '%s %s' % (os.getenv('GYP_DEFINES', default=''),
226 'use_goma=1')
227 if goma_dir:
228 os.environ['GYP_DEFINES'] += ' gomadir=%s' % goma_dir
230 # Produce 64 bit chromium binaries when target architecure is set to x64.
231 if target_arch == 'x64':
232 os.environ['GYP_DEFINES'] += ' target_arch=%s' % target_arch
234 def SetupPlatformBuildEnvironment(opts):
235 """Performs any platform-specific setup.
237 Args:
238 opts: The options parsed from the command line through parse_args().
240 Returns:
241 True if successful.
243 if 'android' in opts.target_platform:
244 CopyAndSaveOriginalEnvironmentVars()
245 return SetupAndroidBuildEnvironment(opts)
246 return True
249 def BuildWithMake(threads, targets, build_type='Release'):
250 """Runs a make command with the given targets.
252 Args:
253 threads: The number of threads to use. None means unspecified/unlimited.
254 targets: List of make targets.
255 build_type: Release or Debug.
257 Returns:
258 True if the command had a 0 exit code, False otherwise.
260 cmd = ['make', 'BUILDTYPE=%s' % build_type]
261 if threads:
262 cmd.append('-j%d' % threads)
263 cmd += targets
264 return_code = bisect_utils.RunProcess(cmd)
265 return not return_code
268 def BuildWithNinja(threads, targets, build_type='Release'):
269 """Runs a ninja command with the given targets."""
270 cmd = ['ninja', '-C', os.path.join('out', build_type)]
271 if threads:
272 cmd.append('-j%d' % threads)
273 cmd += targets
274 return_code = bisect_utils.RunProcess(cmd)
275 return not return_code
278 def BuildWithVisualStudio(targets, build_type='Release'):
279 """Runs a command to build the given targets with Visual Studio."""
280 path_to_devenv = os.path.abspath(
281 os.path.join(os.environ['VS100COMNTOOLS'], '..', 'IDE', 'devenv.com'))
282 path_to_sln = os.path.join(os.getcwd(), 'chrome', 'chrome.sln')
283 cmd = [path_to_devenv, '/build', build_type, path_to_sln]
284 for t in targets:
285 cmd.extend(['/Project', t])
286 return_code = bisect_utils.RunProcess(cmd)
287 return not return_code
290 def CopyAndSaveOriginalEnvironmentVars():
291 """Makes a copy of the current environment variables.
293 Before making a copy of the environment variables and setting a global
294 variable, this function unsets a certain set of environment variables.
296 # TODO: Waiting on crbug.com/255689, will remove this after.
297 vars_to_remove = [
298 'CHROME_SRC',
299 'CHROMIUM_GYP_FILE',
300 'GYP_DEFINES',
301 'GYP_GENERATORS',
302 'GYP_GENERATOR_FLAGS',
303 'OBJCOPY',
305 for key in os.environ:
306 if 'ANDROID' in key:
307 vars_to_remove.append(key)
308 for key in vars_to_remove:
309 if os.environ.has_key(key):
310 del os.environ[key]
312 global ORIGINAL_ENV
313 ORIGINAL_ENV = os.environ.copy()
316 def SetupAndroidBuildEnvironment(opts, path_to_src=None):
317 """Sets up the android build environment.
319 Args:
320 opts: The options parsed from the command line through parse_args().
321 path_to_src: Path to the src checkout.
323 Returns:
324 True if successful.
326 # Revert the environment variables back to default before setting them up
327 # with envsetup.sh.
328 env_vars = os.environ.copy()
329 for k, _ in env_vars.iteritems():
330 del os.environ[k]
331 for k, v in ORIGINAL_ENV.iteritems():
332 os.environ[k] = v
334 envsetup_path = os.path.join('build', 'android', 'envsetup.sh')
335 proc = subprocess.Popen(['bash', '-c', 'source %s && env' % envsetup_path],
336 stdout=subprocess.PIPE,
337 stderr=subprocess.PIPE,
338 cwd=path_to_src)
339 out, _ = proc.communicate()
341 for line in out.splitlines():
342 k, _, v = line.partition('=')
343 os.environ[k] = v
345 # envsetup.sh no longer sets OS=android in GYP_DEFINES environment variable.
346 # (See http://crrev.com/170273005). So, we set this variable explicitly here
347 # in order to build Chrome on Android.
348 if 'GYP_DEFINES' not in os.environ:
349 os.environ['GYP_DEFINES'] = 'OS=android'
350 else:
351 os.environ['GYP_DEFINES'] += ' OS=android'
353 if opts.use_goma:
354 os.environ['GYP_DEFINES'] += ' use_goma=1'
355 return not proc.returncode