run-tests.py 33.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials provided
#       with the distribution.
#     * Neither the name of Google Inc. nor the names of its
#       contributors may be used to endorse or promote products derived
#       from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


31
from collections import OrderedDict
32
import itertools
33
import json
34 35 36
import multiprocessing
import optparse
import os
37
from os.path import getmtime, isdir, join
38
import platform
39
import random
40
import shlex
41 42 43 44 45 46 47
import subprocess
import sys
import time

from testrunner.local import execution
from testrunner.local import progress
from testrunner.local import testsuite
48
from testrunner.local.variants import ALL_VARIANTS
49 50 51 52 53 54
from testrunner.local import utils
from testrunner.local import verbose
from testrunner.network import network_execution
from testrunner.objects import context


55 56 57
# Base dir of the v8 checkout to be used as cwd.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

58 59
DEFAULT_OUT_GN = "out.gn"

60
ARCH_GUESS = utils.DefaultArch()
61 62 63 64 65

# Map of test name synonyms to lists of test suites. Should be ordered by
# expected runtimes (suites with slow test cases first). These groups are
# invoked in seperate steps on the bots.
TEST_MAP = {
66
  # This needs to stay in sync with test/bot_default.isolate.
67
  "bot_default": [
68
    "debugger",
69 70
    "mjsunit",
    "cctest",
71
    "inspector",
72
    "webkit",
73
    "fuzzer",
74 75 76 77 78
    "message",
    "preparser",
    "intl",
    "unittests",
  ],
79
  # This needs to stay in sync with test/default.isolate.
80
  "default": [
81
    "debugger",
82 83
    "mjsunit",
    "cctest",
84
    "inspector",
85
    "fuzzer",
86 87
    "message",
    "preparser",
88
    "intl",
89
    "unittests",
90
  ],
91
  # This needs to stay in sync with test/optimize_for_size.isolate.
92
  "optimize_for_size": [
93
    "debugger",
94 95
    "mjsunit",
    "cctest",
96
    "inspector",
97
    "webkit",
98
    "intl",
99 100
  ],
  "unittests": [
101
    "unittests",
102 103 104
  ],
}

105 106
TIMEOUT_DEFAULT = 60

107 108
# Variants ordered by expected runtime (slowest first).
VARIANTS = ["ignition_staging", "default", "turbofan"]
109

110
MORE_VARIANTS = [
111
  "stress",
112
  "turbofan_opt",
113
  "ignition",
114
  "asm_wasm",
115
  "wasm_traps",
116 117
]

118
EXHAUSTIVE_VARIANTS = MORE_VARIANTS + VARIANTS
119 120 121 122 123 124 125

VARIANT_ALIASES = {
  # The default for developer workstations.
  "dev": VARIANTS,
  # Additional variants, run on all bots.
  "more": MORE_VARIANTS,
  # Additional variants, run on a subset of bots.
126
  "extra": ["nocrankshaft"],
127 128
}

129 130
DEBUG_FLAGS = ["--nohard-abort", "--nodead-code-elimination",
               "--nofold-constants", "--enable-slow-asserts",
131
               "--verify-heap"]
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
RELEASE_FLAGS = ["--nohard-abort", "--nodead-code-elimination",
                 "--nofold-constants"]

MODES = {
  "debug": {
    "flags": DEBUG_FLAGS,
    "timeout_scalefactor": 4,
    "status_mode": "debug",
    "execution_mode": "debug",
    "output_folder": "debug",
  },
  "optdebug": {
    "flags": DEBUG_FLAGS,
    "timeout_scalefactor": 4,
    "status_mode": "debug",
    "execution_mode": "debug",
    "output_folder": "optdebug",
  },
  "release": {
    "flags": RELEASE_FLAGS,
    "timeout_scalefactor": 1,
    "status_mode": "release",
    "execution_mode": "release",
    "output_folder": "release",
  },
157 158 159
  # Normal trybot release configuration. There, dchecks are always on which
  # implies debug is set. Hence, the status file needs to assume debug-like
  # behavior/timeouts.
160
  "tryrelease": {
161 162 163 164 165 166 167 168
    "flags": RELEASE_FLAGS,
    "timeout_scalefactor": 1,
    "status_mode": "debug",
    "execution_mode": "release",
    "output_folder": "release",
  },
  # This mode requires v8 to be compiled with dchecks and slow dchecks.
  "slowrelease": {
169 170 171 172 173 174 175
    "flags": RELEASE_FLAGS + ["--enable-slow-asserts"],
    "timeout_scalefactor": 2,
    "status_mode": "debug",
    "execution_mode": "release",
    "output_folder": "release",
  },
}
176

