1from __future__ import absolute_import
2
3# System modules
4from distutils.version import LooseVersion
5from functools import wraps
6import os
7import platform
8import re
9import sys
10import tempfile
11import subprocess
12
13# Third-party modules
14import six
15import unittest2
16
17# LLDB modules
18import lldb
19from . import configuration
20from . import test_categories
21from . import lldbtest_config
22from lldbsuite.test_event.event_builder import EventBuilder
23from lldbsuite.support import funcutils
24from lldbsuite.test import lldbplatform
25from lldbsuite.test import lldbplatformutil
26
27
28class DecorateMode:
29    Skip, Xfail = range(2)
30
31
32# You can use no_match to reverse the test of the conditional that is used to match keyword
33# arguments in the skip / xfail decorators.  If oslist=["windows", "linux"] skips windows
34# and linux, oslist=no_match(["windows", "linux"]) skips *unless* windows
35# or linux.
36class no_match:
37
38    def __init__(self, item):
39        self.item = item
40
41
42def _check_expected_version(comparison, expected, actual):
43    def fn_leq(x, y): return x <= y
44
45    def fn_less(x, y): return x < y
46
47    def fn_geq(x, y): return x >= y
48
49    def fn_greater(x, y): return x > y
50
51    def fn_eq(x, y): return x == y
52
53    def fn_neq(x, y): return x != y
54
55    op_lookup = {
56        "==": fn_eq,
57        "=": fn_eq,
58        "!=": fn_neq,
59        "<>": fn_neq,
60        ">": fn_greater,
61        "<": fn_less,
62        ">=": fn_geq,
63        "<=": fn_leq
64    }
65    expected_str = '.'.join([str(x) for x in expected])
66    actual_str = '.'.join([str(x) for x in actual])
67
68    return op_lookup[comparison](
69        LooseVersion(actual_str),
70        LooseVersion(expected_str))
71
72
73_re_pattern_type = type(re.compile(''))
74def _match_decorator_property(expected, actual):
75    if actual is None or expected is None:
76        return True
77
78    if isinstance(expected, no_match):
79        return not _match_decorator_property(expected.item, actual)
80    elif isinstance(expected, (_re_pattern_type,) + six.string_types):
81        return re.search(expected, actual) is not None
82    elif hasattr(expected, "__iter__"):
83        return any([x is not None and _match_decorator_property(x, actual)
84                    for x in expected])
85    else:
86        return expected == actual
87
88
89def expectedFailure(expected_fn, bugnumber=None):
90    def expectedFailure_impl(func):
91        if isinstance(func, type) and issubclass(func, unittest2.TestCase):
92            raise Exception(
93                "Decorator can only be used to decorate a test method")
94
95        @wraps(func)
96        def wrapper(*args, **kwargs):
97            self = args[0]
98            if funcutils.requires_self(expected_fn):
99                xfail_reason = expected_fn(self)
100            else:
101                xfail_reason = expected_fn()
102            if xfail_reason is not None:
103                if configuration.results_formatter_object is not None:
104                    # Mark this test as expected to fail.
105                    configuration.results_formatter_object.handle_event(
106                        EventBuilder.event_for_mark_test_expected_failure(self))
107                xfail_func = unittest2.expectedFailure(func)
108                xfail_func(*args, **kwargs)
109            else:
110                func(*args, **kwargs)
111        return wrapper
112    # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows)
113    # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])).  When called
114    # the first way, the first argument will be the actual function because decorators are
115    # weird like that.  So this is basically a check that says "which syntax was the original
116    # function decorated with?"
117    if six.callable(bugnumber):
118        return expectedFailure_impl(bugnumber)
119    else:
120        return expectedFailure_impl
121
122
123def skipTestIfFn(expected_fn, bugnumber=None):
124    def skipTestIfFn_impl(func):
125        if isinstance(func, type) and issubclass(func, unittest2.TestCase):
126            raise Exception(
127                "@skipTestIfFn can only be used to decorate a test method")
128
129        @wraps(func)
130        def wrapper(*args, **kwargs):
131            self = args[0]
132            if funcutils.requires_self(expected_fn):
133                reason = expected_fn(self)
134            else:
135                reason = expected_fn()
136
137            if reason is not None:
138                self.skipTest(reason)
139            else:
140                func(*args, **kwargs)
141        return wrapper
142
143    # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows)
144    # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])).  When called
145    # the first way, the first argument will be the actual function because decorators are
146    # weird like that.  So this is basically a check that says "how was the
147    # decorator used"
148    if six.callable(bugnumber):
149        return skipTestIfFn_impl(bugnumber)
150    else:
151        return skipTestIfFn_impl
152
153
154def _decorateTest(mode,
155                  bugnumber=None, oslist=None, hostoslist=None,
156                  compiler=None, compiler_version=None,
157                  archs=None, triple=None,
158                  debug_info=None,
159                  swig_version=None, py_version=None,
160                  macos_version=None,
161                  remote=None, dwarf_version=None,
162                  setting=None):
163    def fn(self):
164        skip_for_os = _match_decorator_property(
165            lldbplatform.translate(oslist), self.getPlatform())
166        skip_for_hostos = _match_decorator_property(
167            lldbplatform.translate(hostoslist),
168            lldbplatformutil.getHostPlatform())
169        skip_for_compiler = _match_decorator_property(
170            compiler, self.getCompiler()) and self.expectedCompilerVersion(compiler_version)
171        skip_for_arch = _match_decorator_property(
172            archs, self.getArchitecture())
173        skip_for_debug_info = _match_decorator_property(
174            debug_info, self.getDebugInfo())
175        skip_for_triple = _match_decorator_property(
176            triple, lldb.selected_platform.GetTriple())
177        skip_for_remote = _match_decorator_property(
178            remote, lldb.remote_platform is not None)
179
180        skip_for_swig_version = (
181            swig_version is None) or (
182            not hasattr(
183                lldb,
184                'swig_version')) or (
185                _check_expected_version(
186                    swig_version[0],
187                    swig_version[1],
188                    lldb.swig_version))
189        skip_for_py_version = (
190            py_version is None) or _check_expected_version(
191            py_version[0], py_version[1], sys.version_info)
192        skip_for_macos_version = (macos_version is None) or (
193            (platform.mac_ver()[0] != "") and (_check_expected_version(
194                macos_version[0],
195                macos_version[1],
196                platform.mac_ver()[0])))
197        skip_for_dwarf_version = (dwarf_version is None) or (
198            _check_expected_version(dwarf_version[0], dwarf_version[1],
199                                    self.getDwarfVersion()))
200        skip_for_setting = (setting is None) or (
201            setting in configuration.settings)
202
203        # For the test to be skipped, all specified (e.g. not None) parameters must be True.
204        # An unspecified parameter means "any", so those are marked skip by default.  And we skip
205        # the final test if all conditions are True.
206        conditions = [(oslist, skip_for_os, "target o/s"),
207                      (hostoslist, skip_for_hostos, "host o/s"),
208                      (compiler, skip_for_compiler, "compiler or version"),
209                      (archs, skip_for_arch, "architecture"),
210                      (debug_info, skip_for_debug_info, "debug info format"),
211                      (triple, skip_for_triple, "target triple"),
212                      (swig_version, skip_for_swig_version, "swig version"),
213                      (py_version, skip_for_py_version, "python version"),
214                      (macos_version, skip_for_macos_version, "macOS version"),
215                      (remote, skip_for_remote, "platform locality (remote/local)"),
216                      (dwarf_version, skip_for_dwarf_version, "dwarf version"),
217                      (setting, skip_for_setting, "setting")]
218        reasons = []
219        final_skip_result = True
220        for this_condition in conditions:
221            final_skip_result = final_skip_result and this_condition[1]
222            if this_condition[0] is not None and this_condition[1]:
223                reasons.append(this_condition[2])
224        reason_str = None
225        if final_skip_result:
226            mode_str = {
227                DecorateMode.Skip: "skipping",
228                DecorateMode.Xfail: "xfailing"}[mode]
229            if len(reasons) > 0:
230                reason_str = ",".join(reasons)
231                reason_str = "{} due to the following parameter(s): {}".format(
232                    mode_str, reason_str)
233            else:
234                reason_str = "{} unconditionally"
235            if bugnumber is not None and not six.callable(bugnumber):
236                reason_str = reason_str + " [" + str(bugnumber) + "]"
237        return reason_str
238
239    if mode == DecorateMode.Skip:
240        return skipTestIfFn(fn, bugnumber)
241    elif mode == DecorateMode.Xfail:
242        return expectedFailure(fn, bugnumber)
243    else:
244        return None
245
246# provide a function to xfail on defined oslist, compiler version, and archs
247# if none is specified for any argument, that argument won't be checked and thus means for all
248# for example,
249# @expectedFailureAll, xfail for all platform/compiler/arch,
250# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
251# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
252
253
254def expectedFailureAll(bugnumber=None,
255                       oslist=None, hostoslist=None,
256                       compiler=None, compiler_version=None,
257                       archs=None, triple=None,
258                       debug_info=None,
259                       swig_version=None, py_version=None,
260                       macos_version=None,
261                       remote=None, dwarf_version=None,
262                       setting=None):
263    return _decorateTest(DecorateMode.Xfail,
264                         bugnumber=bugnumber,
265                         oslist=oslist, hostoslist=hostoslist,
266                         compiler=compiler, compiler_version=compiler_version,
267                         archs=archs, triple=triple,
268                         debug_info=debug_info,
269                         swig_version=swig_version, py_version=py_version,
270                         macos_version=None,
271                         remote=remote,dwarf_version=dwarf_version,
272                         setting=setting)
273
274
275# provide a function to skip on defined oslist, compiler version, and archs
276# if none is specified for any argument, that argument won't be checked and thus means for all
277# for example,
278# @skipIf, skip for all platform/compiler/arch,
279# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
280# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
281def skipIf(bugnumber=None,
282           oslist=None, hostoslist=None,
283           compiler=None, compiler_version=None,
284           archs=None, triple=None,
285           debug_info=None,
286           swig_version=None, py_version=None,
287           macos_version=None,
288           remote=None, dwarf_version=None,
289           setting=None):
290    return _decorateTest(DecorateMode.Skip,
291                         bugnumber=bugnumber,
292                         oslist=oslist, hostoslist=hostoslist,
293                         compiler=compiler, compiler_version=compiler_version,
294                         archs=archs, triple=triple,
295                         debug_info=debug_info,
296                         swig_version=swig_version, py_version=py_version,
297                         macos_version=macos_version,
298                         remote=remote, dwarf_version=dwarf_version,
299                         setting=setting)
300
301
302def _skip_for_android(reason, api_levels, archs):
303    def impl(obj):
304        result = lldbplatformutil.match_android_device(
305            obj.getArchitecture(), valid_archs=archs, valid_api_levels=api_levels)
306        return reason if result else None
307    return impl
308
309
310def add_test_categories(cat):
311    """Add test categories to a TestCase method"""
312    cat = test_categories.validate(cat, True)
313
314    def impl(func):
315        if isinstance(func, type) and issubclass(func, unittest2.TestCase):
316            raise Exception(
317                "@add_test_categories can only be used to decorate a test method")
318        try:
319            if hasattr(func, "categories"):
320                cat.extend(func.categories)
321            setattr(func, "categories", cat)
322        except AttributeError:
323            raise Exception('Cannot assign categories to inline tests.')
324
325        return func
326
327    return impl
328
329
330def benchmarks_test(func):
331    """Decorate the item as a benchmarks test."""
332    def should_skip_benchmarks_test():
333        return "benchmarks test"
334
335    # Mark this function as such to separate them from the regular tests.
336    result = skipTestIfFn(should_skip_benchmarks_test)(func)
337    result.__benchmarks_test__ = True
338    return result
339
340
341def no_debug_info_test(func):
342    """Decorate the item as a test what don't use any debug info. If this annotation is specified
343       then the test runner won't generate a separate test for each debug info format. """
344    if isinstance(func, type) and issubclass(func, unittest2.TestCase):
345        raise Exception(
346            "@no_debug_info_test can only be used to decorate a test method")
347
348    @wraps(func)
349    def wrapper(self, *args, **kwargs):
350        return func(self, *args, **kwargs)
351
352    # Mark this function as such to separate them from the regular tests.
353    wrapper.__no_debug_info_test__ = True
354    return wrapper
355
356def apple_simulator_test(platform):
357    """
358    Decorate the test as a test requiring a simulator for a specific platform.
359
360    Consider that a simulator is available if you have the corresponding SDK installed.
361    The SDK identifiers for simulators are iphonesimulator, appletvsimulator, watchsimulator
362    """
363    def should_skip_simulator_test():
364        if lldbplatformutil.getHostPlatform() != 'darwin':
365            return "simulator tests are run only on darwin hosts"
366        try:
367            DEVNULL = open(os.devnull, 'w')
368            output = subprocess.check_output(["xcodebuild", "-showsdks"], stderr=DEVNULL).decode("utf-8")
369            if re.search('%ssimulator' % platform, output):
370                return None
371            else:
372                return "%s simulator is not supported on this system." % platform
373        except subprocess.CalledProcessError:
374            return "Simulators are unsupported on this system (xcodebuild failed)"
375
376    return skipTestIfFn(should_skip_simulator_test)
377
378
379def debugserver_test(func):
380    """Decorate the item as a debugserver test."""
381    def should_skip_debugserver_test():
382        return "debugserver tests" if configuration.dont_do_debugserver_test else None
383    return skipTestIfFn(should_skip_debugserver_test)(func)
384
385
386def llgs_test(func):
387    """Decorate the item as a lldb-server test."""
388    def should_skip_llgs_tests():
389        return "llgs tests" if configuration.dont_do_llgs_test else None
390    return skipTestIfFn(should_skip_llgs_tests)(func)
391
392
393def not_remote_testsuite_ready(func):
394    """Decorate the item as a test which is not ready yet for remote testsuite."""
395    def is_remote():
396        return "Not ready for remote testsuite" if lldb.remote_platform else None
397    return skipTestIfFn(is_remote)(func)
398
399
400def expectedFailureOS(
401        oslist,
402        bugnumber=None,
403        compilers=None,
404        debug_info=None,
405        archs=None):
406    return expectedFailureAll(
407        oslist=oslist,
408        bugnumber=bugnumber,
409        compiler=compilers,
410        archs=archs,
411        debug_info=debug_info)
412
413
414def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
415    # For legacy reasons, we support both "darwin" and "macosx" as OS X
416    # triples.
417    return expectedFailureOS(
418        lldbplatform.darwin_all,
419        bugnumber,
420        compilers,
421        debug_info=debug_info)
422
423
424def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
425    """ Mark a test as xfail for Android.
426
427    Arguments:
428        bugnumber - The LLVM pr associated with the problem.
429        api_levels - A sequence of numbers specifying the Android API levels
430            for which a test is expected to fail. None means all API level.
431        arch - A sequence of architecture names specifying the architectures
432            for which a test is expected to fail. None means all architectures.
433    """
434    return expectedFailure(
435        _skip_for_android(
436            "xfailing on android",
437            api_levels,
438            archs),
439        bugnumber)
440
441
442def expectedFailureNetBSD(bugnumber=None):
443    return expectedFailureOS(
444        ['netbsd'],
445        bugnumber)
446
447# Flakey tests get two chances to run. If they fail the first time round, the result formatter
448# makes sure it is run one more time.
449
450
451def expectedFlakey(expected_fn, bugnumber=None):
452    def expectedFailure_impl(func):
453        @wraps(func)
454        def wrapper(*args, **kwargs):
455            self = args[0]
456            if expected_fn(self):
457                # Send event marking test as explicitly eligible for rerunning.
458                if configuration.results_formatter_object is not None:
459                    # Mark this test as rerunnable.
460                    configuration.results_formatter_object.handle_event(
461                        EventBuilder.event_for_mark_test_rerun_eligible(self))
462            func(*args, **kwargs)
463        return wrapper
464    # Some decorators can be called both with no arguments (e.g. @expectedFailureWindows)
465    # or with arguments (e.g. @expectedFailureWindows(compilers=['gcc'])).  When called
466    # the first way, the first argument will be the actual function because decorators are
467    # weird like that.  So this is basically a check that says "which syntax was the original
468    # function decorated with?"
469    if six.callable(bugnumber):
470        return expectedFailure_impl(bugnumber)
471    else:
472        return expectedFailure_impl
473
474
475def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
476    def fn(self):
477        return (self.getPlatform() in oslist and
478                self.expectedCompiler(compilers))
479    return expectedFlakey(fn, bugnumber)
480
481
482def expectedFlakeyDarwin(bugnumber=None, compilers=None):
483    # For legacy reasons, we support both "darwin" and "macosx" as OS X
484    # triples.
485    return expectedFlakeyOS(
486        lldbplatformutil.getDarwinOSTriples(),
487        bugnumber,
488        compilers)
489
490
491def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
492    return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
493
494
495def expectedFlakeyLinux(bugnumber=None, compilers=None):
496    return expectedFlakeyOS(['linux'], bugnumber, compilers)
497
498
499def expectedFlakeyNetBSD(bugnumber=None, compilers=None):
500    return expectedFlakeyOS(['netbsd'], bugnumber, compilers)
501
502
503def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
504    return expectedFlakey(
505        _skip_for_android(
506            "flakey on android",
507            api_levels,
508            archs),
509        bugnumber)
510
511def skipIfOutOfTreeDebugserver(func):
512    """Decorate the item to skip tests if using an out-of-tree debugserver."""
513    def is_out_of_tree_debugserver():
514        return "out-of-tree debugserver" if lldbtest_config.out_of_tree_debugserver else None
515    return skipTestIfFn(is_out_of_tree_debugserver)(func)
516
517def skipIfRemote(func):
518    """Decorate the item to skip tests if testing remotely."""
519    def is_remote():
520        return "skip on remote platform" if lldb.remote_platform else None
521    return skipTestIfFn(is_remote)(func)
522
523
524def skipIfNoSBHeaders(func):
525    """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
526    def are_sb_headers_missing():
527        if lldb.remote_platform:
528            return "skip because SBHeaders tests make no sense remotely"
529
530        if lldbplatformutil.getHostPlatform() == 'darwin':
531            header = os.path.join(
532                os.environ["LLDB_LIB_DIR"],
533                'LLDB.framework',
534                'Versions',
535                'Current',
536                'Headers',
537                'LLDB.h')
538            if os.path.exists(header):
539                return None
540
541        header = os.path.join(
542            os.environ["LLDB_SRC"],
543            "include",
544            "lldb",
545            "API",
546            "LLDB.h")
547        if not os.path.exists(header):
548            return "skip because LLDB.h header not found"
549        return None
550
551    return skipTestIfFn(are_sb_headers_missing)(func)
552
553
554def skipIfiOSSimulator(func):
555    """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
556    def is_ios_simulator():
557        return "skip on the iOS Simulator" if configuration.lldb_platform_name == 'ios-simulator' else None
558    return skipTestIfFn(is_ios_simulator)(func)
559
560def skipIfiOS(func):
561    return skipIfPlatform(["ios"])(func)
562
563def skipIftvOS(func):
564    return skipIfPlatform(["tvos"])(func)
565
566def skipIfwatchOS(func):
567    return skipIfPlatform(["watchos"])(func)
568
569def skipIfbridgeOS(func):
570    return skipIfPlatform(["bridgeos"])(func)
571
572def skipIfDarwinEmbedded(func):
573    """Decorate the item to skip tests that should be skipped on Darwin armv7/arm64 targets."""
574    return skipIfPlatform(
575        lldbplatform.translate(
576            lldbplatform.darwin_embedded))(func)
577
578def skipIfFreeBSD(func):
579    """Decorate the item to skip tests that should be skipped on FreeBSD."""
580    return skipIfPlatform(["freebsd"])(func)
581
582
583def skipIfNetBSD(func):
584    """Decorate the item to skip tests that should be skipped on NetBSD."""
585    return skipIfPlatform(["netbsd"])(func)
586
587
588def skipIfDarwin(func):
589    """Decorate the item to skip tests that should be skipped on Darwin."""
590    return skipIfPlatform(
591        lldbplatform.translate(
592            lldbplatform.darwin_all))(func)
593
594
595def skipIfLinux(func):
596    """Decorate the item to skip tests that should be skipped on Linux."""
597    return skipIfPlatform(["linux"])(func)
598
599
600def skipIfWindows(func):
601    """Decorate the item to skip tests that should be skipped on Windows."""
602    return skipIfPlatform(["windows"])(func)
603
604def skipUnlessWindows(func):
605    """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
606    return skipUnlessPlatform(["windows"])(func)
607
608
609def skipUnlessDarwin(func):
610    """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
611    return skipUnlessPlatform(lldbplatformutil.getDarwinOSTriples())(func)
612
613def skipUnlessTargetAndroid(func):
614    return unittest2.skipUnless(lldbplatformutil.target_is_android(),
615                                "requires target to be Android")(func)
616
617
618def skipIfHostIncompatibleWithRemote(func):
619    """Decorate the item to skip tests if binaries built on this host are incompatible."""
620
621    def is_host_incompatible_with_remote(self):
622        host_arch = self.getLldbArchitecture()
623        host_platform = lldbplatformutil.getHostPlatform()
624        target_arch = self.getArchitecture()
625        target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
626        if not (target_arch == 'x86_64' and host_arch ==
627                'i386') and host_arch != target_arch:
628            return "skipping because target %s is not compatible with host architecture %s" % (
629                target_arch, host_arch)
630        if target_platform != host_platform:
631            return "skipping because target is %s but host is %s" % (
632                target_platform, host_platform)
633        if lldbplatformutil.match_android_device(target_arch):
634            return "skipping because target is android"
635        return None
636    return skipTestIfFn(is_host_incompatible_with_remote)(func)
637
638
639def skipIfPlatform(oslist):
640    """Decorate the item to skip tests if running on one of the listed platforms."""
641    # This decorator cannot be ported to `skipIf` yet because it is used on entire
642    # classes, which `skipIf` explicitly forbids.
643    return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist,
644                            "skip on %s" % (", ".join(oslist)))
645
646
647def skipUnlessPlatform(oslist):
648    """Decorate the item to skip tests unless running on one of the listed platforms."""
649    # This decorator cannot be ported to `skipIf` yet because it is used on entire
650    # classes, which `skipIf` explicitly forbids.
651    return unittest2.skipUnless(lldbplatformutil.getPlatform() in oslist,
652                                "requires one of %s" % (", ".join(oslist)))
653
654def skipUnlessArch(arch):
655    """Decorate the item to skip tests unless running on the specified architecture."""
656
657    def arch_doesnt_match(self):
658        target_arch = self.getArchitecture()
659        if arch != target_arch:
660            return "Test only runs on " + arch + ", but target arch is " + target_arch
661        return None
662
663    return skipTestIfFn(arch_doesnt_match)
664
665def skipIfTargetAndroid(bugnumber=None, api_levels=None, archs=None):
666    """Decorator to skip tests when the target is Android.
667
668    Arguments:
669        api_levels - The API levels for which the test should be skipped. If
670            it is None, then the test will be skipped for all API levels.
671        arch - A sequence of architecture names specifying the architectures
672            for which a test is skipped. None means all architectures.
673    """
674    return skipTestIfFn(
675        _skip_for_android(
676            "skipping for android",
677            api_levels,
678            archs),
679        bugnumber)
680
681def skipUnlessSupportedTypeAttribute(attr):
682    """Decorate the item to skip test unless Clang supports type __attribute__(attr)."""
683    def compiler_doesnt_support_struct_attribute(self):
684        compiler_path = self.getCompiler()
685        f = tempfile.NamedTemporaryFile()
686        cmd = [self.getCompiler(), "-x", "c++", "-c", "-o", f.name, "-"]
687        p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
688        stdout, stderr = p.communicate('struct __attribute__((%s)) Test {};'%attr)
689        if attr in stderr:
690            return "Compiler does not support attribute %s"%(attr)
691        return None
692    return skipTestIfFn(compiler_doesnt_support_struct_attribute)
693
694def skipUnlessHasCallSiteInfo(func):
695    """Decorate the function to skip testing unless call site info from clang is available."""
696
697    def is_compiler_clang_with_call_site_info(self):
698        compiler_path = self.getCompiler()
699        compiler = os.path.basename(compiler_path)
700        if not compiler.startswith("clang"):
701            return "Test requires clang as compiler"
702
703        f = tempfile.NamedTemporaryFile()
704        cmd = "echo 'int main() {}' | " \
705              "%s -g -glldb -O1 -S -emit-llvm -x c -o %s -" % (compiler_path, f.name)
706        if os.popen(cmd).close() is not None:
707            return "Compiler can't compile with call site info enabled"
708
709        with open(f.name, 'r') as ir_output_file:
710            buf = ir_output_file.read()
711
712        if 'DIFlagAllCallsDescribed' not in buf:
713            return "Compiler did not introduce DIFlagAllCallsDescribed IR flag"
714
715        return None
716    return skipTestIfFn(is_compiler_clang_with_call_site_info)(func)
717
718def skipUnlessThreadSanitizer(func):
719    """Decorate the item to skip test unless Clang -fsanitize=thread is supported."""
720
721    def is_compiler_clang_with_thread_sanitizer(self):
722        if is_running_under_asan():
723            return "Thread sanitizer tests are disabled when runing under ASAN"
724
725        compiler_path = self.getCompiler()
726        compiler = os.path.basename(compiler_path)
727        if not compiler.startswith("clang"):
728            return "Test requires clang as compiler"
729        if lldbplatformutil.getPlatform() == 'windows':
730            return "TSAN tests not compatible with 'windows'"
731        # rdar://28659145 - TSAN tests don't look like they're supported on i386
732        if self.getArchitecture() == 'i386' and platform.system() == 'Darwin':
733            return "TSAN tests not compatible with i386 targets"
734        f = tempfile.NamedTemporaryFile()
735        cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name)
736        if os.popen(cmd).close() is not None:
737            return None  # The compiler cannot compile at all, let's *not* skip the test
738        cmd = "echo 'int main() {}' | %s -fsanitize=thread -x c -o %s -" % (compiler_path, f.name)
739        if os.popen(cmd).close() is not None:
740            return "Compiler cannot compile with -fsanitize=thread"
741        return None
742    return skipTestIfFn(is_compiler_clang_with_thread_sanitizer)(func)
743
744def skipUnlessUndefinedBehaviorSanitizer(func):
745    """Decorate the item to skip test unless -fsanitize=undefined is supported."""
746
747    def is_compiler_clang_with_ubsan(self):
748        if is_running_under_asan():
749            return "Undefined behavior sanitizer tests are disabled when runing under ASAN"
750
751        # Write out a temp file which exhibits UB.
752        inputf = tempfile.NamedTemporaryFile(suffix='.c', mode='w')
753        inputf.write('int main() { int x = 0; return x / x; }\n')
754        inputf.flush()
755
756        # We need to write out the object into a named temp file for inspection.
757        outputf = tempfile.NamedTemporaryFile()
758
759        # Try to compile with ubsan turned on.
760        cmd = '%s -fsanitize=undefined %s -o %s' % (self.getCompiler(), inputf.name, outputf.name)
761        if os.popen(cmd).close() is not None:
762            return "Compiler cannot compile with -fsanitize=undefined"
763
764        # Check that we actually see ubsan instrumentation in the binary.
765        cmd = 'nm %s' % outputf.name
766        with os.popen(cmd) as nm_output:
767            if '___ubsan_handle_divrem_overflow' not in nm_output.read():
768                return "Division by zero instrumentation is missing"
769
770        # Find the ubsan dylib.
771        # FIXME: This check should go away once compiler-rt gains support for __ubsan_on_report.
772        cmd = '%s -fsanitize=undefined -x c - -o - -### 2>&1' % self.getCompiler()
773        with os.popen(cmd) as cc_output:
774            driver_jobs = cc_output.read()
775            m = re.search(r'"([^"]+libclang_rt.ubsan_osx_dynamic.dylib)"', driver_jobs)
776            if not m:
777                return "Could not find the ubsan dylib used by the driver"
778            ubsan_dylib = m.group(1)
779
780        # Check that the ubsan dylib has special monitor hooks.
781        cmd = 'nm -gU %s' % ubsan_dylib
782        with os.popen(cmd) as nm_output:
783            syms = nm_output.read()
784            if '___ubsan_on_report' not in syms:
785                return "Missing ___ubsan_on_report"
786            if '___ubsan_get_current_report_data' not in syms:
787                return "Missing ___ubsan_get_current_report_data"
788
789        # OK, this dylib + compiler works for us.
790        return None
791
792    return skipTestIfFn(is_compiler_clang_with_ubsan)(func)
793
794def is_running_under_asan():
795    if ('ASAN_OPTIONS' in os.environ):
796        return "ASAN unsupported"
797    return None
798
799def skipUnlessAddressSanitizer(func):
800    """Decorate the item to skip test unless Clang -fsanitize=thread is supported."""
801
802    def is_compiler_with_address_sanitizer(self):
803        # Also don't run tests that use address sanitizer inside an
804        # address-sanitized LLDB. The tests don't support that
805        # configuration.
806        if is_running_under_asan():
807            return "Address sanitizer tests are disabled when runing under ASAN"
808
809        compiler_path = self.getCompiler()
810        compiler = os.path.basename(compiler_path)
811        f = tempfile.NamedTemporaryFile()
812        if lldbplatformutil.getPlatform() == 'windows':
813            return "ASAN tests not compatible with 'windows'"
814        cmd = "echo 'int main() {}' | %s -x c -o %s -" % (compiler_path, f.name)
815        if os.popen(cmd).close() is not None:
816            return None  # The compiler cannot compile at all, let's *not* skip the test
817        cmd = "echo 'int main() {}' | %s -fsanitize=address -x c -o %s -" % (compiler_path, f.name)
818        if os.popen(cmd).close() is not None:
819            return "Compiler cannot compile with -fsanitize=address"
820        return None
821    return skipTestIfFn(is_compiler_with_address_sanitizer)(func)
822
823def skipIfAsan(func):
824    """Skip this test if the environment is set up to run LLDB *itself* under ASAN."""
825    return skipTestIfFn(is_running_under_asan)(func)
826
827def _get_bool_config_skip_if_decorator(key):
828    config = lldb.SBDebugger.GetBuildConfiguration()
829    value_node = config.GetValueForKey(key)
830    fail_value = True # More likely to notice if something goes wrong
831    have = value_node.GetValueForKey("value").GetBooleanValue(fail_value)
832    return unittest2.skipIf(not have, "requires " + key)
833
834def skipIfCursesSupportMissing(func):
835    return _get_bool_config_skip_if_decorator("curses")(func)
836
837def skipIfXmlSupportMissing(func):
838    return _get_bool_config_skip_if_decorator("xml")(func)
839
840def skipIfEditlineSupportMissing(func):
841    return _get_bool_config_skip_if_decorator("editline")(func)
842
843def skipIfLLVMTargetMissing(target):
844    config = lldb.SBDebugger.GetBuildConfiguration()
845    targets = config.GetValueForKey("targets").GetValueForKey("value")
846    found = False
847    for i in range(targets.GetSize()):
848        if targets.GetItemAtIndex(i).GetStringValue(99) == target:
849            found = True
850            break
851
852    return unittest2.skipIf(not found, "requires " + target)
853
854# Call sysctl on darwin to see if a specified hardware feature is available on this machine.
855def skipUnlessFeature(feature):
856    def is_feature_enabled(self):
857        if platform.system() == 'Darwin':
858            try:
859                DEVNULL = open(os.devnull, 'w')
860                output = subprocess.check_output(["/usr/sbin/sysctl", feature], stderr=DEVNULL).decode("utf-8")
861                # If 'feature: 1' was output, then this feature is available and
862                # the test should not be skipped.
863                if re.match('%s: 1\s*' % feature, output):
864                    return None
865                else:
866                    return "%s is not supported on this system." % feature
867            except subprocess.CalledProcessError:
868                return "%s is not supported on this system." % feature
869    return skipTestIfFn(is_feature_enabled)
870
871def skipIfReproducer(func):
872    """Skip this test if the environment is set up to run LLDB with reproducers."""
873    def is_reproducer():
874        if configuration.capture_path or configuration.replay_path:
875            return "reproducers unsupported"
876        return None
877    return skipTestIfFn(is_reproducer)(func)
878