gm.py 16.5 KB
Newer Older
1
#!/usr/bin/env python3
jkummerow's avatar
jkummerow committed
2 3 4 5 6 7 8 9 10 11 12
# Copyright 2017 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""\
Convenience wrapper for compiling V8 with gn/ninja and running tests.
Sets up build output directories if they don't exist.
Produces simulator builds for non-Intel target architectures.
Uses Goma by default if it is detected (at output directory setup time).
Expects to be run from the root of a V8 checkout.

Usage:
13
    gm.py [<arch>].[<mode>[-<suffix>]].[<target>] [testname...] [--flag]
jkummerow's avatar
jkummerow committed
14 15

All arguments are optional. Most combinations should work, e.g.:
16
    gm.py ia32.debug x64.release x64.release-my-custom-opts d8
17
    gm.py android_arm.release.check --progress=verbose
jkummerow's avatar
jkummerow committed
18
    gm.py x64 mjsunit/foo cctest/test-bar/*
19 20 21

Flags are passed unchanged to the test runner. They must start with -- and must
not contain spaces.
jkummerow's avatar
jkummerow committed
22 23 24
"""
# See HELP below for additional documentation.

25 26
from __future__ import print_function
import errno
jkummerow's avatar
jkummerow committed
27
import os
Z Nguyen-Huu's avatar
Z Nguyen-Huu committed
28
import platform
29
import re
jkummerow's avatar
jkummerow committed
30 31 32
import subprocess
import sys

33 34 35 36
USE_PTY = "linux" in sys.platform
if USE_PTY:
  import pty

37 38
BUILD_TARGETS_TEST = ["d8", "bigint_shell", "cctest", "inspector-test",
                      "unittests", "wasm_api_tests"]
jkummerow's avatar
jkummerow committed
39 40 41 42
BUILD_TARGETS_ALL = ["all"]

# All arches that this script understands.
ARCHES = ["ia32", "x64", "arm", "arm64", "mipsel", "mips64el", "ppc", "ppc64",
Victor Gomes's avatar
Victor Gomes committed
43 44
          "riscv64", "s390", "s390x", "android_arm", "android_arm64", "loong64",
          "fuchsia_x64", "fuchsia_arm64"]
jkummerow's avatar
jkummerow committed
45 46 47 48 49 50 51
# Arches that get built/run when you don't specify any.
DEFAULT_ARCHES = ["ia32", "x64", "arm", "arm64"]
# Modes that this script understands.
MODES = ["release", "debug", "optdebug"]
# Modes that get built/run when you don't specify any.
DEFAULT_MODES = ["release", "debug"]
# Build targets that can be manually specified.
52
TARGETS = ["d8", "cctest", "unittests", "v8_fuzzers", "wasm_api_tests", "wee8",
53 54
           "mkgrokdump", "generate-bytecode-expectations", "inspector-test",
           "bigint_shell"]
jkummerow's avatar
jkummerow committed
55 56 57 58 59 60
# Build targets that get built when you don't specify any (and specified tests
# don't imply any other targets).
DEFAULT_TARGETS = ["d8"]
# Tests that run-tests.py would run by default that can be run with
# BUILD_TARGETS_TESTS.
DEFAULT_TESTS = ["cctest", "debugger", "intl", "message", "mjsunit",
61
                 "unittests"]
jkummerow's avatar
jkummerow committed
62 63 64
# These can be suffixed to any <arch>.<mode> combo, or used standalone,
# or used as global modifiers (affecting all <arch>.<mode> combos).
ACTIONS = {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    "all": {
        "targets": BUILD_TARGETS_ALL,
        "tests": [],
        "clean": False
    },
    "tests": {
        "targets": BUILD_TARGETS_TEST,
        "tests": [],
        "clean": False
    },
    "check": {
        "targets": BUILD_TARGETS_TEST,
        "tests": DEFAULT_TESTS,
        "clean": False
    },
    "checkall": {
        "targets": BUILD_TARGETS_ALL,
        "tests": ["ALL"],
        "clean": False
    },
    "clean": {
        "targets": [],
        "tests": [],
        "clean": True
    },
jkummerow's avatar
jkummerow committed
90 91 92 93 94
}

HELP = """<arch> can be any of: %(arches)s
<mode> can be any of: %(modes)s
<target> can be any of:
95
 - %(targets)s (build respective binary)
jkummerow's avatar
jkummerow committed
96 97 98 99 100
 - all (build all binaries)
 - tests (build test binaries)
 - check (build test binaries, run most tests)
 - checkall (build all binaries, run more tests)
""" % {"arches": " ".join(ARCHES),
101 102
       "modes": " ".join(MODES),
       "targets": ", ".join(TARGETS)}
jkummerow's avatar
jkummerow committed
103 104

TESTSUITES_TARGETS = {"benchmarks": "d8",
105
              "bigint": "bigint_shell",
jkummerow's avatar
jkummerow committed
106 107 108
              "cctest": "cctest",
              "debugger": "d8",
              "fuzzer": "v8_fuzzers",
109
              "inspector": "inspector-test",
jkummerow's avatar
jkummerow committed
110 111 112 113 114 115
              "intl": "d8",
              "message": "d8",
              "mjsunit": "d8",
              "mozilla": "d8",
              "test262": "d8",
              "unittests": "unittests",
116
              "wasm-api-tests": "wasm_api_tests",
117 118
              "wasm-js": "d8",
              "wasm-spec-tests": "d8",
jkummerow's avatar
jkummerow committed
119 120 121 122
              "webkit": "d8"}

OUTDIR = "out"

123 124 125 126 127 128
def _Which(cmd):
  for path in os.environ["PATH"].split(os.pathsep):
    if os.path.exists(os.path.join(path, cmd)):
      return os.path.join(path, cmd)
  return None

129
def DetectGoma():
130 131
  if os.environ.get("GOMA_DIR"):
    return os.environ.get("GOMA_DIR")
132 133
  if os.environ.get("GOMADIR"):
    return os.environ.get("GOMADIR")
134 135 136 137 138 139 140 141 142
  # There is a copy of goma in depot_tools, but it might not be in use on
  # this machine.
  goma = _Which("goma_ctl")
  if goma is None: return None
  cipd_bin = os.path.join(os.path.dirname(goma), ".cipd_bin")
  if not os.path.exists(cipd_bin): return None
  goma_auth = os.path.expanduser("~/.goma_client_oauth2_config")
  if not os.path.exists(goma_auth): return None
  return cipd_bin
143 144 145

GOMADIR = DetectGoma()
IS_GOMA_MACHINE = GOMADIR is not None
jkummerow's avatar
jkummerow committed
146 147 148 149 150 151 152 153 154 155 156 157

USE_GOMA = "true" if IS_GOMA_MACHINE else "false"

RELEASE_ARGS_TEMPLATE = """\
is_component_build = false
is_debug = false
%s
use_goma = {GOMA}
v8_enable_backtrace = true
v8_enable_disassembler = true
v8_enable_object_print = true
v8_enable_verify_heap = true
158
dcheck_always_on = false
159
""".replace("{GOMA}", USE_GOMA)
jkummerow's avatar
jkummerow committed
160 161 162 163 164 165 166 167

DEBUG_ARGS_TEMPLATE = """\
is_component_build = true
is_debug = true
symbol_level = 2
%s
use_goma = {GOMA}
v8_enable_backtrace = true
168
v8_enable_fast_mksnapshot = true
jkummerow's avatar
jkummerow committed
169 170
v8_enable_slow_dchecks = true
v8_optimized_debug = false
171
""".replace("{GOMA}", USE_GOMA)
jkummerow's avatar
jkummerow committed
172 173 174 175 176 177 178 179

OPTDEBUG_ARGS_TEMPLATE = """\
is_component_build = true
is_debug = true
symbol_level = 1
%s
use_goma = {GOMA}
v8_enable_backtrace = true
180
v8_enable_fast_mksnapshot = true
jkummerow's avatar
jkummerow committed
181 182
v8_enable_verify_heap = true
v8_optimized_debug = true
183
""".replace("{GOMA}", USE_GOMA)
jkummerow's avatar
jkummerow committed
184 185 186 187 188 189 190 191 192 193 194 195

ARGS_TEMPLATES = {
  "release": RELEASE_ARGS_TEMPLATE,
  "debug": DEBUG_ARGS_TEMPLATE,
  "optdebug": OPTDEBUG_ARGS_TEMPLATE
}

def PrintHelpAndExit():
  print(__doc__)
  print(HELP)
  sys.exit(0)

196 197 198 199 200 201 202 203 204 205 206
def PrintCompletionsAndExit():
  for a in ARCHES:
    print("%s" % a)
    for m in MODES:
      print("%s" % m)
      print("%s.%s" % (a, m))
      for t in TARGETS:
        print("%s" % t)
        print("%s.%s.%s" % (a, m, t))
  sys.exit(0)

jkummerow's avatar
jkummerow committed
207 208 209 210
def _Call(cmd, silent=False):
  if not silent: print("# %s" % cmd)
  return subprocess.call(cmd, shell=True)

211 212 213
def _CallWithOutputNoTerminal(cmd):
  return subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)

214 215 216 217
def _CallWithOutput(cmd):
  print("# %s" % cmd)
  # The following trickery is required so that the 'cmd' thinks it's running
  # in a real terminal, while this script gets to intercept its output.
218 219 220
  parent, child = pty.openpty()
  p = subprocess.Popen(cmd, shell=True, stdin=child, stdout=child, stderr=child)
  os.close(child)
221 222 223 224
  output = []
  try:
    while True:
      try:
225
        data = os.read(parent, 512).decode('utf-8')
226 227 228 229 230 231 232 233 234 235
      except OSError as e:
        if e.errno != errno.EIO: raise
        break # EIO means EOF on some systems
      else:
        if not data: # EOF
          break
        print(data, end="")
        sys.stdout.flush()
        output.append(data)
  finally:
236
    os.close(parent)
237 238 239
    p.wait()
  return p.returncode, "".join(output)

jkummerow's avatar
jkummerow committed
240 241 242 243 244
def _Write(filename, content):
  print("# echo > %s << EOF\n%sEOF" % (filename, content))
  with open(filename, "w") as f:
    f.write(content)

245
def _Notify(summary, body):
246 247
  if (_Which('notify-send') is not None and
      os.environ.get("DISPLAY") is not None):
248 249 250 251
    _Call("notify-send '{}' '{}'".format(summary, body), silent=True)
  else:
    print("{} - {}".format(summary, body))

252
def _GetMachine():
Z Nguyen-Huu's avatar
Z Nguyen-Huu committed
253
  return platform.machine()
254

jkummerow's avatar
jkummerow committed
255 256 257 258
def GetPath(arch, mode):
  subdir = "%s.%s" % (arch, mode)
  return os.path.join(OUTDIR, subdir)

259 260 261 262 263 264 265 266 267 268
def PrepareMksnapshotCmdline(orig_cmdline, path):
  result = "gdb --args %s/mksnapshot " % path
  for w in orig_cmdline.split(" "):
    if w.startswith("gen/") or w.startswith("snapshot_blob"):
      result += ("%(path)s%(sep)s%(arg)s " %
                 {"path": path, "sep": os.sep, "arg": w})
    else:
      result += "%s " % w
  return result

jkummerow's avatar
jkummerow committed
269
class Config(object):
270 271 272 273 274 275 276
  def __init__(self,
               arch,
               mode,
               targets,
               tests=[],
               clean=False,
               testrunner_args=[]):
jkummerow's avatar
jkummerow committed
277 278 279 280
    self.arch = arch
    self.mode = mode
    self.targets = set(targets)
    self.tests = set(tests)
281
    self.testrunner_args = testrunner_args
282
    self.clean = clean
jkummerow's avatar
jkummerow committed
283

284
  def Extend(self, targets, tests=[], clean=False):
jkummerow's avatar
jkummerow committed
285 286
    self.targets.update(targets)
    self.tests.update(tests)
287
    self.clean |= clean
jkummerow's avatar
jkummerow committed
288 289 290

  def GetTargetCpu(self):
    cpu = "x86"
291 292
    if self.arch == "android_arm":
      cpu = "arm"
Victor Gomes's avatar
Victor Gomes committed
293
    elif self.arch == "android_arm64" or self.arch == "fuchsia_arm64":
294
      cpu = "arm64"
295
    elif self.arch == "arm64" and _GetMachine() in ("aarch64", "arm64"):
296 297
      # arm64 build host:
      cpu = "arm64"
298
    elif self.arch == "arm" and _GetMachine() in ("aarch64", "arm64"):
299
      cpu = "arm"
300 301 302 303
    elif self.arch == "loong64" and _GetMachine() == "loongarch64":
      cpu = "loong64"
    elif self.arch == "mips64el" and _GetMachine() == "mips64":
      cpu = "mips64el"
304 305
    elif "64" in self.arch or self.arch == "s390x":
      # Native x64 or simulator build.
jkummerow's avatar
jkummerow committed
306
      cpu = "x64"
307
    return ["target_cpu = \"%s\"" % cpu]
jkummerow's avatar
jkummerow committed
308 309

  def GetV8TargetCpu(self):
310 311
    if self.arch == "android_arm":
      v8_cpu = "arm"
Victor Gomes's avatar
Victor Gomes committed
312
    elif self.arch == "android_arm64" or self.arch == "fuchsia_arm64":
313 314
      v8_cpu = "arm64"
    elif self.arch in ("arm", "arm64", "mipsel", "mips64el", "ppc", "ppc64",
315
                       "riscv64", "s390", "s390x", "loong64"):
316 317 318 319
      v8_cpu = self.arch
    else:
      return []
    return ["v8_target_cpu = \"%s\"" % v8_cpu]
jkummerow's avatar
jkummerow committed
320

321 322
  def GetTargetOS(self):
    if self.arch in ("android_arm", "android_arm64"):
323
      return ["target_os = \"android\""]
Victor Gomes's avatar
Victor Gomes committed
324 325
    elif self.arch in ("fuchsia_x64", "fuchsia_arm64"):
      return ["target_os = \"fuchsia\""]
326 327 328
    return []

  def GetSpecialCompiler(self):
329 330 331
    if _GetMachine() in ("aarch64", "mips64", "loongarch64"):
      # We have no prebuilt Clang for arm64, mips64 or loongarch64 on Linux,
      # so use the system Clang instead.
332 333
      return ["clang_base_path = \"/usr\"", "clang_use_chrome_plugins = false"]
    return []
334

jkummerow's avatar
jkummerow committed
335
  def GetGnArgs(self):
336 337 338
    # Use only substring before first '-' as the actual mode
    mode = re.match("([^-]+)", self.mode).group(1)
    template = ARGS_TEMPLATES[mode]
339
    arch_specific = (self.GetTargetCpu() + self.GetV8TargetCpu() +
340 341
                     self.GetTargetOS() + self.GetSpecialCompiler())
    return template % "\n".join(arch_specific)
jkummerow's avatar
jkummerow committed
342 343 344 345

  def Build(self):
    path = GetPath(self.arch, self.mode)
    args_gn = os.path.join(path, "args.gn")
346
    build_ninja = os.path.join(path, "build.ninja")
jkummerow's avatar
jkummerow committed
347 348 349 350 351
    if not os.path.exists(path):
      print("# mkdir -p %s" % path)
      os.makedirs(path)
    if not os.path.exists(args_gn):
      _Write(args_gn, self.GetGnArgs())
352
    if not os.path.exists(build_ninja):
jkummerow's avatar
jkummerow committed
353 354
      code = _Call("gn gen %s" % path)
      if code != 0: return code
355 356 357
    elif self.clean:
      code = _Call("gn clean %s" % path)
      if code != 0: return code
jkummerow's avatar
jkummerow committed
358
    targets = " ".join(self.targets)
359 360
    # The implementation of mksnapshot failure detection relies on
    # the "pty" module and GDB presence, so skip it on non-Linux.
361
    if not USE_PTY:
362
      return _Call("autoninja -C %s %s" % (path, targets))
363

364 365
    return_code, output = _CallWithOutput("autoninja -C %s %s" %
                                          (path, targets))
366
    if return_code != 0 and "FAILED:" in output and "snapshot_blob" in output:
367 368 369
      csa_trap = re.compile("Specify option( --csa-trap-on-node=[^ ]*)")
      match = csa_trap.search(output)
      extra_opt = match.group(1) if match else ""
370
      cmdline = re.compile("python3 ../../tools/run.py ./mksnapshot (.*)")
371 372
      orig_cmdline = cmdline.search(output).group(1).strip()
      cmdline = PrepareMksnapshotCmdline(orig_cmdline, path) + extra_opt
373 374
      _Notify("V8 build requires your attention",
              "Detected mksnapshot failure, re-running in GDB...")
375
      _Call(cmdline)
376
    return return_code
jkummerow's avatar
jkummerow committed
377 378

  def RunTests(self):
379 380 381 382 383
    # Special handling for "mkgrokdump": if it was built, run it.
    if (self.arch == "x64" and self.mode == "release" and
        "mkgrokdump" in self.targets):
      _Call("%s/mkgrokdump > tools/v8heapconst.py" %
            GetPath(self.arch, self.mode))
jkummerow's avatar
jkummerow committed
384 385 386 387 388
    if not self.tests: return 0
    if "ALL" in self.tests:
      tests = ""
    else:
      tests = " ".join(self.tests)
389 390
    return _Call('"%s" ' % sys.executable +
                 os.path.join("tools", "run-tests.py") +
391 392 393
                 " --outdir=%s %s %s" % (
                     GetPath(self.arch, self.mode), tests,
                     " ".join(self.testrunner_args)))
jkummerow's avatar
jkummerow committed
394 395 396 397 398 399 400 401 402 403 404 405

def GetTestBinary(argstring):
  for suite in TESTSUITES_TARGETS:
    if argstring.startswith(suite): return TESTSUITES_TARGETS[suite]
  return None

class ArgumentParser(object):
  def __init__(self):
    self.global_targets = set()
    self.global_tests = set()
    self.global_actions = set()
    self.configs = {}
406
    self.testrunner_args = []
jkummerow's avatar
jkummerow committed
407

408
  def PopulateConfigs(self, arches, modes, targets, tests, clean):
jkummerow's avatar
jkummerow committed
409 410 411 412
    for a in arches:
      for m in modes:
        path = GetPath(a, m)
        if path not in self.configs:
413
          self.configs[path] = Config(a, m, targets, tests, clean,
414
                  self.testrunner_args)
jkummerow's avatar
jkummerow committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        else:
          self.configs[path].Extend(targets, tests)

  def ProcessGlobalActions(self):
    have_configs = len(self.configs) > 0
    for action in self.global_actions:
      impact = ACTIONS[action]
      if (have_configs):
        for c in self.configs:
          self.configs[c].Extend(**impact)
      else:
        self.PopulateConfigs(DEFAULT_ARCHES, DEFAULT_MODES, **impact)

  def ParseArg(self, argstring):
    if argstring in ("-h", "--help", "help"):
      PrintHelpAndExit()
431 432
    if argstring == "--print-completions":
      PrintCompletionsAndExit()
jkummerow's avatar
jkummerow committed
433 434 435 436 437
    arches = []
    modes = []
    targets = []
    actions = []
    tests = []
438
    clean = False
439 440
    # Special handling for "mkgrokdump": build it for x64.release.
    if argstring == "mkgrokdump":
441
      self.PopulateConfigs(["x64"], ["release"], ["mkgrokdump"], [], False)
442
      return
443 444 445
    # Specifying a single unit test looks like "unittests/Foo.Bar", test262
    # tests have names like "S15.4.4.7_A4_T1", don't split these.
    if argstring.startswith("unittests/") or argstring.startswith("test262/"):
446
      words = [argstring]
447 448 449 450
    elif argstring.startswith("--"):
      # Pass all other flags to test runner.
      self.testrunner_args.append(argstring)
      return
451
    else:
452
      # Assume it's a word like "x64.release" -> split at the dot.
453
      words = argstring.split('.')
jkummerow's avatar
jkummerow committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    if len(words) == 1:
      word = words[0]
      if word in ACTIONS:
        self.global_actions.add(word)
        return
      if word in TARGETS:
        self.global_targets.add(word)
        return
      maybe_target = GetTestBinary(word)
      if maybe_target is not None:
        self.global_tests.add(word)
        self.global_targets.add(maybe_target)
        return
    for word in words:
      if word in ARCHES:
        arches.append(word)
      elif word in MODES:
        modes.append(word)
      elif word in TARGETS:
        targets.append(word)
      elif word in ACTIONS:
        actions.append(word)
476 477
      elif any(map(lambda x: word.startswith(x + "-"), MODES)):
        modes.append(word)
jkummerow's avatar
jkummerow committed
478 479 480 481 482 483 484 485
      else:
        print("Didn't understand: %s" % word)
        sys.exit(1)
    # Process actions.
    for action in actions:
      impact = ACTIONS[action]
      targets += impact["targets"]
      tests += impact["tests"]
486
      clean |= impact["clean"]
jkummerow's avatar
jkummerow committed
487 488 489 490 491
    # Fill in defaults for things that weren't specified.
    arches = arches or DEFAULT_ARCHES
    modes = modes or DEFAULT_MODES
    targets = targets or DEFAULT_TARGETS
    # Produce configs.
492
    self.PopulateConfigs(arches, modes, targets, tests, clean)
jkummerow's avatar
jkummerow committed
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

  def ParseArguments(self, argv):
    if len(argv) == 0:
      PrintHelpAndExit()
    for argstring in argv:
      self.ParseArg(argstring)
    self.ProcessGlobalActions()
    for c in self.configs:
      self.configs[c].Extend(self.global_targets, self.global_tests)
    return self.configs

def Main(argv):
  parser = ArgumentParser()
  configs = parser.ParseArguments(argv[1:])
  return_code = 0
508
  # If we have Goma but it is not running, start it.
509
  if (IS_GOMA_MACHINE and
510
      _Call("pgrep -x compiler_proxy > /dev/null", silent=True) != 0):
511
    _Call("%s/goma_ctl.py ensure_start" % GOMADIR)
jkummerow's avatar
jkummerow committed
512 513
  for c in configs:
    return_code += configs[c].Build()
514 515 516
  if return_code == 0:
    for c in configs:
      return_code += configs[c].RunTests()
jkummerow's avatar
jkummerow committed
517
  if return_code == 0:
518
    _Notify('Done!', 'V8 compilation finished successfully.')
jkummerow's avatar
jkummerow committed
519
  else:
520
    _Notify('Error!', 'V8 compilation finished with errors.')
jkummerow's avatar
jkummerow committed
521 522 523 524
  return return_code

if __name__ == "__main__":
  sys.exit(Main(sys.argv))