1""" 2A simple testing framework for lldb using python's unit testing framework. 3 4Tests for lldb are written as python scripts which take advantage of the script 5bridging provided by LLDB.framework to interact with lldb core. 6 7A specific naming pattern is followed by the .py script to be recognized as 8a module which implements a test scenario, namely, Test*.py. 9 10To specify the directories where "Test*.py" python test scripts are located, 11you need to pass in a list of directory names. By default, the current 12working directory is searched if nothing is specified on the command line. 13 14Type: 15 16./dotest.py -h 17 18for available options. 19""" 20 21from __future__ import absolute_import 22from __future__ import print_function 23 24# System modules 25import atexit 26import os 27import errno 28import platform 29import signal 30import socket 31import subprocess 32import sys 33 34# Third-party modules 35import six 36import unittest2 37 38# LLDB Modules 39import lldbsuite 40from . import configuration 41from . import dotest_args 42from . import lldbtest_config 43from . import test_categories 44from lldbsuite.test_event import formatter 45from . import test_result 46from lldbsuite.test_event.event_builder import EventBuilder 47from ..support import seven 48 49def is_exe(fpath): 50 """Returns true if fpath is an executable.""" 51 return os.path.isfile(fpath) and os.access(fpath, os.X_OK) 52 53def which(program): 54 """Returns the full path to a program; None otherwise.""" 55 fpath, fname = os.path.split(program) 56 if fpath: 57 if is_exe(program): 58 return program 59 else: 60 for path in os.environ["PATH"].split(os.pathsep): 61 exe_file = os.path.join(path, program) 62 if is_exe(exe_file): 63 return exe_file 64 return None 65 66class _WritelnDecorator(object): 67 """Used to decorate file-like objects with a handy 'writeln' method""" 68 def __init__(self,stream): 69 self.stream = stream 70 71 def __getattr__(self, attr): 72 if attr in ('stream', '__getstate__'): 73 raise AttributeError(attr) 74 return getattr(self.stream,attr) 75 76 def writeln(self, arg=None): 77 if arg: 78 self.write(arg) 79 self.write('\n') # text-mode streams translate to \r\n if needed 80 81# 82# Global variables: 83# 84def usage(parser): 85 parser.print_help() 86 if configuration.verbose > 0: 87 print(""" 88Examples: 89 90This is an example of using the -f option to pinpoint to a specific test class 91and test method to be run: 92 93$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command 94---------------------------------------------------------------------- 95Collected 1 test 96 97test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase) 98Test 'frame variable this' when stopped on a class constructor. ... ok 99 100---------------------------------------------------------------------- 101Ran 1 test in 1.396s 102 103OK 104 105And this is an example of using the -p option to run a single file (the filename 106matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'): 107 108$ ./dotest.py -v -p ObjC 109---------------------------------------------------------------------- 110Collected 4 tests 111 112test_break_with_dsym (TestObjCMethods.FoundationTestCase) 113Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok 114test_break_with_dwarf (TestObjCMethods.FoundationTestCase) 115Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok 116test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase) 117Lookup objective-c data types and evaluate expressions. ... ok 118test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase) 119Lookup objective-c data types and evaluate expressions. ... ok 120 121---------------------------------------------------------------------- 122Ran 4 tests in 16.661s 123 124OK 125 126Running of this script also sets up the LLDB_TEST environment variable so that 127individual test cases can locate their supporting files correctly. The script 128tries to set up Python's search paths for modules by looking at the build tree 129relative to this script. See also the '-i' option in the following example. 130 131Finally, this is an example of using the lldb.py module distributed/installed by 132Xcode4 to run against the tests under the 'forward' directory, and with the '-w' 133option to add some delay between two tests. It uses ARCH=x86_64 to specify that 134as the architecture and CC=clang to specify the compiler used for the test run: 135 136$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward 137 138Session logs for test failures/errors will go into directory '2010-11-11-13_56_16' 139---------------------------------------------------------------------- 140Collected 2 tests 141 142test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase) 143Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok 144test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase) 145Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok 146 147---------------------------------------------------------------------- 148Ran 2 tests in 5.659s 149 150OK 151 152The 'Session ...' verbiage is recently introduced (see also the '-s' option) to 153notify the directory containing the session logs for test failures or errors. 154In case there is any test failure/error, a similar message is appended at the 155end of the stderr output for your convenience. 156 157ENABLING LOGS FROM TESTS 158 159Option 1: 160 161Writing logs into different files per test case:: 162 163This option is particularly useful when multiple dotest instances are created 164by dosep.py 165 166$ ./dotest.py --channel "lldb all" 167 168$ ./dotest.py --channel "lldb all" --channel "gdb-remote packets" 169 170These log files are written to: 171 172<session-dir>/<test-id>-host.log (logs from lldb host process) 173<session-dir>/<test-id>-server.log (logs from debugserver/lldb-server) 174<session-dir>/<test-id>-<test-result>.log (console logs) 175 176By default, logs from successful runs are deleted. Use the --log-success flag 177to create reference logs for debugging. 178 179$ ./dotest.py --log-success 180 181Option 2: (DEPRECATED) 182 183The following options can only enable logs from the host lldb process. 184Only categories from the "lldb" or "gdb-remote" channels can be enabled 185They also do not automatically enable logs in locally running debug servers. 186Also, logs from all test case are written into each log file 187 188o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem 189 with a default option of 'event process' if LLDB_LOG_OPTION is not defined. 190 191o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the 192 'process.gdb-remote' subsystem with a default option of 'packets' if 193 GDB_REMOTE_LOG_OPTION is not defined. 194 195""") 196 sys.exit(0) 197 198def parseOptionsAndInitTestdirs(): 199 """Initialize the list of directories containing our unittest scripts. 200 201 '-h/--help as the first option prints out usage info and exit the program. 202 """ 203 204 do_help = False 205 206 platform_system = platform.system() 207 platform_machine = platform.machine() 208 209 parser = dotest_args.create_parser() 210 args = dotest_args.parse_args(parser, sys.argv[1:]) 211 212 if args.unset_env_varnames: 213 for env_var in args.unset_env_varnames: 214 if env_var in os.environ: 215 # From Python Doc: When unsetenv() is supported, deletion of items in os.environ 216 # is automatically translated into a corresponding call to unsetenv(). 217 del os.environ[env_var] 218 #os.unsetenv(env_var) 219 220 if args.set_env_vars: 221 for env_var in args.set_env_vars: 222 parts = env_var.split('=', 1) 223 if len(parts) == 1: 224 os.environ[parts[0]] = "" 225 else: 226 os.environ[parts[0]] = parts[1] 227 228 # only print the args if being verbose (and parsable is off) 229 if args.v and not args.q: 230 print(sys.argv) 231 232 if args.h: 233 do_help = True 234 235 if args.compilers: 236 configuration.compilers = args.compilers 237 else: 238 # Use a compiler appropriate appropriate for the Apple SDK if one was specified 239 if platform_system == 'Darwin' and args.apple_sdk: 240 configuration.compilers = [seven.get_command_output('xcrun -sdk "%s" -find clang 2> /dev/null' % (args.apple_sdk))] 241 else: 242 # 'clang' on ubuntu 14.04 is 3.4 so we try clang-3.5 first 243 candidateCompilers = ['clang-3.5', 'clang', 'gcc'] 244 for candidate in candidateCompilers: 245 if which(candidate): 246 configuration.compilers = [candidate] 247 break 248 249 if args.channels: 250 lldbtest_config.channels = args.channels 251 252 if args.log_success: 253 lldbtest_config.log_success = args.log_success 254 255 # Set SDKROOT if we are using an Apple SDK 256 if platform_system == 'Darwin' and args.apple_sdk: 257 os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % (args.apple_sdk)) 258 259 if args.archs: 260 configuration.archs = args.archs 261 for arch in configuration.archs: 262 if arch.startswith('arm') and platform_system == 'Darwin' and not args.apple_sdk: 263 os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos.internal --show-sdk-path 2> /dev/null') 264 if not os.path.exists(os.environ['SDKROOT']): 265 os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos --show-sdk-path 2> /dev/null') 266 else: 267 configuration.archs = [platform_machine] 268 269 if args.categoriesList: 270 configuration.categoriesList = set(test_categories.validate(args.categoriesList, False)) 271 configuration.useCategories = True 272 else: 273 configuration.categoriesList = [] 274 275 if args.skipCategories: 276 configuration.skipCategories = test_categories.validate(args.skipCategories, False) 277 278 if args.E: 279 cflags_extras = args.E 280 os.environ['CFLAGS_EXTRAS'] = cflags_extras 281 282 if args.d: 283 sys.stdout.write("Suspending the process %d to wait for debugger to attach...\n" % os.getpid()) 284 sys.stdout.flush() 285 os.kill(os.getpid(), signal.SIGSTOP) 286 287 if args.f: 288 if any([x.startswith('-') for x in args.f]): 289 usage(parser) 290 configuration.filters.extend(args.f) 291 # Shut off multiprocessing mode when additional filters are specified. 292 # The rational is that the user is probably going after a very specific 293 # test and doesn't need a bunch of parallel test runners all looking for 294 # it in a frenzy. Also, '-v' now spits out all test run output even 295 # on success, so the standard recipe for redoing a failing test (with -v 296 # and a -f to filter to the specific test) now causes all test scanning 297 # (in parallel) to print results for do-nothing runs in a very distracting 298 # manner. If we really need filtered parallel runs in the future, consider 299 # adding a --no-output-on-success that prevents -v from setting 300 # output-on-success. 301 configuration.no_multiprocess_test_runner = True 302 303 if args.l: 304 configuration.skip_long_running_test = False 305 306 if args.framework: 307 configuration.lldbFrameworkPath = args.framework 308 309 if args.executable: 310 lldbtest_config.lldbExec = os.path.realpath(args.executable) 311 312 if args.p: 313 if args.p.startswith('-'): 314 usage(parser) 315 configuration.regexp = args.p 316 317 if args.q: 318 configuration.parsable = True 319 320 if args.s: 321 if args.s.startswith('-'): 322 usage(parser) 323 configuration.sdir_name = args.s 324 configuration.session_file_format = args.session_file_format 325 326 if args.t: 327 os.environ['LLDB_COMMAND_TRACE'] = 'YES' 328 329 if args.v: 330 configuration.verbose = 2 331 332 # argparse makes sure we have a number 333 if args.sharp: 334 configuration.count = args.sharp 335 336 if sys.platform.startswith('win32'): 337 os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str(args.disable_crash_dialog) 338 os.environ['LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE'] = str(True) 339 340 if do_help == True: 341 usage(parser) 342 343 if args.no_multiprocess: 344 configuration.no_multiprocess_test_runner = True 345 346 if args.inferior: 347 configuration.is_inferior_test_runner = True 348 349 if args.num_threads: 350 configuration.num_threads = args.num_threads 351 352 if args.test_subdir: 353 configuration.multiprocess_test_subdir = args.test_subdir 354 355 if args.test_runner_name: 356 configuration.test_runner_name = args.test_runner_name 357 358 # Capture test results-related args. 359 if args.curses and not args.inferior: 360 # Act as if the following args were set. 361 args.results_formatter = "lldbsuite.test_event.formatter.curses.Curses" 362 args.results_file = "stdout" 363 364 if args.results_file: 365 configuration.results_filename = args.results_file 366 367 if args.results_port: 368 configuration.results_port = args.results_port 369 370 if args.results_file and args.results_port: 371 sys.stderr.write( 372 "only one of --results-file and --results-port should " 373 "be specified\n") 374 usage(args) 375 376 if args.results_formatter: 377 configuration.results_formatter_name = args.results_formatter 378 if args.results_formatter_options: 379 configuration.results_formatter_options = args.results_formatter_options 380 381 # Default to using the BasicResultsFormatter if no formatter is specified 382 # and we're not a test inferior. 383 if not args.inferior and configuration.results_formatter_name is None: 384 configuration.results_formatter_name = ( 385 "lldbsuite.test_event.formatter.results_formatter.ResultsFormatter") 386 387 # rerun-related arguments 388 configuration.rerun_all_issues = args.rerun_all_issues 389 configuration.rerun_max_file_threshold = args.rerun_max_file_threshold 390 391 if args.lldb_platform_name: 392 configuration.lldb_platform_name = args.lldb_platform_name 393 if args.lldb_platform_url: 394 configuration.lldb_platform_url = args.lldb_platform_url 395 if args.lldb_platform_working_dir: 396 configuration.lldb_platform_working_dir = args.lldb_platform_working_dir 397 398 if args.event_add_entries and len(args.event_add_entries) > 0: 399 entries = {} 400 # Parse out key=val pairs, separated by comma 401 for keyval in args.event_add_entries.split(","): 402 key_val_entry = keyval.split("=") 403 if len(key_val_entry) == 2: 404 (key, val) = key_val_entry 405 val_parts = val.split(':') 406 if len(val_parts) > 1: 407 (val, val_type) = val_parts 408 if val_type == 'int': 409 val = int(val) 410 entries[key] = val 411 # Tell the event builder to create all events with these 412 # key/val pairs in them. 413 if len(entries) > 0: 414 EventBuilder.add_entries_to_all_events(entries) 415 416 # Gather all the dirs passed on the command line. 417 if len(args.args) > 0: 418 configuration.testdirs = list(map(lambda x: os.path.realpath(os.path.abspath(x)), args.args)) 419 # Shut off multiprocessing mode when test directories are specified. 420 configuration.no_multiprocess_test_runner = True 421 422 #print("testdirs:", testdirs) 423 424def getXcodeOutputPaths(lldbRootDirectory): 425 result = [] 426 427 # These are for xcode build directories. 428 xcode3_build_dir = ['build'] 429 xcode4_build_dir = ['build', 'lldb', 'Build', 'Products'] 430 431 configurations = [['Debug'], ['DebugClang'], ['Release'], ['BuildAndIntegration']] 432 xcode_build_dirs = [xcode3_build_dir, xcode4_build_dir] 433 for configuration in configurations: 434 for xcode_build_dir in xcode_build_dirs: 435 outputPath = os.path.join(lldbRootDirectory, *(xcode_build_dir+configuration) ) 436 result.append(outputPath) 437 438 return result 439 440 441def createSocketToLocalPort(port): 442 def socket_closer(s): 443 """Close down an opened socket properly.""" 444 s.shutdown(socket.SHUT_RDWR) 445 s.close() 446 447 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 448 sock.connect(("localhost", port)) 449 return (sock, lambda: socket_closer(sock)) 450 451 452def setupTestResults(): 453 """Sets up test results-related objects based on arg settings.""" 454 # Setup the results formatter configuration. 455 formatter_config = formatter.FormatterConfig() 456 formatter_config.filename = configuration.results_filename 457 formatter_config.formatter_name = configuration.results_formatter_name 458 formatter_config.formatter_options = ( 459 configuration.results_formatter_options) 460 formatter_config.port = configuration.results_port 461 462 # Create the results formatter. 463 formatter_spec = formatter.create_results_formatter( 464 formatter_config) 465 if formatter_spec is not None and formatter_spec.formatter is not None: 466 configuration.results_formatter_object = formatter_spec.formatter 467 468 # Send an initialize message to the formatter. 469 initialize_event = EventBuilder.bare_event("initialize") 470 if isMultiprocessTestRunner(): 471 if (configuration.test_runner_name is not None and 472 configuration.test_runner_name == "serial"): 473 # Only one worker queue here. 474 worker_count = 1 475 else: 476 # Workers will be the number of threads specified. 477 worker_count = configuration.num_threads 478 else: 479 worker_count = 1 480 initialize_event["worker_count"] = worker_count 481 482 formatter_spec.formatter.handle_event(initialize_event) 483 484 # Make sure we clean up the formatter on shutdown. 485 if formatter_spec.cleanup_func is not None: 486 atexit.register(formatter_spec.cleanup_func) 487 488 489def getOutputPaths(lldbRootDirectory): 490 """ 491 Returns typical build output paths for the lldb executable 492 493 lldbDirectory - path to the root of the lldb svn/git repo 494 """ 495 result = [] 496 497 if sys.platform == 'darwin': 498 result.extend(getXcodeOutputPaths(lldbRootDirectory)) 499 500 # cmake builds? look for build or build/host folder next to llvm directory 501 # lldb is located in llvm/tools/lldb so we need to go up three levels 502 llvmParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir, os.pardir, os.pardir)) 503 result.append(os.path.join(llvmParentDir, 'build', 'bin')) 504 result.append(os.path.join(llvmParentDir, 'build', 'host', 'bin')) 505 506 # some cmake developers keep their build directory beside their lldb directory 507 lldbParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir)) 508 result.append(os.path.join(lldbParentDir, 'build', 'bin')) 509 result.append(os.path.join(lldbParentDir, 'build', 'host', 'bin')) 510 511 return result 512 513def setupSysPath(): 514 """ 515 Add LLDB.framework/Resources/Python to the search paths for modules. 516 As a side effect, we also discover the 'lldb' executable and export it here. 517 """ 518 519 # Get the directory containing the current script. 520 if "DOTEST_PROFILE" in os.environ and "DOTEST_SCRIPT_DIR" in os.environ: 521 scriptPath = os.environ["DOTEST_SCRIPT_DIR"] 522 else: 523 scriptPath = os.path.dirname(os.path.realpath(__file__)) 524 if not scriptPath.endswith('test'): 525 print("This script expects to reside in lldb's test directory.") 526 sys.exit(-1) 527 528 os.environ["LLDB_TEST"] = scriptPath 529 530 # Set up the LLDB_SRC environment variable, so that the tests can locate 531 # the LLDB source code. 532 os.environ["LLDB_SRC"] = lldbsuite.lldb_root 533 534 pluginPath = os.path.join(scriptPath, 'plugins') 535 toolsLLDBMIPath = os.path.join(scriptPath, 'tools', 'lldb-mi') 536 toolsLLDBServerPath = os.path.join(scriptPath, 'tools', 'lldb-server') 537 538 # Insert script dir, plugin dir, lldb-mi dir and lldb-server dir to the sys.path. 539 sys.path.insert(0, pluginPath) 540 sys.path.insert(0, toolsLLDBMIPath) # Adding test/tools/lldb-mi to the path makes it easy 541 # to "import lldbmi_testcase" from the MI tests 542 sys.path.insert(0, toolsLLDBServerPath) # Adding test/tools/lldb-server to the path makes it easy 543 # to "import lldbgdbserverutils" from the lldb-server tests 544 545 # This is the root of the lldb git/svn checkout 546 # When this changes over to a package instead of a standalone script, this 547 # will be `lldbsuite.lldb_root` 548 lldbRootDirectory = lldbsuite.lldb_root 549 550 # Some of the tests can invoke the 'lldb' command directly. 551 # We'll try to locate the appropriate executable right here. 552 553 # The lldb executable can be set from the command line 554 # if it's not set, we try to find it now 555 # first, we try the environment 556 if not lldbtest_config.lldbExec: 557 # First, you can define an environment variable LLDB_EXEC specifying the 558 # full pathname of the lldb executable. 559 if "LLDB_EXEC" in os.environ: 560 lldbtest_config.lldbExec = os.environ["LLDB_EXEC"] 561 562 if not lldbtest_config.lldbExec: 563 outputPaths = getOutputPaths(lldbRootDirectory) 564 for outputPath in outputPaths: 565 candidatePath = os.path.join(outputPath, 'lldb') 566 if is_exe(candidatePath): 567 lldbtest_config.lldbExec = candidatePath 568 break 569 570 if not lldbtest_config.lldbExec: 571 # Last, check the path 572 lldbtest_config.lldbExec = which('lldb') 573 574 if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec): 575 print("'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec)) 576 lldbtest_config.lldbExec = None 577 578 if not lldbtest_config.lldbExec: 579 print("The 'lldb' executable cannot be located. Some of the tests may not be run as a result.") 580 sys.exit(-1) 581 582 lldbLibDir = os.path.dirname(lldbtest_config.lldbExec) # confusingly, this is the "bin" directory 583 os.environ["LLDB_LIB_DIR"] = lldbLibDir 584 lldbImpLibDir = os.path.join(lldbLibDir, '..', 'lib') if sys.platform.startswith('win32') else lldbLibDir 585 os.environ["LLDB_IMPLIB_DIR"] = lldbImpLibDir 586 print("LLDB library dir:", os.environ["LLDB_LIB_DIR"]) 587 print("LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"]) 588 os.system('%s -v' % lldbtest_config.lldbExec) 589 590 # Assume lldb-mi is in same place as lldb 591 # If not found, disable the lldb-mi tests 592 lldbMiExec = None 593 if lldbtest_config.lldbExec and is_exe(lldbtest_config.lldbExec + "-mi"): 594 lldbMiExec = lldbtest_config.lldbExec + "-mi" 595 if not lldbMiExec: 596 if not configuration.shouldSkipBecauseOfCategories(["lldb-mi"]): 597 print("The 'lldb-mi' executable cannot be located. The lldb-mi tests can not be run as a result.") 598 configuration.skipCategories.append("lldb-mi") 599 else: 600 os.environ["LLDBMI_EXEC"] = lldbMiExec 601 602 lldbPythonDir = None # The directory that contains 'lldb/__init__.py' 603 if configuration.lldbFrameworkPath: 604 candidatePath = os.path.join(configuration.lldbFrameworkPath, 'Resources', 'Python') 605 if os.path.isfile(os.path.join(candidatePath, 'lldb/__init__.py')): 606 lldbPythonDir = candidatePath 607 if not lldbPythonDir: 608 print('Resources/Python/lldb/__init__.py was not found in ' + configuration.lldbFrameworkPath) 609 sys.exit(-1) 610 else: 611 # If our lldb supports the -P option, use it to find the python path: 612 init_in_python_dir = os.path.join('lldb', '__init__.py') 613 614 lldb_dash_p_result = subprocess.check_output([lldbtest_config.lldbExec, "-P"], stderr=subprocess.STDOUT, universal_newlines=True) 615 616 if lldb_dash_p_result and not lldb_dash_p_result.startswith(("<", "lldb: invalid option:")) \ 617 and not lldb_dash_p_result.startswith("Traceback"): 618 lines = lldb_dash_p_result.splitlines() 619 620 # Workaround for readline vs libedit issue on FreeBSD. If stdout 621 # is not a terminal Python executes 622 # rl_variable_bind ("enable-meta-key", "off"); 623 # This produces a warning with FreeBSD's libedit because the 624 # enable-meta-key variable is unknown. Not an issue on Apple 625 # because cpython commit f0ab6f9f0603 added a #ifndef __APPLE__ 626 # around the call. See http://bugs.python.org/issue19884 for more 627 # information. For now we just discard the warning output. 628 if len(lines) >= 1 and lines[0].startswith("bind: Invalid command"): 629 lines.pop(0) 630 631 # Taking the last line because lldb outputs 632 # 'Cannot read termcap database;\nusing dumb terminal settings.\n' 633 # before the path 634 if len(lines) >= 1 and os.path.isfile(os.path.join(lines[-1], init_in_python_dir)): 635 lldbPythonDir = lines[-1] 636 if "freebsd" in sys.platform or "linux" in sys.platform: 637 os.environ['LLDB_LIB_DIR'] = os.path.join(lldbPythonDir, '..', '..') 638 639 if not lldbPythonDir: 640 if platform.system() == "Darwin": 641 python_resource_dir = ['LLDB.framework', 'Resources', 'Python'] 642 outputPaths = getXcodeOutputPaths(lldbRootDirectory) 643 for outputPath in outputPaths: 644 candidatePath = os.path.join(outputPath, *python_resource_dir) 645 if os.path.isfile(os.path.join(candidatePath, init_in_python_dir)): 646 lldbPythonDir = candidatePath 647 break 648 649 if not lldbPythonDir: 650 print("lldb.py is not found, some tests may fail.") 651 else: 652 print("Unable to load lldb extension module. Possible reasons for this include:") 653 print(" 1) LLDB was built with LLDB_DISABLE_PYTHON=1") 654 print(" 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to") 655 print(" the version of Python that LLDB built and linked against, and PYTHONPATH") 656 print(" should contain the Lib directory for the same python distro, as well as the") 657 print(" location of LLDB\'s site-packages folder.") 658 print(" 3) A different version of Python than that which was built against is exported in") 659 print(" the system\'s PATH environment variable, causing conflicts.") 660 print(" 4) The executable '%s' could not be found. Please check " % lldbtest_config.lldbExec) 661 print(" that it exists and is executable.") 662 663 if lldbPythonDir: 664 lldbPythonDir = os.path.normpath(lldbPythonDir) 665 # Some of the code that uses this path assumes it hasn't resolved the Versions... link. 666 # If the path we've constructed looks like that, then we'll strip out the Versions/A part. 667 (before, frameWithVersion, after) = lldbPythonDir.rpartition("LLDB.framework/Versions/A") 668 if frameWithVersion != "" : 669 lldbPythonDir = before + "LLDB.framework" + after 670 671 lldbPythonDir = os.path.abspath(lldbPythonDir) 672 673 # If tests need to find LLDB_FRAMEWORK, now they can do it 674 os.environ["LLDB_FRAMEWORK"] = os.path.dirname(os.path.dirname(lldbPythonDir)) 675 676 # This is to locate the lldb.py module. Insert it right after sys.path[0]. 677 sys.path[1:1] = [lldbPythonDir] 678 679 680def visit_file(dir, name): 681 # Try to match the regexp pattern, if specified. 682 if configuration.regexp: 683 import re 684 if not re.search(configuration.regexp, name): 685 # We didn't match the regex, we're done. 686 return 687 688 # We found a match for our test. Add it to the suite. 689 690 # Update the sys.path first. 691 if not sys.path.count(dir): 692 sys.path.insert(0, dir) 693 base = os.path.splitext(name)[0] 694 695 # Thoroughly check the filterspec against the base module and admit 696 # the (base, filterspec) combination only when it makes sense. 697 filterspec = None 698 for filterspec in configuration.filters: 699 # Optimistically set the flag to True. 700 filtered = True 701 module = __import__(base) 702 parts = filterspec.split('.') 703 obj = module 704 for part in parts: 705 try: 706 parent, obj = obj, getattr(obj, part) 707 except AttributeError: 708 # The filterspec has failed. 709 filtered = False 710 break 711 712 # If filtered, we have a good filterspec. Add it. 713 if filtered: 714 # print("adding filter spec %s to module %s" % (filterspec, module)) 715 configuration.suite.addTests( 716 unittest2.defaultTestLoader.loadTestsFromName(filterspec, module)) 717 continue 718 719 # Forgo this module if the (base, filterspec) combo is invalid 720 if configuration.filters and not filtered: 721 return 722 723 if not filterspec or not filtered: 724 # Add the entire file's worth of tests since we're not filtered. 725 # Also the fail-over case when the filterspec branch 726 # (base, filterspec) combo doesn't make sense. 727 configuration.suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base)) 728 729 730def visit(prefix, dir, names): 731 """Visitor function for os.path.walk(path, visit, arg).""" 732 733 dir_components = set(dir.split(os.sep)) 734 excluded_components = set(['.svn', '.git']) 735 if dir_components.intersection(excluded_components): 736 return 737 738 # Gather all the Python test file names that follow the Test*.py pattern. 739 python_test_files = [ 740 name 741 for name in names 742 if name.endswith('.py') and name.startswith(prefix)] 743 744 # Visit all the python test files. 745 for name in python_test_files: 746 try: 747 # Ensure we error out if we have multiple tests with the same 748 # base name. 749 # Future improvement: find all the places where we work with base 750 # names and convert to full paths. We have directory structure 751 # to disambiguate these, so we shouldn't need this constraint. 752 if name in configuration.all_tests: 753 raise Exception("Found multiple tests with the name %s" % name) 754 configuration.all_tests.add(name) 755 756 # Run the relevant tests in the python file. 757 visit_file(dir, name) 758 except Exception as ex: 759 # Convert this exception to a test event error for the file. 760 test_filename = os.path.abspath(os.path.join(dir, name)) 761 if configuration.results_formatter_object is not None: 762 # Grab the backtrace for the exception. 763 import traceback 764 backtrace = traceback.format_exc() 765 766 # Generate the test event. 767 configuration.results_formatter_object.handle_event( 768 EventBuilder.event_for_job_test_add_error( 769 test_filename, ex, backtrace)) 770 raise 771 772 773def disabledynamics(): 774 import lldb 775 ci = lldb.DBG.GetCommandInterpreter() 776 res = lldb.SBCommandReturnObject() 777 ci.HandleCommand("setting set target.prefer-dynamic-value no-dynamic-values", res, False) 778 if not res.Succeeded(): 779 raise Exception('disabling dynamic type support failed') 780 781def lldbLoggings(): 782 import lldb 783 """Check and do lldb loggings if necessary.""" 784 785 # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is 786 # defined. Use ${LLDB_LOG} to specify the log file. 787 ci = lldb.DBG.GetCommandInterpreter() 788 res = lldb.SBCommandReturnObject() 789 if ("LLDB_LOG" in os.environ): 790 open(os.environ["LLDB_LOG"], 'w').close() 791 if ("LLDB_LOG_OPTION" in os.environ): 792 lldb_log_option = os.environ["LLDB_LOG_OPTION"] 793 else: 794 lldb_log_option = "event process expr state api" 795 ci.HandleCommand( 796 "log enable -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option, 797 res) 798 if not res.Succeeded(): 799 raise Exception('log enable failed (check LLDB_LOG env variable)') 800 801 if ("LLDB_LINUX_LOG" in os.environ): 802 open(os.environ["LLDB_LINUX_LOG"], 'w').close() 803 if ("LLDB_LINUX_LOG_OPTION" in os.environ): 804 lldb_log_option = os.environ["LLDB_LINUX_LOG_OPTION"] 805 else: 806 lldb_log_option = "event process expr state api" 807 ci.HandleCommand( 808 "log enable -n -f " + os.environ["LLDB_LINUX_LOG"] + " linux " + lldb_log_option, 809 res) 810 if not res.Succeeded(): 811 raise Exception('log enable failed (check LLDB_LINUX_LOG env variable)') 812 813 # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined. 814 # Use ${GDB_REMOTE_LOG} to specify the log file. 815 if ("GDB_REMOTE_LOG" in os.environ): 816 if ("GDB_REMOTE_LOG_OPTION" in os.environ): 817 gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"] 818 else: 819 gdb_remote_log_option = "packets process" 820 ci.HandleCommand( 821 "log enable -n -f " + os.environ["GDB_REMOTE_LOG"] + " gdb-remote " 822 + gdb_remote_log_option, 823 res) 824 if not res.Succeeded(): 825 raise Exception('log enable failed (check GDB_REMOTE_LOG env variable)') 826 827def getMyCommandLine(): 828 return ' '.join(sys.argv) 829 830# ======================================== # 831# # 832# Execution of the test driver starts here # 833# # 834# ======================================== # 835 836def checkDsymForUUIDIsNotOn(): 837 cmd = ["defaults", "read", "com.apple.DebugSymbols"] 838 pipe = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) 839 cmd_output = pipe.stdout.read() 840 if cmd_output and "DBGFileMappedPaths = " in cmd_output: 841 print("%s =>" % ' '.join(cmd)) 842 print(cmd_output) 843 print("Disable automatic lookup and caching of dSYMs before running the test suite!") 844 print("Exiting...") 845 sys.exit(0) 846 847def exitTestSuite(exitCode = None): 848 import lldb 849 lldb.SBDebugger.Terminate() 850 if exitCode: 851 sys.exit(exitCode) 852 853 854def isMultiprocessTestRunner(): 855 # We're not multiprocess when we're either explicitly 856 # the inferior (as specified by the multiprocess test 857 # runner) OR we've been told to skip using the multiprocess 858 # test runner 859 return not (configuration.is_inferior_test_runner or configuration.no_multiprocess_test_runner) 860 861def getVersionForSDK(sdk): 862 sdk = str.lower(sdk) 863 full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk) 864 basename = os.path.basename(full_path) 865 basename = os.path.splitext(basename)[0] 866 basename = str.lower(basename) 867 ver = basename.replace(sdk, '') 868 return ver 869 870def getPathForSDK(sdk): 871 sdk = str.lower(sdk) 872 full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk) 873 if os.path.exists(full_path): return full_path 874 return None 875 876def setDefaultTripleForPlatform(): 877 if configuration.lldb_platform_name == 'ios-simulator': 878 triple_str = 'x86_64-apple-ios%s' % (getVersionForSDK('iphonesimulator')) 879 os.environ['TRIPLE'] = triple_str 880 return {'TRIPLE':triple_str} 881 return {} 882 883def run_suite(): 884 # On MacOS X, check to make sure that domain for com.apple.DebugSymbols defaults 885 # does not exist before proceeding to running the test suite. 886 if sys.platform.startswith("darwin"): 887 checkDsymForUUIDIsNotOn() 888 889 # 890 # Start the actions by first parsing the options while setting up the test 891 # directories, followed by setting up the search paths for lldb utilities; 892 # then, we walk the directory trees and collect the tests into our test suite. 893 # 894 parseOptionsAndInitTestdirs() 895 896 # Setup test results (test results formatter and output handling). 897 setupTestResults() 898 899 # If we are running as the multiprocess test runner, kick off the 900 # multiprocess test runner here. 901 if isMultiprocessTestRunner(): 902 from . import dosep 903 dosep.main(configuration.num_threads, configuration.multiprocess_test_subdir, 904 configuration.test_runner_name, configuration.results_formatter_object) 905 raise Exception("should never get here") 906 elif configuration.is_inferior_test_runner: 907 # Shut off Ctrl-C processing in inferiors. The parallel 908 # test runner handles this more holistically. 909 signal.signal(signal.SIGINT, signal.SIG_IGN) 910 911 setupSysPath() 912 configuration.setupCrashInfoHook() 913 914 # 915 # If '-l' is specified, do not skip the long running tests. 916 if not configuration.skip_long_running_test: 917 os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO" 918 919 # For the time being, let's bracket the test runner within the 920 # lldb.SBDebugger.Initialize()/Terminate() pair. 921 import lldb 922 923 # Create a singleton SBDebugger in the lldb namespace. 924 lldb.DBG = lldb.SBDebugger.Create() 925 926 if configuration.lldb_platform_name: 927 print("Setting up remote platform '%s'" % (configuration.lldb_platform_name)) 928 lldb.remote_platform = lldb.SBPlatform(configuration.lldb_platform_name) 929 if not lldb.remote_platform.IsValid(): 930 print("error: unable to create the LLDB platform named '%s'." % (configuration.lldb_platform_name)) 931 exitTestSuite(1) 932 if configuration.lldb_platform_url: 933 # We must connect to a remote platform if a LLDB platform URL was specified 934 print("Connecting to remote platform '%s' at '%s'..." % (configuration.lldb_platform_name, configuration.lldb_platform_url)) 935 platform_connect_options = lldb.SBPlatformConnectOptions(configuration.lldb_platform_url) 936 err = lldb.remote_platform.ConnectRemote(platform_connect_options) 937 if err.Success(): 938 print("Connected.") 939 else: 940 print("error: failed to connect to remote platform using URL '%s': %s" % (configuration.lldb_platform_url, err)) 941 exitTestSuite(1) 942 else: 943 configuration.lldb_platform_url = None 944 945 platform_changes = setDefaultTripleForPlatform() 946 first = True 947 for key in platform_changes: 948 if first: 949 print("Environment variables setup for platform support:") 950 first = False 951 print("%s = %s" % (key,platform_changes[key])) 952 953 if configuration.lldb_platform_working_dir: 954 print("Setting remote platform working directory to '%s'..." % (configuration.lldb_platform_working_dir)) 955 lldb.remote_platform.SetWorkingDirectory(configuration.lldb_platform_working_dir) 956 lldb.DBG.SetSelectedPlatform(lldb.remote_platform) 957 else: 958 lldb.remote_platform = None 959 configuration.lldb_platform_working_dir = None 960 configuration.lldb_platform_url = None 961 962 target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2] 963 964 # Don't do debugserver tests on everything except OS X. 965 configuration.dont_do_debugserver_test = "linux" in target_platform or "freebsd" in target_platform or "windows" in target_platform 966 967 # Don't do lldb-server (llgs) tests on anything except Linux. 968 configuration.dont_do_llgs_test = not ("linux" in target_platform) 969 970 # 971 # Walk through the testdirs while collecting tests. 972 # 973 for testdir in configuration.testdirs: 974 for (dirpath, dirnames, filenames) in os.walk(testdir): 975 visit('Test', dirpath, filenames) 976 977 # 978 # Now that we have loaded all the test cases, run the whole test suite. 979 # 980 981 # Turn on lldb loggings if necessary. 982 lldbLoggings() 983 984 # Disable default dynamic types for testing purposes 985 disabledynamics() 986 987 # Install the control-c handler. 988 unittest2.signals.installHandler() 989 990 # If sdir_name is not specified through the '-s sdir_name' option, get a 991 # timestamp string and export it as LLDB_SESSION_DIR environment var. This will 992 # be used when/if we want to dump the session info of individual test cases 993 # later on. 994 # 995 # See also TestBase.dumpSessionInfo() in lldbtest.py. 996 import datetime 997 # The windows platforms don't like ':' in the pathname. 998 timestamp_started = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S") 999 if not configuration.sdir_name: 1000 configuration.sdir_name = timestamp_started 1001 os.environ["LLDB_SESSION_DIRNAME"] = os.path.join(os.getcwd(), configuration.sdir_name) 1002 1003 sys.stderr.write("\nSession logs for test failures/errors/unexpected successes" 1004 " will go into directory '%s'\n" % configuration.sdir_name) 1005 sys.stderr.write("Command invoked: %s\n" % getMyCommandLine()) 1006 1007 if not os.path.isdir(configuration.sdir_name): 1008 try: 1009 os.mkdir(configuration.sdir_name) 1010 except OSError as exception: 1011 if exception.errno != errno.EEXIST: 1012 raise 1013 1014 # 1015 # Invoke the default TextTestRunner to run the test suite, possibly iterating 1016 # over different configurations. 1017 # 1018 1019 iterArchs = False 1020 iterCompilers = False 1021 1022 if isinstance(configuration.archs, list) and len(configuration.archs) >= 1: 1023 iterArchs = True 1024 1025 # 1026 # Add some intervention here to sanity check that the compilers requested are sane. 1027 # If found not to be an executable program, the invalid one is dropped from the list. 1028 for i in range(len(configuration.compilers)): 1029 c = configuration.compilers[i] 1030 if which(c): 1031 continue 1032 else: 1033 if sys.platform.startswith("darwin"): 1034 pipe = subprocess.Popen(['xcrun', '-find', c], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) 1035 cmd_output = pipe.stdout.read() 1036 if cmd_output: 1037 if "not found" in cmd_output: 1038 print("dropping %s from the compilers used" % c) 1039 configuration.compilers.remove(i) 1040 else: 1041 configuration.compilers[i] = cmd_output.split('\n')[0] 1042 print("'xcrun -find %s' returning %s" % (c, configuration.compilers[i])) 1043 1044 if not configuration.parsable: 1045 print("compilers=%s" % str(configuration.compilers)) 1046 1047 if not configuration.compilers or len(configuration.compilers) == 0: 1048 print("No eligible compiler found, exiting.") 1049 exitTestSuite(1) 1050 1051 if isinstance(configuration.compilers, list) and len(configuration.compilers) >= 1: 1052 iterCompilers = True 1053 1054 # If we iterate on archs or compilers, there is a chance we want to split stderr/stdout. 1055 if iterArchs or iterCompilers: 1056 old_stderr = sys.stderr 1057 old_stdout = sys.stdout 1058 new_stderr = None 1059 new_stdout = None 1060 1061 # Iterating over all possible architecture and compiler combinations. 1062 for ia in range(len(configuration.archs) if iterArchs else 1): 1063 archConfig = "" 1064 if iterArchs: 1065 os.environ["ARCH"] = configuration.archs[ia] 1066 archConfig = "arch=%s" % configuration.archs[ia] 1067 for ic in range(len(configuration.compilers) if iterCompilers else 1): 1068 if iterCompilers: 1069 os.environ["CC"] = configuration.compilers[ic] 1070 configString = "%s compiler=%s" % (archConfig, configuration.compilers[ic]) 1071 else: 1072 configString = archConfig 1073 1074 if iterArchs or iterCompilers: 1075 # Translate ' ' to '-' for pathname component. 1076 if six.PY2: 1077 import string 1078 tbl = string.maketrans(' ', '-') 1079 else: 1080 tbl = str.maketrans(' ', '-') 1081 configPostfix = configString.translate(tbl) 1082 1083 # Output the configuration. 1084 if not configuration.parsable: 1085 sys.stderr.write("\nConfiguration: " + configString + "\n") 1086 1087 #print("sys.stderr name is", sys.stderr.name) 1088 #print("sys.stdout name is", sys.stdout.name) 1089 1090 # First, write out the number of collected test cases. 1091 if not configuration.parsable: 1092 sys.stderr.write(configuration.separator + "\n") 1093 sys.stderr.write("Collected %d test%s\n\n" 1094 % (configuration.suite.countTestCases(), 1095 configuration.suite.countTestCases() != 1 and "s" or "")) 1096 1097 if configuration.parsable: 1098 v = 0 1099 else: 1100 v = configuration.verbose 1101 1102 # Invoke the test runner. 1103 if configuration.count == 1: 1104 result = unittest2.TextTestRunner(stream=sys.stderr, 1105 verbosity=v, 1106 resultclass=test_result.LLDBTestResult).run(configuration.suite) 1107 else: 1108 # We are invoking the same test suite more than once. In this case, 1109 # mark __ignore_singleton__ flag as True so the signleton pattern is 1110 # not enforced. 1111 test_result.LLDBTestResult.__ignore_singleton__ = True 1112 for i in range(configuration.count): 1113 1114 result = unittest2.TextTestRunner(stream=sys.stderr, 1115 verbosity=v, 1116 resultclass=test_result.LLDBTestResult).run(configuration.suite) 1117 1118 configuration.failed = configuration.failed or not result.wasSuccessful() 1119 1120 if configuration.sdir_has_content and not configuration.parsable: 1121 sys.stderr.write("Session logs for test failures/errors/unexpected successes" 1122 " can be found in directory '%s'\n" % configuration.sdir_name) 1123 1124 if configuration.useCategories and len(configuration.failuresPerCategory) > 0: 1125 sys.stderr.write("Failures per category:\n") 1126 for category in configuration.failuresPerCategory: 1127 sys.stderr.write("%s - %d\n" % (category, configuration.failuresPerCategory[category])) 1128 1129 # Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined. 1130 # This should not be necessary now. 1131 if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ): 1132 print("Terminating Test suite...") 1133 subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())]) 1134 1135 # Exiting. 1136 exitTestSuite(configuration.failed) 1137 1138if __name__ == "__main__": 1139 print(__file__ + " is for use as a module only. It should not be run as a standalone script.") 1140 sys.exit(-1) 1141