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