177 178 179 180 181
GC_STRESS_FLAGS = ["--gc-interval=500", "--stress-compaction",
                   "--concurrent-recompilation-queue-length=64",
                   "--concurrent-recompilation-delay=500",
                   "--concurrent-recompilation"]

182
SUPPORTED_ARCHS = ["android_arm",
183
                   "android_arm64",
184
                   "android_ia32",
185
                   "android_x64",
186 187
                   "arm",
                   "ia32",
danno@chromium.org's avatar
danno@chromium.org committed
188
                   "x87",
189
                   "mips",
190
                   "mipsel",
191
                   "mips64",
192
                   "mips64el",
193 194
                   "s390",
                   "s390x",
195 196
                   "ppc",
                   "ppc64",
197
                   "x64",
198
                   "x32",
199
                   "arm64"]
200 201
# Double the timeout for these:
SLOW_ARCHS = ["android_arm",
202
              "android_arm64",
203
              "android_ia32",
204
              "android_x64",
205
              "arm",
206
              "mips",
207
              "mipsel",
208
              "mips64",
209
              "mips64el",
210 211
              "s390",
              "s390x",
danno@chromium.org's avatar
danno@chromium.org committed
212
              "x87",
213
              "arm64"]
214

215 216 217

def BuildOptions():
  result = optparse.OptionParser()
218
  result.usage = '%prog [options] [tests]'
219
  result.description = """TESTS: %s""" % (TEST_MAP["default"])
220 221
  result.add_option("--arch",
                    help=("The architecture to run tests for, "
222
                          "'auto' or 'native' for auto-detect: %s" % SUPPORTED_ARCHS),
223 224 225 226
                    default="ia32,x64,arm")
  result.add_option("--arch-and-mode",
                    help="Architecture and mode in the format 'arch.mode'",
                    default=None)
227 228 229
  result.add_option("--asan",
                    help="Regard test expectations for ASAN",
                    default=False, action="store_true")
230 231
  result.add_option("--sancov-dir",
                    help="Directory where to collect coverage data")
232 233 234
  result.add_option("--cfi-vptr",
                    help="Run tests with UBSAN cfi_vptr option.",
                    default=False, action="store_true")
235 236 237
  result.add_option("--buildbot",
                    help="Adapt to path structure used on buildbots",
                    default=False, action="store_true")
238 239 240
  result.add_option("--dcheck-always-on",
                    help="Indicates that V8 was compiled with DCHECKs enabled",
                    default=False, action="store_true")
241 242 243
  result.add_option("--novfp3",
                    help="Indicates that V8 was compiled without VFP3 support",
                    default=False, action="store_true")
244 245
  result.add_option("--cat", help="Print the source of the tests",
                    default=False, action="store_true")
246 247 248 249 250 251
  result.add_option("--slow-tests",
                    help="Regard slow tests (run|skip|dontcare)",
                    default="dontcare")
  result.add_option("--pass-fail-tests",
                    help="Regard pass|fail tests (run|skip|dontcare)",
                    default="dontcare")
252 253 254
  result.add_option("--gc-stress",
                    help="Switch on GC stress mode",
                    default=False, action="store_true")
255 256 257
  result.add_option("--gcov-coverage",
                    help="Uses executables instrumented for gcov coverage",
                    default=False, action="store_true")
258 259 260 261 262
  result.add_option("--command-prefix",
                    help="Prepended to each shell command used to run a test",
                    default="")
  result.add_option("--download-data", help="Download missing test suite data",
                    default=False, action="store_true")
263
  result.add_option("--download-data-only",
264
                    help="Deprecated",
265
                    default=False, action="store_true")
266 267 268
  result.add_option("--enable-inspector",
                    help="Indicates a build with inspector support",
                    default=False, action="store_true")
269 270 271 272 273 274 275 276
  result.add_option("--extra-flags",
                    help="Additional flags to pass to each test command",
                    default="")
  result.add_option("--isolates", help="Whether to test isolates",
                    default=False, action="store_true")
  result.add_option("-j", help="The number of parallel tasks to run",
                    default=0, type="int")
  result.add_option("-m", "--mode",
277 278
                    help="The test modes in which to run (comma-separated,"
                    " uppercase for ninja and buildbot builds): %s" % MODES.keys(),
279
                    default="release,debug")
