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