UMA: Improve description of Enterprise.EnrollmentRecovery histogram.
[chromium-blink-merge.git] / build / gyp_chromium
blobf87761dbd6bb50b47bfa0fd860fe48934974cb1d
1 #!/usr/bin/env python
3 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
7 # This script is wrapper for Chromium that adds some support for how GYP
8 # is invoked by Chromium beyond what can be done in the gclient hooks.
10 import glob
11 import gyp_environment
12 import os
13 import re
14 import shlex
15 import subprocess
16 import string
17 import sys
18 import vs_toolchain
20 script_dir = os.path.dirname(os.path.realpath(__file__))
21 chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir))
23 sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib'))
24 import gyp
26 # Assume this file is in a one-level-deep subdirectory of the source root.
27 SRC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29 # Add paths so that pymod_do_main(...) can import files.
30 sys.path.insert(1, os.path.join(chrome_src, 'tools'))
31 sys.path.insert(1, os.path.join(chrome_src, 'tools', 'generate_shim_headers'))
32 sys.path.insert(1, os.path.join(chrome_src, 'tools', 'grit'))
33 sys.path.insert(1, os.path.join(chrome_src, 'chrome', 'tools', 'build'))
34 sys.path.insert(1, os.path.join(chrome_src, 'chromecast', 'tools', 'build'))
35 sys.path.insert(1, os.path.join(chrome_src, 'native_client', 'build'))
36 sys.path.insert(1, os.path.join(chrome_src, 'native_client_sdk', 'src',
37 'build_tools'))
38 sys.path.insert(1, os.path.join(chrome_src, 'remoting', 'tools', 'build'))
39 sys.path.insert(1, os.path.join(chrome_src, 'third_party', 'liblouis'))
40 sys.path.insert(1, os.path.join(chrome_src, 'third_party', 'WebKit',
41 'Source', 'build', 'scripts'))
43 # On Windows, Psyco shortens warm runs of build/gyp_chromium by about
44 # 20 seconds on a z600 machine with 12 GB of RAM, from 90 down to 70
45 # seconds. Conversely, memory usage of build/gyp_chromium with Psyco
46 # maxes out at about 158 MB vs. 132 MB without it.
48 # Psyco uses native libraries, so we need to load a different
49 # installation depending on which OS we are running under. It has not
50 # been tested whether using Psyco on our Mac and Linux builds is worth
51 # it (the GYP running time is a lot shorter, so the JIT startup cost
52 # may not be worth it).
53 if sys.platform == 'win32':
54 try:
55 sys.path.insert(0, os.path.join(chrome_src, 'third_party', 'psyco_win32'))
56 import psyco
57 except:
58 psyco = None
59 else:
60 psyco = None
63 def GetSupplementalFiles():
64 """Returns a list of the supplemental files that are included in all GYP
65 sources."""
66 return glob.glob(os.path.join(chrome_src, '*', 'supplement.gypi'))
69 def ProcessGypDefinesItems(items):
70 """Converts a list of strings to a list of key-value pairs."""
71 result = []
72 for item in items:
73 tokens = item.split('=', 1)
74 # Some GYP variables have hyphens, which we don't support.
75 if len(tokens) == 2:
76 result += [(tokens[0], tokens[1])]
77 else:
78 # No value supplied, treat it as a boolean and set it. Note that we
79 # use the string '1' here so we have a consistent definition whether
80 # you do 'foo=1' or 'foo'.
81 result += [(tokens[0], '1')]
82 return result
85 def GetGypVars(supplemental_files):
86 """Returns a dictionary of all GYP vars."""
87 # Find the .gyp directory in the user's home directory.
88 home_dot_gyp = os.environ.get('GYP_CONFIG_DIR', None)
89 if home_dot_gyp:
90 home_dot_gyp = os.path.expanduser(home_dot_gyp)
91 if not home_dot_gyp:
92 home_vars = ['HOME']
93 if sys.platform in ('cygwin', 'win32'):
94 home_vars.append('USERPROFILE')
95 for home_var in home_vars:
96 home = os.getenv(home_var)
97 if home != None:
98 home_dot_gyp = os.path.join(home, '.gyp')
99 if not os.path.exists(home_dot_gyp):
100 home_dot_gyp = None
101 else:
102 break
104 if home_dot_gyp:
105 include_gypi = os.path.join(home_dot_gyp, "include.gypi")
106 if os.path.exists(include_gypi):
107 supplemental_files += [include_gypi]
109 # GYP defines from the supplemental.gypi files.
110 supp_items = []
111 for supplement in supplemental_files:
112 with open(supplement, 'r') as f:
113 try:
114 file_data = eval(f.read(), {'__builtins__': None}, None)
115 except SyntaxError, e:
116 e.filename = os.path.abspath(supplement)
117 raise
118 variables = file_data.get('variables', [])
119 for v in variables:
120 supp_items += [(v, str(variables[v]))]
122 # GYP defines from the environment.
123 env_items = ProcessGypDefinesItems(
124 shlex.split(os.environ.get('GYP_DEFINES', '')))
126 # GYP defines from the command line. We can't use optparse since we want
127 # to ignore all arguments other than "-D".
128 cmdline_input_items = []
129 for i in range(len(sys.argv))[1:]:
130 if sys.argv[i].startswith('-D'):
131 if sys.argv[i] == '-D' and i + 1 < len(sys.argv):
132 cmdline_input_items += [sys.argv[i + 1]]
133 elif len(sys.argv[i]) > 2:
134 cmdline_input_items += [sys.argv[i][2:]]
135 cmdline_items = ProcessGypDefinesItems(cmdline_input_items)
137 vars_dict = dict(supp_items + env_items + cmdline_items)
138 return vars_dict
141 def GetOutputDirectory():
142 """Returns the output directory that GYP will use."""
143 # GYP generator flags from the command line. We can't use optparse since we
144 # want to ignore all arguments other than "-G".
145 needle = '-Goutput_dir='
146 cmdline_input_items = []
147 for item in sys.argv[1:]:
148 if item.startswith(needle):
149 return item[len(needle):]
151 env_items = shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', ''))
152 needle = 'output_dir='
153 for item in env_items:
154 if item.startswith(needle):
155 return item[len(needle):]
157 return "out"
160 def additional_include_files(supplemental_files, args=[]):
162 Returns a list of additional (.gypi) files to include, without duplicating
163 ones that are already specified on the command line. The list of supplemental
164 include files is passed in as an argument.
166 # Determine the include files specified on the command line.
167 # This doesn't cover all the different option formats you can use,
168 # but it's mainly intended to avoid duplicating flags on the automatic
169 # makefile regeneration which only uses this format.
170 specified_includes = set()
171 for arg in args:
172 if arg.startswith('-I') and len(arg) > 2:
173 specified_includes.add(os.path.realpath(arg[2:]))
175 result = []
176 def AddInclude(path):
177 if os.path.realpath(path) not in specified_includes:
178 result.append(path)
180 # Always include common.gypi.
181 AddInclude(os.path.join(script_dir, 'common.gypi'))
183 # Optionally add supplemental .gypi files if present.
184 for supplement in supplemental_files:
185 AddInclude(supplement)
187 return result
190 if __name__ == '__main__':
191 args = sys.argv[1:]
193 use_analyzer = len(args) and args[0] == '--analyzer'
194 if use_analyzer:
195 args.pop(0)
196 os.environ['GYP_GENERATORS'] = 'analyzer'
197 args.append('-Gconfig_path=' + args.pop(0))
198 args.append('-Ganalyzer_output_path=' + args.pop(0))
200 if int(os.environ.get('GYP_CHROMIUM_NO_ACTION', 0)):
201 print 'Skipping gyp_chromium due to GYP_CHROMIUM_NO_ACTION env var.'
202 sys.exit(0)
204 # Use the Psyco JIT if available.
205 if psyco:
206 psyco.profile()
207 print "Enabled Psyco JIT."
209 # Fall back on hermetic python if we happen to get run under cygwin.
210 # TODO(bradnelson): take this out once this issue is fixed:
211 # http://code.google.com/p/gyp/issues/detail?id=177
212 if sys.platform == 'cygwin':
213 import find_depot_tools
214 depot_tools_path = find_depot_tools.add_depot_tools_to_path()
215 python_dir = sorted(glob.glob(os.path.join(depot_tools_path,
216 'python2*_bin')))[-1]
217 env = os.environ.copy()
218 env['PATH'] = python_dir + os.pathsep + env.get('PATH', '')
219 p = subprocess.Popen(
220 [os.path.join(python_dir, 'python.exe')] + sys.argv,
221 env=env, shell=False)
222 p.communicate()
223 sys.exit(p.returncode)
225 # This could give false positives since it doesn't actually do real option
226 # parsing. Oh well.
227 gyp_file_specified = False
228 for arg in args:
229 if arg.endswith('.gyp'):
230 gyp_file_specified = True
231 break
233 gyp_environment.SetEnvironment()
235 # If we didn't get a file, check an env var, and then fall back to
236 # assuming 'all.gyp' from the same directory as the script.
237 if not gyp_file_specified:
238 gyp_file = os.environ.get('CHROMIUM_GYP_FILE')
239 if gyp_file:
240 # Note that CHROMIUM_GYP_FILE values can't have backslashes as
241 # path separators even on Windows due to the use of shlex.split().
242 args.extend(shlex.split(gyp_file))
243 else:
244 args.append(os.path.join(script_dir, 'all.gyp'))
246 # There shouldn't be a circular dependency relationship between .gyp files,
247 # but in Chromium's .gyp files, on non-Mac platforms, circular relationships
248 # currently exist. The check for circular dependencies is currently
249 # bypassed on other platforms, but is left enabled on the Mac, where a
250 # violation of the rule causes Xcode to misbehave badly.
251 # TODO(mark): Find and kill remaining circular dependencies, and remove this
252 # option. http://crbug.com/35878.
253 # TODO(tc): Fix circular dependencies in ChromiumOS then add linux2 to the
254 # list.
255 if sys.platform not in ('darwin',):
256 args.append('--no-circular-check')
258 # We explicitly don't support the make gyp generator (crbug.com/348686). Be
259 # nice and fail here, rather than choking in gyp.
260 if re.search(r'(^|,|\s)make($|,|\s)', os.environ.get('GYP_GENERATORS', '')):
261 print 'Error: make gyp generator not supported (check GYP_GENERATORS).'
262 sys.exit(1)
264 # If CHROMIUM_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check
265 # to enfore syntax checking.
266 syntax_check = os.environ.get('CHROMIUM_GYP_SYNTAX_CHECK')
267 if syntax_check and int(syntax_check):
268 args.append('--check')
270 supplemental_includes = GetSupplementalFiles()
271 gyp_vars_dict = GetGypVars(supplemental_includes)
273 # TODO(dmikurube): Remove these checks and messages after a while.
274 if ('linux_use_tcmalloc' in gyp_vars_dict or
275 'android_use_tcmalloc' in gyp_vars_dict):
276 print '*****************************************************************'
277 print '"linux_use_tcmalloc" and "android_use_tcmalloc" are deprecated!'
278 print '-----------------------------------------------------------------'
279 print 'You specify "linux_use_tcmalloc" or "android_use_tcmalloc" in'
280 print 'your GYP_DEFINES. Please switch them into "use_allocator" now.'
281 print 'See http://crbug.com/345554 for the details.'
282 print '*****************************************************************'
284 # Automatically turn on crosscompile support for platforms that need it.
285 # (The Chrome OS build sets CC_host / CC_target which implicitly enables
286 # this mode.)
287 if all(('ninja' in os.environ.get('GYP_GENERATORS', ''),
288 gyp_vars_dict.get('OS') in ['android', 'ios'],
289 'GYP_CROSSCOMPILE' not in os.environ)):
290 os.environ['GYP_CROSSCOMPILE'] = '1'
291 if gyp_vars_dict.get('OS') == 'android':
292 args.append('--check')
294 args.extend(
295 ['-I' + i for i in additional_include_files(supplemental_includes, args)])
297 args.extend(['-D', 'gyp_output_dir=' + GetOutputDirectory()])
299 if not use_analyzer:
300 print 'Updating projects from gyp files...'
301 sys.stdout.flush()
303 # Off we go...
304 gyp_rc = gyp.main(args)
306 if not use_analyzer:
307 vs2013_runtime_dll_dirs = vs_toolchain.SetEnvironmentAndGetRuntimeDllDirs()
308 if vs2013_runtime_dll_dirs:
309 x64_runtime, x86_runtime = vs2013_runtime_dll_dirs
310 vs_toolchain.CopyVsRuntimeDlls(
311 os.path.join(chrome_src, GetOutputDirectory()),
312 (x86_runtime, x64_runtime))
314 sys.exit(gyp_rc)