280 281 282
  result.add_option("--no-harness", "--noharness",
                    help="Run without test harness of a given suite",
                    default=False, action="store_true")
283 284 285
  result.add_option("--no-i18n", "--noi18n",
                    help="Skip internationalization tests",
                    default=False, action="store_true")
286 287 288 289 290
  result.add_option("--no-network", "--nonetwork",
                    help="Don't distribute tests on the network",
                    default=(utils.GuessOS() != "linux"),
                    dest="no_network", action="store_true")
  result.add_option("--no-presubmit", "--nopresubmit",
291
                    help='Skip presubmit checks (deprecated)',
292
                    default=False, dest="no_presubmit", action="store_true")
293 294 295
  result.add_option("--no-snap", "--nosnap",
                    help='Test a build compiled without snapshot.',
                    default=False, dest="no_snap", action="store_true")
296 297 298
  result.add_option("--no-sorting", "--nosorting",
                    help="Don't sort tests according to duration of last run.",
                    default=False, dest="no_sorting", action="store_true")
299 300 301
  result.add_option("--no-variants", "--novariants",
                    help="Don't run any testing variants",
                    default=False, dest="no_variants", action="store_true")
302
  result.add_option("--variants",
303 304
                    help="Comma-separated list of testing variants;"
                    " default: \"%s\"" % ",".join(VARIANTS))
305 306
  result.add_option("--exhaustive-variants",
                    default=False, action="store_true",
307 308
                    help="Use exhaustive set of default variants:"
                    " \"%s\"" % ",".join(EXHAUSTIVE_VARIANTS))
309 310
  result.add_option("--outdir", help="Base directory with compile output",
                    default="out")
311 312
  result.add_option("--gn", help="Scan out.gn for the last built configuration",
                    default=False, action="store_true")
313 314 315
  result.add_option("--predictable",
                    help="Compare output of several reruns of each test",
                    default=False, action="store_true")
316 317 318 319
  result.add_option("-p", "--progress",
                    help=("The style of progress indicator"
                          " (verbose, dots, color, mono)"),
                    choices=progress.PROGRESS_INDICATORS.keys(), default="mono")
320
  result.add_option("--quickcheck", default=False, action="store_true",
321
                    help=("Quick check mode (skip slow tests)"))
322 323
  result.add_option("--report", help="Print a summary of the tests to be run",
                    default=False, action="store_true")
324 325
  result.add_option("--json-test-results",
                    help="Path to a file for storing json results.")
326 327 328 329 330 331 332
  result.add_option("--rerun-failures-count",
                    help=("Number of times to rerun each failing test case. "
                          "Very slow tests will be rerun only once."),
                    default=0, type="int")
  result.add_option("--rerun-failures-max",
                    help="Maximum number of failing test cases to rerun.",
                    default=100, type="int")
333 334 335 336 337 338 339 340 341
  result.add_option("--shard-count",
                    help="Split testsuites into this number of shards",
                    default=1, type="int")
  result.add_option("--shard-run",
                    help="Run this shard from the split up tests.",
                    default=1, type="int")
  result.add_option("--shell", help="DEPRECATED! use --shell-dir", default="")
  result.add_option("--shell-dir", help="Directory containing executables",
                    default="")
342 343 344 345
  result.add_option("--dont-skip-slow-simulator-tests",
                    help="Don't skip more slow tests when using a simulator.",
                    default=False, action="store_true",
                    dest="dont_skip_simulator_slow_tests")
346 347 348
  result.add_option("--swarming",
                    help="Indicates running test driver on swarming.",
                    default=False, action="store_true")
349 350 351
  result.add_option("--time", help="Print timing information after running",
                    default=False, action="store_true")
  result.add_option("-t", "--timeout", help="Timeout in seconds",
352
                    default=TIMEOUT_DEFAULT, type="int")
353 354 355
  result.add_option("--tsan",
                    help="Regard test expectations for TSAN",
                    default=False, action="store_true")
356 357 358 359 360 361
  result.add_option("-v", "--verbose", help="Verbose output",
                    default=False, action="store_true")
  result.add_option("--valgrind", help="Run tests through valgrind",
                    default=False, action="store_true")
  result.add_option("--warn-unused", help="Report unused rules",
                    default=False, action="store_true")
362 363 364 365
  result.add_option("--junitout", help="File name of the JUnit output")
  result.add_option("--junittestsuite",
                    help="The testsuite name in the JUnit output file",
                    default="v8tests")
