blob: 9bf0d1b911a22ca065834e94bf7f56907fb0124c [file] [log] [blame]
Takuto Ikutacccca952023-12-01 02:47:55 +00001#!/usr/bin/env vpython3
Bruce Dawsonebebd952017-05-31 14:24:38 -07002# Copyright (c) 2017 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.
Bruce Dawsonebebd952017-05-31 14:24:38 -07005"""
6This script (intended to be invoked by autoninja or autoninja.bat) detects
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +00007whether a build is accelerated using a service like goma. If so, it runs with a
8large -j value, and otherwise it chooses a small one. This auto-adjustment
9makes using remote build acceleration simpler and safer, and avoids errors that
10can cause slow goma builds or swap-storms on unaccelerated builds.
Bruce Dawson30c1cba2023-09-15 18:20:32 +000011
12autoninja tries to detect relevant build settings such as use_remoteexec, and it
13does handle import statements, but it can't handle conditional setting of build
14settings.
Bruce Dawsonebebd952017-05-31 14:24:38 -070015"""
16
Takuto Ikutacccca952023-12-01 02:47:55 +000017import json
Bruce Dawsone952fae2021-02-27 23:33:37 +000018import multiprocessing
Bruce Dawsonebebd952017-05-31 14:24:38 -070019import os
Takuto Ikuta6a1494e2022-05-06 01:22:16 +000020import platform
Bruce Dawsonebebd952017-05-31 14:24:38 -070021import re
Philipp Wollermann0b943402023-10-12 07:13:30 +000022import shlex
Takuto Ikutacccca952023-12-01 02:47:55 +000023import shutil
Bruce Dawsone952fae2021-02-27 23:33:37 +000024import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070025import sys
Takuto Ikutacccca952023-12-01 02:47:55 +000026import warnings
27
28import google.auth
29from google.auth.transport.requests import AuthorizedSession
Bruce Dawsonebebd952017-05-31 14:24:38 -070030
Philipp Wollermann0b943402023-10-12 07:13:30 +000031import autosiso
32import ninja
33import ninja_reclient
34import siso
35
Takuto Ikutadf3e5772023-11-16 07:14:49 +000036if sys.platform in ["darwin", "linux"]:
Mike Frysinger124bb8e2023-09-06 05:48:55 +000037 import resource
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +000038
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000039SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
40
Philipp Wollermann0b943402023-10-12 07:13:30 +000041# See [1] and [2] for the painful details of this next section, which handles
42# escaping command lines so that they can be copied and pasted into a cmd
43# window.
44#
45# pylint: disable=line-too-long
46# [1] https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way # noqa
47# [2] https://web.archive.org/web/20150815000000*/https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/set.mspx # noqa
Takuto Ikutadf3e5772023-11-16 07:14:49 +000048_UNSAFE_FOR_CMD = set("^<>&|()%")
Philipp Wollermann0b943402023-10-12 07:13:30 +000049_ALL_META_CHARS = _UNSAFE_FOR_CMD.union(set('"'))
50
51
Takuto Ikutacccca952023-12-01 02:47:55 +000052def _adc_account():
53 """Returns account used to authenticate with GCP application default credentials."""
54
55 try:
56 # Suppress warnings from google.auth.default.
57 # https://github.com/googleapis/google-auth-library-python/issues/271
58 warnings.filterwarnings(
59 "ignore",
60 "Your application has authenticated using end user credentials from"
61 " Google Cloud SDK without a quota project.",
62 )
63 credentials, _ = google.auth.default(
64 scopes=["https://www.googleapis.com/auth/userinfo.email"])
65 except google.auth.exceptions.DefaultCredentialsError:
66 # Application Default Crendetials is not configured.
67 return None
68 finally:
69 warnings.resetwarnings()
70
71 with AuthorizedSession(credentials) as session:
72 try:
73 response = session.get(
74 "https://www.googleapis.com/oauth2/v1/userinfo")
75 except Exception:
76 # Ignore exception.
77 return None
78
79 return response.json().get("email")
80
81
82def _gcloud_auth_account():
83 """Returns active account authenticated with `gcloud auth login`."""
84 if shutil.which("gcloud") is None:
85 return None
86
87 accounts = json.loads(
88 subprocess.check_output("gcloud auth list --format=json",
89 shell=True,
90 text=True))
91 for account in accounts:
92 if account["status"] == "ACTIVE":
93 return account["account"]
94 return None
95
96
97def _is_google_corp_machine():
98 """This assumes that corp machine has gcert binary in known location."""
99 return shutil.which("gcert") is not None
100
101
102def _is_google_corp_machine_using_external_account():
103 if not _is_google_corp_machine():
104 return False
105
106 account = _adc_account()
107 if account and not account.endswith("@google.com"):
108 return True
109
110 account = _gcloud_auth_account()
111 if not account:
112 return False
113 # Handle service account and google account as internal account.
114 return not (account.endswith("@google.com")
115 or account.endswith("gserviceaccount.com"))
116
117
Philipp Wollermann0b943402023-10-12 07:13:30 +0000118def _quote_for_cmd(arg):
119 # First, escape the arg so that CommandLineToArgvW will parse it properly.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000120 if arg == "" or " " in arg or '"' in arg:
Philipp Wollermann0b943402023-10-12 07:13:30 +0000121 quote_re = re.compile(r'(\\*)"')
122 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
123
124 # Then check to see if the arg contains any metacharacters other than
125 # double quotes; if it does, quote everything (including the double
126 # quotes) for safety.
127 if any(a in _UNSAFE_FOR_CMD for a in arg):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000128 arg = "".join("^" + a if a in _ALL_META_CHARS else a for a in arg)
Philipp Wollermann0b943402023-10-12 07:13:30 +0000129 return arg
130
131
132def _print_cmd(cmd):
133 shell_quoter = shlex.quote
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000134 if sys.platform.startswith("win"):
Philipp Wollermann0b943402023-10-12 07:13:30 +0000135 shell_quoter = _quote_for_cmd
136 print(*[shell_quoter(arg) for arg in cmd], file=sys.stderr)
137
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +0000138
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000139def _gn_lines(output_dir, path):
140 """
141 Generator function that returns args.gn lines one at a time, following
142 import directives as needed.
143 """
144 import_re = re.compile(r'\s*import\("(.*)"\)')
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000145 with open(path, encoding="utf-8") as f:
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000146 for line in f:
147 match = import_re.match(line)
148 if match:
Samuel Attard8a259982023-09-18 17:12:55 +0000149 raw_import_path = match.groups()[0]
150 if raw_import_path[:2] == "//":
151 import_path = os.path.normpath(
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000152 os.path.join(output_dir, "..", "..",
Samuel Attard8a259982023-09-18 17:12:55 +0000153 raw_import_path[2:]))
154 else:
155 import_path = os.path.normpath(
156 os.path.join(os.path.dirname(path), raw_import_path))
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000157 for import_line in _gn_lines(output_dir, import_path):
158 yield import_line
159 else:
160 yield line
161
162
Takuto Ikuta381db682022-04-27 23:54:02 +0000163def main(args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000164 # The -t tools are incompatible with -j
165 t_specified = False
166 j_specified = False
167 offline = False
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000168 output_dir = "."
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000169 input_args = args
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000170 summarize_build = os.environ.get("NINJA_SUMMARIZE_BUILD") == "1"
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000171 # On Windows the autoninja.bat script passes along the arguments enclosed in
172 # double quotes. This prevents multiple levels of parsing of the special '^'
173 # characters needed when compiling a single file but means that this script
174 # gets called with a single argument containing all of the actual arguments,
175 # separated by spaces. When this case is detected we need to do argument
176 # splitting ourselves. This means that arguments containing actual spaces
177 # are not supported by autoninja, but that is not a real limitation.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000178 if (sys.platform.startswith("win") and len(args) == 2
179 and input_args[1].count(" ") > 0):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000180 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +0000181
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000182 # Ninja uses getopt_long, which allow to intermix non-option arguments.
183 # To leave non supported parameters untouched, we do not use getopt.
184 for index, arg in enumerate(input_args[1:]):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000185 if arg.startswith("-j"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000186 j_specified = True
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000187 if arg.startswith("-t"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000188 t_specified = True
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000189 if arg == "-C":
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000190 # + 1 to get the next argument and +1 because we trimmed off
191 # input_args[0]
192 output_dir = input_args[index + 2]
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000193 elif arg.startswith("-C"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000194 # Support -Cout/Default
195 output_dir = arg[2:]
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000196 elif arg in ("-o", "--offline"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000197 offline = True
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000198 elif arg == "-h":
199 print(
200 "autoninja: Use -o/--offline to temporary disable goma.",
201 file=sys.stderr,
202 )
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000203 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +0000204
Takuto Ikuta381db682022-04-27 23:54:02 +0000205 use_goma = False
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000206 use_remoteexec = False
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000207 use_siso = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000208
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000209 # Attempt to auto-detect remote build acceleration. We support gn-based
210 # builds, where we look for args.gn in the build tree, and cmake-based
211 # builds where we look for rules.ninja.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000212 if os.path.exists(os.path.join(output_dir, "args.gn")):
213 for line in _gn_lines(output_dir, os.path.join(output_dir, "args.gn")):
Takuto Ikuta5cbc5212023-11-16 02:38:31 +0000214 # use_goma, or use_remoteexec will activate build
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000215 # acceleration.
216 #
217 # This test can match multi-argument lines. Examples of this
218 # are: is_debug=false use_goma=true is_official_build=false
219 # use_goma=false# use_goma=true This comment is ignored
220 #
221 # Anything after a comment is not consider a valid argument.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000222 line_without_comment = line.split("#")[0]
223 if re.search(r"(^|\s)(use_goma)\s*=\s*true($|\s)",
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000224 line_without_comment):
225 use_goma = True
226 continue
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000227 if re.search(
228 r"(^|\s)(use_remoteexec)\s*=\s*true($|\s)",
229 line_without_comment,
230 ):
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000231 use_remoteexec = True
232 continue
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000233 if re.search(r"(^|\s)(use_siso)\s*=\s*true($|\s)",
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000234 line_without_comment):
235 use_siso = True
236 continue
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000237
Takuto Ikutacccca952023-12-01 02:47:55 +0000238 if use_remoteexec:
239 if _is_google_corp_machine_using_external_account():
240 print(
241 "You can't use a non-@google.com account (%s and/or %s) on"
242 " a corp machine.\n"
243 "Please login via `gcloud auth login --update-adc` with"
244 " your @google.com account instead.\n" %
245 (_adc_account(), _gcloud_auth_account()),
246 file=sys.stderr,
247 )
248 return 1
249
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000250 siso_marker = os.path.join(output_dir, ".siso_deps")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000251 if use_siso:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000252 # autosiso generates a .ninja_log file so the mere existence of a
253 # .ninja_log file doesn't imply that a ninja build was done. However
254 # if there is a .ninja_log but no .siso_deps then that implies a
255 # ninja build.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000256 ninja_marker = os.path.join(output_dir, ".ninja_log")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000257 if os.path.exists(ninja_marker) and not os.path.exists(siso_marker):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000258 print(
259 "Run gn clean before switching from ninja to siso in %s" %
260 output_dir,
261 file=sys.stderr,
262 )
Philipp Wollermann0b943402023-10-12 07:13:30 +0000263 return 1
Fumitoshi Ukai406be822023-10-18 04:18:24 +0000264 if use_goma:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000265 print("Siso does not support Goma.", file=sys.stderr)
266 print(
267 "Do not use use_siso=true and use_goma=true",
268 file=sys.stderr,
269 )
Fumitoshi Ukai406be822023-10-18 04:18:24 +0000270 return 1
Philipp Wollermann0b943402023-10-12 07:13:30 +0000271 if use_remoteexec:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000272 return autosiso.main(["autosiso"] + input_args[1:])
273 return siso.main(["siso", "ninja", "--offline"] + input_args[1:])
Michael Savigny20eda952021-01-20 01:16:27 +0000274
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000275 if os.path.exists(siso_marker):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000276 print(
277 "Run gn clean before switching from siso to ninja in %s" %
278 output_dir,
279 file=sys.stderr,
280 )
Philipp Wollermann0b943402023-10-12 07:13:30 +0000281 return 1
Ben Segall467991e2023-08-09 19:02:09 +0000282
Takuto Ikuta381db682022-04-27 23:54:02 +0000283 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000284 for relative_path in [
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000285 "", # GN keeps them in the root of output_dir
286 "CMakeFiles",
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000287 ]:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000288 path = os.path.join(output_dir, relative_path, "rules.ninja")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000289 if os.path.exists(path):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000290 with open(path, encoding="utf-8") as file_handle:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000291 for line in file_handle:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000292 if re.match(r"^\s*command\s*=\s*\S+gomacc", line):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000293 use_goma = True
294 break
Takuto Ikuta381db682022-04-27 23:54:02 +0000295
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000296 # Strip -o/--offline so ninja doesn't see them.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000297 input_args = [arg for arg in input_args if arg not in ("-o", "--offline")]
Takuto Ikuta381db682022-04-27 23:54:02 +0000298
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000299 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
300 # (case-insensitive) then gomacc will use the local compiler instead of
301 # doing a goma compile. This is convenient if you want to briefly disable
302 # goma. It avoids having to rebuild the world when transitioning between
303 # goma/non-goma builds. However, it is not as fast as doing a "normal"
304 # non-goma build because an extra process is created for each compile step.
305 # Checking this environment variable ensures that autoninja uses an
306 # appropriate -j value in this situation.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000307 goma_disabled_env = os.environ.get("GOMA_DISABLED", "0").lower()
308 if offline or goma_disabled_env in ["true", "t", "yes", "y", "1"]:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000309 use_goma = False
Takuto Ikuta381db682022-04-27 23:54:02 +0000310
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000311 if use_goma:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000312 gomacc_file = ("gomacc.exe"
313 if sys.platform.startswith("win") else "gomacc")
314 goma_dir = os.environ.get("GOMA_DIR",
315 os.path.join(SCRIPT_DIR, ".cipd_bin"))
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000316 gomacc_path = os.path.join(goma_dir, gomacc_file)
317 # Don't invoke gomacc if it doesn't exist.
318 if os.path.exists(gomacc_path):
319 # Check to make sure that goma is running. If not, don't start the
320 # build.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000321 status = subprocess.call(
322 [gomacc_path, "port"],
323 stdout=subprocess.PIPE,
324 stderr=subprocess.PIPE,
325 shell=False,
326 )
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000327 if status == 1:
328 print(
329 'Goma is not running. Use "goma_ctl ensure_start" to start '
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000330 "it.",
331 file=sys.stderr,
332 )
333 if sys.platform.startswith("win"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000334 # Set an exit code of 1 in the batch file.
335 print('cmd "/c exit 1"')
336 else:
337 # Set an exit code of 1 by executing 'false' in the bash
338 # script.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000339 print("false")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000340 sys.exit(1)
341
342 # A large build (with or without goma) tends to hog all system resources.
Philipp Wollermann0b943402023-10-12 07:13:30 +0000343 # Depending on the operating system, we might have mechanisms available
344 # to run at a lower priority, which improves this situation.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000345 if os.environ.get("NINJA_BUILD_IN_BACKGROUND") == "1":
346 if sys.platform in ["darwin", "linux"]:
Philipp Wollermann0b943402023-10-12 07:13:30 +0000347 # nice-level 10 is usually considered a good default for background
348 # tasks. The niceness is inherited by child processes, so we can
349 # just set it here for us and it'll apply to the build tool we
350 # spawn later.
351 os.nice(10)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000352
Philipp Wollermann0b943402023-10-12 07:13:30 +0000353 # Tell goma or reclient to do local compiles.
354 if offline:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000355 os.environ["RBE_remote_disabled"] = "1"
356 os.environ["GOMA_DISABLED"] = "1"
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000357
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000358 # On macOS and most Linux distributions, the default limit of open file
359 # descriptors is too low (256 and 1024, respectively).
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000360 # This causes a large j value to result in 'Too many open files' errors.
361 # Check whether the limit can be raised to a large enough value. If yes,
362 # use `ulimit -n .... &&` as a prefix to increase the limit when running
363 # ninja.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000364 if sys.platform in ["darwin", "linux"]:
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000365 # Increase the number of allowed open file descriptors to the maximum.
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000366 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000367 if fileno_limit < hard_limit:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000368 try:
369 resource.setrlimit(resource.RLIMIT_NOFILE,
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000370 (hard_limit, hard_limit))
Philipp Wollermann0b943402023-10-12 07:13:30 +0000371 except Exception:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000372 pass
373 fileno_limit, hard_limit = resource.getrlimit(
374 resource.RLIMIT_NOFILE)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000375
376 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
377 # PATH.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000378 ninja_path = os.path.join(SCRIPT_DIR, "ninja.py")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000379 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
380 # starting and stopping reproxy.
381 if use_remoteexec:
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000382 ninja_path = os.path.join(SCRIPT_DIR, "ninja_reclient.py")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000383
Philipp Wollermann0b943402023-10-12 07:13:30 +0000384 args = [sys.executable, ninja_path] + input_args[1:]
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000385
386 num_cores = multiprocessing.cpu_count()
387 if not j_specified and not t_specified:
Takuto Ikuta5cbc5212023-11-16 02:38:31 +0000388 if not offline and (use_goma or use_remoteexec):
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000389 args.append("-j")
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000390 default_core_multiplier = 80
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000391 if platform.machine() in ("x86_64", "AMD64"):
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000392 # Assume simultaneous multithreading and therefore half as many
393 # cores as logical processors.
394 num_cores //= 2
395
396 core_multiplier = int(
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000397 os.environ.get("NINJA_CORE_MULTIPLIER",
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000398 default_core_multiplier))
399 j_value = num_cores * core_multiplier
400
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000401 core_limit = int(os.environ.get("NINJA_CORE_LIMIT", j_value))
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000402 j_value = min(j_value, core_limit)
403
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000404 # On Windows, a -j higher than 1000 doesn't improve build times.
Henrique Ferreiro7eb4e482023-09-20 20:25:20 +0000405 # On macOS, ninja is limited to at most FD_SETSIZE (1024) open file
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000406 # descriptors.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000407 if sys.platform in ["darwin", "win32"]:
Henrique Ferreiro7eb4e482023-09-20 20:25:20 +0000408 j_value = min(j_value, 1000)
409
410 # Use a j value that reliably works with the open file descriptors
411 # limit.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000412 if sys.platform in ["darwin", "linux"]:
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000413 j_value = min(j_value, int(fileno_limit * 0.8))
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000414
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000415 args.append("%d" % j_value)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000416 else:
417 j_value = num_cores
418 # Ninja defaults to |num_cores + 2|
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000419 j_value += int(os.environ.get("NINJA_CORE_ADDITION", "2"))
420 args.append("-j")
421 args.append("%d" % j_value)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000422
Philipp Wollermann0b943402023-10-12 07:13:30 +0000423 if summarize_build:
424 # Enable statistics collection in Ninja.
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000425 args += ["-d", "stats"]
Philipp Wollermann0b943402023-10-12 07:13:30 +0000426 # Print the command-line to reassure the user that the right settings
427 # are being used.
428 _print_cmd(args)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000429
Philipp Wollermann0b943402023-10-12 07:13:30 +0000430 if use_remoteexec:
431 return ninja_reclient.main(args[1:])
432 return ninja.main(args[1:])
Takuto Ikuta381db682022-04-27 23:54:02 +0000433
434
Takuto Ikutadf3e5772023-11-16 07:14:49 +0000435if __name__ == "__main__":
Philipp Wollermann0b943402023-10-12 07:13:30 +0000436 try:
437 sys.exit(main(sys.argv))
438 except KeyboardInterrupt:
439 sys.exit(1)