1# -*- Python -*-
2
3# Configuration file for 'lit' test runner.
4# This file contains common rules for various compiler-rt testsuites.
5# It is mostly copied from lit.cfg.py used by Clang.
6import os
7import platform
8import re
9import subprocess
10import json
11
12import lit.formats
13import lit.util
14
15# Get shlex.quote if available (added in 3.3), and fall back to pipes.quote if
16# it's not available.
17try:
18  import shlex
19  sh_quote = shlex.quote
20except:
21  import pipes
22  sh_quote = pipes.quote
23
24def find_compiler_libdir():
25  """
26    Returns the path to library resource directory used
27    by the compiler.
28  """
29  if config.compiler_id != 'Clang':
30    lit_config.warning(f'Determining compiler\'s runtime directory is not supported for {config.compiler_id}')
31    # TODO: Support other compilers.
32    return None
33  def get_path_from_clang(args, allow_failure):
34    clang_cmd = [
35      config.clang.strip(),
36      f'--target={config.target_triple}',
37    ]
38    clang_cmd.extend(args)
39    path = None
40    try:
41      result = subprocess.run(
42        clang_cmd,
43        stdout=subprocess.PIPE,
44        stderr=subprocess.PIPE,
45        check=True
46      )
47      path = result.stdout.decode().strip()
48    except subprocess.CalledProcessError as e:
49      msg = f'Failed to run {clang_cmd}\nrc:{e.returncode}\nstdout:{e.stdout}\ne.stderr{e.stderr}'
50      if allow_failure:
51        lit_config.warning(msg)
52      else:
53        lit_config.fatal(msg)
54    return path, clang_cmd
55
56  # Try using `-print-runtime-dir`. This is only supported by very new versions of Clang.
57  # so allow failure here.
58  runtime_dir, clang_cmd = get_path_from_clang(shlex.split(config.target_cflags)
59                                               + ['-print-runtime-dir'],
60                                               allow_failure=True)
61  if runtime_dir:
62    if os.path.exists(runtime_dir):
63      return os.path.realpath(runtime_dir)
64    # TODO(dliew): This should be a fatal error but it seems to trip the `llvm-clang-win-x-aarch64`
65    # bot which is likely misconfigured
66    lit_config.warning(
67      f'Path reported by clang does not exist: \"{runtime_dir}\". '
68      f'This path was found by running {clang_cmd}.'
69    )
70    return None
71
72  # Fall back for older AppleClang that doesn't support `-print-runtime-dir`
73  # Note `-print-file-name=<path to compiler-rt lib>` was broken for Apple
74  # platforms so we can't use that approach here (see https://reviews.llvm.org/D101682).
75  if config.host_os == 'Darwin':
76    lib_dir, _ = get_path_from_clang(['-print-file-name=lib'], allow_failure=False)
77    runtime_dir = os.path.join(lib_dir, 'darwin')
78    if not os.path.exists(runtime_dir):
79      lit_config.fatal(f'Path reported by clang does not exist: {runtime_dir}')
80    return os.path.realpath(runtime_dir)
81
82  lit_config.warning('Failed to determine compiler\'s runtime directory')
83  return None
84
85
86# Choose between lit's internal shell pipeline runner and a real shell.  If
87# LIT_USE_INTERNAL_SHELL is in the environment, we use that as an override.
88use_lit_shell = os.environ.get("LIT_USE_INTERNAL_SHELL")
89if use_lit_shell:
90    # 0 is external, "" is default, and everything else is internal.
91    execute_external = (use_lit_shell == "0")
92else:
93    # Otherwise we default to internal on Windows and external elsewhere, as
94    # bash on Windows is usually very slow.
95    execute_external = (not sys.platform in ['win32'])
96
97# Allow expanding substitutions that are based on other substitutions
98config.recursiveExpansionLimit = 10
99
100# Setup test format.
101config.test_format = lit.formats.ShTest(execute_external)
102if execute_external:
103  config.available_features.add('shell')
104
105compiler_id = getattr(config, 'compiler_id', None)
106if compiler_id == "Clang":
107  if platform.system() != 'Windows':
108    config.cxx_mode_flags = ["--driver-mode=g++"]
109  else:
110    config.cxx_mode_flags = []
111  # We assume that sanitizers should provide good enough error
112  # reports and stack traces even with minimal debug info.
113  config.debug_info_flags = ["-gline-tables-only"]
114  if platform.system() == 'Windows':
115    # On Windows, use CodeView with column info instead of DWARF. Both VS and
116    # windbg do not behave well when column info is enabled, but users have
117    # requested it because it makes ASan reports more precise.
118    config.debug_info_flags.append("-gcodeview")
119    config.debug_info_flags.append("-gcolumn-info")
120elif compiler_id == 'GNU':
121  config.cxx_mode_flags = ["-x c++"]
122  config.debug_info_flags = ["-g"]
123else:
124  lit_config.fatal("Unsupported compiler id: %r" % compiler_id)
125# Add compiler ID to the list of available features.
126config.available_features.add(compiler_id)
127
128# When LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=on, the initial value of
129# config.compiler_rt_libdir (COMPILER_RT_RESOLVED_LIBRARY_OUTPUT_DIR) has the
130# triple as the trailing path component. The value is incorrect for -m32/-m64.
131# Adjust config.compiler_rt accordingly.
132if config.enable_per_target_runtime_dir:
133    if '-m32' in shlex.split(config.target_cflags):
134        config.compiler_rt_libdir = re.sub(r'/x86_64(?=-[^/]+$)', '/i386', config.compiler_rt_libdir)
135    elif '-m64' in shlex.split(config.target_cflags):
136        config.compiler_rt_libdir = re.sub(r'/i386(?=-[^/]+$)', '/x86_64', config.compiler_rt_libdir)
137
138# Ask the compiler for the path to libraries it is going to use. If this
139# doesn't match config.compiler_rt_libdir then it means we might be testing the
140# compiler's own runtime libraries rather than the ones we just built.
141# Warn about about this and handle appropriately.
142compiler_libdir = find_compiler_libdir()
143if compiler_libdir:
144  compiler_rt_libdir_real = os.path.realpath(config.compiler_rt_libdir)
145  if compiler_libdir != compiler_rt_libdir_real:
146    lit_config.warning(
147      'Compiler lib dir != compiler-rt lib dir\n'
148      f'Compiler libdir:     "{compiler_libdir}"\n'
149      f'compiler-rt libdir:  "{compiler_rt_libdir_real}"')
150    if config.test_standalone_build_libs:
151      # Use just built runtime libraries, i.e. the the libraries this built just built.
152      if not config.test_suite_supports_overriding_runtime_lib_path:
153        # Test suite doesn't support this configuration.
154        # TODO(dliew): This should be an error but it seems several bots are
155        # testing incorrectly and having this as an error breaks them.
156        lit_config.warning(
157            'COMPILER_RT_TEST_STANDALONE_BUILD_LIBS=ON, but this test suite '
158            'does not support testing the just-built runtime libraries '
159            'when the test compiler is configured to use different runtime '
160            'libraries. Either modify this test suite to support this test '
161            'configuration, or set COMPILER_RT_TEST_STANDALONE_BUILD_LIBS=OFF '
162            'to test the runtime libraries included in the compiler instead.'
163        )
164    else:
165      # Use Compiler's resource library directory instead.
166      config.compiler_rt_libdir = compiler_libdir
167    lit_config.note(f'Testing using libraries in "{config.compiler_rt_libdir}"')
168
169# If needed, add cflag for shadow scale.
170if config.asan_shadow_scale != '':
171  config.target_cflags += " -mllvm -asan-mapping-scale=" + config.asan_shadow_scale
172if config.memprof_shadow_scale != '':
173  config.target_cflags += " -mllvm -memprof-mapping-scale=" + config.memprof_shadow_scale
174
175config.environment = dict(os.environ)
176
177# Clear some environment variables that might affect Clang.
178possibly_dangerous_env_vars = ['ASAN_OPTIONS', 'DFSAN_OPTIONS', 'LSAN_OPTIONS',
179                               'MSAN_OPTIONS', 'UBSAN_OPTIONS',
180                               'COMPILER_PATH', 'RC_DEBUG_OPTIONS',
181                               'CINDEXTEST_PREAMBLE_FILE', 'LIBRARY_PATH',
182                               'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH',
183                               'OBJC_INCLUDE_PATH', 'OBJCPLUS_INCLUDE_PATH',
184                               'LIBCLANG_TIMING', 'LIBCLANG_OBJTRACKING',
185                               'LIBCLANG_LOGGING', 'LIBCLANG_BGPRIO_INDEX',
186                               'LIBCLANG_BGPRIO_EDIT', 'LIBCLANG_NOTHREADS',
187                               'LIBCLANG_RESOURCE_USAGE',
188                               'LIBCLANG_CODE_COMPLETION_LOGGING',
189                               'XRAY_OPTIONS']
190# Clang/Win32 may refer to %INCLUDE%. vsvarsall.bat sets it.
191if platform.system() != 'Windows':
192    possibly_dangerous_env_vars.append('INCLUDE')
193for name in possibly_dangerous_env_vars:
194  if name in config.environment:
195    del config.environment[name]
196
197# Tweak PATH to include llvm tools dir.
198if (not config.llvm_tools_dir) or (not os.path.exists(config.llvm_tools_dir)):
199  lit_config.fatal("Invalid llvm_tools_dir config attribute: %r" % config.llvm_tools_dir)
200path = os.path.pathsep.join((config.llvm_tools_dir, config.environment['PATH']))
201config.environment['PATH'] = path
202
203# Help MSVS link.exe find the standard libraries.
204# Make sure we only try to use it when targetting Windows.
205if platform.system() == 'Windows' and '-win' in config.target_triple:
206  config.environment['LIB'] = os.environ['LIB']
207
208config.available_features.add(config.host_os.lower())
209
210if config.target_triple.startswith("ppc") or config.target_triple.startswith("powerpc"):
211  config.available_features.add("ppc")
212
213if re.match(r'^x86_64.*-linux', config.target_triple):
214  config.available_features.add("x86_64-linux")
215
216config.available_features.add("host-byteorder-" + sys.byteorder + "-endian")
217
218if config.have_zlib == "1":
219  config.available_features.add("zlib")
220
221# Use ugly construction to explicitly prohibit "clang", "clang++" etc.
222# in RUN lines.
223config.substitutions.append(
224    (' clang', """\n\n*** Do not use 'clangXXX' in tests,
225     instead define '%clangXXX' substitution in lit config. ***\n\n""") )
226
227if config.host_os == 'NetBSD':
228  nb_commands_dir = os.path.join(config.compiler_rt_src_root,
229                                 "test", "sanitizer_common", "netbsd_commands")
230  config.netbsd_noaslr_prefix = ('sh ' +
231                                 os.path.join(nb_commands_dir, 'run_noaslr.sh'))
232  config.netbsd_nomprotect_prefix = ('sh ' +
233                                     os.path.join(nb_commands_dir,
234                                                  'run_nomprotect.sh'))
235  config.substitutions.append( ('%run_nomprotect',
236                                config.netbsd_nomprotect_prefix) )
237else:
238  config.substitutions.append( ('%run_nomprotect', '%run') )
239
240# Copied from libcxx's config.py
241def get_lit_conf(name, default=None):
242    # Allow overriding on the command line using --param=<name>=<val>
243    val = lit_config.params.get(name, None)
244    if val is None:
245        val = getattr(config, name, None)
246        if val is None:
247            val = default
248    return val
249
250emulator = get_lit_conf('emulator', None)
251
252def get_ios_commands_dir():
253  return os.path.join(config.compiler_rt_src_root, "test", "sanitizer_common", "ios_commands")
254
255# Allow tests to be executed on a simulator or remotely.
256if emulator:
257  config.substitutions.append( ('%run', emulator) )
258  config.substitutions.append( ('%env ', "env ") )
259  # TODO: Implement `%device_rm` to perform removal of files in the emulator.
260  # For now just make it a no-op.
261  lit_config.warning('%device_rm is not implemented')
262  config.substitutions.append( ('%device_rm', 'echo ') )
263  config.compile_wrapper = ""
264elif config.host_os == 'Darwin' and config.apple_platform != "osx":
265  # Darwin tests can be targetting macOS, a device or a simulator. All devices
266  # are declared as "ios", even for iOS derivatives (tvOS, watchOS). Similarly,
267  # all simulators are "iossim". See the table below.
268  #
269  # =========================================================================
270  # Target             | Feature set
271  # =========================================================================
272  # macOS              | darwin
273  # iOS device         | darwin, ios
274  # iOS simulator      | darwin, ios, iossim
275  # tvOS device        | darwin, ios, tvos
276  # tvOS simulator     | darwin, ios, iossim, tvos, tvossim
277  # watchOS device     | darwin, ios, watchos
278  # watchOS simulator  | darwin, ios, iossim, watchos, watchossim
279  # =========================================================================
280
281  ios_or_iossim = "iossim" if config.apple_platform.endswith("sim") else "ios"
282
283  config.available_features.add('ios')
284  device_id_env = "SANITIZER_" + ios_or_iossim.upper() + "_TEST_DEVICE_IDENTIFIER"
285  if ios_or_iossim == "iossim":
286    config.available_features.add('iossim')
287    if device_id_env not in os.environ:
288      lit_config.fatal(
289        '{} must be set in the environment when running iossim tests'.format(
290          device_id_env))
291  if config.apple_platform != "ios" and config.apple_platform != "iossim":
292    config.available_features.add(config.apple_platform)
293
294  ios_commands_dir = get_ios_commands_dir()
295
296  run_wrapper = os.path.join(ios_commands_dir, ios_or_iossim + "_run.py")
297  env_wrapper = os.path.join(ios_commands_dir, ios_or_iossim + "_env.py")
298  compile_wrapper = os.path.join(ios_commands_dir, ios_or_iossim + "_compile.py")
299  prepare_script = os.path.join(ios_commands_dir, ios_or_iossim + "_prepare.py")
300
301  if device_id_env in os.environ:
302    config.environment[device_id_env] = os.environ[device_id_env]
303  config.substitutions.append(('%run', run_wrapper))
304  config.substitutions.append(('%env ', env_wrapper + " "))
305  # Current implementation of %device_rm uses the run_wrapper to do
306  # the work.
307  config.substitutions.append(('%device_rm', '{} rm '.format(run_wrapper)))
308  config.compile_wrapper = compile_wrapper
309
310  try:
311    prepare_output = subprocess.check_output([prepare_script, config.apple_platform, config.clang]).decode().strip()
312  except subprocess.CalledProcessError as e:
313    print("Command failed:")
314    print(e.output)
315    raise e
316  if len(prepare_output) > 0: print(prepare_output)
317  prepare_output_json = prepare_output.split("\n")[-1]
318  prepare_output = json.loads(prepare_output_json)
319  config.environment.update(prepare_output["env"])
320elif config.android:
321  config.available_features.add('android')
322  compile_wrapper = os.path.join(config.compiler_rt_src_root, "test", "sanitizer_common", "android_commands", "android_compile.py") + " "
323  config.compile_wrapper = compile_wrapper
324  config.substitutions.append( ('%run', "") )
325  config.substitutions.append( ('%env ', "env ") )
326else:
327  config.substitutions.append( ('%run', "") )
328  config.substitutions.append( ('%env ', "env ") )
329  # When running locally %device_rm is a no-op.
330  config.substitutions.append( ('%device_rm', 'echo ') )
331  config.compile_wrapper = ""
332
333# Define CHECK-%os to check for OS-dependent output.
334config.substitutions.append( ('CHECK-%os', ("CHECK-" + config.host_os)))
335
336# Define %arch to check for architecture-dependent output.
337config.substitutions.append( ('%arch', (config.host_arch)))
338
339if config.host_os == 'Windows':
340  # FIXME: This isn't quite right. Specifically, it will succeed if the program
341  # does not crash but exits with a non-zero exit code. We ought to merge
342  # KillTheDoctor and not --crash to make the latter more useful and remove the
343  # need for this substitution.
344  config.expect_crash = "not KillTheDoctor "
345else:
346  config.expect_crash = "not --crash "
347
348config.substitutions.append( ("%expect_crash ", config.expect_crash) )
349
350target_arch = getattr(config, 'target_arch', None)
351if target_arch:
352  config.available_features.add(target_arch + '-target-arch')
353  if target_arch in ['x86_64', 'i386']:
354    config.available_features.add('x86-target-arch')
355  config.available_features.add(target_arch + '-' + config.host_os.lower())
356
357compiler_rt_debug = getattr(config, 'compiler_rt_debug', False)
358if not compiler_rt_debug:
359  config.available_features.add('compiler-rt-optimized')
360
361libdispatch = getattr(config, 'compiler_rt_intercept_libdispatch', False)
362if libdispatch:
363  config.available_features.add('libdispatch')
364
365sanitizer_can_use_cxxabi = getattr(config, 'sanitizer_can_use_cxxabi', True)
366if sanitizer_can_use_cxxabi:
367  config.available_features.add('cxxabi')
368
369if not getattr(config, 'sanitizer_uses_static_cxxabi', False):
370  config.available_features.add('shared_cxxabi')
371
372if not getattr(config, 'sanitizer_uses_static_unwind', False):
373  config.available_features.add('shared_unwind')
374
375if config.has_lld:
376  config.available_features.add('lld-available')
377
378if config.use_lld:
379  config.available_features.add('lld')
380
381if config.can_symbolize:
382  config.available_features.add('can-symbolize')
383
384if config.gwp_asan:
385  config.available_features.add('gwp_asan')
386
387lit.util.usePlatformSdkOnDarwin(config, lit_config)
388
389min_macos_deployment_target_substitutions = [
390  (10, 11),
391  (10, 12),
392]
393# TLS requires watchOS 3+
394config.substitutions.append( ('%darwin_min_target_with_tls_support', '%min_macos_deployment_target=10.12') )
395
396if config.host_os == 'Darwin':
397  osx_version = (10, 0, 0)
398  try:
399    osx_version = subprocess.check_output(["sw_vers", "-productVersion"],
400                                          universal_newlines=True)
401    osx_version = tuple(int(x) for x in osx_version.split('.'))
402    if len(osx_version) == 2: osx_version = (osx_version[0], osx_version[1], 0)
403    if osx_version >= (10, 11):
404      config.available_features.add('osx-autointerception')
405      config.available_features.add('osx-ld64-live_support')
406    if osx_version >= (10, 15):
407      config.available_features.add('osx-swift-runtime')
408  except subprocess.CalledProcessError:
409    pass
410
411  config.darwin_osx_version = osx_version
412
413  # Detect x86_64h
414  try:
415    output = subprocess.check_output(["sysctl", "hw.cpusubtype"])
416    output_re = re.match("^hw.cpusubtype: ([0-9]+)$", output)
417    if output_re:
418      cpu_subtype = int(output_re.group(1))
419      if cpu_subtype == 8: # x86_64h
420        config.available_features.add('x86_64h')
421  except:
422    pass
423
424  # 32-bit iOS simulator is deprecated and removed in latest Xcode.
425  if config.apple_platform == "iossim":
426    if config.target_arch == "i386":
427      config.unsupported = True
428
429  def get_macos_aligned_version(macos_vers):
430    platform = config.apple_platform
431    if platform == 'osx':
432      return macos_vers
433
434    macos_major, macos_minor = macos_vers
435    assert macos_major >= 10
436
437    if macos_major == 10:  # macOS 10.x
438      major = macos_minor
439      minor = 0
440    else:                  # macOS 11+
441      major = macos_major + 5
442      minor = macos_minor
443
444    assert major >= 11
445
446    if platform.startswith('ios') or platform.startswith('tvos'):
447      major -= 2
448    elif platform.startswith('watch'):
449      major -= 9
450    else:
451      lit_config.fatal("Unsupported apple platform '{}'".format(platform))
452
453    return (major, minor)
454
455  for vers in min_macos_deployment_target_substitutions:
456    flag = config.apple_platform_min_deployment_target_flag
457    major, minor = get_macos_aligned_version(vers)
458    if 'mtargetos' in flag:
459      sim = '-simulator' if 'sim' in config.apple_platform else ''
460      config.substitutions.append( ('%%min_macos_deployment_target=%s.%s' % vers, '{}{}.{}{}'.format(flag, major, minor, sim)) )
461    else:
462      config.substitutions.append( ('%%min_macos_deployment_target=%s.%s' % vers, '{}={}.{}'.format(flag, major, minor)) )
463else:
464  for vers in min_macos_deployment_target_substitutions:
465    config.substitutions.append( ('%%min_macos_deployment_target=%s.%s' % vers, '') )
466
467if config.android:
468  env = os.environ.copy()
469  if config.android_serial:
470    env['ANDROID_SERIAL'] = config.android_serial
471    config.environment['ANDROID_SERIAL'] = config.android_serial
472
473  adb = os.environ.get('ADB', 'adb')
474
475  # These are needed for tests to upload/download temp files, such as
476  # suppression-files, to device.
477  config.substitutions.append( ('%device_rundir/', "/data/local/tmp/Output/") )
478  config.substitutions.append( ('%push_to_device', "%s -s '%s' push " % (adb, env['ANDROID_SERIAL']) ) )
479  config.substitutions.append( ('%adb_shell ', "%s -s '%s' shell " % (adb, env['ANDROID_SERIAL']) ) )
480  config.substitutions.append( ('%device_rm', "%s -s '%s' shell 'rm ' " % (adb, env['ANDROID_SERIAL']) ) )
481
482  try:
483    android_api_level_str = subprocess.check_output([adb, "shell", "getprop", "ro.build.version.sdk"], env=env).rstrip()
484    android_api_codename = subprocess.check_output([adb, "shell", "getprop", "ro.build.version.codename"], env=env).rstrip().decode("utf-8")
485  except (subprocess.CalledProcessError, OSError):
486    lit_config.fatal("Failed to read ro.build.version.sdk (using '%s' as adb)" % adb)
487  try:
488    android_api_level = int(android_api_level_str)
489  except ValueError:
490    lit_config.fatal("Failed to read ro.build.version.sdk (using '%s' as adb): got '%s'" % (adb, android_api_level_str))
491  android_api_level = min(android_api_level, int(config.android_api_level))
492  for required in [26, 28, 29, 30]:
493    if android_api_level >= required:
494      config.available_features.add('android-%s' % required)
495  # FIXME: Replace with appropriate version when availible.
496  if android_api_level > 30 or (android_api_level == 30 and android_api_codename == 'S'):
497    config.available_features.add('android-thread-properties-api')
498
499  # Prepare the device.
500  android_tmpdir = '/data/local/tmp/Output'
501  subprocess.check_call([adb, "shell", "mkdir", "-p", android_tmpdir], env=env)
502  for file in config.android_files_to_push:
503    subprocess.check_call([adb, "push", file, android_tmpdir], env=env)
504else:
505  config.substitutions.append( ('%device_rundir/', "") )
506  config.substitutions.append( ('%push_to_device', "echo ") )
507  config.substitutions.append( ('%adb_shell', "echo ") )
508
509if config.host_os == 'Linux':
510  # detect whether we are using glibc, and which version
511  # NB: 'ldd' is just one of the tools commonly installed as part of glibc/musl
512  ldd_ver_cmd = subprocess.Popen(['ldd', '--version'],
513                                 stdout=subprocess.PIPE,
514                                 stderr=subprocess.DEVNULL,
515                                 env={'LANG': 'C'})
516  sout, _ = ldd_ver_cmd.communicate()
517  ver_lines = sout.splitlines()
518  if not config.android and len(ver_lines) and ver_lines[0].startswith(b"ldd "):
519    from distutils.version import LooseVersion
520    ver = LooseVersion(ver_lines[0].split()[-1].decode())
521    for required in ["2.27", "2.30", "2.34"]:
522      if ver >= LooseVersion(required):
523        config.available_features.add("glibc-" + required)
524
525sancovcc_path = os.path.join(config.llvm_tools_dir, "sancov")
526if os.path.exists(sancovcc_path):
527  config.available_features.add("has_sancovcc")
528  config.substitutions.append( ("%sancovcc ", sancovcc_path) )
529
530def liblto_path():
531  return os.path.join(config.llvm_shlib_dir, 'libLTO.dylib')
532
533def is_darwin_lto_supported():
534  return os.path.exists(liblto_path())
535
536def is_binutils_lto_supported():
537  if not os.path.exists(os.path.join(config.llvm_shlib_dir, 'LLVMgold.so')):
538    return False
539
540  # We require both ld.bfd and ld.gold exist and support plugins. They are in
541  # the same repository 'binutils-gdb' and usually built together.
542  for exe in (config.gnu_ld_executable, config.gold_executable):
543    try:
544      ld_cmd = subprocess.Popen([exe, '--help'], stdout=subprocess.PIPE, env={'LANG': 'C'})
545      ld_out = ld_cmd.stdout.read().decode()
546      ld_cmd.wait()
547    except OSError:
548      return False
549    if not '-plugin' in ld_out:
550      return False
551
552  return True
553
554def is_windows_lto_supported():
555  return os.path.exists(os.path.join(config.llvm_tools_dir, 'lld-link.exe'))
556
557if config.host_os == 'Darwin' and is_darwin_lto_supported():
558  config.lto_supported = True
559  config.lto_flags = [ '-Wl,-lto_library,' + liblto_path() ]
560elif config.host_os in ['Linux', 'FreeBSD', 'NetBSD']:
561  config.lto_supported = False
562  if config.use_lld:
563    config.lto_supported = True
564  if is_binutils_lto_supported():
565    config.available_features.add('binutils_lto')
566    config.lto_supported = True
567
568  if config.lto_supported:
569    if config.use_lld:
570      config.lto_flags = ["-fuse-ld=lld"]
571    else:
572      config.lto_flags = ["-fuse-ld=gold"]
573elif config.host_os == 'Windows' and is_windows_lto_supported():
574  config.lto_supported = True
575  config.lto_flags = ["-fuse-ld=lld"]
576else:
577  config.lto_supported = False
578
579if config.lto_supported:
580  config.available_features.add('lto')
581  if config.use_thinlto:
582    config.available_features.add('thinlto')
583    config.lto_flags += ["-flto=thin"]
584  else:
585    config.lto_flags += ["-flto"]
586
587if config.have_rpc_xdr_h:
588  config.available_features.add('sunrpc')
589
590# Ask llvm-config about assertion mode.
591try:
592  llvm_config_cmd = subprocess.Popen(
593      [os.path.join(config.llvm_tools_dir, 'llvm-config'), '--assertion-mode'],
594      stdout = subprocess.PIPE,
595      env=config.environment)
596except OSError as e:
597  print("Could not launch llvm-config in " + config.llvm_tools_dir)
598  print("    Failed with error #{0}: {1}".format(e.errno, e.strerror))
599  exit(42)
600
601if re.search(r'ON', llvm_config_cmd.stdout.read().decode('ascii')):
602  config.available_features.add('asserts')
603llvm_config_cmd.wait()
604
605# Sanitizer tests tend to be flaky on Windows due to PR24554, so add some
606# retries. We don't do this on otther platforms because it's slower.
607if platform.system() == 'Windows':
608  config.test_retry_attempts = 2
609
610# No throttling on non-Darwin platforms.
611lit_config.parallelism_groups['shadow-memory'] = None
612
613if platform.system() == 'Darwin':
614  ios_device = config.apple_platform != 'osx' and not config.apple_platform.endswith('sim')
615  # Force sequential execution when running tests on iOS devices.
616  if ios_device:
617    lit_config.warning('Forcing sequential execution for iOS device tests')
618    lit_config.parallelism_groups['ios-device'] = 1
619    config.parallelism_group = 'ios-device'
620
621  # Only run up to 3 processes that require shadow memory simultaneously on
622  # 64-bit Darwin. Using more scales badly and hogs the system due to
623  # inefficient handling of large mmap'd regions (terabytes) by the kernel.
624  else:
625    lit_config.warning('Throttling sanitizer tests that require shadow memory on Darwin')
626    lit_config.parallelism_groups['shadow-memory'] = 3
627
628# Multiple substitutions are necessary to support multiple shared objects used
629# at once.
630# Note that substitutions with numbers have to be defined first to avoid
631# being subsumed by substitutions with smaller postfix.
632for postfix in ["2", "1", ""]:
633  if config.host_os == 'Darwin':
634    config.substitutions.append( ("%ld_flags_rpath_exe" + postfix, '-Wl,-rpath,@executable_path/ %dynamiclib' + postfix) )
635    config.substitutions.append( ("%ld_flags_rpath_so" + postfix, '-install_name @rpath/`basename %dynamiclib{}`'.format(postfix)) )
636  elif config.host_os in ('FreeBSD', 'NetBSD', 'OpenBSD'):
637    config.substitutions.append( ("%ld_flags_rpath_exe" + postfix, "-Wl,-z,origin -Wl,-rpath,\$ORIGIN -L%T -l%xdynamiclib_namespec" + postfix) )
638    config.substitutions.append( ("%ld_flags_rpath_so" + postfix, '') )
639  elif config.host_os == 'Linux':
640    config.substitutions.append( ("%ld_flags_rpath_exe" + postfix, "-Wl,-rpath,\$ORIGIN -L%T -l%xdynamiclib_namespec" + postfix) )
641    config.substitutions.append( ("%ld_flags_rpath_so" + postfix, '') )
642  elif config.host_os == 'SunOS':
643    config.substitutions.append( ("%ld_flags_rpath_exe" + postfix, "-Wl,-R\$ORIGIN -L%T -l%xdynamiclib_namespec" + postfix) )
644    config.substitutions.append( ("%ld_flags_rpath_so" + postfix, '') )
645
646  # Must be defined after the substitutions that use %dynamiclib.
647  config.substitutions.append( ("%dynamiclib" + postfix, '%T/%xdynamiclib_filename' + postfix) )
648  config.substitutions.append( ("%xdynamiclib_filename" + postfix, 'lib%xdynamiclib_namespec{}.so'.format(postfix)) )
649  config.substitutions.append( ("%xdynamiclib_namespec", '%basename_t.dynamic') )
650
651# Provide a substitution that can be used to tell Clang to use a static libstdc++.
652# The substitution expands to nothing on non Linux platforms.
653# FIXME: This should check the target OS, not the host OS.
654if config.host_os == 'Linux':
655  config.substitutions.append( ("%linux_static_libstdcplusplus", "-stdlib=libstdc++ -static-libstdc++") )
656else:
657  config.substitutions.append( ("%linux_static_libstdcplusplus", "") )
658
659config.default_sanitizer_opts = []
660if config.host_os == 'Darwin':
661  # On Darwin, we default to `abort_on_error=1`, which would make tests run
662  # much slower. Let's override this and run lit tests with 'abort_on_error=0'.
663  config.default_sanitizer_opts += ['abort_on_error=0']
664  config.default_sanitizer_opts += ['log_to_syslog=0']
665  if lit.util.which('log'):
666    # Querying the log can only done by a privileged user so
667    # so check if we can query the log.
668    exit_code = -1
669    with open('/dev/null', 'r') as f:
670      # Run a `log show` command the should finish fairly quickly and produce very little output.
671      exit_code = subprocess.call(['log', 'show', '--last', '1m', '--predicate', '1 == 0'], stdout=f, stderr=f)
672    if exit_code == 0:
673      config.available_features.add('darwin_log_cmd')
674    else:
675      lit_config.warning('log command found but cannot queried')
676  else:
677    lit_config.warning('log command not found. Some tests will be skipped.')
678elif config.android:
679  config.default_sanitizer_opts += ['abort_on_error=0']
680
681# Allow tests to use REQUIRES=stable-runtime.  For use when you cannot use XFAIL
682# because the test hangs or fails on one configuration and not the other.
683if config.android or (config.target_arch not in ['arm', 'armhf', 'aarch64']):
684  config.available_features.add('stable-runtime')
685
686if config.asan_shadow_scale:
687  config.available_features.add("shadow-scale-%s" % config.asan_shadow_scale)
688else:
689  config.available_features.add("shadow-scale-3")
690
691if config.memprof_shadow_scale:
692  config.available_features.add("memprof-shadow-scale-%s" % config.memprof_shadow_scale)
693else:
694  config.available_features.add("memprof-shadow-scale-3")
695
696if config.expensive_checks:
697  config.available_features.add("expensive_checks")
698
699# Propagate the LLD/LTO into the clang config option, so nothing else is needed.
700run_wrapper = []
701target_cflags = [getattr(config, 'target_cflags', None)]
702extra_cflags = []
703
704if config.use_lto and config.lto_supported:
705  extra_cflags += config.lto_flags
706elif config.use_lto and (not config.lto_supported):
707  config.unsupported = True
708
709if config.use_lld and config.has_lld and not config.use_lto:
710  extra_cflags += ["-fuse-ld=lld"]
711elif config.use_lld and (not config.has_lld):
712  config.unsupported = True
713
714# Append any extra flags passed in lit_config
715append_target_cflags = lit_config.params.get('append_target_cflags', None)
716if append_target_cflags:
717  lit_config.note('Appending to extra_cflags: "{}"'.format(append_target_cflags))
718  extra_cflags += [append_target_cflags]
719
720config.clang = " " + " ".join(run_wrapper + [config.compile_wrapper, config.clang]) + " "
721config.target_cflags = " " + " ".join(target_cflags + extra_cflags) + " "
722
723if config.host_os == 'Darwin':
724  config.substitutions.append((
725    "%get_pid_from_output",
726    "{} {}/get_pid_from_output.py".format(
727      sh_quote(config.python_executable),
728      sh_quote(get_ios_commands_dir())
729    ))
730  )
731  config.substitutions.append(
732    ("%print_crashreport_for_pid",
733    "{} {}/print_crashreport_for_pid.py".format(
734      sh_quote(config.python_executable),
735      sh_quote(get_ios_commands_dir())
736    ))
737  )
738