366
  result.add_option("--random-seed", default=0, dest="random_seed", type="int",
367
                    help="Default seed for initializing random generator")
368 369 370
  result.add_option("--random-seed-stress-count", default=1, type="int",
                    dest="random_seed_stress_count",
                    help="Number of runs with different random seeds")
371 372 373
  result.add_option("--msan",
                    help="Regard test expectations for MSAN",
                    default=False, action="store_true")
374 375 376
  return result


377 378 379 380 381 382 383
def RandomSeed():
  seed = 0
  while not seed:
    seed = random.SystemRandom().randint(-2147483648, 2147483647)
  return seed


384 385 386 387 388 389 390 391 392
def BuildbotToV8Mode(config):
  """Convert buildbot build configs to configs understood by the v8 runner.

  V8 configs are always lower case and without the additional _x64 suffix for
  64 bit builds on windows with ninja.
  """
  mode = config[:-4] if config.endswith('_x64') else config
  return mode.lower()

393 394
def SetupEnvironment(options):
  """Setup additional environment variables."""
395 396 397 398

  # Many tests assume an English interface.
  os.environ['LANG'] = 'en_US.UTF-8'

399 400 401 402 403 404 405 406
  symbolizer = 'external_symbolizer_path=%s' % (
      os.path.join(
          BASE_DIR, 'third_party', 'llvm-build', 'Release+Asserts', 'bin',
          'llvm-symbolizer',
      )
  )

  if options.asan:
407 408 409 410 411 412 413 414 415
    asan_options = [symbolizer]
    if not utils.GuessOS() == 'macos':
      # LSAN is not available on mac.
      asan_options.append('detect_leaks=1')
      os.environ['LSAN_OPTIONS'] = ":".join([
        'suppressions=%s' % os.path.join(
            BASE_DIR, 'tools', 'memory', 'lsan', 'suppressions.txt'),
      ])
    os.environ['ASAN_OPTIONS'] = ":".join(asan_options)
416

417 418 419 420 421 422 423 424
  if options.sancov_dir:
    assert os.path.exists(options.sancov_dir)
    os.environ['ASAN_OPTIONS'] = ":".join([
      'coverage=1',
      'coverage_dir=%s' % options.sancov_dir,
      symbolizer,
    ])

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
  if options.cfi_vptr:
    os.environ['UBSAN_OPTIONS'] = ":".join([
      'print_stacktrace=1',
      'print_summary=1',
      'symbolize=1',
      symbolizer,
    ])

  if options.msan:
    os.environ['MSAN_OPTIONS'] = symbolizer

  if options.tsan:
    suppressions_file = os.path.join(
        BASE_DIR, 'tools', 'sanitizers', 'tsan_suppressions.txt')
    os.environ['TSAN_OPTIONS'] = " ".join([
      symbolizer,
      'suppressions=%s' % suppressions_file,
      'exit_code=0',
      'report_thread_leaks=0',
      'history_size=7',
      'report_destroy_locked=0',
    ])

448
def ProcessOptions(options):
449
  global VARIANTS
450

451 452 453
  # First try to auto-detect configurations based on the build if GN was
  # used. This can't be overridden by cmd-line arguments.
  options.auto_detect = False
454 455 456 457 458 459 460 461 462 463 464 465
  if options.gn:
    gn_out_dir = os.path.join(BASE_DIR, DEFAULT_OUT_GN)
    latest_timestamp = -1
    latest_config = None
    for gn_config in os.listdir(gn_out_dir):
      gn_config_dir = os.path.join(gn_out_dir, gn_config)
      if not isdir(gn_config_dir):
        continue
      if os.path.getmtime(gn_config_dir) > latest_timestamp:
        latest_timestamp = os.path.getmtime(gn_config_dir)
        latest_config = gn_config
    if latest_config:
466
      print(">>> Latest GN build found is %s" % latest_config)
467 468
      options.outdir = os.path.join(DEFAULT_OUT_GN, latest_config)

469 470 471 472 473 474 475
  if options.buildbot:
    build_config_path = os.path.join(
        BASE_DIR, options.outdir, options.mode, "v8_build_config.json")
  else:
    build_config_path = os.path.join(
        BASE_DIR, options.outdir, "v8_build_config.json")

476 477 478 479 480 481 482 483 484 485
  if os.path.exists(build_config_path):
    try:
      with open(build_config_path) as f:
        build_config = json.load(f)
    except Exception:
      print ("%s exists but contains invalid json. Is your build up-to-date?" %
             build_config_path)
      return False
    options.auto_detect = True

486 487 488 489
    # In auto-detect mode the outdir is always where we found the build config.
    # This ensures that we'll also take the build products from there.
    options.outdir = os.path.dirname(build_config_path)

490 491 492 493 494 495 496
    options.arch_and_mode = None
    options.arch = build_config["v8_target_cpu"]
    if options.arch == 'x86':
      # TODO(machenbach): Transform all to x86 eventually.
      options.arch = 'ia32'
    options.asan = build_config["is_asan"]
    options.dcheck_always_on = build_config["dcheck_always_on"]
497
    options.enable_inspector = build_config["v8_enable_inspector"]
498 499 500 501 502 503
    options.mode = 'debug' if build_config["is_debug"] else 'release'
    options.msan = build_config["is_msan"]
    options.no_i18n = not build_config["v8_enable_i18n_support"]
    options.no_snap = not build_config["v8_use_snapshot"]
    options.tsan = build_config["is_tsan"]

504 505
  # Architecture and mode related stuff.
  if options.arch_and_mode:
506 507 508 509
    options.arch_and_mode = [arch_and_mode.split(".")
        for arch_and_mode in options.arch_and_mode.split(",")]
    options.arch = ",".join([tokens[0] for tokens in options.arch_and_mode])
    options.mode = ",".join([tokens[1] for tokens in options.arch_and_mode])
510 511
  options.mode = options.mode.split(",")
  for mode in options.mode:
512
    if not BuildbotToV8Mode(mode) in MODES:
513 514 515 516 517 518
      print "Unknown mode %s" % mode
      return False
  if options.arch in ["auto", "native"]:
    options.arch = ARCH_GUESS
  options.arch = options.arch.split(",")
  for arch in options.arch:
519
    if not arch in SUPPORTED_ARCHS:
520 521 522
      print "Unknown architecture %s" % arch
      return False

523 524 525 526 527
  # Store the final configuration in arch_and_mode list. Don't overwrite
  # predefined arch_and_mode since it is more expressive than arch and mode.
  if not options.arch_and_mode:
    options.arch_and_mode = itertools.product(options.arch, options.mode)

528 529 530 531 532 533 534 535
  # Special processing of other options, sorted alphabetically.

  if options.buildbot:
    options.no_network = True
  if options.command_prefix:
    print("Specifying --command-prefix disables network distribution, "
          "running tests locally.")
    options.no_network = True
536
  options.command_prefix = shlex.split(options.command_prefix)
537
  options.extra_flags = shlex.split(options.extra_flags)
538 539 540 541

  if options.gc_stress:
    options.extra_flags += GC_STRESS_FLAGS

542
  if options.asan:
543
    options.extra_flags.append("--invoke-weak-callbacks")
544
    options.extra_flags.append("--omit-quit")
545

546 547 548
  if options.novfp3:
    options.extra_flags.append("--noenable-vfp3")

549 550 551 552 553
  if options.exhaustive_variants:
    # This is used on many bots. It includes a larger set of default variants.
    # Other options for manipulating variants still apply afterwards.
    VARIANTS = EXHAUSTIVE_VARIANTS

554 555
  # TODO(machenbach): Figure out how to test a bigger subset of variants on
  # msan and tsan.
556 557 558
  if options.msan:
    VARIANTS = ["default"]

559 560 561
  if options.tsan:
    VARIANTS = ["default"]

562 563
  if options.j == 0:
    options.j = multiprocessing.cpu_count()
564

565 566
  if options.random_seed_stress_count <= 1 and options.random_seed == 0:
    options.random_seed = RandomSeed()
567

568 569 570 571
  def excl(*args):
    """Returns true if zero or one of multiple arguments are true."""
    return reduce(lambda x, y: x + y, args) <= 1

572 573
  if not excl(options.no_variants, bool(options.variants)):
    print("Use only one of --no-variants or --variants.")
574
    return False
575 576 577 578
  if options.quickcheck:
    VARIANTS = ["default", "stress"]
    options.slow_tests = "skip"
    options.pass_fail_tests = "skip"
579
  if options.no_variants:
580 581 582
    VARIANTS = ["default"]
  if options.variants:
    VARIANTS = options.variants.split(",")
583 584 585 586 587 588 589 590

    # Resolve variant aliases.
    VARIANTS = reduce(
        list.__add__,
        (VARIANT_ALIASES.get(v, [v]) for v in VARIANTS),
        [],
    )

591 592
    if not set(VARIANTS).issubset(ALL_VARIANTS):
      print "All variants must be in %s" % str(ALL_VARIANTS)
593
      return False
594 595 596 597 598
  if options.predictable:
    VARIANTS = ["default"]
    options.extra_flags.append("--predictable")
    options.extra_flags.append("--verify_predictable")
    options.extra_flags.append("--no-inline-new")
599

600 601 602
  # Dedupe.
  VARIANTS = list(set(VARIANTS))

603 604 605 606 607 608 609
  if not options.shell_dir:
    if options.shell:
      print "Warning: --shell is deprecated, use --shell-dir instead."
      options.shell_dir = os.path.dirname(options.shell)
  if options.valgrind:
    run_valgrind = os.path.join("tools", "run-valgrind.py")
    # This is OK for distributed running, so we don't need to set no_network.
610
    options.command_prefix = (["python", "-u", run_valgrind] +
611
                              options.command_prefix)
612 613 614 615 616 617 618 619
  def CheckTestMode(name, option):
    if not option in ["run", "skip", "dontcare"]:
      print "Unknown %s mode %s" % (name, option)
      return False
    return True
  if not CheckTestMode("slow test", options.slow_tests):
    return False
  if not CheckTestMode("pass|fail test", options.pass_fail_tests):
620
    return False
621
  if options.no_i18n:
622
    TEST_MAP["bot_default"].remove("intl")
623
    TEST_MAP["default"].remove("intl")
624
  if not options.enable_inspector:
625
    TEST_MAP["default"].remove("inspector")
626 627
    TEST_MAP["bot_default"].remove("inspector")
    TEST_MAP["optimize_for_size"].remove("inspector")
628 629 630
    TEST_MAP["default"].remove("debugger")
    TEST_MAP["bot_default"].remove("debugger")
    TEST_MAP["optimize_for_size"].remove("debugger")
631 632 633
  return True


634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
def ShardTests(tests, options):
  # Read gtest shard configuration from environment (e.g. set by swarming).
  # If none is present, use values passed on the command line.
  shard_count = int(os.environ.get('GTEST_TOTAL_SHARDS', options.shard_count))
  shard_run = os.environ.get('GTEST_SHARD_INDEX')
  if shard_run is not None:
    # The v8 shard_run starts at 1, while GTEST_SHARD_INDEX starts at 0.
    shard_run = int(shard_run) + 1
  else:
    shard_run = options.shard_run

  if options.shard_count > 1:
    # Log if a value was passed on the cmd line and it differs from the
    # environment variables.
    if options.shard_count != shard_count:
      print("shard_count from cmd line differs from environment variable "
            "GTEST_TOTAL_SHARDS")
    if options.shard_run > 1 and options.shard_run != shard_run:
      print("shard_run from cmd line differs from environment variable "
            "GTEST_SHARD_INDEX")

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
  if shard_count < 2:
    return tests
  if shard_run < 1 or shard_run > shard_count:
    print "shard-run not a valid number, should be in [1:shard-count]"
    print "defaulting back to running all tests"
    return tests
  count = 0
  shard = []
  for test in tests:
    if count % shard_count == shard_run - 1:
      shard.append(test)
    count += 1
  return shard


def Main():
671 672 673
  # Use the v8 root as cwd as some test cases use "load" with relative paths.
  os.chdir(BASE_DIR)

674 675 676 677 678
  parser = BuildOptions()
  (options, args) = parser.parse_args()
  if not ProcessOptions(options):
    parser.print_help()
    return 1
679
  SetupEnvironment(options)
680

681 682 683 684 685
  if options.swarming:
    # Swarming doesn't print how isolated commands are called. Lets make this
    # less cryptic by printing it ourselves.
    print ' '.join(sys.argv)

686 687
  exit_code = 0

688
  suite_paths = utils.GetSuitePaths(join(BASE_DIR, "test"))
689

690 691 692 693
  # Use default tests if no test configuration was provided at the cmd line.
  if len(args) == 0:
    args = ["default"]

694 695 696 697
  # Expand arguments with grouped tests. The args should reflect the list of
  # suites as otherwise filters would break.
  def ExpandTestGroups(name):
    if name in TEST_MAP:
698
      return [suite for suite in TEST_MAP[name]]
699 700 701 702 703 704
    else:
      return [name]
  args = reduce(lambda x, y: x + y,
         [ExpandTestGroups(arg) for arg in args],
         [])

705 706 707 708
  args_suites = OrderedDict() # Used as set
  for arg in args:
    args_suites[arg.split('/')[0]] = True
  suite_paths = [ s for s in args_suites if s in suite_paths ]
709 710 711 712

  suites = []
  for root in suite_paths:
    suite = testsuite.TestSuite.LoadTestSuite(
713
        os.path.join(BASE_DIR, "test", root))
714 715 716
    if suite:
      suites.append(suite)

717
  if options.download_data or options.download_data_only:
718 719 720
    for s in suites:
      s.DownloadData()

721 722 723
  if options.download_data_only:
    return exit_code

724 725 726
  for s in suites:
    s.PrepareSources()

727
  for (arch, mode) in options.arch_and_mode:
728
    try:
729
      code = Execute(arch, mode, args, options, suites)
730 731
    except KeyboardInterrupt:
      return 2
732
    exit_code = exit_code or code
733 734 735
  return exit_code


736
def Execute(arch, mode, args, options, suites):
737 738
  print(">>> Running tests for %s.%s" % (arch, mode))

739 740
  shell_dir = options.shell_dir
  if not shell_dir:
741 742 743 744 745
    if options.auto_detect:
      # If an output dir with a build was passed, test directly in that
      # directory.
      shell_dir = os.path.join(BASE_DIR, options.outdir)
    elif options.buildbot:
746 747
      # TODO(machenbach): Get rid of different output folder location on
      # buildbot. Currently this is capitalized Release and Debug.
748
      shell_dir = os.path.join(BASE_DIR, options.outdir, mode)
749
      mode = BuildbotToV8Mode(mode)
750
    else:
751
      shell_dir = os.path.join(
752
          BASE_DIR,
753 754 755
          options.outdir,
          "%s.%s" % (arch, MODES[mode]["output_folder"]),
      )
756 757
  if not os.path.exists(shell_dir):
      raise Exception('Could not find shell_dir: "%s"' % shell_dir)
758 759

  # Populate context object.
760
  mode_flags = MODES[mode]["flags"]
761

762 763 764 765 766
  # Simulators are slow, therefore allow a longer timeout.
  if arch in SLOW_ARCHS:
    options.timeout *= 2

  options.timeout *= MODES[mode]["timeout_scalefactor"]
767 768 769

  if options.predictable:
    # Predictable mode is slower.
770
    options.timeout *= 2
771

772
  ctx = context.Context(arch, MODES[mode]["execution_mode"], shell_dir,
773
                        mode_flags, options.verbose,
774 775
                        options.timeout,
                        options.isolates,
776
                        options.command_prefix,
777
                        options.extra_flags,
778
                        options.no_i18n,
779
                        options.random_seed,
780 781
                        options.no_sorting,
                        options.rerun_failures_count,
782
                        options.rerun_failures_max,
783
                        options.predictable,
784
                        options.no_harness,
785 786
                        use_perf_data=not options.swarming,
                        sancov_dir=options.sancov_dir)
787

788
  # TODO(all): Combine "simulator" and "simulator_run".
789 790
  # TODO(machenbach): In GN we can derive simulator run from
  # target_arch != v8_target_arch in the dumped build config.
791
  simulator_run = not options.dont_skip_simulator_slow_tests and \
792
      arch in ['arm64', 'arm', 'mipsel', 'mips', 'mips64', 'mips64el', \
793
               'ppc', 'ppc64'] and \
794
      ARCH_GUESS and arch != ARCH_GUESS
795 796 797
  # Find available test suites and read test cases from them.
  variables = {
    "arch": arch,
798
    "asan": options.asan,
799
    "deopt_fuzzer": False,
800
    "gc_stress": options.gc_stress,
801
    "gcov_coverage": options.gcov_coverage,
802
    "isolates": options.isolates,
803
    "mode": MODES[mode]["status_mode"],
804
    "no_i18n": options.no_i18n,
805
    "no_snap": options.no_snap,
806
    "simulator_run": simulator_run,
807
    "simulator": utils.UseSimulator(arch),
808
    "system": utils.GuessOS(),
809
    "tsan": options.tsan,
810
    "msan": options.msan,
811
    "dcheck_always_on": options.dcheck_always_on,
812
    "novfp3": options.novfp3,
813
    "predictable": options.predictable,
814
    "byteorder": sys.byteorder,
815 816 817 818 819 820 821 822
  }
  all_tests = []
  num_tests = 0
  for s in suites:
    s.ReadStatusFile(variables)
    s.ReadTestCases(ctx)
    if len(args) > 0:
      s.FilterTestCasesByArgs(args)
823
    all_tests += s.tests
824 825 826

    # First filtering by status applying the generic rules (independent of
    # variants).
827 828
    s.FilterTestCasesByStatus(options.warn_unused, options.slow_tests,
                              options.pass_fail_tests)
829

830 831 832
    if options.cat:
      verbose.PrintTestSource(s.tests)
      continue
833
    variant_gen = s.CreateVariantGenerator(VARIANTS)
834
    variant_tests = [ t.CopyAddingFlags(v, flags)
835
                      for t in s.tests
836 837
                      for v in variant_gen.FilterVariantsByTest(t)
                      for flags in variant_gen.GetFlagSets(t, v) ]
838 839 840 841 842 843 844 845 846 847 848 849

    if options.random_seed_stress_count > 1:
      # Duplicate test for random seed stress mode.
      def iter_seed_flags():
        for i in range(0, options.random_seed_stress_count):
          # Use given random seed for all runs (set by default in execution.py)
          # or a new random seed if none is specified.
          if options.random_seed:
            yield []
          else:
            yield ["--random-seed=%d" % RandomSeed()]
      s.tests = [
850
        t.CopyAddingFlags(t.variant, flags)
851
        for t in variant_tests
852
        for flags in iter_seed_flags()
853 854 855 856
      ]
    else:
      s.tests = variant_tests

857 858 859 860
    # Second filtering by status applying the variant-dependent rules.
    s.FilterTestCasesByStatus(options.warn_unused, options.slow_tests,
                              options.pass_fail_tests, variants=True)

861
    s.tests = ShardTests(s.tests, options)
862 863 864 865 866 867 868 869 870
    num_tests += len(s.tests)

  if options.cat:
    return 0  # We're done here.

  if options.report:
    verbose.PrintReport(all_tests)

  # Run the tests, either locally or distributed on the network.
871
  start_time = time.time()
872 873
  progress_indicator = progress.IndicatorNotifier()
  progress_indicator.Register(progress.PROGRESS_INDICATORS[options.progress]())
874
  if options.junitout:
875 876
    progress_indicator.Register(progress.JUnitTestProgressIndicator(
        options.junitout, options.junittestsuite))
877
  if options.json_test_results:
878
    progress_indicator.Register(progress.JsonTestProgressIndicator(
879 880
        options.json_test_results, arch, MODES[mode]["execution_mode"],
        ctx.random_seed))
881 882 883

  run_networked = not options.no_network
  if not run_networked:
884
    if options.verbose:
885
      print("Network distribution disabled, running tests locally.")
886 887 888 889 890 891 892 893
  elif utils.GuessOS() != "linux":
    print("Network distribution is only supported on Linux, sorry!")
    run_networked = False
  peers = []
  if run_networked:
    peers = network_execution.GetPeers()
    if not peers:
      print("No connection to distribution server; running tests locally.")
894
      run_networked = False
895 896 897 898 899 900 901 902 903
    elif len(peers) == 1:
      print("No other peers on the network; running tests locally.")
      run_networked = False
    elif num_tests <= 100:
      print("Less than 100 tests, running them locally.")
      run_networked = False

  if run_networked:
    runner = network_execution.NetworkedRunner(suites, progress_indicator,
904
                                               ctx, peers, BASE_DIR)
905 906 907 908 909
  else:
    runner = execution.Runner(suites, progress_indicator, ctx)

  exit_code = runner.Run(options.j)
  overall_duration = time.time() - start_time
910 911 912

  if options.time:
    verbose.PrintTestDurations(suites, overall_duration)
913 914 915 916

  if num_tests == 0:
    print("Warning: no tests were run!")

917 918 919 920 921
  if exit_code == 1 and options.json_test_results:
    print("Force exit code 0 after failures. Json test results file generated "
          "with failure information.")
    exit_code = 0

922 923 924 925 926 927 928 929 930 931 932 933
  if options.sancov_dir:
    # If tests ran with sanitizer coverage, merge coverage files in the end.
    try:
      print "Merging sancov files."
      subprocess.check_call([
        sys.executable,
        join(BASE_DIR, "tools", "sanitizers", "sancov_merger.py"),
        "--coverage-dir=%s" % options.sancov_dir])
    except:
      print >> sys.stderr, "Error: Merging sancov files failed."
      exit_code = 1

934 935 936 937 938
  return exit_code


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